Files
carbon-lang/toolchain/check/handle_impl.cpp
T
Dana Jansens a5ba0a0f45 Use GetConstantValueInSpecific to get the impl's specific interface after deduction (#7584)
During impl lookup, for each (generic) impl candidate, we form a
specific for that impl by deducing its generic arguments. Then we
compare the query interface against the impl's specific interface. That
comparison needs the deduced arguments applied to the impl's specific
interface. Previously we were doing this by getting the impl's
constraint facet type with the impl's specific applied (via
`GetConstantValueInSpecific()`) and then identifying that facet type
with the impl's deduced self.

Identify is a fairly expensive operation. It runs subst, trying to
replace `.Self` references. It walks named constraints. It collects
require declarations. We're looking at making it do _more_ in the future
too, including rewrite constraint resolution and collecting rewrite and
same-type constraints. For this reason we have a cache to make it cheap
on the second run, but it's still a very heavyweight operation to
involve in impl lookup, when all we want is to apply the impl's specific
to its target interface.

We almost have all the information we need to avoid the identification
step. We have the impl's specific after deduction. And we have the
SpecificInterface that the impl is targeting in the `Impl` struct. When
we form the specific for the impl itself, we resolve the declaration
block and form new constant values for all instructions in there, but
that does not cover the SpecificInterface that we're storing in the
`Impl` struct. So we add a new instruction to the impl's eval block,
which will be symbolic when the impl is generic and the target interface
depends on a generic parameter. And we store the `InstId` in the `Impl`
struct. This allows us to gets its constant value later with the impl's
specific applied. From that constant value we can then pull out the
SpecificInterface that the impl is targeting.
2026-07-30 19:59:10 +00:00

507 lines
21 KiB
C++

