Skip to content

[cxx-interop] make sure a const operator [] is imported as a mutabl… #69781

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
Nov 13, 2023
Merged
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3569,6 +3569,13 @@ namespace {
if (parameter->isInOut())
// Subscripts with inout parameters are not allowed in Swift.
return nullptr;
// Subscript setter is marked as mutating in Swift even if the
// C++ `operator []` is `const`.
if (importedName.getAccessorKind() ==
ImportedAccessorKind::SubscriptSetter &&
!dc->isModuleScopeContext() &&
!typeDecl->getDeclaredType()->isForeignReferenceType())
func->setSelfAccessKind(SelfAccessKind::Mutating);

auto &getterAndSetter = Impl.cxxSubscripts[{ typeDecl,
parameterType }];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ FunctionsTestSuite.test("base member FRT subscript access") {
FunctionsTestSuite.test("base member FRT subscript accessing reference FRT") {
let copyCounter = getCopyCounter().pointee

let base = makeBaseReturningFRTFromSubscript()!
var base = makeBaseReturningFRTFromSubscript()!
var frt = base[1]
expectEqual(frt.getX(), 1)

Expand Down
13 changes: 13 additions & 0 deletions test/Interop/Cxx/operators/Inputs/member-inline.h
Original file line number Diff line number Diff line change
Expand Up @@ -418,4 +418,17 @@ struct DerivedFromConstIterator : public ConstIterator {};

struct DerivedFromConstIteratorPrivately : private ConstIterator {};

class SubscriptSetterConst {
public:
using T = int;

SubscriptSetterConst() : p(new T[10]) {}

T& operator[](int i) const {
return p[i];
}
private:
T *p;
};

#endif
5 changes: 5 additions & 0 deletions test/Interop/Cxx/operators/member-inline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -378,4 +378,9 @@ OperatorsTestSuite.test("DerivedFromConstIterator.pointee") {
expectEqual(234, res)
}

OperatorsTestSuite.test("SubscriptSetterConst") {
var setterConst = SubscriptSetterConst()
setterConst[0] = 10
}

runAllTests()