handle_let_and_var.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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_match.h"
  16. #include "toolchain/check/return.h"
  17. #include "toolchain/check/subpattern.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. -> void {
  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;
  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;
  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. }
  76. template <Lex::TokenKind::RawEnumType Kind>
  77. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  78. context.decl_introducer_state_stack().Push<Kind>();
  79. // Push a bracketing node and pattern block to establish the pattern context.
  80. context.node_stack().Push(node_id);
  81. context.pattern_block_stack().Push();
  82. context.full_pattern_stack().PushFullPattern(
  83. FullPatternStack::Kind::NameBindingDecl);
  84. BeginSubpattern(context);
  85. return true;
  86. }
  87. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  88. if (context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  89. StartAssociatedConstant(context);
  90. }
  91. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  92. }
  93. auto HandleParseNode(Context& context, Parse::VariableIntroducerId node_id)
  94. -> bool {
  95. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  96. }
  97. auto HandleParseNode(Context& context, Parse::FieldIntroducerId node_id)
  98. -> bool {
  99. context.decl_introducer_state_stack().Push<Lex::TokenKind::Var>();
  100. context.node_stack().Push(node_id);
  101. return true;
  102. }
  103. // Returns a VarStorage inst for the given `var` pattern. If the pattern
  104. // is the body of a returned var, this reuses the return slot, and otherwise it
  105. // adds a new inst.
  106. static auto GetOrAddStorage(Context& context, SemIR::InstId var_pattern_id)
  107. -> SemIR::InstId {
  108. if (context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  109. KeywordModifierSet::Returned)) {
  110. auto& function = GetCurrentFunctionForReturn(context);
  111. auto return_info =
  112. SemIR::ReturnTypeInfo::ForFunction(context.sem_ir(), function);
  113. if (return_info.has_return_slot()) {
  114. return GetCurrentReturnSlot(context);
  115. }
  116. }
  117. auto pattern = context.insts().GetWithLocId(var_pattern_id);
  118. return AddInstWithCleanup(
  119. context, pattern.loc_id,
  120. SemIR::VarStorage{
  121. .type_id =
  122. ExtractScrutineeType(context.sem_ir(), pattern.inst.type_id()),
  123. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  124. context.sem_ir(),
  125. pattern.inst.As<SemIR::VarPattern>().subpattern_id)});
  126. }
  127. auto HandleParseNode(Context& context, Parse::VariablePatternId node_id)
  128. -> bool {
  129. auto subpattern_id = context.node_stack().PopPattern();
  130. auto type_id = context.insts().Get(subpattern_id).type_id();
  131. // In a parameter list, a `var` pattern is always a single `Call` parameter,
  132. // even if it contains multiple binding patterns.
  133. switch (context.full_pattern_stack().CurrentKind()) {
  134. case FullPatternStack::Kind::ExplicitParamList:
  135. case FullPatternStack::Kind::ImplicitParamList:
  136. subpattern_id = AddPatternInst<SemIR::RefParamPattern>(
  137. context, node_id,
  138. {.type_id = type_id,
  139. .subpattern_id = subpattern_id,
  140. .index = SemIR::CallParamIndex::None});
  141. break;
  142. case FullPatternStack::Kind::NameBindingDecl:
  143. break;
  144. }
  145. auto pattern_id = AddPatternInst<SemIR::VarPattern>(
  146. context, node_id, {.type_id = type_id, .subpattern_id = subpattern_id});
  147. context.node_stack().Push(node_id, pattern_id);
  148. return true;
  149. }
  150. // Handle the end of the full-pattern of a let/var declaration (before the
  151. // start of the initializer, if any).
  152. static auto EndFullPattern(Context& context) -> void {
  153. if (context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  154. // Don't emit NameBindingDecl for an associated constant, because it will
  155. // always be empty.
  156. context.pattern_block_stack().PopAndDiscard();
  157. return;
  158. }
  159. auto pattern_block_id = context.pattern_block_stack().Pop();
  160. AddInst<SemIR::NameBindingDecl>(context, context.node_stack().PeekNodeId(),
  161. {.pattern_block_id = pattern_block_id});
  162. // We need to emit the VarStorage insts early, because they may be output
  163. // arguments for the initializer. However, we can't emit them when we emit
  164. // the corresponding `VarPattern`s because they're part of the pattern match,
  165. // not part of the pattern.
  166. // TODO: find a way to do this without walking the whole pattern block.
  167. for (auto inst_id : context.inst_blocks().Get(pattern_block_id)) {
  168. if (context.insts().Is<SemIR::VarPattern>(inst_id)) {
  169. context.var_storage_map().Insert(inst_id,
  170. GetOrAddStorage(context, inst_id));
  171. }
  172. }
  173. }
  174. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  175. EndFullPattern(context);
  176. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  177. context.global_init().Resume();
  178. }
  179. context.node_stack().Push(node_id);
  180. context.full_pattern_stack().StartPatternInitializer();
  181. return true;
  182. }
  183. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  184. -> bool {
  185. if (auto interface_decl =
  186. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  187. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  188. // Start building the definition region of the constant.
  189. StartGenericDefinition(context);
  190. }
  191. return HandleInitializer(context, node_id);
  192. }
  193. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  194. -> bool {
  195. return HandleInitializer(context, node_id);
  196. }
  197. auto HandleParseNode(Context& context, Parse::FieldInitializerId node_id)
  198. -> bool {
  199. context.node_stack().Push(node_id);
  200. return true;
  201. }
  202. namespace {
  203. // State from HandleDecl, returned for type-specific handling.
  204. struct DeclInfo {
  205. // The optional initializer.
  206. SemIR::InstId init_id = SemIR::InstId::None;
  207. // The pattern. For an associated constant, this is the associated constant
  208. // declaration.
  209. SemIR::InstId pattern_id = SemIR::InstId::None;
  210. DeclIntroducerState introducer = DeclIntroducerState();
  211. };
  212. } // namespace
  213. // Handles common logic for `let` and `var` declarations.
  214. // TODO: There's still a lot of divergence here, including logic in
  215. // handle_binding_pattern. These should really be better unified.
  216. template <const Lex::TokenKind& IntroducerTokenKind,
  217. const Parse::NodeKind& IntroducerNodeKind,
  218. const Parse::NodeKind& InitializerNodeKind>
  219. static auto HandleDecl(Context& context) -> DeclInfo {
  220. DeclInfo decl_info = DeclInfo();
  221. // Handle the optional initializer.
  222. if (context.node_stack().PeekNextIs(InitializerNodeKind)) {
  223. decl_info.init_id = context.node_stack().PopExpr();
  224. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  225. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  226. context.global_init().Suspend();
  227. }
  228. context.full_pattern_stack().EndPatternInitializer();
  229. } else {
  230. // For an associated constant declaration, handle the completed declaration
  231. // now. We will have done this at the `=` if there was an initializer.
  232. if (IntroducerTokenKind == Lex::TokenKind::Let) {
  233. if (auto interface_decl =
  234. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  235. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  236. }
  237. }
  238. EndFullPattern(context);
  239. }
  240. context.full_pattern_stack().PopFullPattern();
  241. decl_info.pattern_id = context.node_stack().PopPattern();
  242. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  243. // Process declaration modifiers.
  244. // TODO: For a qualified `let` or `var` declaration, this should use the
  245. // target scope of the name introduced in the declaration. See #2590.
  246. auto parent_scope_inst =
  247. context.name_scopes()
  248. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  249. .second;
  250. decl_info.introducer =
  251. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  252. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  253. return decl_info;
  254. }
  255. // Finishes an associated constant declaration. This is called at the `;` to
  256. // perform any final steps. The `AssociatedConstantDecl` instruction and the
  257. // corresponding `AssociatedConstant` entity are built as part of handling the
  258. // binding pattern, but we still need to finish building the `Generic` object
  259. // and attach the default value, if any is specified.
  260. static auto FinishAssociatedConstant(Context& context, Parse::LetDeclId node_id,
  261. SemIR::InterfaceId interface_id,
  262. DeclInfo& decl_info) -> void {
  263. if (decl_info.pattern_id == SemIR::ErrorInst::InstId) {
  264. context.name_scopes()
  265. .Get(context.interfaces().Get(interface_id).scope_id)
  266. .set_has_error();
  267. if (decl_info.init_id.has_value()) {
  268. DiscardGenericDecl(context);
  269. }
  270. context.inst_block_stack().Pop();
  271. return;
  272. }
  273. auto decl = context.insts().GetAs<SemIR::AssociatedConstantDecl>(
  274. decl_info.pattern_id);
  275. if (decl_info.introducer.modifier_set.HasAnyOf(
  276. KeywordModifierSet::Interface)) {
  277. context.TODO(decl_info.introducer.modifier_node_id(ModifierOrder::Decl),
  278. "interface modifier");
  279. }
  280. // If there was an initializer, convert it and store it on the constant.
  281. if (decl_info.init_id.has_value()) {
  282. // TODO: Diagnose if the `default` modifier was not used.
  283. auto default_value_id =
  284. ConvertToValueOfType(context, node_id, decl_info.init_id, decl.type_id);
  285. auto& assoc_const = context.associated_constants().Get(decl.assoc_const_id);
  286. assoc_const.default_value_id = default_value_id;
  287. FinishGenericDefinition(context, assoc_const.generic_id);
  288. } else {
  289. // TODO: Either allow redeclarations of associated constants or diagnose if
  290. // the `default` modifier was used.
  291. }
  292. // Store the decl block on the declaration.
  293. decl.decl_block_id = context.inst_block_stack().Pop();
  294. ReplaceInstPreservingConstantValue(context, decl_info.pattern_id, decl);
  295. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  296. }
  297. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  298. auto decl_info =
  299. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  300. Parse::NodeKind::LetInitializer>(context);
  301. LimitModifiersOnDecl(
  302. context, decl_info.introducer,
  303. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  304. // At interface scope, we are forming an associated constant, which has
  305. // different rules.
  306. if (auto interface_scope =
  307. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  308. FinishAssociatedConstant(context, node_id, interface_scope->interface_id,
  309. decl_info);
  310. return true;
  311. }
  312. // Diagnose interface modifiers given that we're not building an associated
  313. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  314. // specific error.
  315. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  316. std::nullopt);
  317. if (decl_info.init_id.has_value()) {
  318. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  319. } else {
  320. CARBON_DIAGNOSTIC(
  321. ExpectedInitializerAfterLet, Error,
  322. "expected `=`; `let` declaration must have an initializer");
  323. context.emitter().Emit(SemIR::LocId(node_id).ToTokenOnly(),
  324. ExpectedInitializerAfterLet);
  325. }
  326. return true;
  327. }
  328. auto HandleParseNode(Context& context, Parse::VariableDeclId node_id) -> bool {
  329. auto decl_info =
  330. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  331. Parse::NodeKind::VariableInitializer>(context);
  332. LimitModifiersOnDecl(
  333. context, decl_info.introducer,
  334. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  335. if (context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  336. CARBON_DIAGNOSTIC(VarInInterfaceDecl, Error,
  337. "`var` declaration in interface");
  338. context.emitter().Emit(node_id, VarInInterfaceDecl);
  339. return true;
  340. }
  341. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  342. return true;
  343. }
  344. auto HandleParseNode(Context& context, Parse::FieldDeclId node_id) -> bool {
  345. if (context.node_stack().PeekNextIs(Parse::NodeKind::FieldInitializer)) {
  346. // TODO: In a class scope, we should instead save the initializer
  347. // somewhere so that we can use it as a default.
  348. context.TODO(node_id, "Field initializer");
  349. context.node_stack().PopExpr();
  350. context.node_stack()
  351. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldInitializer>();
  352. }
  353. context.node_stack()
  354. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldIntroducer>();
  355. auto parent_scope_inst =
  356. context.name_scopes()
  357. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  358. .second;
  359. auto introducer =
  360. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Var>();
  361. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  362. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  363. return true;
  364. }
  365. } // namespace Carbon::Check