Implement support for copying C++ classes. (#6434)

When performing impl lookup for `Core.Copy` for a C++ class type, look
for a copy constructor. If we find one, synthesize an impl witness that
calls the constructor.

This adds initial support for impl lookup to delegate to the C++ interop
logic for queries involving C++ types. For now, we don't implement the
rules from #6166 that compare a synthesized type structure for the C++
impl against the best Carbon type structure, but the framework for
building that support is established here.

Currently there is no caching of the lookup here, and we build unique
`ImplWitnessTable`s for each lookup, which leads to each impl lookup
producing a distinct facet value. This results in some errors in generic
contexts; this will be addressed in follow-up changes. This PR aims only
to support the non-generic case.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
This commit is contained in:
Richard Smith
2025-12-02 02:52:23 +00:00
committed by GitHub
co-authored by Dana Jansens Carbon Infra Bot
parent 19660ccde0
commit 372f632d9d
16 changed files with 923 additions and 127 deletions
+190
View File
@@ -0,0 +1,190 @@
// 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 "toolchain/check/cpp/impl_lookup.h"
#include "clang/Sema/Sema.h"
#include "toolchain/base/kind_switch.h"
#include "toolchain/check/cpp/import.h"
#include "toolchain/check/cpp/location.h"
#include "toolchain/check/cpp/overload_resolution.h"
#include "toolchain/check/impl.h"
#include "toolchain/check/impl_lookup.h"
#include "toolchain/check/import_ref.h"
#include "toolchain/check/inst.h"
#include "toolchain/check/type.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::Check {
// If the given type is a C++ class type, returns the corresponding class
// declaration. Otherwise returns nullptr.
// TODO: Handle qualified types.
static auto TypeAsClassDecl(Context& context, SemIR::TypeId type_id)
-> clang::CXXRecordDecl* {
auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
if (!class_type) {
// Not a class.
return nullptr;
}
SemIR::NameScopeId class_scope_id =
context.classes().Get(class_type->class_id).scope_id;
if (!class_scope_id.has_value()) {
return nullptr;
}
const auto& scope = context.name_scopes().Get(class_scope_id);
auto decl_id = scope.clang_decl_context_id();
if (!decl_id.has_value()) {
return nullptr;
}
return dyn_cast<clang::CXXRecordDecl>(
context.clang_decls().Get(decl_id).key.decl);
}
// Builds a witness that the given type implements the given interface,
// populating it with the specified set of values. Returns a corresponding
// lookup result. Produces a diagnostic and returns `None` if the specified
// values aren't suitable for the interface.
static auto BuildWitness(Context& context, SemIR::LocId loc_id,
SemIR::TypeId self_type_id,
SemIR::SpecificInterface specific_interface,
llvm::ArrayRef<SemIR::InstId> values)
-> SemIR::InstId {
const auto& interface =
context.interfaces().Get(specific_interface.interface_id);
auto assoc_entities =
context.inst_blocks().GetOrEmpty(interface.associated_entities_id);
if (assoc_entities.size() != values.size()) {
context.TODO(loc_id, ("Unsupported definition of interface " +
context.names().GetFormatted(interface.name_id))
.str());
return SemIR::ErrorInst::InstId;
}
// Prepare an empty witness table.
auto witness_table_id =
context.inst_blocks().AddUninitialized(assoc_entities.size());
auto witness_table = context.inst_blocks().GetMutable(witness_table_id);
for (auto& witness_value_id : witness_table) {
witness_value_id = SemIR::InstId::ImplWitnessTablePlaceholder;
}
// Build a witness. We use an `ImplWitness` with an `impl_id` of `None` to
// represent a synthesized witness.
// TODO: Stop using `ImplWitnessTable` here and add a distinct instruction
// that doesn't contain an `InstId` and supports deduplication.
auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
context, loc_id,
{.elements_id = witness_table_id, .impl_id = SemIR::ImplId::None});
auto witness_id = AddInst<SemIR::ImplWitness>(
context, loc_id,
{.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
.witness_table_id = witness_table_inst_id,
.specific_id = SemIR::SpecificId::None});
// Fill in the witness table.
for (const auto& [assoc_entity_id, value_id, witness_value_id] :
llvm::zip_equal(assoc_entities, values, witness_table)) {
LoadImportRef(context, assoc_entity_id);
auto decl_id =
context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
context.sem_ir(), specific_interface.specific_id, assoc_entity_id));
CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
auto decl = context.insts().Get(decl_id);
CARBON_KIND_SWITCH(decl) {
case CARBON_KIND(SemIR::StructValue struct_value): {
if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
return SemIR::ErrorInst::InstId;
}
witness_value_id = CheckAssociatedFunctionImplementation(
context,
context.types().GetAs<SemIR::FunctionType>(struct_value.type_id),
value_id, self_type_id, witness_id,
/*defer_thunk_definition=*/false);
break;
}
case SemIR::AssociatedConstantDecl::Kind: {
context.TODO(loc_id,
"Associated constant in interface with synthesized impl");
return SemIR::ErrorInst::InstId;
}
default:
CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
"Unexpected kind of associated entity {0}", decl);
return SemIR::ErrorInst::InstId;
}
}
return witness_id;
}
static auto LookupCopyImpl(Context& context, SemIR::LocId loc_id,
SemIR::TypeId self_type_id,
SemIR::SpecificInterface specific_interface)
-> SemIR::InstId {
auto* class_decl = TypeAsClassDecl(context, self_type_id);
if (!class_decl) {
// TODO: Should we also provide a `Copy` implementation for enumerations?
return SemIR::InstId::None;
}
auto* ctor = context.clang_sema().LookupCopyingConstructor(
class_decl, clang::Qualifiers::Const);
if (!ctor) {
// TODO: If the impl lookup failure is an error, we should produce a
// diagnostic explaining why the class is not copyable.
return SemIR::InstId::None;
}
auto ctor_id =
context.clang_sema().DiagnoseUseOfOverloadedDecl(
ctor, GetCppLocation(context, loc_id))
? SemIR::ErrorInst::InstId
: ImportCppFunctionDecl(context, loc_id, ctor, /*num_params=*/1);
if (auto ctor_decl =
context.insts().TryGetAsWithId<SemIR::FunctionDecl>(ctor_id)) {
CheckCppOverloadAccess(context, loc_id,
clang::DeclAccessPair::make(ctor, ctor->getAccess()),
ctor_decl->inst_id);
} else {
CARBON_CHECK(ctor_id == SemIR::ErrorInst::InstId);
return SemIR::ErrorInst::InstId;
}
return BuildWitness(context, loc_id, self_type_id, specific_interface,
{ctor_id});
}
auto LookupCppImpl(Context& context, SemIR::LocId loc_id,
SemIR::TypeId self_type_id,
SemIR::SpecificInterface specific_interface,
const TypeStructure* best_impl_type_structure,
SemIR::LocId best_impl_loc_id) -> SemIR::InstId {
// Determine whether this is an interface that we have special knowledge of.
auto& interface = context.interfaces().Get(specific_interface.interface_id);
if (!context.name_scopes().IsCorePackage(interface.parent_scope_id)) {
return SemIR::InstId::None;
}
if (!interface.name_id.AsIdentifierId().has_value()) {
return SemIR::InstId::None;
}
if (context.identifiers().Get(interface.name_id.AsIdentifierId()) == "Copy") {
return LookupCopyImpl(context, loc_id, self_type_id, specific_interface);
}
// TODO: Handle other interfaces.
// TODO: Infer a C++ type structure and check whether it's less strict than
// the best Carbon type structure.
static_cast<void>(best_impl_type_structure);
static_cast<void>(best_impl_loc_id);
return SemIR::InstId::None;
}
} // namespace Carbon::Check
+44
View File
@@ -0,0 +1,44 @@
// 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
#ifndef CARBON_TOOLCHAIN_CHECK_CPP_IMPL_LOOKUP_H_
#define CARBON_TOOLCHAIN_CHECK_CPP_IMPL_LOOKUP_H_
#include "toolchain/check/context.h"
#include "toolchain/check/impl_lookup.h"
#include "toolchain/check/type_structure.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/specific_interface.h"
namespace Carbon::Check {
// Performs lookup for an impl witness for a query involving C++ types. Returns
// a witness value, or `None` if a synthesized C++ witness should not be used.
//
// If `interface` is an interface for which we can synthesize a witness based on
// C++ operator overloads or special member functions, performs the suitable C++
// lookup to determine if this interface should be considered implemented for
// the specified type, and if so, synthesizes and returns a suitable witness.
//
// `best_impl_type_structure` provides the type structure of the best-matching
// impl declaration. If this is better than every viable C++ candidate, a "none"
// result will be returned. If this is worse than the best viable C++ candidate
// according to C++ rules, a witness for the C++ candidate will be returned.
// Otherwise, it is at least as good as the best viable C++ candidate, but there
// is some C++ candidate that has a better type structure, in which case the
// result is ambiguous and we diagnose an error. This parameter can be null if
// there is no usable impl for this query.
//
// `best_impl_loc_id` gives the location of the impl corresponding to the best
// type structure, and can be `None` if `best_impl_type_structure` is null. This
// parameter is used only for ambiguity diagnostics.
auto LookupCppImpl(Context& context, SemIR::LocId loc_id,
SemIR::TypeId self_type_id,
SemIR::SpecificInterface specific_interface,
const TypeStructure* best_impl_type_structure,
SemIR::LocId best_impl_loc_id) -> SemIR::InstId;
} // namespace Carbon::Check
#endif // CARBON_TOOLCHAIN_CHECK_CPP_IMPL_LOOKUP_H_
+6
View File
@@ -40,6 +40,7 @@
#include "toolchain/check/convert.h"
#include "toolchain/check/cpp/access.h"
#include "toolchain/check/cpp/custom_type_mapping.h"
#include "toolchain/check/cpp/location.h"
#include "toolchain/check/cpp/macros.h"
#include "toolchain/check/cpp/thunk.h"
#include "toolchain/check/diagnostic_helpers.h"
@@ -1809,6 +1810,11 @@ static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
function_info.SetHasCppThunk(thunk_function_decl_id);
}
}
} else {
// Inform Clang that the function has been referenced. This will trigger
// instantiation if needed.
context.clang_sema().MarkFunctionReferenced(GetCppLocation(context, loc_id),
clang_decl);
}
return function_info.first_owning_decl_id;
+26 -6
View File
@@ -25,7 +25,7 @@ static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
-> std::optional<clang::OverloadedOperatorKind> {
// Unary operators.
if (interface_name == "Destroy" || interface_name == "As" ||
interface_name == "ImplicitAs") {
interface_name == "ImplicitAs" || interface_name == "Copy") {
// TODO: Support destructors and conversions.
return std::nullopt;
}
@@ -280,17 +280,37 @@ auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool {
return clang_method_decl && clang_method_decl->isOverloadedOperator();
}
auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool {
static auto GetAsCppFunctionDecl(Context& context, SemIR::InstId inst_id)
-> clang::FunctionDecl* {
auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
context.insts().Get(inst_id).type_id());
if (!function_type) {
return false;
return nullptr;
}
SemIR::ClangDeclId clang_decl_id =
context.functions().Get(function_type->function_id).clang_decl_id;
return clang_decl_id.has_value() &&
IsCppOperatorMethodDecl(
context.clang_decls().Get(clang_decl_id).key.decl);
return clang_decl_id.has_value()
? dyn_cast<clang::FunctionDecl>(
context.clang_decls().Get(clang_decl_id).key.decl)
: nullptr;
}
auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool {
auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
return function_decl && IsCppOperatorMethodDecl(function_decl);
}
auto IsCppConstructorOrNonMethodOperator(Context& context,
SemIR::InstId inst_id) -> bool {
auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
if (!function_decl) {
return false;
}
if (isa<clang::CXXConstructorDecl>(function_decl)) {
return true;
}
return !isa<clang::CXXMethodDecl>(function_decl) &&
function_decl->isOverloadedOperator();
}
} // namespace Carbon::Check
+6
View File
@@ -25,6 +25,12 @@ auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool;
// than as the first argument.
auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool;
// Returns whether the specified instruction refers to a C++ constructor or
// non-operator method. If so, when mapping from a Carbon interface to a C++
// call, we pass a `self` parameter as the first argument instead.
auto IsCppConstructorOrNonMethodOperator(Context& context,
SemIR::InstId inst_id) -> bool;
} // namespace Carbon::Check
#endif // CARBON_TOOLCHAIN_CHECK_CPP_OPERATORS_H_
@@ -162,7 +162,6 @@ auto PerformCppOverloadResolution(Context& context, SemIR::LocId loc_id,
case clang::OverloadingResult::OR_Success: {
CARBON_CHECK(best_viable_fn->Function);
CARBON_CHECK(!best_viable_fn->RewriteKind);
sema.MarkFunctionReferenced(loc, best_viable_fn->Function);
SemIR::InstId result_id = ImportCppFunctionDecl(
context, loc_id, best_viable_fn->Function, arg_exprs.size());
if (auto fn_decl =