Overload resolution for C++ operators (#6092)

Multiple overloads for the same operator are now resolved using overload
resolution.
This change doesn't try to solve all issues with operator lookup.

Moved the operator lookup logic from `import` to `operators` and changed
it to take the args into account.
Use `Sema::LookupOverloadedBinOp()` (with ADL) when looking up operator
functions to create an overload set.

Verified all demos in #6017, #6020 and #6024 still work.

C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }

 private:
  int value_;
};

class NotMyNumber {};

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator+(NotMyNumber lhs, NotMyNumber rhs) -> NotMyNumber;
```

```c++
// my_number.cpp

#include "my_number.h"

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() + rhs.value());
}

auto operator+(NotMyNumber lhs, NotMyNumber /*rhs*/) -> NotMyNumber {
  return lhs;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  // Arithmetic
  var num1: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  var num2: Cpp.MyNumber = Cpp.MyNumber.MyNumber(5);
  Core.Print(num1.value());
  Core.Print(num2.value());
  Core.Print((num1 + num2).value());

  return 0;
}
```

**After 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
14
5
19
```

**Before this change**

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:14:15: error: semantics TODO: `Unsupported: Lookup succeeded but couldn't find a single result; LookupResultKind: 3`
  Core.Print((num1 + num2).value());
              ^~~~~~~~~~~
main.carbon:14:15: note: in `Cpp` operator `AddWith` lookup
  Core.Print((num1 + num2).value());
              ^~~~~~~~~~~
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
This commit is contained in:
Boaz Brickner
2025-09-19 16:42:46 +00:00
committed by GitHub
parent 05c9fd768e
commit ef488f00fa
10 changed files with 445 additions and 426 deletions
+16 -49
View File
@@ -8,7 +8,7 @@
#include "toolchain/check/call.h"
#include "toolchain/check/context.h"
#include "toolchain/check/cpp/import.h"
#include "toolchain/check/cpp/operators.h"
#include "toolchain/check/generic.h"
#include "toolchain/check/member_access.h"
#include "toolchain/check/name_lookup.h"
@@ -39,35 +39,18 @@ static auto GetOperatorOpFunction(Context& context, SemIR::LocId loc_id,
op_name_id);
}
// If the instruction is a C++ class, returns its parent scope id. Otherwise
// returns `std::nullopt`.
static auto GetCppClassTypeParentScope(Context& context, SemIR::InstId inst_id)
-> std::optional<SemIR::NameScopeId> {
// Returns whether the instruction is a C++ class.
static auto IsCppClassType(Context& context, SemIR::InstId inst_id) -> bool {
auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
context.types().GetInstId(context.insts().Get(inst_id).type_id()));
if (!class_type) {
// Not a class.
return std::nullopt;
return false;
}
const SemIR::Class& class_info = context.classes().Get(class_type->class_id);
if (!class_info.is_complete() ||
!context.name_scopes().Get(class_info.scope_id).is_cpp_scope()) {
// Not a C++ class.
return std::nullopt;
}
SemIR::NameScopeId parent_scope_id = class_info.parent_scope_id;
do {
SemIR::NameScope& scope = context.name_scopes().Get(parent_scope_id);
if (context.insts().Is<SemIR::Namespace>(scope.inst_id())) {
break;
}
parent_scope_id = scope.parent_scope_id();
} while (parent_scope_id.has_value());
return parent_scope_id;
return class_info.is_complete() &&
context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
}
auto BuildUnaryOperator(Context& context, SemIR::LocId loc_id, Operator op,
@@ -78,16 +61,11 @@ auto BuildUnaryOperator(Context& context, SemIR::LocId loc_id, Operator op,
// the C++ operator.
// TODO: Change impl lookup instead. See
// https://github.com/carbon-language/carbon-lang/blob/db0a00d713015436844c55e7ac190a0f95556499/toolchain/check/operator.cpp#L76
// TODO: We should do ADL-only lookup for operators
// (`Sema::ArgumentDependentLookup`), when we support mapping Carbon types
// into C++ types.
auto cpp_parent_scope_id = GetCppClassTypeParentScope(context, operand_id);
if (cpp_parent_scope_id) {
SemIR::ScopeLookupResult cpp_lookup_result =
ImportOperatorFromCpp(context, loc_id, *cpp_parent_scope_id, op);
if (cpp_lookup_result.is_found()) {
return PerformCall(context, loc_id, cpp_lookup_result.target_inst_id(),
{operand_id});
if (IsCppClassType(context, operand_id)) {
SemIR::InstId cpp_inst_id =
LookupCppOperator(context, loc_id, op, {operand_id});
if (cpp_inst_id.has_value() && cpp_inst_id != SemIR::ErrorInst::InstId) {
return PerformCall(context, loc_id, cpp_inst_id, {operand_id});
}
}
@@ -117,22 +95,11 @@ auto BuildBinaryOperator(Context& context, SemIR::LocId loc_id, Operator op,
// https://github.com/carbon-language/carbon-lang/pull/5996/files/5d01fa69511b76f87efbc0387f5e40abcf4c911a#r2308666348
// and
// https://github.com/carbon-language/carbon-lang/pull/5996/files/5d01fa69511b76f87efbc0387f5e40abcf4c911a#r2308664536
// TODO: We should do ADL-only lookup for operators
// (`Sema::ArgumentDependentLookup`), when we support mapping Carbon types
// into C++ types.
llvm::SmallVector<SemIR::NameScopeId, 2> cpp_operand_parent_scope_ids;
for (SemIR::InstId operand_id : {lhs_id, rhs_id}) {
auto cpp_parent_scope_id = GetCppClassTypeParentScope(context, operand_id);
if (!cpp_parent_scope_id || llvm::is_contained(cpp_operand_parent_scope_ids,
*cpp_parent_scope_id)) {
continue;
}
cpp_operand_parent_scope_ids.push_back(*cpp_parent_scope_id);
SemIR::ScopeLookupResult cpp_lookup_result =
ImportOperatorFromCpp(context, loc_id, *cpp_parent_scope_id, op);
if (cpp_lookup_result.is_found()) {
return PerformCall(context, loc_id, cpp_lookup_result.target_inst_id(),
{lhs_id, rhs_id});
if (IsCppClassType(context, lhs_id) || IsCppClassType(context, rhs_id)) {
SemIR::InstId cpp_inst_id =
LookupCppOperator(context, loc_id, op, {lhs_id, rhs_id});
if (cpp_inst_id.has_value() && cpp_inst_id != SemIR::ErrorInst::InstId) {
return PerformCall(context, loc_id, cpp_inst_id, {lhs_id, rhs_id});
}
}