handle_let_and_var.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/check/decl_introducer_state.h"
  7. #include "toolchain/check/handle.h"
  8. #include "toolchain/check/interface.h"
  9. #include "toolchain/check/modifiers.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/lex/token_kind.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/name_scope.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. template <Lex::TokenKind::RawEnumType Kind>
  17. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  18. context.decl_introducer_state_stack().Push<Kind>();
  19. // Push a bracketing node and pattern block to establish the pattern context.
  20. context.node_stack().Push(node_id);
  21. context.pattern_block_stack().Push();
  22. return true;
  23. }
  24. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  25. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  26. }
  27. auto HandleParseNode(Context& context, Parse::VariableIntroducerId node_id)
  28. -> bool {
  29. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  30. }
  31. auto HandleParseNode(Context& context, Parse::ReturnedModifierId node_id)
  32. -> bool {
  33. // This is pushed to be seen by HandleBindingPattern.
  34. context.node_stack().Push(node_id);
  35. return true;
  36. }
  37. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  38. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  39. context.global_init().Resume();
  40. }
  41. context.node_stack().Push(node_id);
  42. return true;
  43. }
  44. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  45. -> bool {
  46. return HandleInitializer(context, node_id);
  47. }
  48. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  49. -> bool {
  50. return HandleInitializer(context, node_id);
  51. }
  52. // Builds an associated constant declaration for a `let`.
  53. static auto BuildAssociatedConstantDecl(Context& context,
  54. Parse::LetDeclId node_id,
  55. SemIR::InstId pattern_id,
  56. SemIR::LocIdAndInst pattern,
  57. SemIR::InterfaceId interface_id,
  58. SemIR::AccessKind access_kind) -> void {
  59. auto& interface_info = context.interfaces().Get(interface_id);
  60. auto binding_pattern = pattern.inst.TryAs<SemIR::BindSymbolicName>();
  61. if (!binding_pattern) {
  62. CARBON_DIAGNOSTIC(ExpectedSymbolicBindingInAssociatedConstant, Error,
  63. "pattern in associated constant declaration must be a "
  64. "single `:!` binding");
  65. context.emitter().Emit(pattern.loc_id,
  66. ExpectedSymbolicBindingInAssociatedConstant);
  67. context.name_scopes().Get(interface_info.scope_id).set_has_error();
  68. return;
  69. }
  70. // Replace the tentative BindName instruction with the associated constant
  71. // declaration.
  72. auto name_id =
  73. context.entity_names().Get(binding_pattern->entity_name_id).name_id;
  74. context.ReplaceLocIdAndInstBeforeConstantUse(
  75. pattern_id,
  76. SemIR::LocIdAndInst(node_id, SemIR::AssociatedConstantDecl{
  77. binding_pattern->type_id, name_id}));
  78. auto decl_id = pattern_id;
  79. context.inst_block_stack().AddInstId(decl_id);
  80. // Add an associated entity name to the interface scope.
  81. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  82. auto name_context =
  83. context.decl_name_stack().MakeUnqualifiedName(pattern.loc_id, name_id);
  84. context.decl_name_stack().AddNameOrDiagnoseDuplicate(name_context, assoc_id,
  85. access_kind);
  86. }
  87. // Adds name bindings. Returns the resulting ID for the references.
  88. static auto HandleNameBinding(Context& context, SemIR::InstId pattern_id,
  89. SemIR::AccessKind access_kind) -> SemIR::InstId {
  90. // Extract the name binding.
  91. if (auto bind_name =
  92. context.insts().TryGetAs<SemIR::AnyBindName>(pattern_id)) {
  93. // Form a corresponding name in the current context, and bind the name to
  94. // the variable.
  95. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  96. context.insts().GetLocId(pattern_id),
  97. context.entity_names().Get(bind_name->entity_name_id).name_id);
  98. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  99. name_context, pattern_id, access_kind);
  100. return bind_name->value_id;
  101. } else if (auto field_decl =
  102. context.insts().TryGetAs<SemIR::FieldDecl>(pattern_id)) {
  103. // Introduce the field name into the class.
  104. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  105. context.insts().GetLocId(pattern_id), field_decl->name_id);
  106. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  107. name_context, pattern_id, access_kind);
  108. return pattern_id;
  109. } else {
  110. // TODO: Handle other kinds of pattern.
  111. return pattern_id;
  112. }
  113. }
  114. namespace {
  115. // State from HandleDecl, returned for type-specific handling.
  116. struct DeclInfo {
  117. // The optional initializer.
  118. std::optional<SemIR::InstId> init_id = std::nullopt;
  119. SemIR::InstId pattern_id = SemIR::InstId::Invalid;
  120. std::optional<SemIR::Inst> parent_scope_inst = std::nullopt;
  121. DeclIntroducerState introducer = DeclIntroducerState();
  122. };
  123. } // namespace
  124. // Handles common logic for `let` and `var` declarations.
  125. // TODO: There's still a lot of divergence here, including logic in
  126. // handle_binding_pattern. These should really be better unified.
  127. template <const Lex::TokenKind& IntroducerTokenKind,
  128. const Parse::NodeKind& IntroducerNodeKind,
  129. const Parse::NodeKind& InitializerNodeKind, typename NodeT>
  130. static auto HandleDecl(Context& context, NodeT node_id)
  131. -> std::optional<DeclInfo> {
  132. std::optional<DeclInfo> decl_info = DeclInfo();
  133. // TODO: Update binding-pattern handling to use the pattern block even in
  134. // a let/var context, and then consume it here.
  135. context.pattern_block_stack().PopAndDiscard();
  136. // Handle the optional initializer.
  137. if (context.node_stack().PeekNextIs<InitializerNodeKind>()) {
  138. decl_info->init_id = context.node_stack().PopExpr();
  139. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  140. }
  141. if (context.node_stack().PeekIs<Parse::NodeKind::TuplePattern>()) {
  142. if (decl_info->init_id &&
  143. context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  144. context.global_init().Suspend();
  145. }
  146. context.TODO(node_id, "tuple pattern in let/var");
  147. decl_info = std::nullopt;
  148. return decl_info;
  149. }
  150. decl_info->pattern_id = context.node_stack().PopPattern();
  151. if constexpr (IntroducerTokenKind == Lex::TokenKind::Var) {
  152. // Pop the `returned` modifier if present.
  153. context.node_stack()
  154. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::ReturnedModifier>();
  155. }
  156. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  157. // Process declaration modifiers.
  158. // TODO: For a qualified `let` or `var` declaration, this should use the
  159. // target scope of the name introduced in the declaration. See #2590.
  160. decl_info->parent_scope_inst =
  161. context.name_scopes()
  162. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  163. .second;
  164. decl_info->introducer =
  165. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  166. CheckAccessModifiersOnDecl(context, decl_info->introducer,
  167. decl_info->parent_scope_inst);
  168. return decl_info;
  169. }
  170. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  171. auto decl_info =
  172. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  173. Parse::NodeKind::LetInitializer>(context, node_id);
  174. if (!decl_info) {
  175. return false;
  176. }
  177. RequireDefaultFinalOnlyInInterfaces(context, decl_info->introducer,
  178. decl_info->parent_scope_inst);
  179. LimitModifiersOnDecl(
  180. context, decl_info->introducer,
  181. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  182. if (decl_info->introducer.modifier_set.HasAnyOf(
  183. KeywordModifierSet::Interface)) {
  184. context.TODO(decl_info->introducer.modifier_node_id(ModifierOrder::Decl),
  185. "interface modifier");
  186. }
  187. auto pattern = context.insts().GetWithLocId(decl_info->pattern_id);
  188. if (decl_info->init_id) {
  189. // Convert the value to match the type of the pattern.
  190. decl_info->init_id = ConvertToValueOfType(
  191. context, node_id, *decl_info->init_id, pattern.inst.type_id());
  192. }
  193. auto interface_scope = context.GetCurrentScopeAs<SemIR::InterfaceDecl>();
  194. // At interface scope, we are forming an associated constant, which has
  195. // different rules.
  196. if (interface_scope) {
  197. BuildAssociatedConstantDecl(
  198. context, node_id, decl_info->pattern_id, pattern,
  199. interface_scope->interface_id,
  200. decl_info->introducer.modifier_set.GetAccessKind());
  201. return true;
  202. }
  203. if (!decl_info->init_id) {
  204. CARBON_DIAGNOSTIC(
  205. ExpectedInitializerAfterLet, Error,
  206. "expected `=`; `let` declaration must have an initializer");
  207. context.emitter().Emit(TokenOnly(node_id), ExpectedInitializerAfterLet);
  208. }
  209. // Update the binding with its value and add it to the current block, after
  210. // the computation of the value.
  211. // TODO: Support other kinds of pattern here.
  212. auto bind_name = pattern.inst.As<SemIR::AnyBindName>();
  213. CARBON_CHECK(!bind_name.value_id.is_valid(),
  214. "Binding should not already have a value!");
  215. bind_name.value_id = decl_info->init_id ? *decl_info->init_id
  216. : SemIR::ErrorInst::SingletonInstId;
  217. context.ReplaceInstBeforeConstantUse(decl_info->pattern_id, bind_name);
  218. context.inst_block_stack().AddInstId(decl_info->pattern_id);
  219. HandleNameBinding(context, decl_info->pattern_id,
  220. decl_info->introducer.modifier_set.GetAccessKind());
  221. if (decl_info->init_id &&
  222. context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  223. context.global_init().Suspend();
  224. }
  225. return true;
  226. }
  227. auto HandleParseNode(Context& context, Parse::VariableDeclId node_id) -> bool {
  228. auto decl_info =
  229. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  230. Parse::NodeKind::VariableInitializer>(context, node_id);
  231. if (!decl_info) {
  232. return false;
  233. }
  234. LimitModifiersOnDecl(context, decl_info->introducer,
  235. KeywordModifierSet::Access);
  236. decl_info->pattern_id =
  237. HandleNameBinding(context, decl_info->pattern_id,
  238. decl_info->introducer.modifier_set.GetAccessKind());
  239. // If there was an initializer, assign it to the storage.
  240. if (decl_info->init_id) {
  241. if (context.GetCurrentScopeAs<SemIR::ClassDecl>()) {
  242. // TODO: In a class scope, we should instead save the initializer
  243. // somewhere so that we can use it as a default.
  244. context.TODO(node_id, "Field initializer");
  245. } else {
  246. decl_info->init_id = Initialize(context, node_id, decl_info->pattern_id,
  247. *decl_info->init_id);
  248. // TODO: Consider using different instruction kinds for assignment
  249. // versus initialization.
  250. context.AddInst<SemIR::Assign>(node_id, {.lhs_id = decl_info->pattern_id,
  251. .rhs_id = *decl_info->init_id});
  252. }
  253. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  254. context.global_init().Suspend();
  255. }
  256. }
  257. return true;
  258. }
  259. } // namespace Carbon::Check