handle_let_and_var.cpp 14 KB

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