handle_let_and_var.cpp 16 KB

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