handle_impl.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/decl_name_stack.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/handle.h"
  12. #include "toolchain/check/impl.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/modifiers.h"
  15. #include "toolchain/check/name_lookup.h"
  16. #include "toolchain/check/name_scope.h"
  17. #include "toolchain/check/pattern_match.h"
  18. #include "toolchain/check/type.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/parse/node_ids.h"
  21. #include "toolchain/parse/typed_nodes.h"
  22. #include "toolchain/sem_ir/generic.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/specific_interface.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. // Returns the implicit `Self` type for an `impl` when it's in a `class`
  28. // declaration.
  29. //
  30. // TODO: Mixin scopes also have a default `Self` type.
  31. static auto GetImplDefaultSelfType(Context& context,
  32. const ClassScope& class_scope)
  33. -> SemIR::TypeId {
  34. return context.classes().Get(class_scope.class_decl.class_id).self_type_id;
  35. }
  36. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  37. -> bool {
  38. // This might be a generic impl.
  39. StartGenericDecl(context);
  40. // Create an instruction block to hold the instructions created for the type
  41. // and interface.
  42. context.inst_block_stack().Push();
  43. // Push the bracketing node.
  44. context.node_stack().Push(node_id);
  45. // Optional modifiers follow.
  46. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  47. // An impl doesn't have a name per se, but it makes the processing more
  48. // consistent to imagine that it does. This also gives us a scope for implicit
  49. // parameters.
  50. context.decl_name_stack().PushScopeAndStartName();
  51. return true;
  52. }
  53. auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
  54. // Push a pattern block for the signature of the `forall`.
  55. context.pattern_block_stack().Push();
  56. context.full_pattern_stack().PushParameterizedDecl();
  57. return true;
  58. }
  59. auto HandleParseNode(Context& context, Parse::ImplTypeAsId node_id) -> bool {
  60. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  61. auto self_type = ExprAsType(context, self_node, self_id);
  62. const auto& introducer = context.decl_introducer_state_stack().innermost();
  63. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  64. // TODO: Also handle the parent scope being a mixin.
  65. if (auto class_scope = TryAsClassScope(
  66. context, context.decl_name_stack().PeekParentScopeId())) {
  67. // If we're not inside a class at all, that will be diagnosed against the
  68. // `extend` elsewhere.
  69. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  70. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  71. "cannot `extend` an `impl` with an explicit self type");
  72. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  73. if (self_type.type_id == GetImplDefaultSelfType(context, *class_scope)) {
  74. // If the explicit self type is the default, suggest removing it with a
  75. // diagnostic, but continue as if no error occurred since the self-type
  76. // is semantically valid.
  77. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  78. "remove the explicit `Self` type here");
  79. diag.Note(self_node, ExtendImplSelfAsDefault);
  80. if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  81. diag.Emit();
  82. }
  83. } else if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  84. // Otherwise, the self-type is an error.
  85. diag.Emit();
  86. self_type.inst_id = SemIR::ErrorInst::TypeInstId;
  87. }
  88. }
  89. }
  90. // Introduce `Self`. Note that we add this name lexically rather than adding
  91. // to the `NameScopeId` of the `impl`, because this happens before we enter
  92. // the `impl` scope or even identify which `impl` we're declaring.
  93. // TODO: Revisit this once #3714 is resolved.
  94. AddNameToLookup(context, SemIR::NameId::SelfType, self_type.inst_id);
  95. context.node_stack().Push(node_id, self_type.inst_id);
  96. return true;
  97. }
  98. auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
  99. -> bool {
  100. auto self_inst_id = SemIR::TypeInstId::None;
  101. if (auto class_scope = TryAsClassScope(
  102. context, context.decl_name_stack().PeekParentScopeId())) {
  103. auto self_type_id = GetImplDefaultSelfType(context, *class_scope);
  104. // Build the implicit access to the enclosing `Self`.
  105. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  106. // expression. We've already done the work to check that the enclosing
  107. // context is a class and found its `Self`, so additionally performing an
  108. // unqualified name lookup would be redundant work, but would avoid
  109. // duplicating the handling of the `Self` expression.
  110. self_inst_id = AddTypeInst(
  111. context, node_id,
  112. SemIR::NameRef{
  113. .type_id = SemIR::TypeType::TypeId,
  114. .name_id = SemIR::NameId::SelfType,
  115. .value_id = context.types().GetTypeInstId(self_type_id)});
  116. } else {
  117. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  118. "`impl as` can only be used in a class");
  119. context.emitter().Emit(node_id, ImplAsOutsideClass);
  120. self_inst_id = SemIR::ErrorInst::TypeInstId;
  121. }
  122. // There's no need to push `Self` into scope here, because we can find it in
  123. // the parent class scope.
  124. context.node_stack().Push(node_id, self_inst_id);
  125. return true;
  126. }
  127. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  128. // associated name that describes them.
  129. static auto PopImplIntroducerAndParamsAsNameComponent(
  130. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  131. -> NameComponent {
  132. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  133. context.node_stack()
  134. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  135. if (implicit_param_patterns_id) {
  136. context.node_stack()
  137. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  138. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  139. // because `impl`s are never actually called at runtime.
  140. auto match_results =
  141. CalleePatternMatch(context, *implicit_param_patterns_id,
  142. SemIR::InstBlockId::None, SemIR::InstId::None);
  143. CARBON_CHECK(match_results.call_params_id == SemIR::InstBlockId::Empty);
  144. CARBON_CHECK(match_results.call_param_patterns_id ==
  145. SemIR::InstBlockId::Empty);
  146. }
  147. Parse::NodeId first_param_node_id =
  148. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  149. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  150. // declaration when performing syntactic match.
  151. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  152. --last_param_iter;
  153. auto pattern_block_id = SemIR::InstBlockId::None;
  154. if (implicit_param_patterns_id) {
  155. pattern_block_id = context.pattern_block_stack().Pop();
  156. context.full_pattern_stack().PopFullPattern();
  157. }
  158. return {.name_loc_id = Parse::NodeId::None,
  159. .name_id = SemIR::NameId::None,
  160. .first_param_node_id = first_param_node_id,
  161. .last_param_node_id = *last_param_iter,
  162. .implicit_params_loc_id = implicit_params_loc_id,
  163. .implicit_param_patterns_id =
  164. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  165. .params_loc_id = Parse::NodeId::None,
  166. .param_patterns_id = SemIR::InstBlockId::None,
  167. .call_param_patterns_id = SemIR::InstBlockId::None,
  168. .call_params_id = SemIR::InstBlockId::None,
  169. .param_ranges = SemIR::Function::CallParamIndexRanges::Empty,
  170. .pattern_block_id = pattern_block_id};
  171. }
  172. // Build an ImplDecl describing the signature of an impl. This handles the
  173. // common logic shared by impl forward declarations and impl definitions.
  174. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id)
  175. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  176. auto [constraint_node, constraint_id] =
  177. context.node_stack().PopExprWithNodeId();
  178. auto [self_type_node, self_type_inst_id] =
  179. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  180. // Pop the `impl` introducer and any `forall` parameters as a "name".
  181. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  182. auto decl_block_id = context.inst_block_stack().Pop();
  183. // Convert the constraint expression to a type.
  184. auto [constraint_type_inst_id, constraint_type_id] =
  185. ExprAsType(context, constraint_node, constraint_id);
  186. // Process modifiers.
  187. // TODO: Should we somehow permit access specifiers on `impl`s?
  188. auto introducer =
  189. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  190. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  191. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  192. // Finish processing the name, which should be empty, but might have
  193. // parameters.
  194. auto name_context = context.decl_name_stack().FinishImplName();
  195. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  196. // TODO: Check for an orphan `impl`.
  197. // Add the impl declaration.
  198. auto impl_decl_id =
  199. AddPlaceholderInst(context, node_id,
  200. SemIR::ImplDecl{.impl_id = SemIR::ImplId::None,
  201. .decl_block_id = decl_block_id});
  202. // This requires that the facet type is identified. It returns None if an
  203. // error was diagnosed.
  204. auto specific_interface = CheckConstraintIsInterface(
  205. context, impl_decl_id, self_type_inst_id, constraint_type_inst_id);
  206. auto impl_id = SemIR::ImplId::None;
  207. {
  208. SemIR::Impl impl = {name_context.MakeEntityWithParamsBase(
  209. name, impl_decl_id,
  210. /*is_extern=*/false, SemIR::LibraryNameId::None),
  211. {.self_id = self_type_inst_id,
  212. .constraint_id = constraint_type_inst_id,
  213. .interface = specific_interface,
  214. .is_final = is_final}};
  215. // There's a bunch of places that may represent a diagnostic that occurred
  216. // in checking the impl up to this point, which we consolidate into this
  217. // bool. Due to lack of an instruction to set to `ErrorInst`, an
  218. // `InterfaceId::None` indicates that the interface could not be identified
  219. // and an error was diagnosed.
  220. bool impl_had_error =
  221. context.types().GetTypeIdForTypeInstId(impl.self_id) ==
  222. SemIR::ErrorInst::TypeId ||
  223. context.types().GetTypeIdForTypeInstId(impl.constraint_id) ==
  224. SemIR::ErrorInst::TypeId ||
  225. !impl.interface.interface_id.has_value();
  226. CARBON_KIND_SWITCH(FindImplId(context, impl)) {
  227. case CARBON_KIND(RedeclaredImpl redeclared_impl): {
  228. // This is a redeclaration of another impl, now held in `impl_id`.
  229. impl_id = redeclared_impl.prev_impl_id;
  230. // Note that we don't reconstruct the witness for a redeclaration, which
  231. // was the instruction that came last in the first declaration's eval
  232. // block. And FinishGenericRedecl allows the redecl to have fewer
  233. // instructions to support this case.
  234. const auto& prev_impl = context.impls().Get(impl_id);
  235. FinishGenericRedecl(context, prev_impl.generic_id);
  236. break;
  237. }
  238. case CARBON_KIND(NewImpl new_impl): {
  239. // This is a new declaration (possibly with an attached definition).
  240. // Create a new `impl_id`, filling the missing generic and witness in
  241. // `Impl` structure.
  242. impl_had_error |= new_impl.find_had_error;
  243. impl.generic_id = BuildGeneric(context, impl_decl_id);
  244. if (impl_had_error) {
  245. // If there's any error in the construction of the impl, then the
  246. // witness can't be constructed. We set it to `ErrorInst` to make the
  247. // impl unusable for impl lookup.
  248. impl.witness_id = SemIR::ErrorInst::InstId;
  249. } else {
  250. context.inst_block_stack().Push();
  251. // This makes either a placeholder witness table or a full witness
  252. // table. The full witness table is deferred to the impl definition
  253. // unless the declaration uses rewrite constraints to set values of
  254. // associated constants in the interface.
  255. //
  256. // The witness instruction contains the SelfSpecific that is
  257. // constructed by BuildGeneric(), but the witness and its rewrites
  258. // also must be part of the generic eval block by coming before
  259. // FinishGenericDecl().
  260. impl.witness_id = AddImplWitnessForDeclaration(
  261. context, node_id, impl,
  262. context.generics().GetSelfSpecific(impl.generic_id));
  263. impl.witness_block_id = context.inst_block_stack().Pop();
  264. }
  265. FinishGenericDecl(context, node_id, impl.generic_id);
  266. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  267. impl_id = AddImpl(context, impl, new_impl.lookup_bucket, extend_node,
  268. name.implicit_params_loc_id);
  269. }
  270. }
  271. }
  272. // `FindImplId` returned an existing ImplId, or we added a new id with
  273. // `AddImpl` above. Write that ImplId into the ImplDecl instruction and finish
  274. // it.
  275. auto impl_decl = context.insts().GetAs<SemIR::ImplDecl>(impl_decl_id);
  276. impl_decl.impl_id = impl_id;
  277. ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
  278. return {impl_id, impl_decl_id};
  279. }
  280. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  281. auto [impl_id, impl_decl_id] = BuildImplDecl(context, node_id);
  282. auto& impl = context.impls().Get(impl_id);
  283. context.decl_name_stack().PopScope();
  284. // Impl definitions are required in the same file as the declaration. We skip
  285. // this requirement if we've already issued an invalid redeclaration error, or
  286. // there is an error that would prevent the impl from being legal to define.
  287. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  288. context.definitions_required_by_decl().push_back(impl_decl_id);
  289. }
  290. return true;
  291. }
  292. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  293. -> bool {
  294. auto [impl_id, impl_decl_id] = BuildImplDecl(context, node_id);
  295. auto& impl = context.impls().Get(impl_id);
  296. CheckRequireDeclsSatisfied(context, node_id, impl);
  297. CARBON_CHECK(!impl.has_definition_started());
  298. impl.definition_id = impl_decl_id;
  299. impl.scope_id =
  300. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  301. context.decl_name_stack().PeekParentScopeId());
  302. context.scope_stack().PushForEntity(
  303. impl_decl_id, impl.scope_id,
  304. context.generics().GetSelfSpecific(impl.generic_id));
  305. StartGenericDefinition(context, impl.generic_id);
  306. ImplWitnessStartDefinition(context, impl);
  307. context.inst_block_stack().Push();
  308. context.node_stack().Push(node_id, impl_id);
  309. // TODO: Handle the case where there's control flow in the impl body. For
  310. // example:
  311. //
  312. // impl C as I {
  313. // fn F() -> if true then i32 else f64;
  314. // }
  315. //
  316. // We may need to track a list of instruction blocks here, as we do for a
  317. // function.
  318. impl.body_block_id = context.inst_block_stack().PeekOrAdd();
  319. return true;
  320. }
  321. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  322. -> bool {
  323. auto impl_id =
  324. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  325. auto& impl = context.impls().Get(impl_id);
  326. FinishImplWitness(context, impl);
  327. impl.defined = true;
  328. FinishGenericDefinition(context, impl.generic_id);
  329. context.inst_block_stack().Pop();
  330. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  331. return true;
  332. }
  333. } // namespace Carbon::Check