handle_impl.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/decl_name_stack.h"
  9. #include "toolchain/check/deduce.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/merge.h"
  15. #include "toolchain/check/modifiers.h"
  16. #include "toolchain/check/name_lookup.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/typed_nodes.h"
  21. #include "toolchain/sem_ir/generic.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/typed_insts.h"
  24. namespace Carbon::Check {
  25. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  26. -> bool {
  27. // This might be a generic impl.
  28. StartGenericDecl(context);
  29. // Create an instruction block to hold the instructions created for the type
  30. // and interface.
  31. context.inst_block_stack().Push();
  32. // Push the bracketing node.
  33. context.node_stack().Push(node_id);
  34. // Optional modifiers follow.
  35. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  36. // An impl doesn't have a name per se, but it makes the processing more
  37. // consistent to imagine that it does. This also gives us a scope for implicit
  38. // parameters.
  39. context.decl_name_stack().PushScopeAndStartName();
  40. return true;
  41. }
  42. auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
  43. // Push a pattern block for the signature of the `forall`.
  44. context.pattern_block_stack().Push();
  45. context.full_pattern_stack().PushFullPattern(
  46. FullPatternStack::Kind::ImplicitParamList);
  47. return true;
  48. }
  49. auto HandleParseNode(Context& context, Parse::TypeImplAsId node_id) -> bool {
  50. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  51. auto self_type_inst_id = ExprAsType(context, self_node, self_id).inst_id;
  52. context.node_stack().Push(node_id, self_type_inst_id);
  53. // Introduce `Self`. Note that we add this name lexically rather than adding
  54. // to the `NameScopeId` of the `impl`, because this happens before we enter
  55. // the `impl` scope or even identify which `impl` we're declaring.
  56. // TODO: Revisit this once #3714 is resolved.
  57. AddNameToLookup(context, SemIR::NameId::SelfType, self_type_inst_id);
  58. return true;
  59. }
  60. // If the specified name scope corresponds to a class, returns the corresponding
  61. // class declaration.
  62. // TODO: Should this be somewhere more central?
  63. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  64. -> std::optional<SemIR::ClassDecl> {
  65. if (!scope_id.has_value()) {
  66. return std::nullopt;
  67. }
  68. auto& scope = context.name_scopes().Get(scope_id);
  69. if (!scope.inst_id().has_value()) {
  70. return std::nullopt;
  71. }
  72. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id());
  73. }
  74. static auto GetDefaultSelfType(Context& context) -> SemIR::TypeId {
  75. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  76. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  77. return context.classes().Get(class_decl->class_id).self_type_id;
  78. }
  79. // TODO: This is also valid in a mixin.
  80. return SemIR::TypeId::None;
  81. }
  82. auto HandleParseNode(Context& context, Parse::DefaultSelfImplAsId node_id)
  83. -> bool {
  84. auto self_inst_id = SemIR::TypeInstId::None;
  85. if (auto self_type_id = GetDefaultSelfType(context);
  86. self_type_id.has_value()) {
  87. // Build the implicit access to the enclosing `Self`.
  88. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  89. // expression. We've already done the work to check that the enclosing
  90. // context is a class and found its `Self`, so additionally performing an
  91. // unqualified name lookup would be redundant work, but would avoid
  92. // duplicating the handling of the `Self` expression.
  93. self_inst_id = AddTypeInst(
  94. context, node_id,
  95. SemIR::NameRef{.type_id = SemIR::TypeType::TypeId,
  96. .name_id = SemIR::NameId::SelfType,
  97. .value_id = context.types().GetInstId(self_type_id)});
  98. } else {
  99. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  100. "`impl as` can only be used in a class");
  101. context.emitter().Emit(node_id, ImplAsOutsideClass);
  102. self_inst_id = SemIR::ErrorInst::TypeInstId;
  103. }
  104. // There's no need to push `Self` into scope here, because we can find it in
  105. // the parent class scope.
  106. context.node_stack().Push(node_id, self_inst_id);
  107. return true;
  108. }
  109. static auto DiagnoseExtendImplOutsideClass(Context& context,
  110. Parse::AnyImplDeclId node_id)
  111. -> void {
  112. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  113. "`extend impl` can only be used in a class");
  114. context.emitter().Emit(node_id, ExtendImplOutsideClass);
  115. }
  116. // Process an `extend impl` declaration by extending the impl scope with the
  117. // `impl`'s scope.
  118. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  119. Parse::AnyImplDeclId node_id, SemIR::ImplId impl_id,
  120. Parse::NodeId self_type_node, SemIR::TypeId self_type_id,
  121. Parse::NodeId params_node,
  122. SemIR::TypeInstId constraint_type_inst_id,
  123. SemIR::TypeId constraint_type_id) -> bool {
  124. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  125. if (!parent_scope_id.has_value()) {
  126. DiagnoseExtendImplOutsideClass(context, node_id);
  127. return false;
  128. }
  129. // TODO: This is also valid in a mixin.
  130. if (!TryAsClassScope(context, parent_scope_id)) {
  131. DiagnoseExtendImplOutsideClass(context, node_id);
  132. return false;
  133. }
  134. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  135. if (params_node.has_value()) {
  136. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  137. "cannot `extend` a parameterized `impl`");
  138. context.emitter().Emit(extend_node, ExtendImplForall);
  139. parent_scope.set_has_error();
  140. return false;
  141. }
  142. if (context.parse_tree().node_kind(self_type_node) ==
  143. Parse::NodeKind::TypeImplAs) {
  144. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  145. "cannot `extend` an `impl` with an explicit self type");
  146. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  147. // If the explicit self type is not the default, just bail out.
  148. if (self_type_id != GetDefaultSelfType(context)) {
  149. diag.Emit();
  150. parent_scope.set_has_error();
  151. return false;
  152. }
  153. // The explicit self type is the same as the default self type, so suggest
  154. // removing it and recover as if it were not present.
  155. if (auto self_as =
  156. context.parse_tree_and_subtrees().ExtractAs<Parse::TypeImplAs>(
  157. self_type_node)) {
  158. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  159. "remove the explicit `Self` type here");
  160. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  161. }
  162. diag.Emit();
  163. }
  164. const auto& impl = context.impls().Get(impl_id);
  165. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  166. parent_scope.set_has_error();
  167. } else {
  168. bool is_complete = RequireCompleteType(
  169. context, constraint_type_id, SemIR::LocId(constraint_type_inst_id),
  170. [&] {
  171. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  172. "`extend impl as` incomplete facet type {0}",
  173. InstIdAsType);
  174. return context.emitter().Build(impl.latest_decl_id(),
  175. ExtendImplAsIncomplete,
  176. constraint_type_inst_id);
  177. });
  178. if (!is_complete) {
  179. parent_scope.set_has_error();
  180. return false;
  181. }
  182. }
  183. parent_scope.AddExtendedScope(constraint_type_inst_id);
  184. return true;
  185. }
  186. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  187. // associated name that describes them.
  188. static auto PopImplIntroducerAndParamsAsNameComponent(
  189. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  190. -> NameComponent {
  191. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  192. context.node_stack()
  193. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  194. if (implicit_param_patterns_id) {
  195. context.node_stack()
  196. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  197. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  198. // because `impl`s are never actually called at runtime.
  199. auto call_params_id =
  200. CalleePatternMatch(context, *implicit_param_patterns_id,
  201. SemIR::InstBlockId::None, SemIR::InstId::None);
  202. CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
  203. llvm::all_of(context.inst_blocks().Get(call_params_id),
  204. [](SemIR::InstId inst_id) {
  205. return inst_id == SemIR::ErrorInst::InstId;
  206. }));
  207. }
  208. Parse::NodeId first_param_node_id =
  209. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  210. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  211. // declaration when performing syntactic match.
  212. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  213. --last_param_iter;
  214. auto pattern_block_id = SemIR::InstBlockId::None;
  215. if (implicit_param_patterns_id) {
  216. pattern_block_id = context.pattern_block_stack().Pop();
  217. context.full_pattern_stack().PopFullPattern();
  218. }
  219. return {.name_loc_id = Parse::NodeId::None,
  220. .name_id = SemIR::NameId::None,
  221. .first_param_node_id = first_param_node_id,
  222. .last_param_node_id = *last_param_iter,
  223. .implicit_params_loc_id = implicit_params_loc_id,
  224. .implicit_param_patterns_id =
  225. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  226. .params_loc_id = Parse::NodeId::None,
  227. .param_patterns_id = SemIR::InstBlockId::None,
  228. .call_params_id = SemIR::InstBlockId::None,
  229. .return_slot_pattern_id = SemIR::InstId::None,
  230. .pattern_block_id = pattern_block_id};
  231. }
  232. static auto MergeImplRedecl(Context& context, SemIR::Impl& new_impl,
  233. SemIR::ImplId prev_impl_id) -> bool {
  234. auto& prev_impl = context.impls().Get(prev_impl_id);
  235. // If the parameters aren't the same, then this is not a redeclaration of this
  236. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  237. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  238. DeclParams(prev_impl), SemIR::SpecificId::None,
  239. /*diagnose=*/false, /*check_syntax=*/true,
  240. /*check_self=*/true)) {
  241. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  242. return false;
  243. }
  244. return true;
  245. }
  246. static auto IsValidImplRedecl(Context& context, SemIR::Impl& new_impl,
  247. SemIR::ImplId prev_impl_id) -> bool {
  248. auto& prev_impl = context.impls().Get(prev_impl_id);
  249. // TODO: Following #3763, disallow redeclarations in different scopes.
  250. // Following #4672, disallowing defining non-extern declarations in another
  251. // file.
  252. if (auto import_ref =
  253. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  254. // TODO: Handle extern.
  255. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  256. "redeclaration of imported impl");
  257. // TODO: Note imported declaration
  258. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  259. return false;
  260. }
  261. if (prev_impl.has_definition_started()) {
  262. // Impls aren't merged in order to avoid generic region lookup into a
  263. // mismatching table.
  264. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  265. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  266. InstIdAsRawType);
  267. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  268. "previous definition was here");
  269. context.emitter()
  270. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  271. new_impl.constraint_id)
  272. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  273. .Emit();
  274. return false;
  275. }
  276. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  277. return true;
  278. }
  279. // Checks that the constraint specified for the impl is valid and identified.
  280. // Returns the interface that the impl implements. On error, issues a diagnostic
  281. // and returns `None`.
  282. static auto CheckConstraintIsInterface(Context& context,
  283. SemIR::InstId impl_decl_id,
  284. SemIR::TypeInstId constraint_id)
  285. -> SemIR::SpecificInterface {
  286. auto facet_type_id = context.types().GetTypeIdForTypeInstId(constraint_id);
  287. if (facet_type_id == SemIR::ErrorInst::TypeId) {
  288. return SemIR::SpecificInterface::None;
  289. }
  290. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  291. if (!facet_type) {
  292. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  293. InstIdAsType);
  294. context.emitter().Emit(impl_decl_id, ImplAsNonFacetType, constraint_id);
  295. return SemIR::SpecificInterface::None;
  296. }
  297. auto identified_id = RequireIdentifiedFacetType(context, *facet_type);
  298. const auto& identified = context.identified_facet_types().Get(identified_id);
  299. if (!identified.is_valid_impl_as_target()) {
  300. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  301. "impl as {0} interfaces, expected 1", int);
  302. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  303. identified.num_interfaces_to_impl());
  304. return SemIR::SpecificInterface::None;
  305. }
  306. return identified.impl_as_target_interface();
  307. }
  308. static auto DiagnoseUnusedGenericBinding(Context& context,
  309. Parse::NodeId node_id,
  310. const NameComponent& name,
  311. SemIR::ImplId impl_id) -> void {
  312. auto deduced_specific_id = SemIR::SpecificId::None;
  313. auto& impl = context.impls().Get(impl_id);
  314. if (!impl.generic_id.has_value() ||
  315. impl.witness_id == SemIR::ErrorInst::InstId) {
  316. return;
  317. }
  318. // TODO: Deduce has side effects in the semir by generating `Converted`
  319. // instructions which we will not use here. We should stop generating
  320. // those when deducing for impl lookup, but for now we discard them by
  321. // pushing an InstBlock on the stack and dropping it right after.
  322. context.inst_block_stack().Push();
  323. deduced_specific_id = DeduceImplArguments(
  324. context, node_id, impl, context.constant_values().Get(impl.self_id),
  325. impl.interface.specific_id);
  326. context.inst_block_stack().PopAndDiscard();
  327. if (deduced_specific_id.has_value()) {
  328. // Deduction succeeded, all bindings were used.
  329. return;
  330. }
  331. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  332. "`impl` with unused generic binding");
  333. // TODO: This location may be incorrect, the binding may be inherited
  334. // from an outer declaration. It would be nice to get the particular
  335. // binding that was undeducible back from DeduceImplArguments here and
  336. // use that.
  337. auto loc = name.implicit_params_loc_id.has_value()
  338. ? name.implicit_params_loc_id
  339. : node_id;
  340. context.emitter().Emit(loc, ImplUnusedBinding);
  341. // Don't try to match the impl at all, save us work and possible future
  342. // diagnostics.
  343. FillImplWitnessWithErrors(context, context.impls().Get(impl_id));
  344. }
  345. // Build an ImplDecl describing the signature of an impl. This handles the
  346. // common logic shared by impl forward declarations and impl definitions.
  347. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  348. bool is_definition)
  349. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  350. auto [constraint_node, constraint_id] =
  351. context.node_stack().PopExprWithNodeId();
  352. auto [self_type_node, self_type_inst_id] =
  353. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  354. // Pop the `impl` introducer and any `forall` parameters as a "name".
  355. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  356. auto decl_block_id = context.inst_block_stack().Pop();
  357. // Convert the constraint expression to a type.
  358. auto [constraint_type_inst_id, constraint_type_id] =
  359. ExprAsType(context, constraint_node, constraint_id);
  360. // Process modifiers.
  361. // TODO: Should we somehow permit access specifiers on `impl`s?
  362. auto introducer =
  363. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  364. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  365. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  366. // Finish processing the name, which should be empty, but might have
  367. // parameters.
  368. auto name_context = context.decl_name_stack().FinishImplName();
  369. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  370. // TODO: Check for an orphan `impl`.
  371. // Add the impl declaration.
  372. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  373. .decl_block_id = decl_block_id};
  374. auto impl_decl_id = AddPlaceholderInst(context, node_id, impl_decl);
  375. SemIR::Impl impl_info = {name_context.MakeEntityWithParamsBase(
  376. name, impl_decl_id,
  377. /*is_extern=*/false, SemIR::LibraryNameId::None),
  378. {.self_id = self_type_inst_id,
  379. .constraint_id = constraint_type_inst_id,
  380. .interface = CheckConstraintIsInterface(
  381. context, impl_decl_id, constraint_type_inst_id),
  382. .is_final = is_final}};
  383. // Add the impl declaration.
  384. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl_info);
  385. // TODO: Detect two impl declarations with the same self type and interface,
  386. // and issue an error if they don't match.
  387. for (auto prev_impl_id : lookup_bucket_ref) {
  388. if (MergeImplRedecl(context, impl_info, prev_impl_id)) {
  389. if (IsValidImplRedecl(context, impl_info, prev_impl_id)) {
  390. impl_decl.impl_id = prev_impl_id;
  391. } else {
  392. // IsValidImplRedecl() has issued a diagnostic, avoid generating more
  393. // diagnostics for this declaration.
  394. impl_info.witness_id = SemIR::ErrorInst::InstId;
  395. }
  396. break;
  397. }
  398. }
  399. // Create a new impl if this isn't a valid redeclaration.
  400. if (!impl_decl.impl_id.has_value()) {
  401. impl_info.generic_id = BuildGeneric(context, impl_decl_id);
  402. if (impl_info.witness_id != SemIR::ErrorInst::InstId) {
  403. if (impl_info.interface.interface_id.has_value()) {
  404. impl_info.witness_id =
  405. ImplWitnessForDeclaration(context, impl_info, is_definition);
  406. } else {
  407. impl_info.witness_id = SemIR::ErrorInst::InstId;
  408. // TODO: We might also want to mark that the name scope for the impl has
  409. // an error -- at least once we start making name lookups within the
  410. // impl also look into the facet (eg, so you can name associated
  411. // constants from within the impl).
  412. }
  413. }
  414. FinishGenericDecl(context, SemIR::LocId(impl_decl_id),
  415. impl_info.generic_id);
  416. // From here on, use the `Impl` from the `ImplStore` instead of `impl_info`
  417. // in order to make and see any changes to the `Impl`.
  418. impl_decl.impl_id = context.impls().Add(impl_info);
  419. lookup_bucket_ref.push_back(impl_decl.impl_id);
  420. AssignImplIdInWitness(context, impl_decl.impl_id, impl_info.witness_id);
  421. // Looking to see if there are any generic bindings on the `impl`
  422. // declaration that are not deducible. If so, and the `impl` does not
  423. // actually use all its generic bindings, and will never be matched. This
  424. // should be diagnossed to the user.
  425. bool has_error_in_implicit_pattern = false;
  426. if (name.implicit_param_patterns_id.has_value()) {
  427. for (auto inst_id :
  428. context.inst_blocks().Get(name.implicit_param_patterns_id)) {
  429. if (inst_id == SemIR::ErrorInst::InstId) {
  430. has_error_in_implicit_pattern = true;
  431. break;
  432. }
  433. }
  434. }
  435. if (!has_error_in_implicit_pattern) {
  436. DiagnoseUnusedGenericBinding(context, node_id, name, impl_decl.impl_id);
  437. }
  438. } else {
  439. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  440. FinishGenericRedecl(context, stored_impl_info.generic_id);
  441. }
  442. // Write the impl ID into the ImplDecl.
  443. ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
  444. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  445. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  446. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  447. auto self_type_id =
  448. context.types().GetTypeIdForTypeInstId(stored_impl_info.self_id);
  449. if (self_type_id != SemIR::ErrorInst::TypeId) {
  450. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  451. if (stored_impl_info.generic_id.has_value()) {
  452. constraint_type_inst_id = AddTypeInst<SemIR::SpecificConstant>(
  453. context, SemIR::LocId(constraint_type_inst_id),
  454. {.type_id = SemIR::TypeType::TypeId,
  455. .inst_id = constraint_type_inst_id,
  456. .specific_id = context.generics().GetSelfSpecific(
  457. stored_impl_info.generic_id)});
  458. }
  459. if (!ExtendImpl(context, extend_node, node_id, impl_decl.impl_id,
  460. self_type_node, self_type_id, name.implicit_params_loc_id,
  461. constraint_type_inst_id, constraint_type_id)) {
  462. // Don't allow the invalid impl to be used.
  463. FillImplWitnessWithErrors(context, stored_impl_info);
  464. }
  465. }
  466. }
  467. // Impl definitions are required in the same file as the declaration. We skip
  468. // this requirement if we've already issued an invalid redeclaration error, or
  469. // there is an error that would prevent the impl from being legal to define.
  470. if (!is_definition) {
  471. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  472. if (stored_impl_info.witness_id != SemIR::ErrorInst::InstId) {
  473. context.definitions_required_by_decl().push_back(impl_decl_id);
  474. }
  475. }
  476. return {impl_decl.impl_id, impl_decl_id};
  477. }
  478. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  479. BuildImplDecl(context, node_id, /*is_definition=*/false);
  480. context.decl_name_stack().PopScope();
  481. return true;
  482. }
  483. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  484. -> bool {
  485. auto [impl_id, impl_decl_id] =
  486. BuildImplDecl(context, node_id, /*is_definition=*/true);
  487. auto& impl_info = context.impls().Get(impl_id);
  488. CARBON_CHECK(!impl_info.has_definition_started());
  489. impl_info.definition_id = impl_decl_id;
  490. impl_info.scope_id =
  491. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  492. context.decl_name_stack().PeekParentScopeId());
  493. context.scope_stack().PushForEntity(
  494. impl_decl_id, impl_info.scope_id,
  495. context.generics().GetSelfSpecific(impl_info.generic_id));
  496. StartGenericDefinition(context, impl_info.generic_id);
  497. ImplWitnessStartDefinition(context, impl_info);
  498. context.inst_block_stack().Push();
  499. context.node_stack().Push(node_id, impl_id);
  500. // TODO: Handle the case where there's control flow in the impl body. For
  501. // example:
  502. //
  503. // impl C as I {
  504. // fn F() -> if true then i32 else f64;
  505. // }
  506. //
  507. // We may need to track a list of instruction blocks here, as we do for a
  508. // function.
  509. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  510. return true;
  511. }
  512. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  513. -> bool {
  514. auto impl_id =
  515. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  516. FinishImplWitness(context, impl_id);
  517. auto& impl_info = context.impls().Get(impl_id);
  518. impl_info.defined = true;
  519. FinishGenericDefinition(context, impl_info.generic_id);
  520. context.inst_block_stack().Pop();
  521. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  522. return true;
  523. }
  524. } // namespace Carbon::Check