Skip to content

Commit 98bbb81

Browse files
committed
[C++] Make const member variables read-only
This imports const members of C++ structs/classes stored properties with an inaccessible setter. Note that in C++ there are ways to change the values of const members, so we don't use `WriteImplKind::Immutable` storage. Resolves: [SR-12463](https://bugs.swift.org/browse/SR-12463)
1 parent 6434890 commit 98bbb81

File tree

5 files changed

+25
-0
lines changed

5 files changed

+25
-0
lines changed

lib/ClangImporter/ImportDecl.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3918,6 +3918,12 @@ namespace {
39183918
/*IsCaptureList*/false,
39193919
Impl.importSourceLoc(decl->getLocation()),
39203920
name, dc);
3921+
if (decl->getType().isConstQualified()) {
3922+
// Note that in C++ there are ways to change the values of const
3923+
// members, so we don't use WriteImplKind::Immutable storage.
3924+
assert(result->supportsMutation());
3925+
result->overwriteSetterAccess(AccessLevel::Private);
3926+
}
39213927
result->setIsObjC(false);
39223928
result->setIsDynamic(false);
39233929
result->setInterfaceType(type);
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
class MyClass {
2+
public:
3+
const int const_member = 23;
4+
};
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module CxxMemberVariables {
2+
header "member-variables.h"
3+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// RUN: %target-swift-ide-test -print-module -module-to-print=CxxMemberVariables -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s
2+
3+
// CHECK: struct MyClass {
4+
// CHECK-NEXT: var const_member: Int32 { get }
5+
// CHECK-NEXT: init()
6+
// CHECK-NEXT: }
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop
2+
3+
import CxxMemberVariables
4+
5+
var s = MyClass()
6+
s.const_member = 42 // expected-error {{cannot assign to property: 'const_member' setter is inaccessible}}

0 commit comments

Comments
 (0)