Skip to content

embedded: add swift_dynamicCastClass runtime function #74332

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 13, 2024
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
14 changes: 14 additions & 0 deletions stdlib/public/core/EmbeddedRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,20 @@ func isValidPointerForNativeRetain(object: Builtin.RawPointer) -> Bool {
public func swift_setDeallocating(object: Builtin.RawPointer) {
}

@_cdecl("swift_dynamicCastClass")
public func swift_dynamicCastClass(object: UnsafeMutableRawPointer, targetMetadata: UnsafeRawPointer) -> UnsafeMutableRawPointer? {
let sourceObj = object.assumingMemoryBound(to: HeapObject.self)
var type = _swift_embedded_get_heap_object_metadata_pointer(sourceObj).assumingMemoryBound(to: ClassMetadata.self)
let targetType = targetMetadata.assumingMemoryBound(to: ClassMetadata.self)
while type != targetType {
guard let superType = type.pointee.superclassMetadata else {
return nil
}
type = UnsafeMutablePointer(superType)
}
return object
}

@_cdecl("swift_isUniquelyReferenced_native")
public func swift_isUniquelyReferenced_native(object: Builtin.RawPointer) -> Bool {
if !isValidPointerForNativeRetain(object: object) { return false }
Expand Down
26 changes: 26 additions & 0 deletions test/embedded/classes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ class MyClass {
}

class MySubClass: MyClass {
var x = 27

override init() { print("MySubClass.init") }
deinit { print("MySubClass.deinit") }
override func foo() { print("MySubClass.foo") }

func printX() {
print(x)
}
}

class MySubSubClass: MySubClass {
Expand All @@ -26,6 +32,17 @@ class MySubSubClass: MySubClass {
override func foo() { print("MySubSubClass.foo") }
}

class OtherSubClass: MyClass {}

func testCasting(_ title: StaticString, _ c: MyClass) {
print(title, terminator: "")
if let s = c as? MySubClass {
s.printX()
} else {
print("-")
}
}

@main
struct Main {
static var o: (MyClass?, MyClass?, MyClass?) = (nil, nil, nil)
Expand Down Expand Up @@ -69,5 +86,14 @@ struct Main {
// CHECK: MySubClass.deinit
// CHECK: MyClass.deinit
print("")

// CHECK: base: -
testCasting("base: ", MyClass())
// CHECK: sub: 27
testCasting("sub: ", MySubClass())
// CHECK: subsub: 27
testCasting("subsub: ", MySubSubClass())
// CHECK: other: -
testCasting("other: ", OtherSubClass())
}
}