semantics_handle_variable.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(SemanticsNode::Assign::Make(
  31. parse_node, context.semantics_ir().GetNode(cast_value_id).type_id(),
  32. storage_id, cast_value_id));
  33. }
  34. context.node_stack()
  35. .PopAndDiscardSoloParseNode<ParseNodeKind::VariableIntroducer>();
  36. return true;
  37. }
  38. auto SemanticsHandleVariableIntroducer(SemanticsContext& context,
  39. ParseTree::Node parse_node) -> bool {
  40. // No action, just a bracketing node.
  41. context.node_stack().Push(parse_node);
  42. return true;
  43. }
  44. auto SemanticsHandleVariableInitializer(SemanticsContext& context,
  45. ParseTree::Node parse_node) -> bool {
  46. // No action, just a bracketing node.
  47. context.node_stack().Push(parse_node);
  48. return true;
  49. }
  50. } // namespace Carbon