Use the plain identifier for Carbon names in C++ (#7897)

C++ interop used `GetFormatted` to turn a Carbon name into a C++ name.
For an identifier that is a Carbon keyword, such as `base`,
`GetFormatted` adds an `r#` prefix, so the C++ name came out as `r#base`
instead of `base`. This showed up in three places:

- A failed call to the C++ function `base` was reported as "no matching
function for call to 'r#base'".
- An exported Carbon function was mangled as `_ZN6CarbonL6r#baseEv`
instead of `_ZN6CarbonL4baseEv`.
- Its thunk was named `r#base__carbon_thunk` instead of
`base__carbon_thunk`.

All three now use `GetClangIdentifierInfo`, which `export.cpp` already
uses for other C++ names. The name is always an identifier in these
places: an overload set is only imported by looking up an identifier in
C++, and only functions declared in Carbon are exported, which are
always named by an identifier. So they check for an identifier, as the
export of a class name already does, rather than falling back to
`GetFormatted`. This removes a TODO about naming a `NameId::CppOperator`
overload set, which can't happen: C++ operators are resolved in
`operators.cpp` without an overload set.

Assisted-by: Claude Code
This commit is contained in:
Chandler Carruth authored and GitHub committed 2026-10-05 17:44:20 +00:00
1 parent 8f258eaaa6
commit c1e83b0b78
4 files changed
+124 -11

No files matched your search

+12 -5
View File
@@ -702,16 +702,24 @@ struct FunctionInfo {
return SemIR::TypeId::None;
}
// Get the identifier that names this function. Only functions declared in
// Carbon are exported, and a Carbon declaration always names its function
// with an identifier.
auto GetIdentifier(Context& context) const -> clang::IdentifierInfo* {
auto* identifier_info = GetClangIdentifierInfo(context, function.name_id);
CARBON_CHECK(identifier_info, "non-identifier function name {0}",
function.name_id);
return identifier_info;
}
// Get the clang::DeclarationName of this function's C++ counterpart.
auto GetCppName(Context& context) const -> clang::DeclarationName {
if (export_as_constructor) {
auto* record_decl = cast<clang::CXXRecordDecl>(decl_context);
return context.ast_context().DeclarationNames.getCXXConstructorName(
context.ast_context().getCanonicalTagType(record_decl));
} else {
return &context.ast_context().Idents.get(
context.names().GetFormatted(function.name_id));
}
return GetIdentifier(context);
}
SemIR::FunctionId function_id;
@@ -1300,8 +1308,7 @@ static auto BuildCarbonToCarbonThunk(Context& context, SemIR::LocId loc_id,
std::string_view extra_name = "")
-> FunctionInfo {
// Create the thunk's name.
llvm::SmallString<64> thunk_name =
context.names().GetFormatted(target.function.name_id);
llvm::SmallString<64> thunk_name = target.GetIdentifier(context)->getName();
thunk_name += "__carbon_thunk";
thunk_name += extra_name;
auto& ident = context.ast_context().Idents.get(thunk_name);