handle_variable.cpp 1.9 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/check/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/sem_ir/node.h"
  7. namespace Carbon::Check {
  8. auto HandleVariableDeclaration(Context& context, Parse::Node parse_node)
  9. -> bool {
  10. // Handle the optional initializer.
  11. auto init_id = SemIR::NodeId::Invalid;
  12. bool has_init =
  13. context.parse_tree().node_kind(context.node_stack().PeekParseNode()) !=
  14. Parse::NodeKind::PatternBinding;
  15. if (has_init) {
  16. init_id = context.node_stack().PopExpression();
  17. context.node_stack()
  18. .PopAndDiscardSoloParseNode<Parse::NodeKind::VariableInitializer>();
  19. }
  20. // Get the storage and add it to name lookup.
  21. SemIR::NodeId var_id =
  22. context.node_stack().Pop<Parse::NodeKind::PatternBinding>();
  23. auto var = context.semantics_ir().GetNodeAs<SemIR::VarStorage>(var_id);
  24. context.AddNameToLookup(var.parse_node, var.name_id, var_id);
  25. // If there was an initializer, assign it to storage.
  26. if (has_init) {
  27. init_id = Initialize(context, parse_node, var_id, init_id);
  28. // TODO: Consider using different node kinds for assignment versus
  29. // initialization.
  30. context.AddNode(SemIR::Assign(parse_node, var_id, init_id));
  31. }
  32. context.node_stack()
  33. .PopAndDiscardSoloParseNode<Parse::NodeKind::VariableIntroducer>();
  34. return true;
  35. }
  36. auto HandleVariableIntroducer(Context& context, Parse::Node parse_node)
  37. -> bool {
  38. // No action, just a bracketing node.
  39. context.node_stack().Push(parse_node);
  40. return true;
  41. }
  42. auto HandleVariableInitializer(Context& context, Parse::Node parse_node)
  43. -> bool {
  44. // No action, just a bracketing node.
  45. context.node_stack().Push(parse_node);
  46. return true;
  47. }
  48. } // namespace Carbon::Check