Skip to content

Commit ecd62c0

Browse files
committed
[cxx-interop] make sure a const operator [] is imported as a mutable setter
1 parent 7af7f43 commit ecd62c0

File tree

4 files changed

+26
-1
lines changed

4 files changed

+26
-1
lines changed

lib/ClangImporter/ImportDecl.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3560,6 +3560,13 @@ namespace {
35603560
if (parameter->isInOut())
35613561
// Subscripts with inout parameters are not allowed in Swift.
35623562
return nullptr;
3563+
// Subscript setter is marked as mutating in Swift even if the
3564+
// C++ `operator []` is `const`.
3565+
if (importedName.getAccessorKind() ==
3566+
ImportedAccessorKind::SubscriptSetter &&
3567+
!dc->isModuleScopeContext() &&
3568+
!typeDecl->getDeclaredType()->isForeignReferenceType())
3569+
func->setSelfAccessKind(SelfAccessKind::Mutating);
35633570

35643571
auto &getterAndSetter = Impl.cxxSubscripts[{ typeDecl,
35653572
parameterType }];

test/Interop/Cxx/foreign-reference/member-inheritance.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ FunctionsTestSuite.test("base member FRT subscript access") {
4949
FunctionsTestSuite.test("base member FRT subscript accessing reference FRT") {
5050
let copyCounter = getCopyCounter().pointee
5151

52-
let base = makeBaseReturningFRTFromSubscript()!
52+
var base = makeBaseReturningFRTFromSubscript()!
5353
var frt = base[1]
5454
expectEqual(frt.getX(), 1)
5555

test/Interop/Cxx/operators/Inputs/member-inline.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,4 +418,17 @@ struct DerivedFromConstIterator : public ConstIterator {};
418418

419419
struct DerivedFromConstIteratorPrivately : private ConstIterator {};
420420

421+
class SubscriptSetterConst {
422+
public:
423+
using T = int;
424+
425+
SubscriptSetterConst() : p(new T[10]) {}
426+
427+
T& operator[](int i) const {
428+
return p[i];
429+
}
430+
private:
431+
T *p;
432+
};
433+
421434
#endif

test/Interop/Cxx/operators/member-inline.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,4 +378,9 @@ OperatorsTestSuite.test("DerivedFromConstIterator.pointee") {
378378
expectEqual(234, res)
379379
}
380380

381+
OperatorsTestSuite.test("SubscriptSetterConst") {
382+
var setterConst = SubscriptSetterConst()
383+
setterConst[0] = 10
384+
}
385+
381386
runAllTests()

0 commit comments

Comments
 (0)