handle_let_and_var.cpp 11 KB

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