handle_impl.cpp 23 KB

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