handle_let_and_var.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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/generic.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/interface.h"
  10. #include "toolchain/check/keyword_modifier_set.h"
  11. #include "toolchain/check/modifiers.h"
  12. #include "toolchain/check/pattern_match.h"
  13. #include "toolchain/check/return.h"
  14. #include "toolchain/diagnostics/diagnostic_emitter.h"
  15. #include "toolchain/lex/token_kind.h"
  16. #include "toolchain/parse/node_kind.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/name_scope.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. // Handles the start of a declaration of an associated constant.
  23. static auto StartAssociatedConstant(Context& context) -> void {
  24. // An associated constant is always generic.
  25. StartGenericDecl(context);
  26. // Collect the declarations nested in the associated constant in a decl
  27. // block. This is popped by FinishAssociatedConstantDecl.
  28. context.inst_block_stack().Push();
  29. }
  30. // Handles the end of the declaration region of an associated constant. This is
  31. // called at the `=` or the `;` of the declaration, whichever comes first.
  32. static auto EndAssociatedConstantDeclRegion(Context& context,
  33. SemIR::InterfaceId interface_id)
  34. -> void {
  35. // TODO: Stop special-casing tuple patterns once they behave like other
  36. // patterns.
  37. if (context.node_stack().PeekIs(Parse::NodeKind::TuplePattern)) {
  38. DiscardGenericDecl(context);
  39. return;
  40. }
  41. // Peek the pattern. For a valid associated constant, the corresponding
  42. // instruction will be an `AssociatedConstantDecl` instruction.
  43. auto decl_id = context.node_stack().PeekPattern();
  44. auto assoc_const_decl =
  45. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  46. if (!assoc_const_decl) {
  47. // The pattern wasn't suitable for an associated constant. We'll detect
  48. // and diagnose this later. For now, just clean up the generic stack.
  49. DiscardGenericDecl(context);
  50. return;
  51. }
  52. // Finish the declaration region of this generic.
  53. auto& assoc_const =
  54. context.associated_constants().Get(assoc_const_decl->assoc_const_id);
  55. assoc_const.generic_id = BuildGenericDecl(context, decl_id);
  56. // Build a corresponding associated entity and add it into scope. Note
  57. // that we do this outside the generic region.
  58. // TODO: The instruction is added to the associated constant's decl block.
  59. // It probably should be in the interface's body instead.
  60. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  61. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  62. context.node_stack().PeekNodeId(), assoc_const.name_id);
  63. auto access_kind = context.decl_introducer_state_stack()
  64. .innermost()
  65. .modifier_set.GetAccessKind();
  66. context.decl_name_stack().AddNameOrDiagnose(name_context, assoc_id,
  67. access_kind);
  68. }
  69. template <Lex::TokenKind::RawEnumType Kind>
  70. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  71. context.decl_introducer_state_stack().Push<Kind>();
  72. // Push a bracketing node and pattern block to establish the pattern context.
  73. context.node_stack().Push(node_id);
  74. context.pattern_block_stack().Push();
  75. context.full_pattern_stack().PushFullPattern(
  76. FullPatternStack::Kind::NameBindingDecl);
  77. context.BeginSubpattern();
  78. return true;
  79. }
  80. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  81. if (context.GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  82. StartAssociatedConstant(context);
  83. }
  84. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  85. }
  86. auto HandleParseNode(Context& context, Parse::VariableIntroducerId node_id)
  87. -> bool {
  88. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  89. }
  90. // Returns a VarStorage inst for the given pattern. If the pattern
  91. // is the body of a returned var, this reuses the return slot, and otherwise it
  92. // adds a new inst.
  93. static auto GetOrAddStorage(Context& context, SemIR::InstId pattern_id)
  94. -> SemIR::InstId {
  95. if (context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  96. KeywordModifierSet::Returned)) {
  97. auto& function = GetCurrentFunctionForReturn(context);
  98. auto return_info =
  99. SemIR::ReturnTypeInfo::ForFunction(context.sem_ir(), function);
  100. if (return_info.has_return_slot()) {
  101. return GetCurrentReturnSlot(context);
  102. }
  103. }
  104. auto pattern = context.insts().GetWithLocId(pattern_id);
  105. auto subpattern =
  106. context.insts().Get(pattern.inst.As<SemIR::VarPattern>().subpattern_id);
  107. // Try to populate name_id on a best-effort basis.
  108. auto name_id = SemIR::NameId::None;
  109. if (auto binding_pattern = subpattern.TryAs<SemIR::BindingPattern>()) {
  110. name_id =
  111. context.entity_names().Get(binding_pattern->entity_name_id).name_id;
  112. }
  113. return context.AddInst(SemIR::LocIdAndInst::UncheckedLoc(
  114. pattern.loc_id, SemIR::VarStorage{.type_id = pattern.inst.type_id(),
  115. .pretty_name_id = name_id}));
  116. }
  117. auto HandleParseNode(Context& context, Parse::VariablePatternId node_id)
  118. -> bool {
  119. auto subpattern_id = SemIR::InstId::None;
  120. if (context.node_stack().PeekIs(Parse::NodeKind::TuplePattern)) {
  121. context.node_stack().PopAndIgnore();
  122. CARBON_CHECK(
  123. context.node_stack().PeekIs(Parse::NodeKind::TuplePatternStart));
  124. context.node_stack().PopAndIgnore();
  125. context.inst_block_stack().PopAndDiscard();
  126. context.TODO(node_id, "tuple pattern in let/var");
  127. subpattern_id = SemIR::ErrorInst::SingletonInstId;
  128. } else {
  129. subpattern_id = context.node_stack().PopPattern();
  130. }
  131. auto type_id = context.insts().Get(subpattern_id).type_id();
  132. auto pattern_id = context.AddPatternInst<SemIR::VarPattern>(
  133. node_id, {.type_id = type_id, .subpattern_id = subpattern_id});
  134. context.node_stack().Push(node_id, pattern_id);
  135. return true;
  136. }
  137. // Handle the end of the full-pattern of a let/var declaration (before the
  138. // start of the initializer, if any).
  139. static auto EndFullPattern(Context& context) -> void {
  140. if (context.GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  141. // Don't emit NameBindingDecl for an associated constant, because it will
  142. // always be empty.
  143. context.pattern_block_stack().PopAndDiscard();
  144. return;
  145. }
  146. auto pattern_block_id = context.pattern_block_stack().Pop();
  147. context.AddInst<SemIR::NameBindingDecl>(
  148. context.node_stack().PeekNodeId(),
  149. {.pattern_block_id = pattern_block_id});
  150. // We need to emit the VarStorage insts early, because they may be output
  151. // arguments for the initializer. However, we can't emit them when we emit
  152. // the corresponding `VarPattern`s because they're part of the pattern match,
  153. // not part of the pattern.
  154. // TODO: find a way to do this without walking the whole pattern block.
  155. for (auto inst_id : context.inst_blocks().Get(pattern_block_id)) {
  156. if (context.insts().Is<SemIR::VarPattern>(inst_id)) {
  157. context.var_storage_map().Insert(inst_id,
  158. GetOrAddStorage(context, inst_id));
  159. }
  160. }
  161. }
  162. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  163. EndFullPattern(context);
  164. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  165. context.global_init().Resume();
  166. }
  167. context.node_stack().Push(node_id);
  168. context.full_pattern_stack().StartPatternInitializer();
  169. return true;
  170. }
  171. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  172. -> bool {
  173. if (auto interface_decl = context.GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  174. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  175. // Start building the definition region of the constant.
  176. StartGenericDefinition(context);
  177. }
  178. return HandleInitializer(context, node_id);
  179. }
  180. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  181. -> bool {
  182. return HandleInitializer(context, node_id);
  183. }
  184. namespace {
  185. // State from HandleDecl, returned for type-specific handling.
  186. struct DeclInfo {
  187. // The optional initializer.
  188. SemIR::InstId init_id = SemIR::InstId::None;
  189. // The pattern. For an associated constant, this is the associated constant
  190. // declaration.
  191. SemIR::InstId pattern_id = SemIR::InstId::None;
  192. DeclIntroducerState introducer = DeclIntroducerState();
  193. };
  194. } // namespace
  195. // Handles common logic for `let` and `var` declarations.
  196. // TODO: There's still a lot of divergence here, including logic in
  197. // handle_binding_pattern. These should really be better unified.
  198. template <const Lex::TokenKind& IntroducerTokenKind,
  199. const Parse::NodeKind& IntroducerNodeKind,
  200. const Parse::NodeKind& InitializerNodeKind>
  201. static auto HandleDecl(Context& context) -> DeclInfo {
  202. DeclInfo decl_info = DeclInfo();
  203. // Handle the optional initializer.
  204. if (context.node_stack().PeekNextIs(InitializerNodeKind)) {
  205. decl_info.init_id = context.node_stack().PopExpr();
  206. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  207. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  208. context.global_init().Suspend();
  209. }
  210. context.full_pattern_stack().EndPatternInitializer();
  211. } else {
  212. // For an associated constant declaration, handle the completed declaration
  213. // now. We will have done this at the `=` if there was an initializer.
  214. if (IntroducerTokenKind == Lex::TokenKind::Let) {
  215. if (auto interface_decl =
  216. context.GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  217. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  218. }
  219. }
  220. EndFullPattern(context);
  221. }
  222. context.full_pattern_stack().PopFullPattern();
  223. if (auto [tuple_pattern_node_id, tuple_inst_block_id] =
  224. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::TuplePattern>();
  225. tuple_inst_block_id) {
  226. context.TODO(tuple_pattern_node_id, "tuple pattern in let/var");
  227. // TODO: Tuple patterns don't behave like other patterns. They are
  228. // associated with an InstBlockId on the node stack rather than an InstId,
  229. // and leave behind an entry on the subpattern stack and one on the node
  230. // stack.
  231. context.EndSubpatternAsExpr(SemIR::ErrorInst::SingletonInstId);
  232. context.node_stack().PopForSoloNodeId<Parse::NodeKind::TuplePatternStart>();
  233. decl_info.pattern_id = SemIR::ErrorInst::SingletonInstId;
  234. } else {
  235. decl_info.pattern_id = context.node_stack().PopPattern();
  236. }
  237. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  238. // Process declaration modifiers.
  239. // TODO: For a qualified `let` or `var` declaration, this should use the
  240. // target scope of the name introduced in the declaration. See #2590.
  241. auto parent_scope_inst =
  242. context.name_scopes()
  243. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  244. .second;
  245. decl_info.introducer =
  246. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  247. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  248. return decl_info;
  249. }
  250. // Finishes an associated constant declaration. This is called at the `;` to
  251. // perform any final steps. The `AssociatedConstantDecl` instruction and the
  252. // corresponding `AssociatedConstant` entity are built as part of handling the
  253. // binding pattern, but we still need to finish building the `Generic` object
  254. // and attach the default value, if any is specified.
  255. static auto FinishAssociatedConstant(Context& context, Parse::LetDeclId node_id,
  256. SemIR::InterfaceId interface_id,
  257. DeclInfo& decl_info) -> void {
  258. auto decl = context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  259. decl_info.pattern_id);
  260. if (!decl) {
  261. if (decl_info.pattern_id != SemIR::ErrorInst::SingletonInstId) {
  262. CARBON_DIAGNOSTIC(ExpectedSymbolicBindingInAssociatedConstant, Error,
  263. "pattern in associated constant declaration must be a "
  264. "single `:!` binding");
  265. context.emitter().Emit(context.insts().GetLocId(decl_info.pattern_id),
  266. ExpectedSymbolicBindingInAssociatedConstant);
  267. }
  268. context.name_scopes()
  269. .Get(context.interfaces().Get(interface_id).scope_id)
  270. .set_has_error();
  271. if (decl_info.init_id.has_value()) {
  272. DiscardGenericDecl(context);
  273. }
  274. context.inst_block_stack().Pop();
  275. return;
  276. }
  277. if (decl_info.introducer.modifier_set.HasAnyOf(
  278. KeywordModifierSet::Interface)) {
  279. context.TODO(decl_info.introducer.modifier_node_id(ModifierOrder::Decl),
  280. "interface modifier");
  281. }
  282. // If there was an initializer, convert it and store it on the constant.
  283. if (decl_info.init_id.has_value()) {
  284. // TODO: Diagnose if the `default` modifier was not used.
  285. auto default_value_id = ConvertToValueOfType(
  286. context, node_id, decl_info.init_id, decl->type_id);
  287. auto& assoc_const =
  288. context.associated_constants().Get(decl->assoc_const_id);
  289. assoc_const.default_value_id = default_value_id;
  290. FinishGenericDefinition(context, assoc_const.generic_id);
  291. } else {
  292. // TODO: Either allow redeclarations of associated constants or diagnose if
  293. // the `default` modifier was used.
  294. }
  295. // Store the decl block on the declaration.
  296. decl->decl_block_id = context.inst_block_stack().Pop();
  297. context.ReplaceInstPreservingConstantValue(decl_info.pattern_id, *decl);
  298. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  299. }
  300. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  301. auto decl_info =
  302. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  303. Parse::NodeKind::LetInitializer>(context);
  304. LimitModifiersOnDecl(
  305. context, decl_info.introducer,
  306. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  307. // At interface scope, we are forming an associated constant, which has
  308. // different rules.
  309. if (auto interface_scope =
  310. context.GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  311. FinishAssociatedConstant(context, node_id, interface_scope->interface_id,
  312. decl_info);
  313. return true;
  314. }
  315. // Diagnose interface modifiers given that we're not building an associated
  316. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  317. // specific error.
  318. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  319. std::nullopt);
  320. if (decl_info.init_id.has_value()) {
  321. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  322. } else {
  323. CARBON_DIAGNOSTIC(
  324. ExpectedInitializerAfterLet, Error,
  325. "expected `=`; `let` declaration must have an initializer");
  326. context.emitter().Emit(TokenOnly(node_id), ExpectedInitializerAfterLet);
  327. }
  328. return true;
  329. }
  330. auto HandleParseNode(Context& context, Parse::VariableDeclId node_id) -> bool {
  331. auto decl_info =
  332. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  333. Parse::NodeKind::VariableInitializer>(context);
  334. LimitModifiersOnDecl(
  335. context, decl_info.introducer,
  336. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  337. if (context.GetCurrentScopeAs<SemIR::ClassDecl>()) {
  338. if (decl_info.init_id.has_value()) {
  339. // TODO: In a class scope, we should instead save the initializer
  340. // somewhere so that we can use it as a default.
  341. context.TODO(node_id, "Field initializer");
  342. }
  343. return true;
  344. }
  345. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  346. return true;
  347. }
  348. } // namespace Carbon::Check