handle_let_and_var.cpp 15 KB

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