handle_variable.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/inst.h"
  7. namespace Carbon::Check {
  8. auto HandleVariableDecl(Context& context, Parse::Node parse_node) -> bool {
  9. // Handle the optional initializer.
  10. auto init_id = SemIR::InstId::Invalid;
  11. bool has_init =
  12. context.parse_tree().node_kind(context.node_stack().PeekParseNode()) !=
  13. Parse::NodeKind::PatternBinding;
  14. if (has_init) {
  15. init_id = context.node_stack().PopExpr();
  16. context.node_stack()
  17. .PopAndDiscardSoloParseNode<Parse::NodeKind::VariableInitializer>();
  18. }
  19. // Extract the name binding.
  20. auto value_id = context.node_stack().Pop<Parse::NodeKind::PatternBinding>();
  21. if (auto bind_name = context.insts().Get(value_id).TryAs<SemIR::BindName>()) {
  22. // Form a corresponding name in the current context, and bind the name to
  23. // the variable.
  24. context.decl_name_stack().AddNameToLookup(
  25. context.decl_name_stack().MakeUnqualifiedName(bind_name->parse_node,
  26. bind_name->name_id),
  27. value_id);
  28. value_id = bind_name->value_id;
  29. }
  30. // If there was an initializer, assign it to the storage.
  31. if (has_init) {
  32. if (context.insts().Get(value_id).Is<SemIR::VarStorage>()) {
  33. init_id = Initialize(context, parse_node, value_id, init_id);
  34. // TODO: Consider using different instruction kinds for assignment versus
  35. // initialization.
  36. context.AddInst(SemIR::Assign{parse_node, value_id, init_id});
  37. } else {
  38. // TODO: In a class scope, we should instead save the initializer
  39. // somewhere so that we can use it as a default.
  40. context.TODO(parse_node, "Field initializer");
  41. }
  42. }
  43. context.node_stack()
  44. .PopAndDiscardSoloParseNode<Parse::NodeKind::VariableIntroducer>();
  45. return true;
  46. }
  47. auto HandleVariableIntroducer(Context& context, Parse::Node parse_node)
  48. -> bool {
  49. // No action, just a bracketing node.
  50. context.node_stack().Push(parse_node);
  51. return true;
  52. }
  53. auto HandleVariableInitializer(Context& context, Parse::Node parse_node)
  54. -> bool {
  55. // No action, just a bracketing node.
  56. context.node_stack().Push(parse_node);
  57. return true;
  58. }
  59. } // namespace Carbon::Check