handle_let_and_var.cpp 16 KB

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