handle_let_and_var.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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/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. // Peek the pattern. For a valid associated constant, the corresponding
  35. // instruction will be an `AssociatedConstantDecl` instruction.
  36. auto decl_id = context.node_stack().PeekPattern();
  37. auto assoc_const_decl =
  38. context.insts().GetAs<SemIR::AssociatedConstantDecl>(decl_id);
  39. // Finish the declaration region of this generic.
  40. auto& assoc_const =
  41. context.associated_constants().Get(assoc_const_decl.assoc_const_id);
  42. assoc_const.generic_id = BuildGenericDecl(context, decl_id);
  43. // Build a corresponding associated entity and add it into scope. Note
  44. // that we do this outside the generic region.
  45. // TODO: The instruction is added to the associated constant's decl block.
  46. // It probably should be in the interface's body instead.
  47. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  48. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  49. context.node_stack().PeekNodeId(), assoc_const.name_id);
  50. auto access_kind = context.decl_introducer_state_stack()
  51. .innermost()
  52. .modifier_set.GetAccessKind();
  53. context.decl_name_stack().AddNameOrDiagnose(name_context, assoc_id,
  54. access_kind);
  55. return assoc_const.generic_id;
  56. }
  57. template <Lex::TokenKind::RawEnumType Kind>
  58. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  59. context.decl_introducer_state_stack().Push<Kind>();
  60. // Push a bracketing node and pattern block to establish the pattern context.
  61. context.node_stack().Push(node_id);
  62. context.pattern_block_stack().Push();
  63. context.full_pattern_stack().PushFullPattern(
  64. FullPatternStack::Kind::NameBindingDecl);
  65. BeginSubpattern(context);
  66. return true;
  67. }
  68. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  69. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  70. }
  71. auto HandleParseNode(Context& context,
  72. Parse::AssociatedConstantIntroducerId node_id) -> bool {
  73. // An associated constant is always generic.
  74. StartGenericDecl(context);
  75. // Collect the declarations nested in the associated constant in a decl
  76. // block. This is popped by FinishAssociatedConstantDecl.
  77. context.inst_block_stack().Push();
  78. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  79. }
  80. auto HandleParseNode(Context& context, Parse::VariableIntroducerId node_id)
  81. -> bool {
  82. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  83. }
  84. auto HandleParseNode(Context& context, Parse::FieldIntroducerId node_id)
  85. -> bool {
  86. context.decl_introducer_state_stack().Push<Lex::TokenKind::Var>();
  87. context.node_stack().Push(node_id);
  88. return true;
  89. }
  90. auto HandleParseNode(Context& context, Parse::VariablePatternId node_id)
  91. -> bool {
  92. auto subpattern_id = context.node_stack().PopPattern();
  93. auto type_id = context.insts().Get(subpattern_id).type_id();
  94. if (subpattern_id == SemIR::ErrorInst::InstId) {
  95. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  96. return true;
  97. }
  98. // In a parameter list, a `var` pattern is always a single `Call` parameter,
  99. // even if it contains multiple binding patterns.
  100. switch (context.full_pattern_stack().CurrentKind()) {
  101. case FullPatternStack::Kind::ExplicitParamList:
  102. case FullPatternStack::Kind::ImplicitParamList:
  103. subpattern_id = AddPatternInst<SemIR::VarParamPattern>(
  104. context, node_id,
  105. {.type_id = type_id,
  106. .subpattern_id = subpattern_id,
  107. .index = context.full_pattern_stack().NextCallParamIndex()});
  108. break;
  109. case FullPatternStack::Kind::NameBindingDecl:
  110. break;
  111. }
  112. auto pattern_id = AddPatternInst<SemIR::VarPattern>(
  113. context, node_id, {.type_id = type_id, .subpattern_id = subpattern_id});
  114. context.node_stack().Push(node_id, pattern_id);
  115. return true;
  116. }
  117. // Handle the end of the full-pattern of a let/var declaration (before the
  118. // start of the initializer, if any).
  119. static auto EndFullPattern(Context& context) -> void {
  120. if (context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>()) {
  121. // Don't emit NameBindingDecl for an associated constant, because it will
  122. // always be empty.
  123. context.pattern_block_stack().PopAndDiscard();
  124. return;
  125. }
  126. auto pattern_block_id = context.pattern_block_stack().Pop();
  127. AddInst<SemIR::NameBindingDecl>(context, context.node_stack().PeekNodeId(),
  128. {.pattern_block_id = pattern_block_id});
  129. // Emit storage for any `var`s in the pattern now.
  130. bool returned =
  131. context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  132. KeywordModifierSet::Returned);
  133. AddPatternVarStorage(context, pattern_block_id, returned);
  134. }
  135. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  136. EndFullPattern(context);
  137. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  138. context.global_init().Resume();
  139. }
  140. context.node_stack().Push(node_id);
  141. context.full_pattern_stack().StartPatternInitializer();
  142. return true;
  143. }
  144. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  145. -> bool {
  146. return HandleInitializer(context, node_id);
  147. }
  148. auto HandleParseNode(Context& context,
  149. Parse::AssociatedConstantInitializerId node_id) -> bool {
  150. auto interface_decl =
  151. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  152. auto generic_id =
  153. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  154. // Start building the definition region of the constant.
  155. StartGenericDefinition(context, generic_id);
  156. return HandleInitializer(context, node_id);
  157. }
  158. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  159. -> bool {
  160. return HandleInitializer(context, node_id);
  161. }
  162. auto HandleParseNode(Context& context, Parse::FieldInitializerId node_id)
  163. -> bool {
  164. context.node_stack().Push(node_id);
  165. return true;
  166. }
  167. namespace {
  168. // State from HandleDecl, returned for type-specific handling.
  169. struct DeclInfo {
  170. // The optional initializer.
  171. SemIR::InstId init_id = SemIR::InstId::None;
  172. // The pattern. For an associated constant, this is the associated constant
  173. // declaration.
  174. SemIR::InstId pattern_id = SemIR::InstId::None;
  175. DeclIntroducerState introducer = DeclIntroducerState();
  176. };
  177. } // namespace
  178. // Handles common logic for `let` and `var` declarations.
  179. // TODO: There's still a lot of divergence here, including logic in
  180. // handle_binding_pattern. These should really be better unified.
  181. template <const Lex::TokenKind& IntroducerTokenKind,
  182. const Parse::NodeKind& IntroducerNodeKind,
  183. const Parse::NodeKind& InitializerNodeKind>
  184. static auto HandleDecl(Context& context) -> DeclInfo {
  185. DeclInfo decl_info = DeclInfo();
  186. // Handle the optional initializer.
  187. if (context.node_stack().PeekNextIs(InitializerNodeKind)) {
  188. decl_info.init_id = context.node_stack().PopExpr();
  189. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  190. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  191. context.global_init().Suspend();
  192. }
  193. context.full_pattern_stack().EndPatternInitializer();
  194. } else {
  195. // For an associated constant declaration, handle the completed declaration
  196. // now. We will have done this at the `=` if there was an initializer.
  197. if (IntroducerNodeKind == Parse::NodeKind::AssociatedConstantIntroducer) {
  198. auto interface_decl =
  199. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  200. EndAssociatedConstantDeclRegion(context, interface_decl->interface_id);
  201. }
  202. EndFullPattern(context);
  203. }
  204. context.full_pattern_stack().PopFullPattern();
  205. decl_info.pattern_id = context.node_stack().PopPattern();
  206. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  207. // Process declaration modifiers.
  208. // TODO: For a qualified `let` or `var` declaration, this should use the
  209. // target scope of the name introduced in the declaration. See #2590.
  210. auto parent_scope_inst =
  211. context.name_scopes()
  212. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  213. .second;
  214. decl_info.introducer =
  215. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  216. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  217. return decl_info;
  218. }
  219. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  220. auto decl_info =
  221. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  222. Parse::NodeKind::LetInitializer>(context);
  223. LimitModifiersOnDecl(
  224. context, decl_info.introducer,
  225. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  226. // Diagnose interface modifiers given that we're not building an associated
  227. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  228. // specific error.
  229. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  230. std::nullopt);
  231. if (decl_info.init_id.has_value()) {
  232. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  233. } else {
  234. CARBON_DIAGNOSTIC(
  235. ExpectedInitializerAfterLet, Error,
  236. "expected `=`; `let` declaration must have an initializer");
  237. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  238. ExpectedInitializerAfterLet);
  239. }
  240. return true;
  241. }
  242. auto HandleParseNode(Context& context, Parse::AssociatedConstantDeclId node_id)
  243. -> bool {
  244. auto decl_info =
  245. HandleDecl<Lex::TokenKind::Let,
  246. Parse::NodeKind::AssociatedConstantIntroducer,
  247. Parse::NodeKind::AssociatedConstantInitializer>(context);
  248. LimitModifiersOnDecl(
  249. context, decl_info.introducer,
  250. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  251. auto interface_scope =
  252. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  253. // The `AssociatedConstantDecl` instruction and the
  254. // corresponding `AssociatedConstant` entity are built as part of handling the
  255. // binding pattern, but we still need to finish building the `Generic` object
  256. // and attach the default value, if any is specified.
  257. if (decl_info.pattern_id == SemIR::ErrorInst::InstId) {
  258. context.name_scopes()
  259. .Get(context.interfaces().Get(interface_scope->interface_id).scope_id)
  260. .set_has_error();
  261. if (decl_info.init_id.has_value()) {
  262. DiscardGenericDecl(context);
  263. }
  264. context.inst_block_stack().Pop();
  265. return true;
  266. }
  267. auto decl = context.insts().GetAs<SemIR::AssociatedConstantDecl>(
  268. decl_info.pattern_id);
  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 =
  278. ConvertToValueOfType(context, node_id, decl_info.init_id, decl.type_id);
  279. auto& assoc_const = context.associated_constants().Get(decl.assoc_const_id);
  280. assoc_const.default_value_id = default_value_id;
  281. FinishGenericDefinition(context, assoc_const.generic_id);
  282. } else {
  283. // TODO: Either allow redeclarations of associated constants or diagnose if
  284. // the `default` modifier was used.
  285. }
  286. // Store the decl block on the declaration.
  287. decl.decl_block_id = context.inst_block_stack().Pop();
  288. ReplaceInstPreservingConstantValue(context, decl_info.pattern_id, decl);
  289. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  290. return true;
  291. }
  292. auto HandleParseNode(Context& context, Parse::VariableDeclId /*node_id*/)
  293. -> bool {
  294. auto decl_info =
  295. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  296. Parse::NodeKind::VariableInitializer>(context);
  297. LimitModifiersOnDecl(
  298. context, decl_info.introducer,
  299. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  300. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  301. return true;
  302. }
  303. auto HandleParseNode(Context& context, Parse::FieldDeclId node_id) -> bool {
  304. if (context.node_stack().PeekNextIs(Parse::NodeKind::FieldInitializer)) {
  305. // TODO: In a class scope, we should instead save the initializer
  306. // somewhere so that we can use it as a default.
  307. context.TODO(node_id, "Field initializer");
  308. context.node_stack().PopExpr();
  309. context.node_stack()
  310. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldInitializer>();
  311. }
  312. context.node_stack()
  313. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldIntroducer>();
  314. auto parent_scope_inst =
  315. context.name_scopes()
  316. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  317. .second;
  318. auto introducer =
  319. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Var>();
  320. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  321. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  322. return true;
  323. }
  324. } // namespace Carbon::Check