handle_let_and_var.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 "toolchain/check/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/check/decl_introducer_state.h"
  7. #include "toolchain/check/handle.h"
  8. #include "toolchain/check/interface.h"
  9. #include "toolchain/check/modifiers.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/lex/token_kind.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/name_scope.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. template <Lex::TokenKind::RawEnumType Kind>
  17. static auto HandleIntroducer(Context& context, Parse::NodeId node_id) -> bool {
  18. context.decl_introducer_state_stack().Push<Kind>();
  19. // Push a bracketing node to establish the pattern context.
  20. context.node_stack().Push(node_id);
  21. return true;
  22. }
  23. auto HandleLetIntroducer(Context& context, Parse::LetIntroducerId node_id)
  24. -> bool {
  25. return HandleIntroducer<Lex::TokenKind::Let>(context, node_id);
  26. }
  27. auto HandleVariableIntroducer(Context& context,
  28. Parse::VariableIntroducerId node_id) -> bool {
  29. return HandleIntroducer<Lex::TokenKind::Var>(context, node_id);
  30. }
  31. auto HandleReturnedModifier(Context& context, Parse::ReturnedModifierId node_id)
  32. -> bool {
  33. // This is pushed to be seen by HandleBindingPattern.
  34. context.node_stack().Push(node_id);
  35. return true;
  36. }
  37. static auto HandleInitializer(Context& context, Parse::NodeId node_id) -> bool {
  38. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  39. context.global_init().Resume();
  40. }
  41. context.node_stack().Push(node_id);
  42. return true;
  43. }
  44. auto HandleLetInitializer(Context& context, Parse::LetInitializerId node_id)
  45. -> bool {
  46. return HandleInitializer(context, node_id);
  47. }
  48. auto HandleVariableInitializer(Context& context,
  49. Parse::VariableInitializerId node_id) -> bool {
  50. return HandleInitializer(context, node_id);
  51. }
  52. // Builds an associated constant declaration for a `let`.
  53. static auto BuildAssociatedConstantDecl(Context& context,
  54. Parse::LetDeclId node_id,
  55. SemIR::InstId pattern_id,
  56. SemIR::LocIdAndInst pattern,
  57. SemIR::InterfaceId interface_id,
  58. SemIR::AccessKind access_kind) -> void {
  59. auto& interface_info = context.interfaces().Get(interface_id);
  60. auto binding_pattern = pattern.inst.TryAs<SemIR::BindSymbolicName>();
  61. if (!binding_pattern) {
  62. CARBON_DIAGNOSTIC(ExpectedSymbolicBindingInAssociatedConstant, Error,
  63. "Pattern in associated constant declaration must be a "
  64. "single `:!` binding.");
  65. context.emitter().Emit(pattern.loc_id,
  66. ExpectedSymbolicBindingInAssociatedConstant);
  67. context.name_scopes().Get(interface_info.scope_id).has_error = true;
  68. return;
  69. }
  70. // Replace the tentative BindName instruction with the associated constant
  71. // declaration.
  72. auto name_id =
  73. context.bind_names().Get(binding_pattern->bind_name_id).name_id;
  74. context.ReplaceLocIdAndInstBeforeConstantUse(
  75. pattern_id,
  76. SemIR::LocIdAndInst(node_id, SemIR::AssociatedConstantDecl{
  77. binding_pattern->type_id, name_id}));
  78. auto decl_id = pattern_id;
  79. context.inst_block_stack().AddInstId(decl_id);
  80. // Add an associated entity name to the interface scope.
  81. auto assoc_id = BuildAssociatedEntity(context, interface_id, decl_id);
  82. auto name_context =
  83. context.decl_name_stack().MakeUnqualifiedName(pattern.loc_id, name_id);
  84. context.decl_name_stack().AddNameOrDiagnoseDuplicate(name_context, assoc_id,
  85. access_kind);
  86. }
  87. // Adds name bindings. Returns the resulting ID for the references.
  88. static auto HandleNameBinding(Context& context, SemIR::InstId pattern_id,
  89. SemIR::AccessKind access_kind) -> SemIR::InstId {
  90. // Extract the name binding.
  91. if (auto bind_name =
  92. context.insts().TryGetAs<SemIR::AnyBindName>(pattern_id)) {
  93. // Form a corresponding name in the current context, and bind the name to
  94. // the variable.
  95. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  96. context.insts().GetLocId(pattern_id),
  97. context.bind_names().Get(bind_name->bind_name_id).name_id);
  98. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  99. name_context, pattern_id, access_kind);
  100. return bind_name->value_id;
  101. } else if (auto field_decl =
  102. context.insts().TryGetAs<SemIR::FieldDecl>(pattern_id)) {
  103. // Introduce the field name into the class.
  104. auto name_context = context.decl_name_stack().MakeUnqualifiedName(
  105. context.insts().GetLocId(pattern_id), field_decl->name_id);
  106. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  107. name_context, pattern_id, access_kind);
  108. return pattern_id;
  109. } else {
  110. // TODO: Handle other kinds of pattern.
  111. return pattern_id;
  112. }
  113. }
  114. namespace {
  115. // State from HandleDecl, returned for type-specific handling.
  116. struct DeclInfo {
  117. // The optional initializer.
  118. std::optional<SemIR::InstId> init_id = std::nullopt;
  119. SemIR::InstId pattern_id = SemIR::InstId::Invalid;
  120. std::optional<SemIR::Inst> parent_scope_inst = std::nullopt;
  121. DeclIntroducerState introducer = DeclIntroducerState();
  122. };
  123. } // namespace
  124. // Handles common logic for `let` and `var` declarations.
  125. // TODO: There's still a lot of divergence here, including logic in
  126. // handle_binding_pattern. These should really be better unified.
  127. template <const Lex::TokenKind& IntroducerTokenKind,
  128. const Parse::NodeKind& IntroducerNodeKind,
  129. const Parse::NodeKind& InitializerNodeKind, typename NodeT>
  130. static auto HandleDecl(Context& context, NodeT node_id)
  131. -> std::optional<DeclInfo> {
  132. std::optional<DeclInfo> decl_info = DeclInfo();
  133. // Handle the optional initializer.
  134. if (context.node_stack().PeekNextIs<InitializerNodeKind>()) {
  135. decl_info->init_id = context.node_stack().PopExpr();
  136. context.node_stack().PopAndDiscardSoloNodeId<InitializerNodeKind>();
  137. }
  138. if (context.node_stack().PeekIs<Parse::NodeKind::TuplePattern>()) {
  139. if (decl_info->init_id &&
  140. context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  141. context.global_init().Suspend();
  142. }
  143. context.TODO(node_id, "tuple pattern in let/var");
  144. decl_info = std::nullopt;
  145. return decl_info;
  146. }
  147. decl_info->pattern_id = context.node_stack().PopPattern();
  148. if constexpr (IntroducerTokenKind == Lex::TokenKind::Var) {
  149. // Pop the `returned` modifier if present.
  150. context.node_stack()
  151. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::ReturnedModifier>();
  152. }
  153. context.node_stack().PopAndDiscardSoloNodeId<IntroducerNodeKind>();
  154. // Process declaration modifiers.
  155. // TODO: For a qualified `let` or `var` declaration, this should use the
  156. // target scope of the name introduced in the declaration. See #2590.
  157. decl_info->parent_scope_inst =
  158. context.name_scopes()
  159. .GetInstIfValid(context.scope_stack().PeekNameScopeId())
  160. .second;
  161. decl_info->introducer =
  162. context.decl_introducer_state_stack().Pop<IntroducerTokenKind>();
  163. CheckAccessModifiersOnDecl(context, decl_info->introducer,
  164. decl_info->parent_scope_inst);
  165. return decl_info;
  166. }
  167. auto HandleLetDecl(Context& context, Parse::LetDeclId node_id) -> bool {
  168. auto decl_info =
  169. HandleDecl<Lex::TokenKind::Let, Parse::NodeKind::LetIntroducer,
  170. Parse::NodeKind::LetInitializer>(context, node_id);
  171. if (!decl_info) {
  172. return false;
  173. }
  174. RequireDefaultFinalOnlyInInterfaces(context, decl_info->introducer,
  175. decl_info->parent_scope_inst);
  176. LimitModifiersOnDecl(
  177. context, decl_info->introducer,
  178. KeywordModifierSet::Access | KeywordModifierSet::Interface);
  179. if (decl_info->introducer.modifier_set.HasAnyOf(
  180. KeywordModifierSet::Interface)) {
  181. context.TODO(decl_info->introducer.modifier_node_id(ModifierOrder::Decl),
  182. "interface modifier");
  183. }
  184. auto pattern = context.insts().GetWithLocId(decl_info->pattern_id);
  185. if (decl_info->init_id) {
  186. // Convert the value to match the type of the pattern.
  187. decl_info->init_id = ConvertToValueOfType(
  188. context, node_id, *decl_info->init_id, pattern.inst.type_id());
  189. }
  190. auto interface_scope = context.GetCurrentScopeAs<SemIR::InterfaceDecl>();
  191. // At interface scope, we are forming an associated constant, which has
  192. // different rules.
  193. if (interface_scope) {
  194. BuildAssociatedConstantDecl(
  195. context, node_id, decl_info->pattern_id, pattern,
  196. interface_scope->interface_id,
  197. decl_info->introducer.modifier_set.GetAccessKind());
  198. return true;
  199. }
  200. if (!decl_info->init_id) {
  201. CARBON_DIAGNOSTIC(
  202. ExpectedInitializerAfterLet, Error,
  203. "Expected `=`; `let` declaration must have an initializer.");
  204. context.emitter().Emit(TokenOnly(node_id), ExpectedInitializerAfterLet);
  205. }
  206. // Update the binding with its value and add it to the current block, after
  207. // the computation of the value.
  208. // TODO: Support other kinds of pattern here.
  209. auto bind_name = pattern.inst.As<SemIR::AnyBindName>();
  210. CARBON_CHECK(!bind_name.value_id.is_valid())
  211. << "Binding should not already have a value!";
  212. bind_name.value_id =
  213. decl_info->init_id ? *decl_info->init_id : SemIR::InstId::BuiltinError;
  214. context.ReplaceInstBeforeConstantUse(decl_info->pattern_id, bind_name);
  215. context.inst_block_stack().AddInstId(decl_info->pattern_id);
  216. HandleNameBinding(context, decl_info->pattern_id,
  217. decl_info->introducer.modifier_set.GetAccessKind());
  218. if (decl_info->init_id &&
  219. context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  220. context.global_init().Suspend();
  221. }
  222. return true;
  223. }
  224. auto HandleVariableDecl(Context& context, Parse::VariableDeclId node_id)
  225. -> bool {
  226. auto decl_info =
  227. HandleDecl<Lex::TokenKind::Var, Parse::NodeKind::VariableIntroducer,
  228. Parse::NodeKind::VariableInitializer>(context, node_id);
  229. if (!decl_info) {
  230. return false;
  231. }
  232. LimitModifiersOnDecl(context, decl_info->introducer,
  233. KeywordModifierSet::Access);
  234. decl_info->pattern_id =
  235. HandleNameBinding(context, decl_info->pattern_id,
  236. decl_info->introducer.modifier_set.GetAccessKind());
  237. // If there was an initializer, assign it to the storage.
  238. if (decl_info->init_id) {
  239. if (context.GetCurrentScopeAs<SemIR::ClassDecl>()) {
  240. // TODO: In a class scope, we should instead save the initializer
  241. // somewhere so that we can use it as a default.
  242. context.TODO(node_id, "Field initializer");
  243. } else {
  244. decl_info->init_id = Initialize(context, node_id, decl_info->pattern_id,
  245. *decl_info->init_id);
  246. // TODO: Consider using different instruction kinds for assignment
  247. // versus initialization.
  248. context.AddInst<SemIR::Assign>(node_id, {.lhs_id = decl_info->pattern_id,
  249. .rhs_id = *decl_info->init_id});
  250. }
  251. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  252. context.global_init().Suspend();
  253. }
  254. }
  255. return true;
  256. }
  257. } // namespace Carbon::Check