handle_let_and_var.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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/convert.h"
  7. #include "toolchain/check/decl_introducer_state.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/handle.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/interface.h"
  12. #include "toolchain/check/keyword_modifier_set.h"
  13. #include "toolchain/check/modifiers.h"
  14. #include "toolchain/check/pattern.h"
  15. #include "toolchain/check/pattern_match.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_ids.h"
  20. #include "toolchain/parse/node_kind.h"
  21. #include "toolchain/parse/typed_nodes.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 end of the declaration region of an associated constant. This is
  30. // called at the `=` or the `;` of the declaration, whichever comes first.
  31. static auto EndAssociatedConstantDeclRegion(Context& context,
  32. SemIR::InterfaceId interface_id)
  33. -> SemIR::GenericId {
  34. // TODO: Stop special-casing tuple patterns once they behave like other
  35. // patterns.
  36. if (context.node_stack().PeekIs(Parse::NodeKind::TuplePattern)) {
  37. DiscardGenericDecl(context);
  38. return SemIR::GenericId::None;
  39. }
  40. // Peek the pattern. For a valid associated constant, the corresponding
  41. // instruction will be an `AssociatedConstantDecl` instruction.
  42. auto decl_id = context.node_stack().PeekPattern();
  43. auto assoc_const_decl =
  44. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  45. if (!assoc_const_decl) {
  46. // The pattern wasn't suitable for an associated constant. We'll detect
  47. // and diagnose this later. For now, just clean up the generic stack.
  48. DiscardGenericDecl(context);
  49. return SemIR::GenericId::None;
  50. }
  51. // Finish the declaration region of this generic.
  52. auto& assoc_const =
  53. context.associated_constants().Get(assoc_const_decl->assoc_const_id);
  54. assoc_const.generic_id = BuildGenericDecl(context, decl_id);
  55. // Build a corresponding associated entity and add it into scope. Note
  56. // that we do this outside the generic region.
  57. // TODO: The instruction is added to the associated constant's decl block.
  58. // It probably should be in the interface's body instead.
  59. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  60. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  61. context.node_stack().PeekNodeId(), assoc_const.name_id);
  62. auto access_kind = context.decl_introducer_state_stack()
  63. .innermost()
  64. .modifier_set.GetAccessKind();
  65. context.decl_name_stack().AddNameOrDiagnose(name_context, assoc_id,
  66. access_kind);
  67. return assoc_const.generic_id;
  68. }
  69. template <Lex::TokenKind::RawEnumType Kind>
  70. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  71. context.decl_introducer_state_stack().Push<Kind>();
  72. // Push a bracketing node and pattern block to establish the pattern context.
  73. context.node_stack().Push(node_id);
  74. context.pattern_block_stack().Push();
  75. context.full_pattern_stack().PushFullPattern(
  76. FullPatternStack::Kind::NameBindingDecl);
  77. BeginSubpattern(context);
  78. return true;
  79. }
  80. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  81. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  82. }
  83. auto HandleParseNode(Context& context,
  84. Parse::AssociatedConstantIntroducerId node_id) -> bool {
  85. // An associated constant is always generic.
  86. StartGenericDecl(context);
  87. // Collect the declarations nested in the associated constant in a decl
  88. // block. This is popped by FinishAssociatedConstantDecl.
  89. context.inst_block_stack().Push();
  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. auto HandleParseNode(Context& context, Parse::FieldIntroducerId node_id)
  97. -> bool {
  98. context.decl_introducer_state_stack().Push<Lex::TokenKind::Var>();
  99. context.node_stack().Push(node_id);
  100. return true;
  101. }
  102. auto HandleParseNode(Context& context, Parse::VariablePatternId node_id)
  103. -> bool {
  104. auto subpattern_id = context.node_stack().PopPattern();
  105. auto type_id = context.insts().Get(subpattern_id).type_id();
  106. if (subpattern_id == SemIR::ErrorInst::InstId) {
  107. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  108. return true;
  109. }
  110. // In a parameter list, a `var` pattern is always a single `Call` parameter,
  111. // even if it contains multiple binding patterns.
  112. switch (context.full_pattern_stack().CurrentKind()) {
  113. case FullPatternStack::Kind::ExplicitParamList:
  114. case FullPatternStack::Kind::ImplicitParamList:
  115. subpattern_id = AddPatternInst<SemIR::VarParamPattern>(
  116. context, node_id,
  117. {.type_id = type_id,
  118. .subpattern_id = subpattern_id,
  119. .index = SemIR::CallParamIndex::None});
  120. break;
  121. case FullPatternStack::Kind::NameBindingDecl:
  122. break;
  123. }
  124. auto pattern_id = AddPatternInst<SemIR::VarPattern>(
  125. context, node_id, {.type_id = type_id, .subpattern_id = subpattern_id});
  126. context.node_stack().Push(node_id, pattern_id);
  127. return true;
  128. }
  129. // Handle the end of the full-pattern of a let/var declaration (before the
  130. // start of the initializer, if any).
  131. static auto EndFullPattern(Context& context) -> void {
  132. if (context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  133. // Don't emit NameBindingDecl for an associated constant, because it will
  134. // always be empty.
  135. context.pattern_block_stack().PopAndDiscard();
  136. return;
  137. }
  138. auto pattern_block_id = context.pattern_block_stack().Pop();
  139. AddInst<SemIR::NameBindingDecl>(context, context.node_stack().PeekNodeId(),
  140. {.pattern_block_id = pattern_block_id});
  141. // Emit storage for any `var`s in the pattern now.
  142. bool returned =
  143. context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  144. KeywordModifierSet::Returned);
  145. AddPatternVarStorage(context, pattern_block_id, returned);
  146. }
  147. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  148. EndFullPattern(context);
  149. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  150. context.global_init().Resume();
  151. }
  152. context.node_stack().Push(node_id);
  153. context.full_pattern_stack().StartPatternInitializer();
  154. return true;
  155. }
  156. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  157. -> bool {
  158. return HandleInitializer(context, node_id);
  159. }
  160. auto HandleParseNode(Context& context,
  161. Parse::AssociatedConstantInitializerId node_id) -> bool {
  162. auto interface_decl =
  163. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  164. auto generic_id =
  165. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  166. // Start building the definition region of the constant.
  167. StartGenericDefinition(context, generic_id);
  168. return HandleInitializer(context, node_id);
  169. }
  170. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  171. -> bool {
  172. return HandleInitializer(context, node_id);
  173. }
  174. auto HandleParseNode(Context& context, Parse::FieldInitializerId node_id)
  175. -> bool {
  176. context.node_stack().Push(node_id);
  177. return true;
  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 (IntroducerNodeKind == Parse::NodeKind::AssociatedConstantIntroducer) {
  210. auto interface_decl =
  211. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  212. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  213. }
  214. EndFullPattern(context);
  215. }
  216. context.full_pattern_stack().PopFullPattern();
  217. decl_info.pattern_id = context.node_stack().PopPattern();
  218. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  219. // Process declaration modifiers.
  220. // TODO: For a qualified `let` or `var` declaration, this should use the
  221. // target scope of the name introduced in the declaration. See #2590.
  222. auto parent_scope_inst =
  223. context.name_scopes()
  224. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  225. .second;
  226. decl_info.introducer =
  227. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  228. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  229. return decl_info;
  230. }
  231. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  232. auto decl_info =
  233. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  234. Parse::NodeKind::LetInitializer>(context);
  235. LimitModifiersOnDecl(
  236. context, decl_info.introducer,
  237. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  238. // Diagnose interface modifiers given that we're not building an associated
  239. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  240. // specific error.
  241. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  242. std::nullopt);
  243. if (decl_info.init_id.has_value()) {
  244. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  245. } else {
  246. CARBON_DIAGNOSTIC(
  247. ExpectedInitializerAfterLet, Error,
  248. "expected `=`; `let` declaration must have an initializer");
  249. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  250. ExpectedInitializerAfterLet);
  251. }
  252. return true;
  253. }
  254. auto HandleParseNode(Context& context, Parse::AssociatedConstantDeclId node_id)
  255. -> bool {
  256. auto decl_info =
  257. HandleDecl<Lex::TokenKind::Let,
  258. Parse::NodeKind::AssociatedConstantIntroducer,
  259. Parse::NodeKind::AssociatedConstantInitializer>(context);
  260. LimitModifiersOnDecl(
  261. context, decl_info.introducer,
  262. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  263. auto interface_scope =
  264. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  265. // The `AssociatedConstantDecl` instruction and the
  266. // corresponding `AssociatedConstant` entity are built as part of handling the
  267. // binding pattern, but we still need to finish building the `Generic` object
  268. // and attach the default value, if any is specified.
  269. if (decl_info.pattern_id == SemIR::ErrorInst::InstId) {
  270. context.name_scopes()
  271. .Get(context.interfaces().Get(interface_scope->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 true;
  278. }
  279. auto decl = context.insts().GetAs<SemIR::AssociatedConstantDecl>(
  280. decl_info.pattern_id);
  281. if (decl_info.introducer.modifier_set.HasAnyOf(
  282. KeywordModifierSet::Interface)) {
  283. context.TODO(decl_info.introducer.modifier_node_id(ModifierOrder::Decl),
  284. "interface modifier");
  285. }
  286. // If there was an initializer, convert it and store it on the constant.
  287. if (decl_info.init_id.has_value()) {
  288. // TODO: Diagnose if the `default` modifier was not used.
  289. auto default_value_id =
  290. ConvertToValueOfType(context, node_id, decl_info.init_id, decl.type_id);
  291. auto& assoc_const = context.associated_constants().Get(decl.assoc_const_id);
  292. assoc_const.default_value_id = default_value_id;
  293. FinishGenericDefinition(context, assoc_const.generic_id);
  294. } else {
  295. // TODO: Either allow redeclarations of associated constants or diagnose if
  296. // the `default` modifier was used.
  297. }
  298. // Store the decl block on the declaration.
  299. decl.decl_block_id = context.inst_block_stack().Pop();
  300. ReplaceInstPreservingConstantValue(context, decl_info.pattern_id, decl);
  301. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  302. return true;
  303. }
  304. auto HandleParseNode(Context& context, Parse::VariableDeclId /*node_id*/)
  305. -> bool {
  306. auto decl_info =
  307. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  308. Parse::NodeKind::VariableInitializer>(context);
  309. LimitModifiersOnDecl(
  310. context, decl_info.introducer,
  311. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  312. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  313. return true;
  314. }
  315. auto HandleParseNode(Context& context, Parse::FieldDeclId node_id) -> bool {
  316. if (context.node_stack().PeekNextIs(Parse::NodeKind::FieldInitializer)) {
  317. // TODO: In a class scope, we should instead save the initializer
  318. // somewhere so that we can use it as a default.
  319. context.TODO(node_id, "Field initializer");
  320. context.node_stack().PopExpr();
  321. context.node_stack()
  322. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldInitializer>();
  323. }
  324. context.node_stack()
  325. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldIntroducer>();
  326. auto parent_scope_inst =
  327. context.name_scopes()
  328. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  329. .second;
  330. auto introducer =
  331. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Var>();
  332. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  333. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  334. return true;
  335. }
  336. } // namespace Carbon::Check