handle_let_and_var.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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/call.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/core_identifier.h"
  9. #include "toolchain/check/decl_introducer_state.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/member_access.h"
  15. #include "toolchain/check/modifiers.h"
  16. #include "toolchain/check/name_lookup.h"
  17. #include "toolchain/check/pattern.h"
  18. #include "toolchain/check/pattern_match.h"
  19. #include "toolchain/diagnostics/emitter.h"
  20. #include "toolchain/diagnostics/format_providers.h"
  21. #include "toolchain/lex/token_kind.h"
  22. #include "toolchain/parse/node_ids.h"
  23. #include "toolchain/parse/node_kind.h"
  24. #include "toolchain/parse/typed_nodes.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/name_scope.h"
  28. #include "toolchain/sem_ir/pattern.h"
  29. #include "toolchain/sem_ir/type.h"
  30. #include "toolchain/sem_ir/typed_insts.h"
  31. namespace Carbon::Check {
  32. // Handles the end of the declaration region of an associated constant. This is
  33. // called at the `=` or the `;` of the declaration, whichever comes first.
  34. static auto EndAssociatedConstantDeclRegion(Context& context,
  35. SemIR::InterfaceId interface_id)
  36. -> void {
  37. // Peek the pattern. For a valid associated constant, the corresponding
  38. // instruction will be an `AssociatedConstantDecl` instruction.
  39. auto decl_id = context.node_stack().PeekPattern();
  40. auto assoc_const_decl =
  41. context.insts().GetAs<SemIR::AssociatedConstantDecl>(decl_id);
  42. auto& assoc_const =
  43. context.associated_constants().Get(assoc_const_decl.assoc_const_id);
  44. // Build a corresponding associated entity and add it into scope.
  45. //
  46. // TODO: The instruction is added to the associated constant's decl block.
  47. // It probably should be in the interface-with-self body instead.
  48. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  49. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  50. context.node_stack().PeekNodeId(), assoc_const.name_id);
  51. auto access_kind = context.decl_introducer_state_stack()
  52. .innermost()
  53. .modifier_set.GetAccessKind();
  54. context.decl_name_stack().AddNameOrDiagnose(name_context, assoc_id,
  55. access_kind);
  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().PushNameBindingDecl();
  64. BeginSubpattern(context);
  65. return true;
  66. }
  67. auto HandleParseNode(Context& context, Parse::LetIntroducerId node_id) -> bool {
  68. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  69. }
  70. auto HandleParseNode(Context& context,
  71. Parse::AssociatedConstantIntroducerId node_id) -> bool {
  72. // Collect the declarations nested in the associated constant in a decl
  73. // block. This is popped by FinishAssociatedConstantDecl.
  74. context.inst_block_stack().Push();
  75. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  76. }
  77. auto HandleParseNode(Context& context, Parse::VariableIntroducerId node_id)
  78. -> bool {
  79. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  80. }
  81. auto HandleParseNode(Context& context, Parse::FieldIntroducerId node_id)
  82. -> bool {
  83. context.decl_introducer_state_stack().Push<Lex::TokenKind::Var>();
  84. context.node_stack().Push(node_id);
  85. return true;
  86. }
  87. auto HandleParseNode(Context& context, Parse::VariablePatternId node_id)
  88. -> bool {
  89. auto subpattern_id = context.node_stack().PopPattern();
  90. auto type_id = context.insts().Get(subpattern_id).type_id();
  91. if (subpattern_id == SemIR::ErrorInst::InstId) {
  92. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  93. return true;
  94. }
  95. auto pattern_id = SemIR::InstId::None;
  96. // In a parameter list, a `var` pattern is always a single `Call` parameter,
  97. // even if it contains multiple binding patterns.
  98. switch (context.full_pattern_stack().CurrentKind()) {
  99. case FullPatternStack::Kind::ExplicitParamList:
  100. case FullPatternStack::Kind::ImplicitParamList:
  101. pattern_id = AddInst<SemIR::VarParamPattern>(
  102. context, node_id,
  103. {.type_id = type_id, .subpattern_id = subpattern_id});
  104. break;
  105. case FullPatternStack::Kind::NameBindingDecl:
  106. pattern_id = AddInst<SemIR::VarPattern>(
  107. context, node_id,
  108. {.type_id = type_id, .subpattern_id = subpattern_id});
  109. break;
  110. case FullPatternStack::Kind::NotInEitherParamList:
  111. CARBON_FATAL("Unreachable");
  112. }
  113. context.node_stack().Push(node_id, pattern_id);
  114. return true;
  115. }
  116. // Handle the end of the full-pattern of a let/var declaration (before the
  117. // start of the initializer, if any).
  118. static auto EndFullPattern(Context& context) -> void {
  119. EndSubpattern(context, context.node_stack());
  120. auto scope_id = context.scope_stack().PeekNameScopeId();
  121. if (scope_id.has_value() &&
  122. context.name_scopes().Get(scope_id).is_interface_definition()) {
  123. // Don't emit NameBindingDecl for an associated constant, because it will
  124. // always be empty.
  125. context.pattern_block_stack().PopAndDiscard();
  126. return;
  127. }
  128. auto pattern_block_id = context.pattern_block_stack().Pop();
  129. AddInst<SemIR::NameBindingDecl>(context, context.node_stack().PeekNodeId(),
  130. {.pattern_block_id = pattern_block_id});
  131. // Emit storage for any `var`s in the pattern now.
  132. bool returned =
  133. context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  134. KeywordModifierSet::Returned);
  135. AddPatternVarStorage(context, pattern_block_id, returned);
  136. }
  137. static auto StartPatternInitializer(Context& context) -> bool {
  138. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  139. context.global_init().Resume();
  140. }
  141. context.full_pattern_stack().StartPatternInitializer();
  142. return true;
  143. }
  144. static auto EndPatternInitializer(Context& context) -> void {
  145. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  146. context.global_init().Suspend();
  147. }
  148. context.full_pattern_stack().EndPatternInitializer();
  149. }
  150. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  151. EndFullPattern(context);
  152. context.node_stack().Push(node_id);
  153. StartPatternInitializer(context);
  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. EndFullPattern(context);
  163. auto interface_decl =
  164. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  165. EndAssociatedConstantDeclRegion(context, interface_decl.interface_id);
  166. context.node_stack().Push(node_id);
  167. StartPatternInitializer(context);
  168. return true;
  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. // Make a default initialization expression for a `var` declaration.
  180. static auto MakeDefaultInit(Context& context, SemIR::LocId loc_id,
  181. SemIR::InstId pattern_id) -> SemIR::InstId {
  182. loc_id = context.insts().GetLocIdForDesugaring(loc_id);
  183. // Extract the matched type from the pattern.
  184. //
  185. // TODO: Diagnose if the pattern doesn't have a type, for example `var 123;`
  186. // or `var a: auto;`.
  187. auto pattern_type_id = context.insts().Get(pattern_id).type_id();
  188. auto type_inst_id = context.types().GetTypeInstId(
  189. SemIR::ExtractScrutineeType(context.sem_ir(), pattern_type_id));
  190. if (type_inst_id == SemIR::ErrorInst::InstId) {
  191. return SemIR::ErrorInst::InstId;
  192. }
  193. // Form `Type as Core.DefaultOrUnformed`.
  194. auto interface_id =
  195. LookupNameInCore(context, loc_id, CoreIdentifier::DefaultOrUnformed);
  196. auto interface_type = ExprAsType(context, loc_id, interface_id);
  197. auto facet_id = ConvertToValueOfType(context, loc_id, type_inst_id,
  198. interface_type.type_id);
  199. // Form a call to `facet.Op()`.
  200. auto op_name_id = context.core_identifiers().AddNameId(CoreIdentifier::Op);
  201. auto op_id = PerformMemberAccess(context, loc_id, facet_id, op_name_id);
  202. return PerformCall(context, loc_id, op_id, {});
  203. }
  204. namespace {
  205. // State from HandleDecl, returned for type-specific handling.
  206. struct DeclInfo {
  207. // The optional initializer.
  208. SemIR::InstId init_id = SemIR::InstId::None;
  209. // The pattern. For an associated constant, this is the associated constant
  210. // declaration.
  211. SemIR::InstId pattern_id = SemIR::InstId::None;
  212. DeclIntroducerState introducer = DeclIntroducerState();
  213. };
  214. } // namespace
  215. // Handles common logic for `let` and `var` declarations.
  216. // TODO: There's still a lot of divergence here, including logic in
  217. // handle_binding_pattern. These should really be better unified.
  218. template <const Lex::TokenKind& IntroducerTokenKind,
  219. const Parse::NodeKind& IntroducerNodeKind,
  220. const Parse::NodeKind& InitializerNodeKind>
  221. static auto HandleDecl(Context& context, Parse::NodeId node_id) -> DeclInfo {
  222. DeclInfo decl_info = DeclInfo();
  223. // Handle the optional initializer.
  224. if (context.node_stack().PeekNextIs(InitializerNodeKind)) {
  225. decl_info.init_id = context.node_stack().PopExpr();
  226. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  227. EndPatternInitializer(context);
  228. } else {
  229. EndFullPattern(context);
  230. // For an associated constant declaration, handle the completed declaration
  231. // now. We will have done this at the `=` if there was an initializer.
  232. if constexpr (IntroducerNodeKind ==
  233. Parse::NodeKind::AssociatedConstantIntroducer) {
  234. auto interface_decl =
  235. context.scope_stack()
  236. .GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  237. EndAssociatedConstantDeclRegion(context, interface_decl.interface_id);
  238. }
  239. // A variable declaration without an explicit initializer is initialized by
  240. // calling `(T as Core.DefaultOrUnformed).Op()`.
  241. if constexpr (IntroducerNodeKind == Parse::NodeKind::VariableIntroducer) {
  242. StartPatternInitializer(context);
  243. decl_info.init_id =
  244. MakeDefaultInit(context, node_id, context.node_stack().PeekPattern());
  245. EndPatternInitializer(context);
  246. }
  247. }
  248. context.full_pattern_stack().PopFullPattern();
  249. decl_info.pattern_id = context.node_stack().PopPattern();
  250. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  251. // Process declaration modifiers.
  252. // TODO: For a qualified `let` or `var` declaration, this should use the
  253. // target scope of the name introduced in the declaration. See #2590.
  254. auto parent_scope_inst =
  255. context.name_scopes()
  256. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  257. .second;
  258. decl_info.introducer =
  259. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  260. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  261. return decl_info;
  262. }
  263. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  264. auto decl_info =
  265. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  266. Parse::NodeKind::LetInitializer>(context, node_id);
  267. LimitModifiersOnDecl(
  268. context, decl_info.introducer,
  269. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  270. // Diagnose interface modifiers given that we're not building an associated
  271. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  272. // specific error.
  273. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  274. SemIR::NameScopeId::None);
  275. if (decl_info.init_id.has_value()) {
  276. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  277. } else {
  278. CARBON_DIAGNOSTIC(
  279. ExpectedInitializerAfterLet, Error,
  280. "expected `=`; `let` declaration must have an initializer");
  281. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  282. ExpectedInitializerAfterLet);
  283. }
  284. return true;
  285. }
  286. auto HandleParseNode(Context& context, Parse::AssociatedConstantDeclId node_id)
  287. -> bool {
  288. auto decl_info = HandleDecl<Lex::TokenKind::Let,
  289. Parse::NodeKind::AssociatedConstantIntroducer,
  290. Parse::NodeKind::AssociatedConstantInitializer>(
  291. context, node_id);
  292. LimitModifiersOnDecl(
  293. context, decl_info.introducer,
  294. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  295. auto interface_scope =
  296. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  297. // The `AssociatedConstantDecl` instruction and the corresponding
  298. // `AssociatedConstant` entity are built as part of handling the binding
  299. // pattern, but we still need to attach the default value, if any is
  300. // specified.
  301. if (decl_info.pattern_id == SemIR::ErrorInst::InstId) {
  302. const auto& interface =
  303. context.interfaces().Get(interface_scope.interface_id);
  304. context.name_scopes().Get(interface.scope_with_self_id).set_has_error();
  305. context.inst_block_stack().Pop();
  306. return true;
  307. }
  308. auto decl = context.insts().GetAs<SemIR::AssociatedConstantDecl>(
  309. decl_info.pattern_id);
  310. if (decl_info.introducer.modifier_set.HasAnyOf(
  311. KeywordModifierSet::Interface)) {
  312. context.TODO(decl_info.introducer.modifier_node_id(ModifierOrder::Decl),
  313. "interface modifier");
  314. }
  315. // If there was an initializer, convert it and store it on the constant.
  316. if (decl_info.init_id.has_value()) {
  317. // TODO: Diagnose if the `default` modifier was not used.
  318. auto default_value_id =
  319. ConvertToValueOfType(context, node_id, decl_info.init_id, decl.type_id);
  320. auto& assoc_const = context.associated_constants().Get(decl.assoc_const_id);
  321. assoc_const.default_value_id = default_value_id;
  322. } else {
  323. // TODO: Either allow redeclarations of associated constants or diagnose if
  324. // the `default` modifier was used.
  325. }
  326. // Store the decl block on the declaration.
  327. decl.decl_block_id = context.inst_block_stack().Pop();
  328. ReplaceInstPreservingConstantValue(context, decl_info.pattern_id, decl);
  329. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  330. return true;
  331. }
  332. auto HandleParseNode(Context& context, Parse::VariableDeclId node_id) -> bool {
  333. auto decl_info =
  334. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  335. Parse::NodeKind::VariableInitializer>(context, node_id);
  336. LimitModifiersOnDecl(
  337. context, decl_info.introducer,
  338. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  339. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  340. return true;
  341. }
  342. auto HandleParseNode(Context& context, Parse::FieldDeclId node_id) -> bool {
  343. if (context.node_stack().PeekNextIs(Parse::NodeKind::FieldInitializer)) {
  344. // TODO: In a class scope, we should instead save the initializer
  345. // somewhere so that we can use it as a default.
  346. context.TODO(node_id, "Field initializer");
  347. context.node_stack().PopExpr();
  348. context.node_stack()
  349. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldInitializer>();
  350. }
  351. context.node_stack()
  352. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldIntroducer>();
  353. auto parent_scope_inst =
  354. context.name_scopes()
  355. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  356. .second;
  357. auto introducer =
  358. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Var>();
  359. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  360. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  361. return true;
  362. }
  363. } // namespace Carbon::Check