mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-04 22:02:52 +01:00
C++ Interop: Add support for <<= and >>= (#6325)
C++ Interop Demo:
```c++
// my_number.h
class MyNumber {
public:
explicit MyNumber(int value) : value_(value) {}
auto value() const -> int { return value_; }
auto set_value(int value) -> void { value_ = value; }
private:
int value_;
};
auto operator<<=(MyNumber& lhs, int rhs) -> MyNumber&;
auto operator>>=(MyNumber& lhs, int rhs) -> MyNumber&;
```
```c++
// my_number.cpp
#include "my_number.h"
auto operator<<=(MyNumber& lhs, int rhs) -> MyNumber& {
lhs.set_value(lhs.value() << rhs);
return lhs;
}
auto operator>>=(MyNumber& lhs, int rhs) -> MyNumber& {
lhs.set_value(lhs.value() >> rhs);
return lhs;
}
```
```carbon
// main.carbon
library "Main";
import Core library "io";
import Cpp library "my_number.h";
fn Run() -> i32 {
var num: Cpp.MyNumber = Cpp.MyNumber.MyNumber(3);
Core.Print(num.value());
num <<= 2;
Core.Print(num.value());
num >>= 1;
Core.Print(num.value());
return 0;
}
```
```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
3
12
6
```
Part of https://github.com/carbon-language/carbon-lang/issues/5995.
This commit is contained in:
@@ -125,9 +125,14 @@ static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
|
||||
CARBON_CHECK(op_name == "Op");
|
||||
return clang::OO_CaretEqual;
|
||||
}
|
||||
// TODO: Add support for `LeftShiftAssignWith` (`OO_LessLessEqual`) and
|
||||
// `RightShiftAssignWith` (`OO_GreaterGreaterEqual`) when references are
|
||||
// supported.
|
||||
if (interface_name == "LeftShiftAssignWith") {
|
||||
CARBON_CHECK(op_name == "Op");
|
||||
return clang::OO_LessLessEqual;
|
||||
}
|
||||
if (interface_name == "RightShiftAssignWith") {
|
||||
CARBON_CHECK(op_name == "Op");
|
||||
return clang::OO_GreaterGreaterEqual;
|
||||
}
|
||||
|
||||
// Relational Operators.
|
||||
if (interface_name == "EqWith") {
|
||||
|
||||
Reference in New Issue
Block a user