semantics_handle_variable.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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().Pop<SemanticsNodeId>();
  16. context.node_stack().PopAndDiscardSoloParseNode(
  17. ParseNodeKind::VariableInitializer);
  18. }
  19. // Get the storage and add it to name lookup.
  20. auto binding_id =
  21. context.node_stack().Pop<SemanticsNodeId>(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().PopAndDiscardSoloParseNode(
  35. 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