Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Sources/JavaScriptKit/FundamentalObjects/JSBigInt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@ private var constructor: JSObject { JSObject.global.BigInt.object! }
/// class](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)
/// that exposes its properties in a type-safe and Swifty way.
public final class JSBigInt: JSObject {
@_spi(JSObject_id)
override public init(id: JavaScriptObjectRef) {
super.init(id: id)
override public init(_ ref: consuming JSUniqueRef) {
super.init(ref)
}

/// Instantiate a new `JSBigInt` with given Int64 value in a slow path
/// This doesn't require [JS-BigInt-integration](https://github.com/WebAssembly/JS-BigInt-integration) feature.
public init(_slowBridge value: Int64) {
let value = UInt64(bitPattern: value)
super.init(id: swjs_i64_to_bigint_slow(UInt32(value & 0xffff_ffff), UInt32(value >> 32), true))
let id = swjs_i64_to_bigint_slow(UInt32(value & 0xffff_ffff), UInt32(value >> 32), true)
super.init(JSUniqueRef(adopting: id))
}

/// Instantiate a new `JSBigInt` with given UInt64 value in a slow path
/// This doesn't require [JS-BigInt-integration](https://github.com/WebAssembly/JS-BigInt-integration) feature.
public init(_slowBridge value: UInt64) {
super.init(id: swjs_i64_to_bigint_slow(UInt32(value & 0xffff_ffff), UInt32(value >> 32), false))
let id = swjs_i64_to_bigint_slow(UInt32(value & 0xffff_ffff), UInt32(value >> 32), false)
super.init(JSUniqueRef(adopting: id))
}

override public var jsValue: JSValue {
Expand Down
10 changes: 6 additions & 4 deletions Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ public class JSOneshotClosure: JSObject, JSClosureProtocol {
_ body: @escaping (sending [JSValue]) -> JSValue
) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
super.init(JSUniqueRef(adopting: 0))

// 2. Create a new JavaScript function which calls the given Swift function.
hostFuncRef = JavaScriptHostFuncRef(bitPattern: ObjectIdentifier(self))
_id = withExtendedLifetime(JSString(file)) { file in
let id = withExtendedLifetime(JSString(file)) { file in
swjs_create_oneshot_function(hostFuncRef, line, file.asInternalJSRef())
}
_replacePlaceholderRef(with: id)

// 3. Retain the given body in static storage by `funcRef`.
JSClosure.sharedClosures.wrappedValue[hostFuncRef] = .init(
Expand Down Expand Up @@ -176,13 +177,14 @@ public class JSClosure: JSObject, JSClosureProtocol {
_ body: @escaping (sending [JSValue]) -> JSValue
) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
super.init(JSUniqueRef(adopting: 0))

// 2. Create a new JavaScript function which calls the given Swift function.
hostFuncRef = JavaScriptHostFuncRef(bitPattern: ObjectIdentifier(self))
_id = withExtendedLifetime(JSString(file)) { file in
let id = withExtendedLifetime(JSString(file)) { file in
swjs_create_function(hostFuncRef, line, file.asInternalJSRef())
}
_replacePlaceholderRef(with: id)

// 3. Retain the given body in static storage by `funcRef`.
Self.sharedClosures.wrappedValue[hostFuncRef] = .init(
Expand Down
41 changes: 22 additions & 19 deletions Sources/JavaScriptKit/FundamentalObjects/JSObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,39 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral {
internal static var constructor: JSObject { _constructor.wrappedValue }
private static let _constructor = LazyThreadLocal(initialize: { JSObject.global.Object.object! })

/// The reference this object owns. Releasing it is left to `JSUniqueRef`'s `deinit`.
@usableFromInline
internal var _id: JavaScriptObjectRef
internal var _ref: JSUniqueRef

#if _runtime(_multithreaded)
package let ownerTid: Int32
package var ownerTid: Int32 { _ref.ownerTid }
#endif

@_spi(JSObject_id)
@_spi(BridgeJS)
@inlinable
public var id: JavaScriptObjectRef { _id }
public var id: JavaScriptObjectRef { _ref._id }

/// Creates an object that takes over the reference `ref` owns.
public init(_ ref: consuming JSUniqueRef) {
self._ref = ref
}

/// Creates an object that takes over `id`, a reference the caller owns.
@_spi(JSObject_id)
@_spi(BridgeJS)
public init(id: JavaScriptObjectRef) {
self._id = id
#if _runtime(_multithreaded)
self.ownerTid = swjs_get_worker_thread_id_cached()
#endif
public convenience init(id: JavaScriptObjectRef) {
self.init(JSUniqueRef(adopting: id))
}

/// Replaces a placeholder reference of 0 with `id`, a reference the caller owns.
///
/// For subclasses that need `self` before they can create their JavaScript object.
internal func _replacePlaceholderRef(with id: JavaScriptObjectRef) {
var ref = JSUniqueRef(adopting: id)
swap(&_ref, &ref)
let placeholder = ref.unsafeTake()
assert(placeholder == 0, "replaced a reference other than the placeholder")
}

/// Creates an empty JavaScript object.
Expand Down Expand Up @@ -281,17 +295,6 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral {
JSObject(id: _JS_Predef_Value_Global)
})

deinit {
#if _runtime(_multithreaded)
if ownerTid != swjs_get_worker_thread_id_cached() {
// If the object is not owned by the current thread
swjs_release_remote(ownerTid, id)
return
}
#endif
swjs_release(id)
}

/// Returns a Boolean value indicating whether two values point to same objects, using the `===` operator in JS.
///
/// - Parameters:
Expand Down
6 changes: 3 additions & 3 deletions Sources/JavaScriptKit/FundamentalObjects/JSSymbol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public class JSSymbol: JSObject {
// can’t do `self =` so we have to get the ID manually
let result = Symbol.invokeNonThrowingJSFunction(arguments: [description.jsValue])
precondition(result.kind == .symbol)
super.init(id: UInt32(result.payload1))
super.init(JSUniqueRef(adopting: result.payload1))
}
@_disfavoredOverload
public convenience init(_ description: String) {
self.init(JSString(description))
}

override init(id: JavaScriptObjectRef) {
super.init(id: id)
override public init(_ ref: consuming JSUniqueRef) {
super.init(ref)
}

@available(*, unavailable, message: "JSSymbol does not support dictionary literal initialization")
Expand Down
60 changes: 60 additions & 0 deletions Sources/JavaScriptKit/FundamentalObjects/JSUniqueRef.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import _CJavaScriptKit

/// Owns one reference to a JavaScript value and releases it when destroyed.
///
/// Unlike ``JSObject``, a `JSUniqueRef` is a noncopyable value, so owning a reference
/// costs no Swift heap allocation or reference counting.
@frozen public struct JSUniqueRef: ~Copyable {
@usableFromInline
internal let _id: JavaScriptObjectRef

#if _runtime(_multithreaded)
@usableFromInline
internal let ownerTid: Int32
#endif

@_spi(BridgeJS)
@inlinable
public var id: JavaScriptObjectRef {
#if _runtime(_multithreaded)
precondition(
ownerTid == swjs_get_worker_thread_id_cached(),
"JSUniqueRef is being used on a thread other than the one that created it"
)
#endif
return _id
}

/// Takes over a reference the caller owns.
@_spi(BridgeJS)
@inlinable
public init(adopting id: JavaScriptObjectRef) {
self._id = id
#if _runtime(_multithreaded)
self.ownerTid = swjs_get_worker_thread_id_cached()
#endif
}

/// Returns the reference without releasing it. The caller becomes its owner.
@_spi(BridgeJS)
@inlinable
public consuming func unsafeTake() -> JavaScriptObjectRef {
let id = self.id
discard self
return id
}

deinit {
#if _runtime(_multithreaded)
if ownerTid != swjs_get_worker_thread_id_cached() {
swjs_release_remote(ownerTid, _id)
return
}
#endif
swjs_release(_id)
}
}

/// The reference is valid only on the thread that created it.
@available(*, unavailable)
extension JSUniqueRef: Sendable {}
44 changes: 44 additions & 0 deletions Tests/JavaScriptKitTests/JSUniqueRefTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
@_spi(BridgeJS) import JavaScriptKit
import Testing

@_extern(wasm, module: "JavaScriptKitTests", name: "retainNew")
@_extern(c)
private func retainNew(_ ref: Int32) -> Int32

@_extern(wasm, module: "JavaScriptKitTests", name: "isLive")
@_extern(c)
private func isLive(_ ref: Int32) -> Bool

@Suite struct JSUniqueRefTests {
@Test func droppingReleasesTheReference() {
let ref = Self.uniqueRef(to: JSObject())
let id = ref.id
#expect(isLive(Int32(bitPattern: id)))
_ = consume ref
#expect(!isLive(Int32(bitPattern: id)))
}

@Test func unsafeTakeKeepsTheReference() {
let ref = Self.uniqueRef(to: JSObject())
let id = ref.unsafeTake()
#expect(isLive(Int32(bitPattern: id)))
_ = JSUniqueRef(adopting: id)
#expect(!isLive(Int32(bitPattern: id)))
}

@Test func convertingToJSObjectTakesOverTheReference() {
let object = JSObject()
let ref = Self.uniqueRef(to: object)
let id = ref.id
var converted: JSObject? = JSObject(ref)
#expect(converted!.id == id)
#expect(converted! == object)
converted = nil
#expect(!isLive(Int32(bitPattern: id)))
#expect(isLive(Int32(bitPattern: object.id)))
}

private static func uniqueRef(to object: JSObject) -> JSUniqueRef {
JSUniqueRef(adopting: .init(bitPattern: retainNew(Int32(bitPattern: object.id))))
}
}
12 changes: 12 additions & 0 deletions Tests/prelude.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,18 @@ export async function setupOptions(options, context) {
importObject["JavaScriptEventLoopTestSupportTests"] = {
"isMainThread": () => context.isMainThread,
}
importObject["JavaScriptKitTests"] = {
// Returns a new reference, owned by the caller, to the value `ref` references.
"retainNew": (ref) => _swift.memory.retain(_swift.memory.getObject(ref)),
"isLive": (ref) => {
try {
_swift.memory.getObject(ref);
return true;
} catch {
return false;
}
},
};
const bridgeJSRuntimeTests = importObject["BridgeJSRuntimeTests"] || {};
bridgeJSRuntimeTests["runJsWorks"] = () => {
const exports = getExports();
Expand Down
Loading