Files
carbon-lang/toolchain/check/handle_impl.cpp
T
Dana Jansens 14998d6045 Consolidate error handling behaviour for ApplyExtendImplAs (Refactor Impl construction 4/7) (#6468)
Propagate error state in an `extend impl` declaration out to the
enclosing scope. We can do this generically in `ApplyExtendImplAs` so we
don't have to do it explicitly in other places.

Collapse `DiagnoseExtendImplOutsideClass` into `ApplyExtendImplAs` as it
had only the one caller and is very small, so this simplifies the code,
making `ApplyExtendImplAs` a clear set of diagnostics. And push the
construction of the SpecificConstant down into `ApplyExtendImplAs` so it
is only constructed if it's needed, instead of constructing it and
throwing it away in error cases.

Ensure any error in the declaration results in the witness being an
ErrorInst so the impl will not be used in impl lookup. This simplifies
some branches by combining them into a single if statement.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6467.
2025-12-11 19:05:17 +00:00

327 lines
13 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/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/type.h"
#include "toolchain/check/type_completion.h"
#include "toolchain/parse/typed_nodes.h"
#include "toolchain/sem_ir/generic.h"
#include "toolchain/sem_ir/ids.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().PushFullPattern(
FullPatternStack::Kind::ImplicitParamList);
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);
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().GetInstId(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);
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 call_params_id =
CalleePatternMatch(context, *implicit_param_patterns_id,
SemIR::InstBlockId::None, SemIR::InstBlockId::None);
CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
llvm::all_of(context.inst_blocks().Get(call_params_id),
[](SemIR::InstId inst_id) {
return inst_id == SemIR::ErrorInst::InstId;
}));
}
Parse::NodeId 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_params_id = SemIR::InstBlockId::None,
.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.
static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
bool is_definition)
-> std::pair<SemIR::ImplId, SemIR::InstId> {
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.
auto [constraint_type_inst_id, constraint_type_id] =
ExprAsType(context, constraint_node, constraint_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);
// TODO: Check for an orphan `impl`.
// 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});
// This requires that the facet type is identified. It returns None if an
// error was diagnosed.
auto specific_interface = CheckConstraintIsInterface(context, impl_decl_id,
constraint_type_inst_id);
auto impl_id = SemIR::ImplId::None;
{
SemIR::Impl impl_info = {
name_context.MakeEntityWithParamsBase(name, impl_decl_id,
/*is_extern=*/false,
SemIR::LibraryNameId::None),
{.self_id = self_type_inst_id,
.constraint_id = constraint_type_inst_id,
.interface = specific_interface,
.is_final = is_final}};
auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
impl_id = GetOrAddImpl(context, node_id, name.implicit_params_loc_id,
impl_info, is_definition, extend_node);
}
// `GetOrAddImpl` either filled in the `impl_info` and returned a fresh
// ImplId, or if we're redeclaring a previous impl, returned an existing
// ImplId. 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};
}
auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
auto [impl_id, impl_decl_id] =
BuildImplDecl(context, node_id, /*is_definition=*/false);
auto& impl = context.impls().Get(impl_id);
context.decl_name_stack().PopScope();
// 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] =
BuildImplDecl(context, node_id, /*is_definition=*/true);
auto& impl = context.impls().Get(impl_id);
CARBON_CHECK(!impl.has_definition_started());
impl.definition_id = impl_decl_id;
impl.scope_id =
context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
context.decl_name_stack().PeekParentScopeId());
context.scope_stack().PushForEntity(
impl_decl_id, impl.scope_id,
context.generics().GetSelfSpecific(impl.generic_id));
StartGenericDefinition(context, impl.generic_id);
// This requires that the facet type is complete.
ImplWitnessStartDefinition(context, impl);
context.inst_block_stack().Push();
context.node_stack().Push(node_id, impl_id);
// 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>();
FinishImplWitness(context, impl_id);
auto& impl = context.impls().Get(impl_id);
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