semantics_handle_variable.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 binding_id =
  21. context.node_stack().Pop<ParseNodeKind::PatternBinding>();
  22. auto binding = context.semantics_ir().GetNode(binding_id);
  23. auto [name_id, storage_id] = binding.GetAsBindName();
  24. context.AddNameToLookup(binding.parse_node(), name_id, storage_id);
  25. // If there was an initializer, assign it to storage.
  26. if (has_init) {
  27. auto cast_value_id = context.ImplicitAsRequired(
  28. parse_node, expr_node_id,
  29. context.semantics_ir().GetNode(storage_id).type_id());
  30. context.AddNode(
  31. SemanticsNode::Assign::Make(parse_node, storage_id, cast_value_id));
  32. }
  33. context.node_stack()
  34. .PopAndDiscardSoloParseNode<ParseNodeKind::VariableIntroducer>();
  35. return true;
  36. }
  37. auto SemanticsHandleVariableIntroducer(SemanticsContext& context,
  38. ParseTree::Node parse_node) -> bool {
  39. // No action, just a bracketing node.
  40. context.node_stack().Push(parse_node);
  41. return true;
  42. }
  43. auto SemanticsHandleVariableInitializer(SemanticsContext& context,
  44. ParseTree::Node parse_node) -> bool {
  45. // No action, just a bracketing node.
  46. context.node_stack().Push(parse_node);
  47. return true;
  48. }
  49. } // namespace Carbon