semantics_handle_variable.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 {
  7. auto SemanticsHandleVariableDeclaration(SemanticsContext& context,
  8. ParseTree::Node parse_node) -> bool {
  9. // Handle the optional initializer.
  10. auto expr_node_id = SemanticsNodeId::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. SemanticsNodeId 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. auto cast_value_id =
  28. context.ImplicitAsRequired(parse_node, expr_node_id, var.type_id());
  29. context.AddNode(
  30. SemanticsNode::Assign::Make(parse_node, var_id, cast_value_id));
  31. }
  32. context.node_stack()
  33. .PopAndDiscardSoloParseNode<ParseNodeKind::VariableIntroducer>();
  34. return true;
  35. }
  36. auto SemanticsHandleVariableIntroducer(SemanticsContext& context,
  37. ParseTree::Node parse_node) -> bool {
  38. // No action, just a bracketing node.
  39. context.node_stack().Push(parse_node);
  40. return true;
  41. }
  42. auto SemanticsHandleVariableInitializer(SemanticsContext& context,
  43. ParseTree::Node parse_node) -> bool {
  44. // No action, just a bracketing node.
  45. context.node_stack().Push(parse_node);
  46. return true;
  47. }
  48. } // namespace Carbon