From e41862d55f2f1083c2bf04d84b3b5278874c8e83 Mon Sep 17 00:00:00 2001 From: Dana Jansens Date: Wed, 14 Oct 2026 17:54:41 +0000 Subject: [PATCH] Handle ImplSelfWitness appearing in the RHS of a rewrite constraint in impl decl (#7943) Normally ImplSelfWitness would be replaced in an impl decl by the time we are constructing the witness table. If it was part of an access to an associated constant, rewrite constraint resolution would have replaced that access with the value assigned to the associated constant already. But we can use `.Self` in places where it converts and forms a FacetValue, which preserves the ImplSelfWitness in the witness block of the FacetValue. In that case, we want to replace it with the impl's ImplWitness before we put it into the witness table. This is a followup fix for https://github.com/carbon-language/carbon-lang/pull/7930 which introduces the CARBON_FATAL incorrectly, now that we know how to run into it. Add some tests that cover these situations, including one that tries to access using the FacetValue and its witness, which fails, as a TODO test. --- toolchain/check/eval_inst.cpp | 3 + toolchain/check/impl.cpp | 112 +++++------------- .../testdata/facet/early_rewrites.carbon | 72 +++++++++++ .../impl/impl_as_named_constraint.carbon | 10 +- .../check/testdata/impl/period_self.carbon | 31 +++++ .../lower/testdata/impl/period_self.carbon | 20 ++-- 6 files changed, 153 insertions(+), 95 deletions(-) create mode 100644 toolchain/check/testdata/impl/period_self.carbon diff --git a/toolchain/check/eval_inst.cpp b/toolchain/check/eval_inst.cpp index ac03d5d5307f..a48ec5585386 100644 --- a/toolchain/check/eval_inst.cpp +++ b/toolchain/check/eval_inst.cpp @@ -313,6 +313,9 @@ static auto TryFindValueInRewriteConstraints( // grouped together, as in ResolveFacetTypeRewriteConstraints(), and limited // to just the `ImplWitnessAccess` entries, then a binary search may work // here. + // + // TODO: Use the identified facet type so we can find rewrites from named + // constraints too. Then we don't need to SubstPeriodSelf below anymore. for (const auto& rewrite : context.declared_facet_types() .Get(access_self_declared_facet_type_id) .rewrite_constraints) { diff --git a/toolchain/check/impl.cpp b/toolchain/check/impl.cpp index 8bef1e8620ab..2d5e23ccc7ae 100644 --- a/toolchain/check/impl.cpp +++ b/toolchain/check/impl.cpp @@ -395,16 +395,18 @@ auto AddImpl(Context& context, const SemIR::Impl& impl, return impl_id; } -// Replace IdentifiedWitness that refers to the current impl with a new -// ImplSelfWitness, preventing further evaluation of any ImplWitnessAccess -// containing it. -class SubstWithImplSelfWitness : public SubstIdentifiedWitnessesCallbacks { +// Substitute the impl's ImplWitness for any IdentifiedWitness that refers to +// the current impl's interface, as well as any ImplSelfWitness which always +// implicitly refers to the current impl. +class SubstWithImplWitness : public SubstIdentifiedWitnessesCallbacks { public: - SubstWithImplSelfWitness(Context* context, SemIR::LocId loc_id, - const SemIR::Impl* impl) + SubstWithImplWitness(Context* context, const SemIR::Impl* impl, + SemIR::InstId impl_witness_id) : SubstIdentifiedWitnessesCallbacks(context), - loc_id_(loc_id), - impl_(impl) {} + impl_(impl), + impl_witness_id_(impl_witness_id) { + CARBON_CHECK(impl_witness_id.has_value()); + } auto ReplaceIdentified(SemIR::IdentifiedWitness witness) -> SemIR::InstId override { @@ -419,28 +421,21 @@ class SubstWithImplSelfWitness : public SubstIdentifiedWitnessesCallbacks { if (impl_->interface != witness_interface) { return SemIR::InstId::None; } - - auto const_id = EvalOrAddInst( - context(), loc_id_, - {.type_id = GetSingletonType(context(), SemIR::WitnessType::TypeInstId), - .period_self = impl_->self_id, - .specific_interface_id = - context().specific_interfaces().Add(impl_->interface)}); - return context().constant_values().GetInstId(const_id); + return impl_witness_id_; } auto ReplaceImplSelfWitness(SemIR::ImplSelfWitness witness) -> SemIR::InstId override { - // ImplSelfWitness is only introduced via the impl decl, and should have - // been replaced already when building the witness table from the impl decl. - // Notwithstanding the fact that we then can re-introduce some through this - // class, those won't be passed back to the class here. - CARBON_FATAL("found unexpected ImplSelfWitness {0}", witness); + CARBON_CHECK(context().constant_values().Get(impl_->self_id) == + context().constant_values().Get(witness.period_self)); + CARBON_CHECK(context().specific_interfaces().Get( + witness.specific_interface_id) == impl_->interface); + return impl_witness_id_; } private: - SemIR::LocId loc_id_; const SemIR::Impl* impl_; + SemIR::InstId impl_witness_id_; }; auto AddImplWitnessForDeclaration(Context& context, SemIR::LocId loc_id, @@ -519,30 +514,20 @@ auto AddImplWitnessForDeclaration(Context& context, SemIR::LocId loc_id, continue; } - // The LHS of the rewrite contains an ImplSelfWitness that could be replaced - // with ImplWitness, however that would resolve the ImplWitnessAccess that + // The LHS of the rewrite contains a witness that could be replaced with + // ImplWitness, however that would resolve the ImplWitnessAccess that // contains it, and try to access the very element of the witness table that // we are setting. That results in a diagnostic for accessing the table // entry before it's set. So we just leave it be. // - // The RHS of the rewrite typically won't contain any witnesses for the - // current impl, as rewrite resolution replaced any references to an - // associated constant with the value of that associated constant. However - // it is possible in erroneous situations like `impl as Z where .Z2 = .Z1` - // where `.Z1` is never given a value. We don't want to produce another - // error here, but we also don't want `.Z1` to do an impl lookup. So we - // substitute the IdentifiedWitness with an ImplSelfWitness, which indicates - // that we know it points to the current impl but that impl is not ready - // yet. While that creates a bit of a weird situation with an - // ImplSelfWitness in the witness table, it ensures the access will never - // resolve, which is what we want. - // - // TODO: In the future, when we allow rewrites inside the body of the impl - // definition, we may run into this situation in non-erroneous conditions, - // and want to substitute the ImplSelfWitness out of the witness table once - // we have a value known for the associated constant being accessed with the - // witness. - SubstWithImplSelfWitness callbacks(&context, loc_id, &impl); + // The RHS of the rewrite may also contain ImplSelfWitness for the current + // impl. Usually they are gone already, as early rewrite replacement and + // rewrite resolution replace any references to an associated constant with + // the value of that associated constant. However FacetValues using `.Self` + // may encode such witnesses, and it is also possible when an associated + // constant is used from the impl declaration but is not set in the + // declaration. + SubstWithImplWitness callbacks(&context, &impl, witness_inst_id); rewrite.rhs = SubstIdentifiedWitnesses(context, loc_id, rewrite.rhs, callbacks); @@ -835,45 +820,6 @@ auto FinishImplWitness(Context& context, const SemIR::Impl& impl) -> void { // TODO: Diagnose if any declarations in the impl are not in used_decl_ids. } -// Substitute the impl's ImplWitness for any IdentifiedWitness that refers to -// the current impl's interface, as well as any ImplSelfWitness which always -// implicitly refers to the current impl. -class SubstWithImplWitness : public SubstIdentifiedWitnessesCallbacks { - public: - SubstWithImplWitness(Context* context, const SemIR::Impl* impl) - : SubstIdentifiedWitnessesCallbacks(context), impl_(impl) { - CARBON_CHECK(impl_->witness_id.has_value()); - } - - auto ReplaceIdentified(SemIR::IdentifiedWitness witness) - -> SemIR::InstId override { - auto impl_self = context().constant_values().Get(impl_->self_id); - auto witness_self = - context().constant_values().Get(witness.query_self_inst_id); - if (impl_self != witness_self) { - return SemIR::InstId::None; - } - auto witness_interface = context().specific_interfaces().Get( - witness.query_specific_interface_id); - if (impl_->interface != witness_interface) { - return SemIR::InstId::None; - } - return impl_->witness_id; - } - - auto ReplaceImplSelfWitness(SemIR::ImplSelfWitness witness) - -> SemIR::InstId override { - CARBON_CHECK(context().constant_values().Get(impl_->self_id) == - context().constant_values().Get(witness.period_self)); - CARBON_CHECK(context().specific_interfaces().Get( - witness.specific_interface_id) == impl_->interface); - return impl_->witness_id; - } - - private: - const SemIR::Impl* impl_; -}; - auto CheckRequireDeclsSatisfied(Context& context, SemIR::LocId loc_id, SemIR::Impl& impl, SemIR::TypeInstId full_constraint_id, @@ -893,7 +839,7 @@ auto CheckRequireDeclsSatisfied(Context& context, SemIR::LocId loc_id, // This replaces both IdentifiedWitness and ImplSelfWitness referring to // this impl with the impl's ImplWitness. That causes any access through the // witness to resolve to the value from the impl's witness table. - SubstWithImplWitness callbacks(&context, &impl); + SubstWithImplWitness callbacks(&context, &impl, impl.witness_id); req = SubstIdentifiedWitnesses(context, loc_id, req, callbacks); if (req.self_facet_value == self_const_id && @@ -931,7 +877,7 @@ auto CheckRequireDeclsSatisfied(Context& context, SemIR::LocId loc_id, // This replaces both IdentifiedWitness and ImplSelfWitness referring to // this impl with the impl's ImplWitness. That causes any access through the // witness to resolve to the value from the impl's witness table. - SubstWithImplWitness callbacks(&context, &impl); + SubstWithImplWitness callbacks(&context, &impl, impl.witness_id); auto subst_equiv = SubstIdentifiedWitnesses(context, loc_id, equiv, callbacks); diff --git a/toolchain/check/testdata/facet/early_rewrites.carbon b/toolchain/check/testdata/facet/early_rewrites.carbon index f3caa4d1b80d..2a287a72ec2d 100644 --- a/toolchain/check/testdata/facet/early_rewrites.carbon +++ b/toolchain/check/testdata/facet/early_rewrites.carbon @@ -89,6 +89,78 @@ fn G(generic T: J where .J1 = D) { F(T); } +// --- fail_todo_period_self_used_in_access_in_nested_specific.carbon +library "[[@TEST_NAME]]"; + +interface Z { + let Z1: type; + let Z2: type; +} + +interface Y {} +impl forall [T: Z] T as Y {} + +class C(T: Z & Y, U: T.(Z.Z1)) {} + +class D; +// This forms the specific `C(.Self)` where `.Self` is of type `Z` +// but we need type `Z & Y` so a conversion takes place. This forms +// a FacetValue with two witnesses. The witness for `Y` is symbolic +// (due to .Self) and points to the impl above. But the witness for +// `Z` is not symbolic and points to the impl being declared here. +// The use of `T.(Z.Z1)` in the class decl ensures we find the value +// from this impl's witness table. +// +// TODO: Right now the type of `U` ends up with an ImplSelfWitness +// which does not resolve the access. So () can't convert to it. +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific.carbon:[[@LINE+10]]:38: error: cannot implicitly convert expression of type `type` to `.(Z.Z1)` [ConversionFailure] +// CHECK:STDERR: impl D as Z where .Z1 = () and .Z2 = C(.Self, .Z1) {} +// CHECK:STDERR: ^~~~~~~~~~~~~ +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific.carbon:[[@LINE+7]]:38: note: type `type` does not implement interface `Core.ImplicitAs(.(Z.Z1))` [MissingImplInMemberAccessInContext] +// CHECK:STDERR: impl D as Z where .Z1 = () and .Z2 = C(.Self, .Z1) {} +// CHECK:STDERR: ^~~~~~~~~~~~~ +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific.carbon:[[@LINE-19]]:1: note: while deducing parameters of generic declared here [DeductionGenericHere] +// CHECK:STDERR: class C(T: Z & Y, U: T.(Z.Z1)) {} +// CHECK:STDERR: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// CHECK:STDERR: +impl D as Z where .Z1 = () and .Z2 = C(.Self, .Z1) {} + +// --- fail_todo_period_self_used_in_access_in_nested_specific_before_rewrite_of_access.carbon +library "[[@TEST_NAME]]"; + +interface Z { + let Z1: type; + let Z2: type; +} + +interface Y {} +impl forall [T: Z] T as Y {} + +class C(T: Z & Y, U: T.(Z.Z1)) {} + +class D; +// This forms the specific `C(.Self)` where `.Self` is of type `Z` +// but we need type `Z & Y` so a conversion takes place. This forms +// a FacetValue with two witnesses. The witness for `Y` is symbolic +// (due to .Self) and points to the impl above. But the witness for +// `Z` is not symbolic and points to the impl being declared here. +// The use of `T.(Z.Z1)` in the class decl ensures we find the value +// from this impl's witness table. +// +// TODO: Right now the type of `U` ends up with an ImplSelfWitness +// which does not resolve the access. So `.Z1` can't convert to it. +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific_before_rewrite_of_access.carbon:[[@LINE+10]]:25: error: cannot implicitly convert expression of type `type` to `.(Z.Z1)` [ConversionFailure] +// CHECK:STDERR: impl D as Z where .Z2 = C(.Self, .Z1) and .Z1 = () {} +// CHECK:STDERR: ^~~~~~~~~~~~~ +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific_before_rewrite_of_access.carbon:[[@LINE+7]]:25: note: type `type` does not implement interface `Core.ImplicitAs(.(Z.Z1))` [MissingImplInMemberAccessInContext] +// CHECK:STDERR: impl D as Z where .Z2 = C(.Self, .Z1) and .Z1 = () {} +// CHECK:STDERR: ^~~~~~~~~~~~~ +// CHECK:STDERR: fail_todo_period_self_used_in_access_in_nested_specific_before_rewrite_of_access.carbon:[[@LINE-19]]:1: note: while deducing parameters of generic declared here [DeductionGenericHere] +// CHECK:STDERR: class C(T: Z & Y, U: T.(Z.Z1)) {} +// CHECK:STDERR: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// CHECK:STDERR: +impl D as Z where .Z2 = C(.Self, .Z1) and .Z1 = () {} + // --- fail_todo_nested_constraint_visible_in_type_parameter.carbon library "[[@TEST_NAME]]"; diff --git a/toolchain/check/testdata/impl/impl_as_named_constraint.carbon b/toolchain/check/testdata/impl/impl_as_named_constraint.carbon index 3e364411238d..9003d545e64b 100644 --- a/toolchain/check/testdata/impl/impl_as_named_constraint.carbon +++ b/toolchain/check/testdata/impl/impl_as_named_constraint.carbon @@ -278,10 +278,18 @@ constraint N { } class C; +// TODO: Since these errors have the same location, it would be nice to omit +// the first one. Once rewrites can be done in the impl defn body, these errors +// won't always have the same location (with the location being the decl) +// though. +// CHECK:STDERR: fail_impl_as_constraint_missing_rewrite.carbon:[[@LINE+11]]:1: error: accessing member from impl before it has a defined value [ImplAccessMemberBeforeSet] +// CHECK:STDERR: impl C as N {} +// CHECK:STDERR: ^~~~~~~~~~~~~ +// CHECK:STDERR: // CHECK:STDERR: fail_impl_as_constraint_missing_rewrite.carbon:[[@LINE+7]]:1: error: associated constant I1 not given a value in impl of interface I [ImplAssociatedConstantNeedsValue] // CHECK:STDERR: impl C as N {} // CHECK:STDERR: ^~~~~~~~~~~~~ -// CHECK:STDERR: fail_impl_as_constraint_missing_rewrite.carbon:[[@LINE-12]]:7: note: associated constant declared here [AssociatedConstantHere] +// CHECK:STDERR: fail_impl_as_constraint_missing_rewrite.carbon:[[@LINE-20]]:7: note: associated constant declared here [AssociatedConstantHere] // CHECK:STDERR: let I1: type; // CHECK:STDERR: ^~~~~~~~ // CHECK:STDERR: diff --git a/toolchain/check/testdata/impl/period_self.carbon b/toolchain/check/testdata/impl/period_self.carbon new file mode 100644 index 000000000000..1692903fc996 --- /dev/null +++ b/toolchain/check/testdata/impl/period_self.carbon @@ -0,0 +1,31 @@ +// Part of the Carbon Language project, under the Apache License v2.0 with LLVM +// Exceptions. See /LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/convert.carbon +// +// AUTOUPDATE +// TIP: To test this file alone, run: +// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/check/testdata/impl/period_self.carbon +// TIP: To dump output, run: +// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/check/testdata/impl/period_self.carbon + +// --- period_self_converted_in_impl_as_decl.carbon +library "[[@TEST_NAME]]"; + +interface Z { + let Z1: type; +} + +interface Y {} +impl forall [T: Z] T as Y {} + +class C(T: Z & Y) {} + +class D; +// This forms the specific `C(.Self)` where `.Self` is of type `Z` +// but we need type `Z & Y` so a conversion takes place. This forms +// a FacetValue with two witnesses. The witness for `Y` is symbolic +// (due to .Self) and points to the impl above. But the witness for +// `Z` is not symbolic and points to the impl being declared here. +impl D as Z where .Z1 = C(.Self) {} diff --git a/toolchain/lower/testdata/impl/period_self.carbon b/toolchain/lower/testdata/impl/period_self.carbon index 5ddd8c053eb4..bccf68423c9a 100644 --- a/toolchain/lower/testdata/impl/period_self.carbon +++ b/toolchain/lower/testdata/impl/period_self.carbon @@ -11,7 +11,6 @@ // TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/lower/testdata/impl/period_self.carbon // --- library_with_period_self_in_impl.carbon - library "[[@TEST_NAME]]"; interface J {} @@ -32,7 +31,6 @@ fn F[T: type](x: A(T)) { } // --- import_period_self_in_impl.carbon - library "[[@TEST_NAME]]"; import library "library_with_period_self_in_impl"; @@ -89,21 +87,21 @@ fn G(a: A(B)) { // CHECK:STDOUT: !22 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: null, size: 64) // CHECK:STDOUT: !23 = !{null, !22} // CHECK:STDOUT: !24 = !DISubroutineType(types: !23) -// CHECK:STDOUT: !25 = distinct !DISubprogram(name: "G", linkageName: "_CG.Main", scope: null, file: !20, line: 6, type: !24, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !31) +// CHECK:STDOUT: !25 = distinct !DISubprogram(name: "G", linkageName: "_CG.Main", scope: null, file: !20, line: 5, type: !24, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !31) // CHECK:STDOUT: !26 = !DILocalVariable(arg: 1, scope: !25, type: !22) -// CHECK:STDOUT: !29 = !DILocation(line: 7, column: 3, scope: !25) -// CHECK:STDOUT: !30 = !DILocation(line: 6, column: 1, scope: !25) +// CHECK:STDOUT: !29 = !DILocation(line: 6, column: 3, scope: !25) +// CHECK:STDOUT: !30 = !DILocation(line: 5, column: 1, scope: !25) // CHECK:STDOUT: !31 = !{!26} -// CHECK:STDOUT: !32 = distinct !DISubprogram(name: "F", linkageName: "_CF.Main.a6a60dfee2d7d273", scope: null, file: !18, line: 17, type: !24, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !39) +// CHECK:STDOUT: !32 = distinct !DISubprogram(name: "F", linkageName: "_CF.Main.a6a60dfee2d7d273", scope: null, file: !18, line: 16, type: !24, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !39) // CHECK:STDOUT: !33 = !DILocalVariable(arg: 1, scope: !32, type: !22) -// CHECK:STDOUT: !35 = !DILocation(line: 18, column: 3, scope: !32) +// CHECK:STDOUT: !35 = !DILocation(line: 17, column: 3, scope: !32) // CHECK:STDOUT: !36 = !{!22, !22} // CHECK:STDOUT: !37 = !DISubroutineType(types: !36) -// CHECK:STDOUT: !38 = !DILocation(line: 17, column: 1, scope: !32) +// CHECK:STDOUT: !38 = !DILocation(line: 16, column: 1, scope: !32) // CHECK:STDOUT: !39 = !{!33} -// CHECK:STDOUT: !40 = distinct !DISubprogram(name: "Convert", linkageName: "_CConvert.A.5d7343568c0b5715.Main:As.00d5ad878904f3d1.Core.229c89d4d5cd2a3b", scope: null, file: !18, line: 12, type: !37, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !47) +// CHECK:STDOUT: !40 = distinct !DISubprogram(name: "Convert", linkageName: "_CConvert.A.5d7343568c0b5715.Main:As.00d5ad878904f3d1.Core.229c89d4d5cd2a3b", scope: null, file: !18, line: 11, type: !37, spFlags: DISPFlagDefinition, unit: !21, retainedNodes: !47) // CHECK:STDOUT: !41 = !DILocalVariable(arg: 1, scope: !40, type: !22) -// CHECK:STDOUT: !45 = !DILocation(line: 13, column: 12, scope: !40) -// CHECK:STDOUT: !46 = !DILocation(line: 13, column: 5, scope: !40) +// CHECK:STDOUT: !45 = !DILocation(line: 12, column: 12, scope: !40) +// CHECK:STDOUT: !46 = !DILocation(line: 12, column: 5, scope: !40) // CHECK:STDOUT: !47 = !{!41} // CHECK:STDOUT: