Skip to content

Commit

Permalink
Inherit JSFunction from JSClosure (#239)
Browse files Browse the repository at this point in the history
There is no reason not to make JSClosure to be compatible with
JSFunction. We can treat JSClosure as a JSFunction and call it
from not only JavaScript but also Swift.
  • Loading branch information
kateinoigakukun authored Apr 7, 2024
1 parent 32538ec commit 3e07fdc
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func test(_ name: String, testBlock: () throws -> Void) throws {
print(error)
throw error
}
print("\(name)")
}

struct MessageError: Error {
Expand Down
25 changes: 10 additions & 15 deletions IntegrationTests/TestSuites/Sources/PrimaryTests/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,16 @@ try test("Closure Lifetime") {
}
#endif

do {
let c1 = JSClosure { _ in .number(4) }
try expectEqual(c1(), .number(4))
}

do {
let c1 = JSClosure { _ in fatalError("Crash while closure evaluation") }
let error = try expectThrow(try evalClosure.throws(c1)) as! JSValue
try expectEqual(error.description, "RuntimeError: unreachable")
}
}

try test("Host Function Registration") {
Expand Down Expand Up @@ -420,21 +430,6 @@ try test("ObjectRef Lifetime") {
#endif
}

#if JAVASCRIPTKIT_WITHOUT_WEAKREFS
func closureScope() -> ObjectIdentifier {
let closure = JSClosure { _ in .undefined }
let result = ObjectIdentifier(closure)
closure.release()
return result
}

try test("Closure Identifiers") {
let oid1 = closureScope()
let oid2 = closureScope()
try expectEqual(oid1, oid2)
}
#endif

func checkArray<T>(_ array: [T]) throws where T: TypedArrayElement & Equatable {
try expectEqual(toString(JSTypedArray(array).jsValue.object!), jsStringify(array))
try checkArrayUnsafeBytes(array)
Expand Down
2 changes: 1 addition & 1 deletion Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public class JSOneshotClosure: JSObject, JSClosureProtocol {
/// button.removeEventListener!("click", JSValue.function(eventListenter))
/// ```
///
public class JSClosure: JSObject, JSClosureProtocol {
public class JSClosure: JSFunction, JSClosureProtocol {

// Note: Retain the closure object itself also to avoid funcRef conflicts
fileprivate static var sharedClosures: [JavaScriptHostFuncRef: (object: JSObject, body: ([JSValue]) -> JSValue)] = [:]
Expand Down

0 comments on commit 3e07fdc

Please sign in to comment.