Add initial support for exporting generic Carbon functions to C++ (#7462)

This allows C++ to call Carbon functions with generic type parameters,
with some conditions. Example:
```carbon
interface I {
  fn Doit(self);
}
class A {
  impl as I { fn Doit(unused self) {} }
}
class B {
  impl as I { fn Doit(unused self) {} }
}
fn F[T:! I](t: T) {
  t.Doit();
}

inline Cpp '''
void G() {
  Carbon::A a;
  Carbon::B b;
  Carbon::F(a);
  Carbon::F(b);
}
''';
```

The initial support is limited; only explicit parameters are handled
currently.

`CarbonExternalASTSource::GetOrExportFunctionToCpp` now generates a
`clang::FunctionTemplateDecl` for generic Carbon functions. If C++ code
attempts to call that templated function,
`CarbonExternalASTSource::LoadExternalSpecializations` will be called
with the template argument types of that call site. Then we can generate
a specialized thunk for those argument types for C++ to call.
This commit is contained in:
Nicholas Bishop
2026-07-08 00:51:21 +00:00
committed by GitHub
parent eab71802f7
commit c8fdeef911
7 changed files with 1160 additions and 51 deletions
+11 -1
View File
@@ -52,8 +52,18 @@ auto ExportFieldToCpp(Context& context, SemIR::InstId field_inst_id,
SemIR::FieldDecl field_decl) -> clang::FieldDecl*;
// Get a `clang::FunctionDecl` that can be used to call a Carbon function.
// If the function is generic, a `clang::FunctionTemplateDecl` will be
// created instead.
auto ExportFunctionToCpp(Context& context, SemIR::LocId loc_id,
SemIR::FunctionId function_id) -> clang::FunctionDecl*;
SemIR::FunctionId function_id) -> clang::NamedDecl*;
// Creates a C++ function template specialization for a generic Carbon
// function.
//
// Returns true if a specialization was added, false otherwise.
auto ExportFunctionSpecializationToCpp(
Context& context, clang::FunctionTemplateDecl* function_template_decl,
llvm::ArrayRef<clang::TemplateArgument> template_args) -> bool;
// Export a Carbon destructor into C++.
//