// 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 <optional>
#include <utility>
#include "toolchain/base/kind_switch.h"
#include "toolchain/check/context.h"
#include "toolchain/check/convert.h"
#include "toolchain/check/decl_name_stack.h"
#include "toolchain/check/generic.h"
#include "toolchain/check/handle.h"
#include "toolchain/check/impl.h"
#include "toolchain/check/inst.h"
#include "toolchain/check/modifiers.h"
#include "toolchain/check/name_lookup.h"
#include "toolchain/check/name_scope.h"
#include "toolchain/check/pattern_match.h"
#include "toolchain/check/period_self.h"
#include "toolchain/check/type.h"
#include "toolchain/check/type_completion.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/parse/typed_nodes.h"
#include "toolchain/sem_ir/generic.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/specific_interface.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::Check {
// Returns the implicit `Self` type for an `impl` when it's in a `class`
// declaration.
//
// TODO: Mixin scopes also have a default `Self` type.
static auto GetImplDefaultSelfType(Context& context,
const ClassScope& class_scope)
-> SemIR::TypeId {
return context.classes().Get(class_scope.class_decl.class_id).self_type_id;
}
auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
-> bool {
// This might be a generic impl.
StartGenericDecl(context);
// Create an instruction block to hold the instructions created for the type
// and interface.
context.inst_block_stack().Push();
// Push the bracketing node.
context.node_stack().Push(node_id);
// Optional modifiers follow.
context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
// An impl doesn't have a name per se, but it makes the processing more
// consistent to imagine that it does. This also gives us a scope for implicit
// parameters.
context.decl_name_stack().PushScopeAndStartName();
return true;
}
auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
// Push a pattern block for the signature of the `forall`.
context.pattern_block_stack().Push();
context.full_pattern_stack().PushParameterizedDecl();
return true;
}
auto HandleParseNode(Context& context, Parse::ImplTypeAsId node_id) -> bool {
auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
auto self_type = ExprAsType(context, self_node, self_id);
const auto& introducer = context.decl_introducer_state_stack().innermost();
if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
// TODO: Also handle the parent scope being a mixin.
if (auto class_scope = TryAsClassScope(
context, context.decl_name_stack().PeekParentScopeId())) {
// If we're not inside a class at all, that will be diagnosed against the
// `extend` elsewhere.
auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
"cannot `extend` an `impl` with an explicit self type");
auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
if (self_type.type_id == GetImplDefaultSelfType(context, *class_scope)) {
// If the explicit self type is the default, suggest removing it with a
// diagnostic, but continue as if no error occurred since the self-type
// is semantically valid.
CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
"remove the explicit `Self` type here");
diag.Note(self_node, ExtendImplSelfAsDefault);
if (self_type.type_id != SemIR::ErrorInst::TypeId) {
diag.Emit();
}
} else if (self_type.type_id != SemIR::ErrorInst::TypeId) {
// Otherwise, the self-type is an error.
diag.Emit();
self_type.inst_id = SemIR::ErrorInst::TypeInstId;
}
}
}
// Introduce `Self`. Note that we add this name lexically rather than adding
// to the `NameScopeId` of the `impl`, because this happens before we enter
// the `impl` scope or even identify which `impl` we're declaring.
// TODO: Revisit this once #3714 is resolved.
AddNameToLookup(context, SemIR::NameId::SelfType, self_type.inst_id);
context.node_stack().Push(node_id, self_type.inst_id);
// The value in here, if any, is populated by the `where` expression that
// introduces a `.Self` in the impl's constraint facet type.
context.declaring_impl_decls().push_back(SemIR::SpecificInterface::None);
return true;
}
auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
-> bool {
auto self_inst_id = SemIR::TypeInstId::None;
if (auto class_scope = TryAsClassScope(
context, context.decl_name_stack().PeekParentScopeId())) {
auto self_type_id = GetImplDefaultSelfType(context, *class_scope);
// Build the implicit access to the enclosing `Self`.
// TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
// expression. We've already done the work to check that the enclosing
// context is a class and found its `Self`, so additionally performing an
// unqualified name lookup would be redundant work, but would avoid
// duplicating the handling of the `Self` expression.
self_inst_id = AddTypeInst(
context, node_id,
SemIR::NameRef{
.type_id = SemIR::TypeType::TypeId,
.name_id = SemIR::NameId::SelfType,
.value_id = context.types().GetTypeInstId(self_type_id)});
} else {
CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
"`impl as` can only be used in a class");
context.emitter().Emit(node_id, ImplAsOutsideClass);
self_inst_id = SemIR::ErrorInst::TypeInstId;
}
// There's no need to push `Self` into scope here, because we can find it in
// the parent class scope.
context.node_stack().Push(node_id, self_inst_id);
// The value in here, if any, is populated by the `where` expression that
// introduces a `.Self` in the impl's constraint facet type.
context.declaring_impl_decls().push_back(SemIR::SpecificInterface::None);
return true;
}
// Pops the parameters of an `impl`, forming a `NameComponent` with no
// associated name that describes them.
static auto PopImplIntroducerAndParamsAsNameComponent(
Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
-> NameComponent {
auto [implicit_params_loc_id, implicit_param_patterns_id] =
context.node_stack()
.PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
if (implicit_param_patterns_id) {
context.node_stack()
.PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
// Emit the `forall` match. This shouldn't produce any valid `Call` params,
// because `impl`s are never actually called at runtime.
auto match_results =
CalleePatternMatch(context, *implicit_param_patterns_id,
SemIR::InstBlockId::None, SemIR::InstId::None);
CARBON_CHECK(match_results.call_params_id == SemIR::InstBlockId::Empty);
CARBON_CHECK(match_results.call_param_patterns_id ==
SemIR::InstBlockId::Empty);
}
auto first_param_node_id =
context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
// Subtracting 1 since we don't want to include the final `{` or `;` of the
// declaration when performing syntactic match.
Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
--last_param_iter;
auto pattern_block_id = SemIR::InstBlockId::None;
if (implicit_param_patterns_id) {
pattern_block_id = context.pattern_block_stack().Pop();
context.full_pattern_stack().PopFullPattern();
}
return {.name_loc_id = Parse::NodeId::None,
.name_id = SemIR::NameId::None,
.first_param_node_id = first_param_node_id,
.last_param_node_id = *last_param_iter,
.implicit_params_loc_id = implicit_params_loc_id,
.implicit_param_patterns_id =
implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
.params_loc_id = Parse::NodeId::None,
.param_patterns_id = SemIR::InstBlockId::None,
.call_param_patterns_id = SemIR::InstBlockId::None,
.call_params_id = SemIR::InstBlockId::None,
.param_ranges = SemIR::Function::CallParamIndexRanges::Empty,
.pattern_block_id = pattern_block_id};
}
// Build an ImplDecl describing the signature of an impl. This handles the
// common logic shared by impl forward declarations and impl definitions. It
// also sets the `definition_id` on the Impl structure.
static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
bool has_definition)
-> std::tuple<SemIR::ImplId, SemIR::InstId, SemIR::TypeInstId> {
auto [constraint_node, constraint_id] =
context.node_stack().PopExprWithNodeId();
auto [self_type_node, self_type_inst_id] =
context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
// Pop the `impl` introducer and any `forall` parameters as a "name".
auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
auto decl_block_id = context.inst_block_stack().Pop();
// Convert the constraint expression to a type. This contains all constraints,
// including rewrites and other constrains on the RHS of `where`.
auto full_constraint_type_inst_id =
ExprAsType(context, constraint_node, constraint_id).inst_id;
// Process modifiers.
// TODO: Should we somehow permit access specifiers on `impl`s?
auto introducer =
context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
// Finish processing the name, which should be empty, but might have
// parameters.
auto name_context = context.decl_name_stack().FinishImplName();
CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
// Add the impl declaration.
auto impl_decl_id =
AddPlaceholderInst(context, node_id,
SemIR::ImplDecl{.impl_id = SemIR::ImplId::None,
.decl_block_id = decl_block_id});
if (!CheckConstraintIsFacetType(context, node_id,
full_constraint_type_inst_id)) {
full_constraint_type_inst_id = SemIR::ErrorInst::TypeInstId;
}
// This requires that the facet type is identified, and returns the single
// interface from the identified facet type. It returns None if an error was
// diagnosed.
auto specific_interface = CheckConstraintIsInterface(
context, node_id, self_type_inst_id, full_constraint_type_inst_id);
if (!specific_interface.interface_id.has_value()) {
full_constraint_type_inst_id = SemIR::ErrorInst::TypeInstId;
}
// Store an instruction in the decl's eval block that contains the target
// interface's specific, whose constant value will be updated when specifics
// are applied to the impl.
//
// We can use ImplSelfWitness for this because it contains a
// SpecificInterfaceId operand, and it has a constant_kind of `Always` so it
// never evaluates to some other type of inst.
//
// TODO: We could avoid the extra indirection through a SpecificInterfaceId if
// we introduced a new instruction with a SpecificId operand instead of
// reusing ImplSelfWitness for this.
auto interface_inst_id =
specific_interface.interface_id.has_value()
? AddInst<SemIR::ImplSelfWitness>(
context, node_id,
{.type_id =
GetSingletonType(context, SemIR::WitnessType::TypeInstId),
.period_self = self_type_inst_id,
.specific_interface_id =
context.specific_interfaces().Add(specific_interface)})
: SemIR::ErrorInst::InstId;
// Strip off anything on the RHS of `where`, as they are not part of the
// constraint being implemented, they just represent requirements that must be
// met when the impl is defined. This drops any `.Self` references from the
// resulting impl's `constraint_id` as they don't make sense outside the scope
// of the impl declaration.
auto extend_constraint_type_inst_id = full_constraint_type_inst_id;
if (auto where = context.insts().TryGetAs<SemIR::WhereExpr>(
extend_constraint_type_inst_id)) {
for (auto req_id : context.inst_blocks().Get(where->requirements_id)) {
if (auto base = context.insts().TryGetAs<SemIR::RequirementBaseFacetType>(
req_id)) {
extend_constraint_type_inst_id = base->base_type_inst_id;
break;
}
}
}
// The impl decl has a scope stack entry for the DeclNameStack, so we look at
// the parent scope of that.
auto parent_scope_inst_id = context.scope_stack().PeekParentInstId();
auto impl_id = SemIR::ImplId::None;
{
SemIR::Impl impl = {name_context.MakeEntityWithParamsBase(
name, impl_decl_id,
/*is_extern=*/false, SemIR::LibraryNameId::None),
{.parent_scope_inst_id = parent_scope_inst_id,
.is_final = is_final,
.self_id = self_type_inst_id,
.constraint_id = extend_constraint_type_inst_id,
.interface = specific_interface,
.interface_inst_id = interface_inst_id}};
if (has_definition) {
impl.definition_id = impl_decl_id;
}
// There's a bunch of places that may represent a diagnostic that occurred
// in checking the impl up to this point, which we consolidate into this
// bool. Due to lack of an instruction to set to `ErrorInst`, an
// `InterfaceId::None` indicates that the interface could not be identified
// and an error was diagnosed.
bool impl_had_error =
context.types().GetTypeIdForTypeInstId(impl.self_id) ==
SemIR::ErrorInst::TypeId ||
context.types().GetTypeIdForTypeInstId(impl.constraint_id) ==
SemIR::ErrorInst::TypeId;
if (is_final && context.match_first_context()) {
CARBON_DIAGNOSTIC(FinalImplInMatchFirst, Error,
"`final impl` in `match_first` block");
CARBON_DIAGNOSTIC(
FinalImplInMatchFirstNote, Note,
"the `match_first` block can be modified as `final` instead");
context.emitter()
.Build(node_id, FinalImplInMatchFirst)
.Note(context.match_first_context()->decl_id,
FinalImplInMatchFirstNote)
.Emit();
impl_had_error = true;
}
CARBON_KIND_SWITCH(FindImplId(context, impl)) {
case CARBON_KIND(RedeclaredImpl redeclared_impl): {
// This is a redeclaration of another impl, now held in `impl_id`.
impl_id = redeclared_impl.prev_impl_id;
// Note that we don't reconstruct the witness for a redeclaration, which
// was the instruction that came last in the first declaration's eval
// block. And FinishGenericRedecl allows the redecl to have fewer
// instructions to support this case.
auto& prev_impl = context.impls().Get(impl_id);
FinishGenericRedecl(context, prev_impl.generic_id);
if (has_definition) {
prev_impl.definition_id = impl_decl_id;
}
if (auto& match_first = context.match_first_context()) {
if (prev_impl.match_first_id.has_value()) {
if (!impl_had_error) {
CARBON_DIAGNOSTIC(
ImplInTwoMatchFirst, Error,
"impl declared in `match_first` more than once");
CARBON_DIAGNOSTIC(ImplInTwoMatchFirstNote, Note,
"previous declaration here");
context.emitter()
.Build(node_id, ImplInTwoMatchFirst)
.Note(prev_impl.decl_loc_in_match_first,
ImplInTwoMatchFirstNote)
.Emit();
}
impl_had_error = true;
}
if (!impl_had_error) {
prev_impl.match_first_id = match_first->decl_id;
prev_impl.decl_loc_in_match_first = SemIR::LocId(impl_decl_id);
prev_impl.match_first_position = match_first->block_size;
prev_impl.match_first_is_final = match_first->is_final;
match_first->block_size += 1;
}
}
break;
}
case CARBON_KIND(NewImpl new_impl): {
// This is a new declaration (possibly with an attached definition).
// Create a new `impl_id`, filling the missing generic and witness in
// `Impl` structure.
impl_had_error |= new_impl.find_had_error;
impl.generic_id = BuildGeneric(context, impl_decl_id);
if (impl_had_error) {
// If there's any error in the construction of the impl, then the
// witness can't be constructed. We set it to `ErrorInst` to make the
// impl unusable for impl lookup.
impl.witness_id = SemIR::ErrorInst::InstId;
} else {
context.inst_block_stack().Push();
// This makes either a placeholder witness table or a full witness
// table. The full witness table is deferred to the impl definition
// unless the declaration uses rewrite constraints to set values of
// associated constants in the interface.
//
// The witness instruction contains the SelfSpecific that is
// constructed by BuildGeneric(), but the witness and its rewrites
// also must be part of the generic eval block by coming before
// FinishGenericDecl().
impl.witness_id = AddImplWitnessForDeclaration(
context, node_id, impl, full_constraint_type_inst_id,
context.generics().GetSelfSpecific(impl.generic_id));
impl.witness_block_id = context.inst_block_stack().Pop();
if (auto& match_first = context.match_first_context()) {
impl.match_first_id = match_first->decl_id;
impl.decl_loc_in_match_first = SemIR::LocId(impl_decl_id);
impl.match_first_position = match_first->block_size;
impl.match_first_is_final = match_first->is_final;
match_first->block_size += 1;
}
}
FinishGenericDecl(context, node_id, impl.generic_id);
auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
impl_id = AddImpl(context, impl, new_impl.lookup_bucket, extend_node,
name.implicit_params_loc_id);
}
}
}
// `FindImplId` returned an existing ImplId, or we added a new id with
// `AddImpl` above. Write that ImplId into the ImplDecl instruction and finish
// it.
auto impl_decl = context.insts().GetAs<SemIR::ImplDecl>(impl_decl_id);
impl_decl.impl_id = impl_id;
ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
return {impl_id, impl_decl_id, full_constraint_type_inst_id};
}
auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
auto [impl_id, impl_decl_id, _] = BuildImplDecl(context, node_id, false);
auto& impl = context.impls().Get(impl_id);
context.decl_name_stack().PopScope();
context.declaring_impl_decls().pop_back();
// Impl definitions are required in the same file as the declaration. We skip
// this requirement if we've already issued an invalid redeclaration error, or
// there is an error that would prevent the impl from being legal to define.
if (impl.witness_id != SemIR::ErrorInst::InstId) {
context.definitions_required_by_decl().push_back(impl_decl_id);
}
return true;
}
auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
-> bool {
auto [impl_id, impl_decl_id, full_constraint_id] =
BuildImplDecl(context, node_id, true);
auto& impl = context.impls().Get(impl_id);
impl.scope_id =
context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
context.decl_name_stack().PeekParentScopeId());
context.name_scopes().Get(impl.scope_id).set_self_type_id(impl.self_id);
context.name_scopes().Get(impl.scope_id).AddExtendedScope(impl.constraint_id);
context.scope_stack().PushForEntity(
impl_decl_id, impl.scope_id,
context.generics().GetSelfSpecific(impl.generic_id));
StartGenericDefinition(context, impl.generic_id);
ImplWitnessStartDefinition(context, impl);
CheckRequireDeclsSatisfied(context, node_id, impl, full_constraint_id);
context.inst_block_stack().Push();
context.node_stack().Push(node_id, impl_id);
context.declaring_impl_decls().pop_back();
// TODO: Handle the case where there's control flow in the impl body. For
// example:
//
// impl C as I {
// fn F() -> if true then i32 else f64;
// }
//
// We may need to track a list of instruction blocks here, as we do for a
// function.
impl.body_block_id = context.inst_block_stack().PeekOrAdd();
return true;
}
auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
-> bool {
auto impl_id =
context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
auto& impl = context.impls().Get(impl_id);
FinishImplWitness(context, impl);
impl.defined = true;
FinishGenericDefinition(context, impl.generic_id);
context.inst_block_stack().Pop();
// The decl_name_stack and scopes are popped by `ProcessNodeIds`.
return true;
}
} // namespace Carbon::Check