handle_let_and_var.cpp 16 KB

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