handle_variable.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // Extract the name binding.
  21. SemIR::NodeId bind_name_id =
  22. context.node_stack().Pop<Parse::NodeKind::PatternBinding>();
  23. auto bind_name = context.nodes().GetAs<SemIR::BindName>(bind_name_id);
  24. // Form a corresponding name in the current context, and bind the name to the
  25. // variable.
  26. context.declaration_name_stack().AddNameToLookup(
  27. context.declaration_name_stack().MakeUnqualifiedName(bind_name.parse_node,
  28. bind_name.name_id),
  29. bind_name_id);
  30. // If there was an initializer, assign it to the storage.
  31. if (has_init) {
  32. auto var_id = bind_name.value_id;
  33. if (context.nodes().Get(var_id).Is<SemIR::VarStorage>()) {
  34. init_id = Initialize(context, parse_node, var_id, init_id);
  35. // TODO: Consider using different node kinds for assignment versus
  36. // initialization.
  37. context.AddNode(SemIR::Assign{parse_node, var_id, init_id});
  38. } else {
  39. // TODO: In a class scope, we should instead save the initializer
  40. // somewhere so that we can use it as a default.
  41. context.TODO(parse_node, "Field initializer");
  42. }
  43. }
  44. context.node_stack()
  45. .PopAndDiscardSoloParseNode<Parse::NodeKind::VariableIntroducer>();
  46. return true;
  47. }
  48. auto HandleVariableIntroducer(Context& context, Parse::Node parse_node)
  49. -> bool {
  50. // No action, just a bracketing node.
  51. context.node_stack().Push(parse_node);
  52. return true;
  53. }
  54. auto HandleVariableInitializer(Context& context, Parse::Node parse_node)
  55. -> bool {
  56. // No action, just a bracketing node.
  57. context.node_stack().Push(parse_node);
  58. return true;
  59. }
  60. } // namespace Carbon::Check