Skip to content

[5.9][cxx-interop] add a testcase to verify that 'borrowing' works with co… #66693

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// RUN: rm -rf %t
// RUN: split-file %s %t
// RUN: %target-build-swift %t/test.swift -I %t -o %t/out -Xfrontend -enable-experimental-cxx-interop -O
// RUN: %target-codesign %t/out
// RUN: %target-run %t/out

// Verify that a non-const ref value parameter can't implicitly receive
// aborrowed value.
// RUN: %target-swift-frontend -DBORROW_PASS_TO_VALUE_PARAM -emit-ir -o /dev/null -I %t %t/test.swift -enable-experimental-cxx-interop -verify

//--- Inputs/module.modulemap
module CxxTest {
header "test.h"
requires cplusplus
}

//--- Inputs/test.h

inline int &getCopyCounter() {
static int value = 0;
return value;
}

class BorrowMe {
public:
BorrowMe(): x_(11) {}
BorrowMe(const BorrowMe &) {
++getCopyCounter();
}

const int &x() const { return x_; }
int &x() { return x_; }
private:
int x_;
};

inline int takeBorrowConstRef(const BorrowMe &value) {
return value.x();
}

inline int takeBorrowByVal(BorrowMe value) {
return value.x();
}

//--- test.swift

import CxxTest

extension BorrowMe {
borrowing func getX() -> CInt {
__xUnsafe().pointee
}

var x: CInt {
getX()
}
}

func testBorrowingParam(_ value: borrowing BorrowMe) {
let x = takeBorrowConstRef(value)
assert(x == 11)
#if BORROW_PASS_TO_VALUE_PARAM
takeBorrowByVal(value) // expected-error@-4 {{'value' is borrowed and cannot be consumed}} expected-note {{consumed here}}
takeBorrowByVal(copy value) // ok
#endif
}

public func testBorrowingSafeReferenceUse() {
let x: CInt
do {
let p = BorrowMe()
x = p.x
testBorrowingParam(p)
}
if x != 11 { fatalError("wrong value") }
assert(getCopyCounter().pointee == 0)
}

testBorrowingSafeReferenceUse()