mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 22:02:23 +01:00
C++ interop: Support importing operators defined in namespaces (#6024)
C++ Interop Demo:
```c++
// my_number.h
namespace MyNamespace {
class MyNumber {
public:
explicit MyNumber(int value) : value_(value) {}
auto value() const -> int { return value_; }
private:
int value_;
};
auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber;
} // namespace MyNamespace
```
```c++
// my_number.cpp
#include "my_number.h"
namespace MyNamespace {
auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber {
return MyNumber(lhs.value() + rhs.value());
}
} // namespace MyNamespace
```
```carbon
// main.carbon
library "Main";
import Core library "io";
import Cpp library "my_number.h";
fn Run() -> i32 {
let n1: Cpp.MyNamespace.MyNumber = Cpp.MyNamespace.MyNumber.MyNumber(5);
Core.Print(n1.value());
let n2: Cpp.MyNamespace.MyNumber = Cpp.MyNamespace.MyNumber.MyNumber(7);
Core.Print(n2.value());
let n3: Cpp.MyNamespace.MyNumber = n1 + n2;
Core.Print(n3.value());
return 0;
}
```
Before this change:
```
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:13:38: error: cannot access member of interface `Core.AddWith(Cpp.MyNamespace.MyNumber)` in type `Cpp.MyNamespace.MyNumber` that does not implement that interface
let n3: Cpp.MyNamespace.MyNumber = n1 + n2;
^~~~~~~
```
With this change:
```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
5
7
12
```
Part of https://github.com/carbon-language/carbon-lang/issues/5995.
This commit is contained in:
@@ -2211,7 +2211,8 @@ static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto ImportOperatorFromCpp(Context& context, SemIR::LocId loc_id, Operator op)
|
||||
auto ImportOperatorFromCpp(Context& context, SemIR::LocId loc_id,
|
||||
SemIR::NameScopeId scope_id, Operator op)
|
||||
-> SemIR::ScopeLookupResult {
|
||||
Diagnostics::AnnotationScope annotate_diagnostics(
|
||||
&context.emitter(), [&](auto& builder) {
|
||||
@@ -2231,7 +2232,7 @@ auto ImportOperatorFromCpp(Context& context, SemIR::LocId loc_id, Operator op)
|
||||
// into C++ types. See
|
||||
// https://github.com/carbon-language/carbon-lang/pull/5996/files/5d01fa69511b76f87efbc0387f5e40abcf4c911a#r2316950123
|
||||
auto decl_and_access = ClangLookupDeclarationName(
|
||||
context, loc_id, SemIR::NameScopeId::None,
|
||||
context, loc_id, scope_id,
|
||||
context.ast_context().DeclarationNames.getCXXOperatorName(*op_kind));
|
||||
|
||||
if (!decl_and_access) {
|
||||
|
||||
Reference in New Issue
Block a user