handle_impl.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. // Create an instruction block to hold the instructions created for the type
  28. // and interface.
  29. context.inst_block_stack().Push();
  30. // Push the bracketing node.
  31. context.node_stack().Push(node_id);
  32. // Optional modifiers follow.
  33. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  34. // An impl doesn't have a name per se, but it makes the processing more
  35. // consistent to imagine that it does. This also gives us a scope for implicit
  36. // parameters.
  37. context.decl_name_stack().PushScopeAndStartName();
  38. // This might be a generic impl.
  39. StartGenericDecl(context);
  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,
  168. context.insts().GetLocId(constraint_type_inst_id), [&] {
  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. // Build an ImplDecl describing the signature of an impl. This handles the
  307. // common logic shared by impl forward declarations and impl definitions.
  308. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  309. bool is_definition)
  310. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  311. auto [constraint_node, constraint_id] =
  312. context.node_stack().PopExprWithNodeId();
  313. auto [self_type_node, self_type_inst_id] =
  314. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  315. auto self_type_id = context.types().GetTypeIdForTypeInstId(self_type_inst_id);
  316. // Pop the `impl` introducer and any `forall` parameters as a "name".
  317. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  318. auto decl_block_id = context.inst_block_stack().Pop();
  319. // Convert the constraint expression to a type.
  320. auto [constraint_type_inst_id, constraint_type_id] =
  321. ExprAsType(context, constraint_node, constraint_id);
  322. // Process modifiers.
  323. // TODO: Should we somehow permit access specifiers on `impl`s?
  324. auto introducer =
  325. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  326. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  327. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  328. // Finish processing the name, which should be empty, but might have
  329. // parameters.
  330. auto name_context = context.decl_name_stack().FinishImplName();
  331. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  332. // TODO: Check for an orphan `impl`.
  333. // Add the impl declaration.
  334. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  335. .decl_block_id = decl_block_id};
  336. auto impl_decl_id = AddPlaceholderInst(context, node_id, impl_decl);
  337. SemIR::Impl impl_info = {name_context.MakeEntityWithParamsBase(
  338. name, impl_decl_id,
  339. /*is_extern=*/false, SemIR::LibraryNameId::None),
  340. {.self_id = self_type_inst_id,
  341. .constraint_id = constraint_type_inst_id,
  342. .interface = CheckConstraintIsInterface(
  343. context, impl_decl_id, constraint_type_inst_id),
  344. .is_final = is_final}};
  345. // Add the impl declaration.
  346. bool invalid_redeclaration = false;
  347. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl_info);
  348. // TODO: Detect two impl declarations with the same self type and interface,
  349. // and issue an error if they don't match.
  350. for (auto prev_impl_id : lookup_bucket_ref) {
  351. if (MergeImplRedecl(context, impl_info, prev_impl_id)) {
  352. if (IsValidImplRedecl(context, impl_info, prev_impl_id)) {
  353. impl_decl.impl_id = prev_impl_id;
  354. } else {
  355. // IsValidImplRedecl() has issued a diagnostic, avoid generating more
  356. // diagnostics for this declaration.
  357. invalid_redeclaration = true;
  358. }
  359. break;
  360. }
  361. }
  362. // Create a new impl if this isn't a valid redeclaration.
  363. if (!impl_decl.impl_id.has_value()) {
  364. impl_info.generic_id = BuildGeneric(context, impl_decl_id);
  365. if (impl_info.interface.interface_id.has_value()) {
  366. impl_info.witness_id =
  367. ImplWitnessForDeclaration(context, impl_info, is_definition);
  368. } else {
  369. impl_info.witness_id = SemIR::ErrorInst::InstId;
  370. // TODO: We might also want to mark that the name scope for the impl has
  371. // an error -- at least once we start making name lookups within the impl
  372. // also look into the facet (eg, so you can name associated constants from
  373. // within the impl).
  374. }
  375. FinishGenericDecl(context, impl_decl_id, impl_info.generic_id);
  376. impl_decl.impl_id = context.impls().Add(impl_info);
  377. lookup_bucket_ref.push_back(impl_decl.impl_id);
  378. AssignImplIdInWitness(context, impl_decl.impl_id, impl_info.witness_id);
  379. // Looking to see if there are any generic bindings on the `impl`
  380. // declaration that are not deducible. If so, and the `impl` does not
  381. // actually use all its generic bindings, and will never be matched. This
  382. // should be diagnossed to the user.
  383. bool has_error_in_implicit_pattern = false;
  384. if (name.implicit_param_patterns_id.has_value()) {
  385. for (auto inst_id :
  386. context.inst_blocks().Get(name.implicit_param_patterns_id)) {
  387. if (inst_id == SemIR::ErrorInst::InstId) {
  388. has_error_in_implicit_pattern = true;
  389. break;
  390. }
  391. }
  392. }
  393. if (impl_info.generic_id.has_value() && !has_error_in_implicit_pattern &&
  394. impl_info.witness_id != SemIR::ErrorInst::InstId) {
  395. context.inst_block_stack().Push();
  396. auto deduced_specific_id = DeduceImplArguments(
  397. context, node_id,
  398. DeduceImpl{.self_id = impl_info.self_id,
  399. .generic_id = impl_info.generic_id,
  400. .specific_id = impl_info.interface.specific_id},
  401. context.constant_values().Get(impl_info.self_id),
  402. impl_info.interface.specific_id);
  403. // TODO: Deduce has side effects in the semir by generating `Converted`
  404. // instructions which we will not use here. We should stop generating
  405. // those when deducing for impl lookup, but for now we discard them by
  406. // pushing an InstBlock on the stack and dropping it here.
  407. context.inst_block_stack().PopAndDiscard();
  408. if (!deduced_specific_id.has_value()) {
  409. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  410. "`impl` with unused generic binding");
  411. // TODO: This location may be incorrect, the binding may be inherited
  412. // from an outer declaration. It would be nice to get the particular
  413. // binding that was undeducible back from DeduceImplArguments here and
  414. // use that.
  415. auto loc = name.implicit_params_loc_id.has_value()
  416. ? name.implicit_params_loc_id
  417. : node_id;
  418. context.emitter().Emit(loc, ImplUnusedBinding);
  419. // Don't try to match the impl at all, save us work and possible future
  420. // diagnostics.
  421. FillImplWitnessWithErrors(context, impl_info);
  422. context.impls().Get(impl_decl.impl_id).witness_id =
  423. SemIR::ErrorInst::InstId;
  424. }
  425. }
  426. } else {
  427. auto prev_decl_generic_id =
  428. context.impls().Get(impl_decl.impl_id).generic_id;
  429. FinishGenericRedecl(context, prev_decl_generic_id);
  430. }
  431. // Write the impl ID into the ImplDecl.
  432. ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
  433. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  434. if (self_type_id != SemIR::ErrorInst::TypeId &&
  435. introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  436. auto extend_node = introducer.modifier_node_id(ModifierOrder::Decl);
  437. if (impl_info.generic_id.has_value()) {
  438. constraint_type_inst_id = AddTypeInst<SemIR::SpecificConstant>(
  439. context, context.insts().GetLocId(constraint_type_inst_id),
  440. {.type_id = SemIR::TypeType::TypeId,
  441. .inst_id = constraint_type_inst_id,
  442. .specific_id =
  443. context.generics().GetSelfSpecific(impl_info.generic_id)});
  444. }
  445. if (!ExtendImpl(context, extend_node, node_id, impl_decl.impl_id,
  446. self_type_node, self_type_id, name.implicit_params_loc_id,
  447. constraint_type_inst_id, constraint_type_id)) {
  448. // Don't allow the invalid impl to be used.
  449. FillImplWitnessWithErrors(context, impl_info);
  450. context.impls().Get(impl_decl.impl_id).witness_id =
  451. SemIR::ErrorInst::InstId;
  452. }
  453. }
  454. // Impl definitions are required in the same file as the declaration. We skip
  455. // this requirement if we've already issued an invalid redeclaration error, or
  456. // there is an error that would prevent the impl from being legal to define.
  457. if (!is_definition && !invalid_redeclaration &&
  458. context.impls().Get(impl_decl.impl_id).witness_id !=
  459. SemIR::ErrorInst::InstId) {
  460. context.definitions_required_by_decl().push_back(impl_decl_id);
  461. }
  462. return {impl_decl.impl_id, impl_decl_id};
  463. }
  464. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  465. BuildImplDecl(context, node_id, /*is_definition=*/false);
  466. context.decl_name_stack().PopScope();
  467. return true;
  468. }
  469. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  470. -> bool {
  471. auto [impl_id, impl_decl_id] =
  472. BuildImplDecl(context, node_id, /*is_definition=*/true);
  473. auto& impl_info = context.impls().Get(impl_id);
  474. CARBON_CHECK(!impl_info.has_definition_started());
  475. impl_info.definition_id = impl_decl_id;
  476. impl_info.scope_id =
  477. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  478. context.decl_name_stack().PeekParentScopeId());
  479. context.scope_stack().Push(
  480. impl_decl_id, impl_info.scope_id,
  481. context.generics().GetSelfSpecific(impl_info.generic_id));
  482. StartGenericDefinition(context);
  483. ImplWitnessStartDefinition(context, impl_info);
  484. context.inst_block_stack().Push();
  485. context.node_stack().Push(node_id, impl_id);
  486. // TODO: Handle the case where there's control flow in the impl body. For
  487. // example:
  488. //
  489. // impl C as I {
  490. // fn F() -> if true then i32 else f64;
  491. // }
  492. //
  493. // We may need to track a list of instruction blocks here, as we do for a
  494. // function.
  495. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  496. return true;
  497. }
  498. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  499. -> bool {
  500. auto impl_id =
  501. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  502. auto& impl_info = context.impls().Get(impl_id);
  503. CARBON_CHECK(!impl_info.is_complete());
  504. FinishImplWitness(context, impl_info);
  505. impl_info.defined = true;
  506. FinishGenericDefinition(context, impl_info.generic_id);
  507. context.inst_block_stack().Pop();
  508. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  509. return true;
  510. }
  511. } // namespace Carbon::Check