semantics_handle_variable.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/semantics/semantics_context.h"
  5. #include "toolchain/semantics/semantics_node.h"
  6. namespace Carbon::Check {
  7. auto HandleVariableDeclaration(Context& context, ParseTree::Node parse_node)
  8. -> bool {
  9. // Handle the optional initializer.
  10. auto expr_node_id = SemIR::NodeId::Invalid;
  11. bool has_init =
  12. context.parse_tree().node_kind(context.node_stack().PeekParseNode()) !=
  13. ParseNodeKind::PatternBinding;
  14. if (has_init) {
  15. expr_node_id = context.node_stack().PopExpression();
  16. context.node_stack()
  17. .PopAndDiscardSoloParseNode<ParseNodeKind::VariableInitializer>();
  18. }
  19. // Get the storage and add it to name lookup.
  20. SemIR::NodeId var_id =
  21. context.node_stack().Pop<ParseNodeKind::PatternBinding>();
  22. auto var = context.semantics_ir().GetNode(var_id);
  23. auto name_id = var.GetAsVarStorage();
  24. context.AddNameToLookup(var.parse_node(), name_id, var_id);
  25. // If there was an initializer, assign it to storage.
  26. if (has_init) {
  27. context.Initialize(parse_node, var_id, expr_node_id);
  28. }
  29. context.node_stack()
  30. .PopAndDiscardSoloParseNode<ParseNodeKind::VariableIntroducer>();
  31. return true;
  32. }
  33. auto HandleVariableIntroducer(Context& context, ParseTree::Node parse_node)
  34. -> bool {
  35. // No action, just a bracketing node.
  36. context.node_stack().Push(parse_node);
  37. return true;
  38. }
  39. auto HandleVariableInitializer(Context& context, ParseTree::Node parse_node)
  40. -> bool {
  41. // No action, just a bracketing node.
  42. context.node_stack().Push(parse_node);
  43. return true;
  44. }
  45. } // namespace Carbon::Check