handle_let_and_var.cpp 16 KB

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