handle_let_and_var.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // In a parameter list, a `var` pattern is always a single `Call` parameter,
  96. // even if it contains multiple binding patterns.
  97. switch (context.full_pattern_stack().CurrentKind()) {
  98. case FullPatternStack::Kind::ExplicitParamList:
  99. case FullPatternStack::Kind::ImplicitParamList:
  100. subpattern_id = AddPatternInst<SemIR::VarParamPattern>(
  101. context, node_id,
  102. {.type_id = type_id, .subpattern_id = subpattern_id});
  103. break;
  104. case FullPatternStack::Kind::NameBindingDecl:
  105. break;
  106. case FullPatternStack::Kind::NotInEitherParamList:
  107. CARBON_FATAL("Unreachable");
  108. }
  109. auto pattern_id = AddPatternInst<SemIR::VarPattern>(
  110. context, node_id, {.type_id = type_id, .subpattern_id = subpattern_id});
  111. context.node_stack().Push(node_id, pattern_id);
  112. return true;
  113. }
  114. // Handle the end of the full-pattern of a let/var declaration (before the
  115. // start of the initializer, if any).
  116. static auto EndFullPattern(Context& context) -> void {
  117. auto scope_id = context.scope_stack().PeekNameScopeId();
  118. if (scope_id.has_value() &&
  119. context.name_scopes().Get(scope_id).is_interface_definition()) {
  120. // Don't emit NameBindingDecl for an associated constant, because it will
  121. // always be empty.
  122. context.pattern_block_stack().PopAndDiscard();
  123. return;
  124. }
  125. auto pattern_block_id = context.pattern_block_stack().Pop();
  126. AddInst<SemIR::NameBindingDecl>(context, context.node_stack().PeekNodeId(),
  127. {.pattern_block_id = pattern_block_id});
  128. // Emit storage for any `var`s in the pattern now.
  129. bool returned =
  130. context.decl_introducer_state_stack().innermost().modifier_set.HasAnyOf(
  131. KeywordModifierSet::Returned);
  132. AddPatternVarStorage(context, pattern_block_id, returned);
  133. }
  134. static auto StartPatternInitializer(Context& context) -> bool {
  135. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  136. context.global_init().Resume();
  137. }
  138. context.full_pattern_stack().StartPatternInitializer();
  139. return true;
  140. }
  141. static auto EndPatternInitializer(Context& context) -> void {
  142. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  143. context.global_init().Suspend();
  144. }
  145. context.full_pattern_stack().EndPatternInitializer();
  146. }
  147. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  148. EndFullPattern(context);
  149. context.node_stack().Push(node_id);
  150. StartPatternInitializer(context);
  151. return true;
  152. }
  153. auto HandleParseNode(Context& context, Parse::LetInitializerId node_id)
  154. -> bool {
  155. return HandleInitializer(context, node_id);
  156. }
  157. auto HandleParseNode(Context& context,
  158. Parse::AssociatedConstantInitializerId node_id) -> bool {
  159. auto interface_decl =
  160. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  161. EndAssociatedConstantDeclRegion(context, interface_decl.interface_id);
  162. return HandleInitializer(context, node_id);
  163. }
  164. auto HandleParseNode(Context& context, Parse::VariableInitializerId node_id)
  165. -> bool {
  166. return HandleInitializer(context, node_id);
  167. }
  168. auto HandleParseNode(Context& context, Parse::FieldInitializerId node_id)
  169. -> bool {
  170. context.node_stack().Push(node_id);
  171. return true;
  172. }
  173. // Make a default initialization expression for a `var` declaration.
  174. static auto MakeDefaultInit(Context& context, SemIR::LocId loc_id,
  175. SemIR::InstId pattern_id) -> SemIR::InstId {
  176. loc_id = context.insts().GetLocIdForDesugaring(loc_id);
  177. // Extract the matched type from the pattern.
  178. //
  179. // TODO: Diagnose if the pattern doesn't have a type, for example `var 123;`
  180. // or `var a: auto;`.
  181. auto pattern_type_id = context.insts().Get(pattern_id).type_id();
  182. auto type_inst_id = context.types().GetTypeInstId(
  183. SemIR::ExtractScrutineeType(context.sem_ir(), pattern_type_id));
  184. if (type_inst_id == SemIR::ErrorInst::InstId) {
  185. return SemIR::ErrorInst::InstId;
  186. }
  187. // Form `Type as Core.DefaultOrUnformed`.
  188. auto interface_id =
  189. LookupNameInCore(context, loc_id, CoreIdentifier::DefaultOrUnformed);
  190. auto interface_type = ExprAsType(context, loc_id, interface_id);
  191. auto facet_id = ConvertToValueOfType(context, loc_id, type_inst_id,
  192. interface_type.type_id);
  193. // Form a call to `facet.Op()`.
  194. auto op_name_id = context.core_identifiers().AddNameId(CoreIdentifier::Op);
  195. auto op_id = PerformMemberAccess(context, loc_id, facet_id, op_name_id);
  196. return PerformCall(context, loc_id, op_id, {});
  197. }
  198. namespace {
  199. // State from HandleDecl, returned for type-specific handling.
  200. struct DeclInfo {
  201. // The optional initializer.
  202. SemIR::InstId init_id = SemIR::InstId::None;
  203. // The pattern. For an associated constant, this is the associated constant
  204. // declaration.
  205. SemIR::InstId pattern_id = SemIR::InstId::None;
  206. DeclIntroducerState introducer = DeclIntroducerState();
  207. };
  208. } // namespace
  209. // Handles common logic for `let` and `var` declarations.
  210. // TODO: There's still a lot of divergence here, including logic in
  211. // handle_binding_pattern. These should really be better unified.
  212. template <const Lex::TokenKind& IntroducerTokenKind,
  213. const Parse::NodeKind& IntroducerNodeKind,
  214. const Parse::NodeKind& InitializerNodeKind>
  215. static auto HandleDecl(Context& context, Parse::NodeId node_id) -> DeclInfo {
  216. DeclInfo decl_info = DeclInfo();
  217. // Handle the optional initializer.
  218. if (context.node_stack().PeekNextIs(InitializerNodeKind)) {
  219. decl_info.init_id = context.node_stack().PopExpr();
  220. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  221. EndPatternInitializer(context);
  222. } else {
  223. // For an associated constant declaration, handle the completed declaration
  224. // now. We will have done this at the `=` if there was an initializer.
  225. if constexpr (IntroducerNodeKind ==
  226. Parse::NodeKind::AssociatedConstantIntroducer) {
  227. auto interface_decl =
  228. context.scope_stack()
  229. .GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  230. EndAssociatedConstantDeclRegion(context, interface_decl.interface_id);
  231. }
  232. EndFullPattern(context);
  233. // A variable declaration without an explicit initializer is initialized by
  234. // calling `(T as Core.DefaultOrUnformed).Op()`.
  235. if constexpr (IntroducerNodeKind == Parse::NodeKind::VariableIntroducer) {
  236. StartPatternInitializer(context);
  237. decl_info.init_id =
  238. MakeDefaultInit(context, node_id, context.node_stack().PeekPattern());
  239. EndPatternInitializer(context);
  240. }
  241. }
  242. context.full_pattern_stack().PopFullPattern();
  243. decl_info.pattern_id = context.node_stack().PopPattern();
  244. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  245. // Process declaration modifiers.
  246. // TODO: For a qualified `let` or `var` declaration, this should use the
  247. // target scope of the name introduced in the declaration. See #2590.
  248. auto parent_scope_inst =
  249. context.name_scopes()
  250. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  251. .second;
  252. decl_info.introducer =
  253. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  254. CheckAccessModifiersOnDecl(context, decl_info.introducer, parent_scope_inst);
  255. return decl_info;
  256. }
  257. auto HandleParseNode(Context& context, Parse::LetDeclId node_id) -> bool {
  258. auto decl_info =
  259. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  260. Parse::NodeKind::LetInitializer>(context, node_id);
  261. LimitModifiersOnDecl(
  262. context, decl_info.introducer,
  263. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  264. // Diagnose interface modifiers given that we're not building an associated
  265. // constant. We use this rather than `LimitModifiersOnDecl` to get a more
  266. // specific error.
  267. RequireDefaultFinalOnlyInInterfaces(context, decl_info.introducer,
  268. SemIR::NameScopeId::None);
  269. if (decl_info.init_id.has_value()) {
  270. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  271. } else {
  272. CARBON_DIAGNOSTIC(
  273. ExpectedInitializerAfterLet, Error,
  274. "expected `=`; `let` declaration must have an initializer");
  275. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  276. ExpectedInitializerAfterLet);
  277. }
  278. return true;
  279. }
  280. auto HandleParseNode(Context& context, Parse::AssociatedConstantDeclId node_id)
  281. -> bool {
  282. auto decl_info = HandleDecl<Lex::TokenKind::Let,
  283. Parse::NodeKind::AssociatedConstantIntroducer,
  284. Parse::NodeKind::AssociatedConstantInitializer>(
  285. context, node_id);
  286. LimitModifiersOnDecl(
  287. context, decl_info.introducer,
  288. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  289. auto interface_scope =
  290. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceWithSelfDecl>();
  291. // The `AssociatedConstantDecl` instruction and the corresponding
  292. // `AssociatedConstant` entity are built as part of handling the binding
  293. // pattern, but we still need to attach the default value, if any is
  294. // specified.
  295. if (decl_info.pattern_id == SemIR::ErrorInst::InstId) {
  296. const auto& interface =
  297. context.interfaces().Get(interface_scope.interface_id);
  298. context.name_scopes().Get(interface.scope_with_self_id).set_has_error();
  299. context.inst_block_stack().Pop();
  300. return true;
  301. }
  302. auto decl = context.insts().GetAs<SemIR::AssociatedConstantDecl>(
  303. decl_info.pattern_id);
  304. if (decl_info.introducer.modifier_set.HasAnyOf(
  305. KeywordModifierSet::Interface)) {
  306. context.TODO(decl_info.introducer.modifier_node_id(ModifierOrder::Decl),
  307. "interface modifier");
  308. }
  309. // If there was an initializer, convert it and store it on the constant.
  310. if (decl_info.init_id.has_value()) {
  311. // TODO: Diagnose if the `default` modifier was not used.
  312. auto default_value_id =
  313. ConvertToValueOfType(context, node_id, decl_info.init_id, decl.type_id);
  314. auto& assoc_const = context.associated_constants().Get(decl.assoc_const_id);
  315. assoc_const.default_value_id = default_value_id;
  316. } else {
  317. // TODO: Either allow redeclarations of associated constants or diagnose if
  318. // the `default` modifier was used.
  319. }
  320. // Store the decl block on the declaration.
  321. decl.decl_block_id = context.inst_block_stack().Pop();
  322. ReplaceInstPreservingConstantValue(context, decl_info.pattern_id, decl);
  323. context.inst_block_stack().AddInstId(decl_info.pattern_id);
  324. return true;
  325. }
  326. auto HandleParseNode(Context& context, Parse::VariableDeclId node_id) -> bool {
  327. auto decl_info =
  328. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  329. Parse::NodeKind::VariableInitializer>(context, node_id);
  330. LimitModifiersOnDecl(
  331. context, decl_info.introducer,
  332. KeywordModifierSet::Access | KeywordModifierSet::Returned);
  333. LocalPatternMatch(context, decl_info.pattern_id, decl_info.init_id);
  334. return true;
  335. }
  336. auto HandleParseNode(Context& context, Parse::FieldDeclId node_id) -> bool {
  337. if (context.node_stack().PeekNextIs(Parse::NodeKind::FieldInitializer)) {
  338. // TODO: In a class scope, we should instead save the initializer
  339. // somewhere so that we can use it as a default.
  340. context.TODO(node_id, "Field initializer");
  341. context.node_stack().PopExpr();
  342. context.node_stack()
  343. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldInitializer>();
  344. }
  345. context.node_stack()
  346. .PopAndDiscardSoloNodeId<Parse::NodeKind::FieldIntroducer>();
  347. auto parent_scope_inst =
  348. context.name_scopes()
  349. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  350. .second;
  351. auto introducer =
  352. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Var>();
  353. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  354. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  355. return true;
  356. }
  357. } // namespace Carbon::Check