handle_impl.cpp 24 KB

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