From 2f814865ea0dc3a97208a388d2730476ec98fe67 Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Sun, 18 Feb 2018 10:36:41 +0000 Subject: [PATCH 01/47] Initial commit --- .gitignore | 4 + Package.swift | 37 ++++++ README.md | 30 +++++ Sources/CJavaScriptCore/dumb.c | 0 Sources/CJavaScriptCore/include/include.h | 16 +++ .../CJavaScriptCore/include/module.modulemap | 15 +++ Sources/JavaScriptCore/JSContext.swift | 118 +++++++++++++++++ Sources/JavaScriptCore/JSError.swift | 24 ++++ Sources/JavaScriptCore/JSValue.swift | 120 ++++++++++++++++++ Sources/JavaScriptCore/shims.swift | 85 +++++++++++++ Tests/JavaScriptCoreTests/JSValueTests.swift | 34 +++++ .../JavaScriptCoreTests.swift | 108 ++++++++++++++++ .../JavaScriptCoreTests/XCTestManifests.swift | 26 ++++ Tests/LinuxMain.swift | 8 ++ 14 files changed, 625 insertions(+) create mode 100644 .gitignore create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/CJavaScriptCore/dumb.c create mode 100644 Sources/CJavaScriptCore/include/include.h create mode 100644 Sources/CJavaScriptCore/include/module.modulemap create mode 100644 Sources/JavaScriptCore/JSContext.swift create mode 100644 Sources/JavaScriptCore/JSError.swift create mode 100644 Sources/JavaScriptCore/JSValue.swift create mode 100644 Sources/JavaScriptCore/shims.swift create mode 100644 Tests/JavaScriptCoreTests/JSValueTests.swift create mode 100644 Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift create mode 100644 Tests/JavaScriptCoreTests/XCTestManifests.swift create mode 100644 Tests/LinuxMain.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02c0875 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..270201d --- /dev/null +++ b/Package.swift @@ -0,0 +1,37 @@ +// swift-tools-version:4.0 +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import PackageDescription + +let package = Package( + name: "JavaScript", + products: [ + .library( + name: "JavaScriptCore", + targets: ["JavaScriptCore"]) + ], + dependencies: [ + .package( + url: "https://github.com/tris-foundation/test.git", + .branch("master")) + ], + targets: [ + .target( + name: "CJavaScriptCore", + dependencies: []), + .target( + name: "JavaScriptCore", + dependencies: ["CJavaScriptCore"]), + .testTarget( + name: "JavaScriptCoreTests", + dependencies: ["Test", "JavaScriptCore"]) + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..8b4b82a --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +# JavaScript + +Linux version of JavaScriptCore written in Swift with closure support. + +## Requirements + +```bash +apt install libjavascriptcoregtk-1.0-dev +``` + +## Package.swift + +```swift +.package(url: "https://github.com/tris-foundation/javascript.git", .branch("master")) +``` + +## Usage + +```swift +let context = JSContext() +try context.evaluate("40 + 2") + +try context.createFunction(name: "getResult") { + return .string("result string") +} +let result = try context.evaluate("getResult()") +assertTrue(result.isString) +assertEqual(try result.toString(), "result string") +assertEqual("\(result)", "result string") +``` diff --git a/Sources/CJavaScriptCore/dumb.c b/Sources/CJavaScriptCore/dumb.c new file mode 100644 index 0000000..e69de29 diff --git a/Sources/CJavaScriptCore/include/include.h b/Sources/CJavaScriptCore/include/include.h new file mode 100644 index 0000000..f05d9e2 --- /dev/null +++ b/Sources/CJavaScriptCore/include/include.h @@ -0,0 +1,16 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +#ifndef __JAVASCRIPTCORE_H__ +#define __JAVASCRIPTCORE_H__ + +#include + +#endif diff --git a/Sources/CJavaScriptCore/include/module.modulemap b/Sources/CJavaScriptCore/include/module.modulemap new file mode 100644 index 0000000..85ec74f --- /dev/null +++ b/Sources/CJavaScriptCore/include/module.modulemap @@ -0,0 +1,15 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +module CJavaScriptCore [system] { + header "include.h" + link "javascriptcoregtk-1.0" + export * +} diff --git a/Sources/JavaScriptCore/JSContext.swift b/Sources/JavaScriptCore/JSContext.swift new file mode 100644 index 0000000..e60b4cf --- /dev/null +++ b/Sources/JavaScriptCore/JSContext.swift @@ -0,0 +1,118 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import CJavaScriptCore +import struct Foundation.URL + +public class JSContext { + let group: JSContextGroupRef + let context: JSGlobalContextRef + var exception: JSObjectRef? = nil + + var global: JSObjectRef { + return JSContextGetGlobalObject(context)! + } + + public init() { + guard let group = JSContextGroupCreate(), + let context = JSGlobalContextCreateInGroup(group, nil) else { + fatalError("can't create context") + } + + self.group = group + self.context = context + } + + deinit { + JSGlobalContextRelease(context) + JSContextGroupRelease(group) + } + + @discardableResult + public func evaluate( + _ script: String, + source: String? = nil + ) throws -> JSValue { + let file = JSStringCreateWithUTF8CString(source) + let script = JSStringCreateWithUTF8CString(script) + defer { + JSStringRelease(file) + JSStringRelease(script) + } + let result = try JSEvaluateScript(context, script, global, file, 0) + return JSValue(context: context, pointer: result) + } + + @discardableResult + public func createFunction( + name: String, + callback: @escaping JSObjectCallAsFunctionCallback + ) throws -> JSObjectRef { + let name = JSStringCreateWithUTF8CString(name) + defer { JSStringRelease(name) } + let function = JSObjectMakeFunctionWithCallback(context, name, callback) + try JSObjectSetProperty(context, global, name, function, .none) + return function! + } +} + +// MARK: register swift closure as javascript function + +public enum ReturnValue { + case undefined + case null + case bool(Bool) + case number(Double) + case string(String) +} + +var functions: [OpaquePointer: [OpaquePointer: () throws -> ReturnValue]] = [:] + +extension JSContext { + public func createFunction( + name: String, + _ body: @escaping () throws -> ReturnValue + ) throws { + let function = try createFunction(name: name, callback: wrapper) + functions[global, default: [:]][function] = body + } +} + +func wrapper( + ctx: JSContextRef!, + function: JSObjectRef!, + thisObject: JSObjectRef!, + argumentCount: Int, + arguments: UnsafePointer?, + exception: UnsafeMutablePointer? +) -> JSValueRef? { + guard let body = functions[thisObject]?[function] else { + if let exception = exception { + let error = "swift error: unregistered function" + exception.pointee = JSValue(string: error, in: thisObject).pointer + } + return nil + } + do { + let result = try body() + switch result { + case .undefined: return JSValueMakeUndefined(ctx) + case .null: return JSValueMakeNull(ctx) + case .bool(let value): return JSValueMakeBoolean(ctx, value) + case .number(let value): return JSValueMakeNumber(ctx, value) + case .string(let value): return JSValue(string: value, in: ctx).pointer + } + } catch { + if let exception = exception { + exception.pointee = JSValue(string: "\(error)", in: ctx).pointer + } + return nil + } +} diff --git a/Sources/JavaScriptCore/JSError.swift b/Sources/JavaScriptCore/JSError.swift new file mode 100644 index 0000000..58e44d2 --- /dev/null +++ b/Sources/JavaScriptCore/JSError.swift @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import CJavaScriptCore + +public struct JSError: Error, CustomStringConvertible { + public var description: String + + init(context: JSContextRef, pointer: JSValueRef) { + let value = JSValue(context: context, pointer: pointer) + do { + self.description = try value.toString() + } catch { + self.description = "\(error)" + } + } +} diff --git a/Sources/JavaScriptCore/JSValue.swift b/Sources/JavaScriptCore/JSValue.swift new file mode 100644 index 0000000..834f3b3 --- /dev/null +++ b/Sources/JavaScriptCore/JSValue.swift @@ -0,0 +1,120 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import CJavaScriptCore + +public class JSValue { + let context: JSContextRef + let pointer: JSValueRef + + init(context: JSContextRef, pointer: JSValueRef) { + self.context = context + self.pointer = pointer + } + + init(undefinedIn context: JSContextRef) { + self.context = context + self.pointer = JSValueMakeUndefined(context) + } + + init(bool: Bool, in context: JSContextRef) { + self.context = context + self.pointer = JSValueMakeBoolean(context, bool) + } + + init(number: Double, in context: JSContextRef) { + self.context = context + self.pointer = JSValueMakeNumber(context, number) + } + + init(string: String, in context: JSContextRef) { + self.context = context + let bytes = [UInt16](string.utf16) + let stringRef = JSStringCreateWithCharacters(bytes, bytes.count) + self.pointer = JSValueMakeString(context, stringRef) + } +} + +extension JSValue { + convenience + public init(undefinedIn context: JSContext) { + self.init(undefinedIn: context.context) + } + + convenience + public init(bool: Bool, in context: JSContext) { + self.init(bool: bool, in: context.context) + } + + convenience + public init(number: Double, in context: JSContext) { + self.init(number: number, in: context.context) + } + + convenience + public init(string: String, in context: JSContext) { + self.init(string: string, in: context.context) + } +} + +extension JSValue { + public var isNull: Bool { + return JSValueIsNull(context, pointer) + } + + public var isUndefined: Bool { + return JSValueIsUndefined(context, pointer) + } + + public var isBool: Bool { + return JSValueIsBoolean(context, pointer) + } + + public var isNumber: Bool { + return JSValueIsNumber(context, pointer) + } + + public var isString: Bool { + return JSValueIsString(context, pointer) + } +} + +extension JSValue { + public func toBool() -> Bool { + return JSValueToBoolean(context, pointer) + } + + public func toDouble() throws -> Double { + return try JSValueToNumber(context, pointer) + } + + public func toInt() throws -> Int { + return Int(try JSValueToNumber(context, pointer)) + } + + public func toString() throws -> String { + let stringRef = try JSValueToStringCopy(context, pointer) + defer { JSStringRelease(stringRef) } + let len = JSStringGetLength(stringRef) + let characters = JSStringGetCharactersPtr(stringRef) + let buffer = UnsafeBufferPointer(start: characters!, count: len) + return String(decoding: buffer, as: UTF16.self) + } +} + +extension JSValue: CustomStringConvertible { + public var description: String { + do { + return try toString() + } catch { + return "unknown" + } + } +} diff --git a/Sources/JavaScriptCore/shims.swift b/Sources/JavaScriptCore/shims.swift new file mode 100644 index 0000000..d6558b8 --- /dev/null +++ b/Sources/JavaScriptCore/shims.swift @@ -0,0 +1,85 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import CJavaScriptCore + +public func JSValueToStringCopy( + _ ctx: JSContextRef, + _ value: JSValueRef +) throws -> JSStringRef { + var exception: JSValueRef? = nil + let result = JSValueToStringCopy(ctx, value, &exception) + if let exception = exception { + throw JSError(context: ctx, pointer: exception) + } + return result! +} + +public func JSValueToNumber( + _ ctx: JSContextRef, + _ value: JSValueRef +) throws -> Double { + var exception: JSValueRef? = nil + let result = JSValueToNumber(ctx, value, &exception) + if let exception = exception { + throw JSError(context: ctx, pointer: exception) + } + return result +} + +@discardableResult +public func JSEvaluateScript( + _ ctx: JSContextRef!, + _ script: JSStringRef!, + _ thisObject: JSObjectRef!, + _ sourceURL: JSStringRef!, + _ startingLineNumber: Int32 +) throws -> JSValueRef { + var exception: JSValueRef? = nil + let result = JSEvaluateScript( + ctx, script, thisObject, sourceURL, startingLineNumber, &exception) + if let exception = exception { + // FIXME: Exited with signal code 11 + throw JSError(context: ctx, pointer: exception) + } + return result! +} + +public struct JSPropertyAttributes: OptionSet { + public let rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// Specifies that a property has no special attributes. + static let none = JSPropertyAttributes(rawValue: UInt32(kJSPropertyAttributeNone)) + /// Specifies that a property is read-only. + static let readOnly = JSPropertyAttributes(rawValue: UInt32(kJSPropertyAttributeNone)) + /// Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops. + static let dontEnum = JSPropertyAttributes(rawValue: UInt32(kJSPropertyAttributeNone)) + /// Specifies that the delete operation should fail on a property. + static let dontDelete = JSPropertyAttributes(rawValue: UInt32(kJSPropertyAttributeNone)) +} + +public func JSObjectSetProperty( + _ ctx: JSContextRef!, + _ object: JSObjectRef!, + _ propertyName: JSStringRef!, + _ value: JSValueRef!, + _ attributes: JSPropertyAttributes +) throws { + var exception: JSValueRef? = nil + JSObjectSetProperty( + ctx, object, propertyName, value, attributes.rawValue, &exception) + if let exception = exception { + throw JSError(context: ctx, pointer: exception) + } +} diff --git a/Tests/JavaScriptCoreTests/JSValueTests.swift b/Tests/JavaScriptCoreTests/JSValueTests.swift new file mode 100644 index 0000000..0ba1956 --- /dev/null +++ b/Tests/JavaScriptCoreTests/JSValueTests.swift @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import Test +@testable import JavaScriptCore + +final class JSValueTests: TestCase { + func testToInt() { + do { + let context = JSContext() + let result = try context.evaluate("40 + 2") + assertEqual(try result.toInt(), 42) + } catch { + fail(String(describing: error)) + } + } + + func testToString() { + do { + let context = JSContext() + let result = try context.evaluate("40 + 2") + assertEqual(try result.toString(), "42") + } catch { + fail(String(describing: error)) + } + } +} diff --git a/Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift b/Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift new file mode 100644 index 0000000..ac780fb --- /dev/null +++ b/Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift @@ -0,0 +1,108 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import Test +@testable import JavaScriptCore + +final class JavaScriptCoreTests: TestCase { + func testEvaluate() { + let context = JSContext() + assertNoThrow(try context.evaluate("40 + 2")) + } + + func testException() { + let context = JSContext() + assertThrowsError(try context.evaluate("x()")) { error in + assertEqual("\(error)", "ReferenceError: Can't find variable: x") + } + } + + func testFunction() { + do { + let context = JSContext() + try context.createFunction(name: "test") { ctx, _, _, _, _, _ in + return JSValue(string: "success", in: ctx!).pointer + } + let result = try context.evaluate("test()") + assertEqual(try result.toString(), "success") + } catch { + fail(String(describing: error)) + } + } + + func testClosure() { + do { + let context = JSContext() + + + var captured = false + try context.createFunction(name: "testUndefined") { + captured = true + return .undefined + } + let undefinedResult = try context.evaluate("testUndefined()") + assertTrue(captured) + assertTrue(undefinedResult.isUndefined) + assertFalse(undefinedResult.isNull) + assertFalse(undefinedResult.isBool) + assertFalse(undefinedResult.isNumber) + assertFalse(undefinedResult.isString) + assertEqual(try undefinedResult.toString(), "undefined") + + + try context.createFunction(name: "testNull") { + return .null + } + let nullResult = try context.evaluate("testNull()") + assertFalse(nullResult.isUndefined) + assertTrue(nullResult.isNull) + assertFalse(nullResult.isBool) + assertFalse(nullResult.isNumber) + assertFalse(nullResult.isString) + assertEqual(try nullResult.toString(), "null") + + + try context.createFunction(name: "testBool") { + return .bool(true) + } + let boolResult = try context.evaluate("testBool()") + assertFalse(boolResult.isUndefined) + assertFalse(boolResult.isNull) + assertTrue(boolResult.isBool) + assertFalse(boolResult.isNumber) + assertFalse(boolResult.isString) + assertEqual(boolResult.toBool(), true) + + try context.createFunction(name: "testNumber") { + return .number(3.14) + } + let numberResult = try context.evaluate("testNumber()") + assertFalse(numberResult.isUndefined) + assertFalse(numberResult.isNull) + assertFalse(numberResult.isBool) + assertTrue(numberResult.isNumber) + assertFalse(numberResult.isString) + assertEqual(try numberResult.toDouble(), 3.14) + + try context.createFunction(name: "testString") { + return .string("success") + } + let stringResult = try context.evaluate("testString()") + assertFalse(stringResult.isUndefined) + assertFalse(stringResult.isNull) + assertFalse(stringResult.isBool) + assertFalse(stringResult.isNumber) + assertTrue(stringResult.isString) + assertEqual(try stringResult.toString(), "success") + } catch { + fail(String(describing: error)) + } + } +} diff --git a/Tests/JavaScriptCoreTests/XCTestManifests.swift b/Tests/JavaScriptCoreTests/XCTestManifests.swift new file mode 100644 index 0000000..8ba4bd3 --- /dev/null +++ b/Tests/JavaScriptCoreTests/XCTestManifests.swift @@ -0,0 +1,26 @@ +import XCTest + +extension JSValueTests { + static let __allTests = [ + ("testToInt", testToInt), + ("testToString", testToString), + ] +} + +extension JavaScriptCoreTests { + static let __allTests = [ + ("testClosure", testClosure), + ("testEvaluate", testEvaluate), + ("testException", testException), + ("testFunction", testFunction), + ] +} + +#if !os(macOS) +public func __allTests() -> [XCTestCaseEntry] { + return [ + testCase(JSValueTests.__allTests), + testCase(JavaScriptCoreTests.__allTests), + ] +} +#endif diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift new file mode 100644 index 0000000..5d0b0ab --- /dev/null +++ b/Tests/LinuxMain.swift @@ -0,0 +1,8 @@ +import XCTest + +import JavaScriptCoreTests + +var tests = [XCTestCaseEntry]() +tests += JavaScriptCoreTests.__allTests() + +XCTMain(tests) From 1f7f7b4fdc91cf3bfa9aef2b75cc092d3797b39b Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Sun, 18 Feb 2018 10:48:20 +0000 Subject: [PATCH 02/47] [FIXME] Bundle header files to omit extra build args and support dev on macOS --- .../include/JavaScriptCore/JSBase.h | 151 ++++ .../include/JavaScriptCore/JSContextRef.h | 158 ++++ .../include/JavaScriptCore/JSObjectRef.h | 694 ++++++++++++++++++ .../include/JavaScriptCore/JSStringRef.h | 145 ++++ .../include/JavaScriptCore/JSValueRef.h | 301 ++++++++ .../include/JavaScriptCore/JavaScript.h | 36 + .../JavaScriptCore/WebKitAvailability.h | 36 + 7 files changed, 1521 insertions(+) create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JSBase.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JSContextRef.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JSObjectRef.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JSStringRef.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JSValueRef.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/JavaScript.h create mode 100644 Sources/CJavaScriptCore/include/JavaScriptCore/WebKitAvailability.h diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JSBase.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JSBase.h new file mode 100644 index 0000000..153d359 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JSBase.h @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSBase_h +#define JSBase_h + +#ifndef __cplusplus +#include +#endif + +#ifdef __OBJC__ +#import +#endif + +/* JavaScript engine interface */ + +/*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */ +typedef const struct OpaqueJSContextGroup* JSContextGroupRef; + +/*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */ +typedef const struct OpaqueJSContext* JSContextRef; + +/*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */ +typedef struct OpaqueJSContext* JSGlobalContextRef; + +/*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */ +typedef struct OpaqueJSString* JSStringRef; + +/*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */ +typedef struct OpaqueJSClass* JSClassRef; + +/*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */ +typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef; + +/*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */ +typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef; + + +/* JavaScript data types */ + +/*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */ +typedef const struct OpaqueJSValue* JSValueRef; + +/*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */ +typedef struct OpaqueJSValue* JSObjectRef; + +/* JavaScript symbol exports */ +/* These rules should stay the same as in WebKit2/Shared/API/c/WKBase.h */ + +#undef JS_EXPORT +#if defined(JS_NO_EXPORT) +#define JS_EXPORT +#elif defined(__GNUC__) && !defined(__CC_ARM) && !defined(__ARMCC__) +#define JS_EXPORT __attribute__((visibility("default"))) +#elif defined(WIN32) || defined(_WIN32) || defined(_WIN32_WCE) || defined(__CC_ARM) || defined(__ARMCC__) +#if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore) +#define JS_EXPORT __declspec(dllexport) +#else +#define JS_EXPORT __declspec(dllimport) +#endif +#else /* !defined(JS_NO_EXPORT) */ +#define JS_EXPORT +#endif /* defined(JS_NO_EXPORT) */ + +/* JS tests uses WTF but has no config.h, so we need to set the export defines here. */ +#ifndef WTF_EXPORT_PRIVATE +#define WTF_EXPORT_PRIVATE JS_EXPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Script Evaluation */ + +/*! +@function JSEvaluateScript +@abstract Evaluates a string of JavaScript. +@param ctx The execution context to use. +@param script A JSString containing the script to evaluate. +@param thisObject The object to use as "this," or NULL to use the global object as "this." +@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. +@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The JSValue that results from evaluating script, or NULL if an exception is thrown. +*/ +JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); + +/*! +@function JSCheckScriptSyntax +@abstract Checks for syntax errors in a string of JavaScript. +@param ctx The execution context to use. +@param script A JSString containing the script to check for syntax errors. +@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. +@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1. +@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception. +@result true if the script is syntactically correct, otherwise false. +*/ +JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); + +/*! +@function JSGarbageCollect +@abstract Performs a JavaScript garbage collection. +@param ctx The execution context to use. +@discussion JavaScript values that are on the machine stack, in a register, + protected by JSValueProtect, set as the global object of an execution context, + or reachable from any such value will not be collected. + + During JavaScript execution, you are not required to call this function; the + JavaScript engine will garbage collect as needed. JavaScript values created + within a context group are automatically destroyed when the last reference + to the context group is released. +*/ +JS_EXPORT void JSGarbageCollect(JSContextRef ctx); + +#ifdef __cplusplus +} +#endif + +/* Enable the Objective-C API for platforms with a modern runtime. */ +#if !defined(JSC_OBJC_API_ENABLED) +#ifndef JSC_OBJC_API_AVAILABLE_MAC_OS_X_1080 +#define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE))) +#else +#define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE))) +#endif +#endif + +#endif /* JSBase_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JSContextRef.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JSContextRef.h new file mode 100644 index 0000000..c8db1e5 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JSContextRef.h @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSContextRef_h +#define JSContextRef_h + +#include +#include +#include + +#ifndef __cplusplus +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*! +@function +@abstract Creates a JavaScript context group. +@discussion A JSContextGroup associates JavaScript contexts with one another. + Contexts in the same group may share and exchange JavaScript objects. Sharing and/or exchanging + JavaScript objects between contexts in different groups will produce undefined behavior. + When objects from the same context group are used in multiple threads, explicit + synchronization is required. +@result The created JSContextGroup. +*/ +JS_EXPORT JSContextGroupRef JSContextGroupCreate() CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Retains a JavaScript context group. +@param group The JSContextGroup to retain. +@result A JSContextGroup that is the same as group. +*/ +JS_EXPORT JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Releases a JavaScript context group. +@param group The JSContextGroup to release. +*/ +JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Creates a global JavaScript execution context. +@discussion JSGlobalContextCreate allocates a global object and populates it with all the + built-in JavaScript objects, such as Object, Function, String, and Array. + + In WebKit version 4.0 and later, the context is created in a unique context group. + Therefore, scripts may execute in it concurrently with scripts executing in other contexts. + However, you may not use values created in the context in other contexts. +@param globalObjectClass The class to use when creating the global object. Pass + NULL to use the default object class. +@result A JSGlobalContext with a global object of class globalObjectClass. +*/ +JS_EXPORT JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass) CF_AVAILABLE(10_5, 7_0); + +/*! +@function +@abstract Creates a global JavaScript execution context in the context group provided. +@discussion JSGlobalContextCreateInGroup allocates a global object and populates it with + all the built-in JavaScript objects, such as Object, Function, String, and Array. +@param globalObjectClass The class to use when creating the global object. Pass + NULL to use the default object class. +@param group The context group to use. The created global context retains the group. + Pass NULL to create a unique group for the context. +@result A JSGlobalContext with a global object of class globalObjectClass and a context + group equal to group. +*/ +JS_EXPORT JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass) CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Retains a global JavaScript execution context. +@param ctx The JSGlobalContext to retain. +@result A JSGlobalContext that is the same as ctx. +*/ +JS_EXPORT JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx); + +/*! +@function +@abstract Releases a global JavaScript execution context. +@param ctx The JSGlobalContext to release. +*/ +JS_EXPORT void JSGlobalContextRelease(JSGlobalContextRef ctx); + +/*! +@function +@abstract Gets the global object of a JavaScript execution context. +@param ctx The JSContext whose global object you want to get. +@result ctx's global object. +*/ +JS_EXPORT JSObjectRef JSContextGetGlobalObject(JSContextRef ctx); + +/*! +@function +@abstract Gets the context group to which a JavaScript execution context belongs. +@param ctx The JSContext whose group you want to get. +@result ctx's group. +*/ +JS_EXPORT JSContextGroupRef JSContextGetGroup(JSContextRef ctx) CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Gets the global context of a JavaScript execution context. +@param ctx The JSContext whose global context you want to get. +@result ctx's global context. +*/ +JS_EXPORT JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx) CF_AVAILABLE(10_7, 7_0); + +/*! +@function +@abstract Gets a copy of the name of a context. +@param ctx The JSGlobalContext whose name you want to get. +@result The name for ctx. +@discussion A JSGlobalContext's name is exposed for remote debugging to make it +easier to identify the context you would like to attach to. +*/ +JS_EXPORT JSStringRef JSGlobalContextCopyName(JSGlobalContextRef ctx); + +/*! +@function +@abstract Sets the remote debugging name for a context. +@param ctx The JSGlobalContext that you want to name. +@param name The remote debugging name to set on ctx. +*/ +JS_EXPORT void JSGlobalContextSetName(JSGlobalContextRef ctx, JSStringRef name); + +#ifdef __cplusplus +} +#endif + +#endif /* JSContextRef_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JSObjectRef.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JSObjectRef.h new file mode 100644 index 0000000..5e7fd69 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JSObjectRef.h @@ -0,0 +1,694 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSObjectRef_h +#define JSObjectRef_h + +#include +#include +#include + +#ifndef __cplusplus +#include +#endif +#include /* for size_t */ + +#ifdef __cplusplus +extern "C" { +#endif + +/*! +@enum JSPropertyAttribute +@constant kJSPropertyAttributeNone Specifies that a property has no special attributes. +@constant kJSPropertyAttributeReadOnly Specifies that a property is read-only. +@constant kJSPropertyAttributeDontEnum Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops. +@constant kJSPropertyAttributeDontDelete Specifies that the delete operation should fail on a property. +*/ +enum { + kJSPropertyAttributeNone = 0, + kJSPropertyAttributeReadOnly = 1 << 1, + kJSPropertyAttributeDontEnum = 1 << 2, + kJSPropertyAttributeDontDelete = 1 << 3 +}; + +/*! +@typedef JSPropertyAttributes +@abstract A set of JSPropertyAttributes. Combine multiple attributes by logically ORing them together. +*/ +typedef unsigned JSPropertyAttributes; + +/*! +@enum JSClassAttribute +@constant kJSClassAttributeNone Specifies that a class has no special attributes. +@constant kJSClassAttributeNoAutomaticPrototype Specifies that a class should not automatically generate a shared prototype for its instance objects. Use kJSClassAttributeNoAutomaticPrototype in combination with JSObjectSetPrototype to manage prototypes manually. +*/ +enum { + kJSClassAttributeNone = 0, + kJSClassAttributeNoAutomaticPrototype = 1 << 1 +}; + +/*! +@typedef JSClassAttributes +@abstract A set of JSClassAttributes. Combine multiple attributes by logically ORing them together. +*/ +typedef unsigned JSClassAttributes; + +/*! +@typedef JSObjectInitializeCallback +@abstract The callback invoked when an object is first created. +@param ctx The execution context to use. +@param object The JSObject being created. +@discussion If you named your function Initialize, you would declare it like this: + +void Initialize(JSContextRef ctx, JSObjectRef object); + +Unlike the other object callbacks, the initialize callback is called on the least +derived class (the parent class) first, and the most derived class last. +*/ +typedef void +(*JSObjectInitializeCallback) (JSContextRef ctx, JSObjectRef object); + +/*! +@typedef JSObjectFinalizeCallback +@abstract The callback invoked when an object is finalized (prepared for garbage collection). An object may be finalized on any thread. +@param object The JSObject being finalized. +@discussion If you named your function Finalize, you would declare it like this: + +void Finalize(JSObjectRef object); + +The finalize callback is called on the most derived class first, and the least +derived class (the parent class) last. + +You must not call any function that may cause a garbage collection or an allocation +of a garbage collected object from within a JSObjectFinalizeCallback. This includes +all functions that have a JSContextRef parameter. +*/ +typedef void +(*JSObjectFinalizeCallback) (JSObjectRef object); + +/*! +@typedef JSObjectHasPropertyCallback +@abstract The callback invoked when determining whether an object has a property. +@param ctx The execution context to use. +@param object The JSObject to search for the property. +@param propertyName A JSString containing the name of the property look up. +@result true if object has the property, otherwise false. +@discussion If you named your function HasProperty, you would declare it like this: + +bool HasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName); + +If this function returns false, the hasProperty request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain. + +This callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value would be expensive. + +If this callback is NULL, the getProperty callback will be used to service hasProperty requests. +*/ +typedef bool +(*JSObjectHasPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName); + +/*! +@typedef JSObjectGetPropertyCallback +@abstract The callback invoked when getting a property's value. +@param ctx The execution context to use. +@param object The JSObject to search for the property. +@param propertyName A JSString containing the name of the property to get. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result The property's value if object has the property, otherwise NULL. +@discussion If you named your function GetProperty, you would declare it like this: + +JSValueRef GetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +If this function returns NULL, the get request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain. +*/ +typedef JSValueRef +(*JSObjectGetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +/*! +@typedef JSObjectSetPropertyCallback +@abstract The callback invoked when setting a property's value. +@param ctx The execution context to use. +@param object The JSObject on which to set the property's value. +@param propertyName A JSString containing the name of the property to set. +@param value A JSValue to use as the property's value. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result true if the property was set, otherwise false. +@discussion If you named your function SetProperty, you would declare it like this: + +bool SetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + +If this function returns false, the set request forwards to object's statically declared properties, then its parent class chain (which includes the default object class). +*/ +typedef bool +(*JSObjectSetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + +/*! +@typedef JSObjectDeletePropertyCallback +@abstract The callback invoked when deleting a property. +@param ctx The execution context to use. +@param object The JSObject in which to delete the property. +@param propertyName A JSString containing the name of the property to delete. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result true if propertyName was successfully deleted, otherwise false. +@discussion If you named your function DeleteProperty, you would declare it like this: + +bool DeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +If this function returns false, the delete request forwards to object's statically declared properties, then its parent class chain (which includes the default object class). +*/ +typedef bool +(*JSObjectDeletePropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +/*! +@typedef JSObjectGetPropertyNamesCallback +@abstract The callback invoked when collecting the names of an object's properties. +@param ctx The execution context to use. +@param object The JSObject whose property names are being collected. +@param accumulator A JavaScript property name accumulator in which to accumulate the names of object's properties. +@discussion If you named your function GetPropertyNames, you would declare it like this: + +void GetPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames); + +Property name accumulators are used by JSObjectCopyPropertyNames and JavaScript for...in loops. + +Use JSPropertyNameAccumulatorAddName to add property names to accumulator. A class's getPropertyNames callback only needs to provide the names of properties that the class vends through a custom getProperty or setProperty callback. Other properties, including statically declared properties, properties vended by other classes, and properties belonging to object's prototype, are added independently. +*/ +typedef void +(*JSObjectGetPropertyNamesCallback) (JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames); + +/*! +@typedef JSObjectCallAsFunctionCallback +@abstract The callback invoked when an object is called as a function. +@param ctx The execution context to use. +@param function A JSObject that is the function being called. +@param thisObject A JSObject that is the 'this' variable in the function's scope. +@param argumentCount An integer count of the number of arguments in arguments. +@param arguments A JSValue array of the arguments passed to the function. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result A JSValue that is the function's return value. +@discussion If you named your function CallAsFunction, you would declare it like this: + +JSValueRef CallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +If your callback were invoked by the JavaScript expression 'myObject.myFunction()', function would be set to myFunction, and thisObject would be set to myObject. + +If this callback is NULL, calling your object as a function will throw an exception. +*/ +typedef JSValueRef +(*JSObjectCallAsFunctionCallback) (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +/*! +@typedef JSObjectCallAsConstructorCallback +@abstract The callback invoked when an object is used as a constructor in a 'new' expression. +@param ctx The execution context to use. +@param constructor A JSObject that is the constructor being called. +@param argumentCount An integer count of the number of arguments in arguments. +@param arguments A JSValue array of the arguments passed to the function. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result A JSObject that is the constructor's return value. +@discussion If you named your function CallAsConstructor, you would declare it like this: + +JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +If your callback were invoked by the JavaScript expression 'new myConstructor()', constructor would be set to myConstructor. + +If this callback is NULL, using your object as a constructor in a 'new' expression will throw an exception. +*/ +typedef JSObjectRef +(*JSObjectCallAsConstructorCallback) (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +/*! +@typedef JSObjectHasInstanceCallback +@abstract hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression. +@param ctx The execution context to use. +@param constructor The JSObject that is the target of the 'instanceof' expression. +@param possibleInstance The JSValue being tested to determine if it is an instance of constructor. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result true if possibleInstance is an instance of constructor, otherwise false. +@discussion If you named your function HasInstance, you would declare it like this: + +bool HasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + +If your callback were invoked by the JavaScript expression 'someValue instanceof myObject', constructor would be set to myObject and possibleInstance would be set to someValue. + +If this callback is NULL, 'instanceof' expressions that target your object will return false. + +Standard JavaScript practice calls for objects that implement the callAsConstructor callback to implement the hasInstance callback as well. +*/ +typedef bool +(*JSObjectHasInstanceCallback) (JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + +/*! +@typedef JSObjectConvertToTypeCallback +@abstract The callback invoked when converting an object to a particular JavaScript type. +@param ctx The execution context to use. +@param object The JSObject to convert. +@param type A JSType specifying the JavaScript type to convert to. +@param exception A pointer to a JSValueRef in which to return an exception, if any. +@result The objects's converted value, or NULL if the object was not converted. +@discussion If you named your function ConvertToType, you would declare it like this: + +JSValueRef ConvertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception); + +If this function returns false, the conversion request forwards to object's parent class chain (which includes the default object class). + +This function is only invoked when converting an object to number or string. An object converted to boolean is 'true.' An object converted to object is itself. +*/ +typedef JSValueRef +(*JSObjectConvertToTypeCallback) (JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception); + +/*! +@struct JSStaticValue +@abstract This structure describes a statically declared value property. +@field name A null-terminated UTF8 string containing the property's name. +@field getProperty A JSObjectGetPropertyCallback to invoke when getting the property's value. +@field setProperty A JSObjectSetPropertyCallback to invoke when setting the property's value. May be NULL if the ReadOnly attribute is set. +@field attributes A logically ORed set of JSPropertyAttributes to give to the property. +*/ +typedef struct { + const char* name; + JSObjectGetPropertyCallback getProperty; + JSObjectSetPropertyCallback setProperty; + JSPropertyAttributes attributes; +} JSStaticValue; + +/*! +@struct JSStaticFunction +@abstract This structure describes a statically declared function property. +@field name A null-terminated UTF8 string containing the property's name. +@field callAsFunction A JSObjectCallAsFunctionCallback to invoke when the property is called as a function. +@field attributes A logically ORed set of JSPropertyAttributes to give to the property. +*/ +typedef struct { + const char* name; + JSObjectCallAsFunctionCallback callAsFunction; + JSPropertyAttributes attributes; +} JSStaticFunction; + +/*! +@struct JSClassDefinition +@abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL. +@field version The version number of this structure. The current version is 0. +@field attributes A logically ORed set of JSClassAttributes to give to the class. +@field className A null-terminated UTF8 string containing the class's name. +@field parentClass A JSClass to set as the class's parent class. Pass NULL use the default object class. +@field staticValues A JSStaticValue array containing the class's statically declared value properties. Pass NULL to specify no statically declared value properties. The array must be terminated by a JSStaticValue whose name field is NULL. +@field staticFunctions A JSStaticFunction array containing the class's statically declared function properties. Pass NULL to specify no statically declared function properties. The array must be terminated by a JSStaticFunction whose name field is NULL. +@field initialize The callback invoked when an object is first created. Use this callback to initialize the object. +@field finalize The callback invoked when an object is finalized (prepared for garbage collection). Use this callback to release resources allocated for the object, and perform other cleanup. +@field hasProperty The callback invoked when determining whether an object has a property. If this field is NULL, getProperty is called instead. The hasProperty callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value is expensive. +@field getProperty The callback invoked when getting a property's value. +@field setProperty The callback invoked when setting a property's value. +@field deleteProperty The callback invoked when deleting a property. +@field getPropertyNames The callback invoked when collecting the names of an object's properties. +@field callAsFunction The callback invoked when an object is called as a function. +@field hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression. +@field callAsConstructor The callback invoked when an object is used as a constructor in a 'new' expression. +@field convertToType The callback invoked when converting an object to a particular JavaScript type. +@discussion The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties. Statically declared properties autmatically service requests like getProperty, setProperty, and getPropertyNames. Property access callbacks are required only to implement unusual properties, like array indexes, whose names are not known at compile-time. + +If you named your getter function "GetX" and your setter function "SetX", you would declare a JSStaticValue array containing "X" like this: + +JSStaticValue StaticValueArray[] = { + { "X", GetX, SetX, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +Standard JavaScript practice calls for storing function objects in prototypes, so they can be shared. The default JSClass created by JSClassCreate follows this idiom, instantiating objects with a shared, automatically generating prototype containing the class's function objects. The kJSClassAttributeNoAutomaticPrototype attribute specifies that a JSClass should not automatically generate such a prototype. The resulting JSClass instantiates objects with the default object prototype, and gives each instance object its own copy of the class's function objects. + +A NULL callback specifies that the default object callback should substitute, except in the case of hasProperty, where it specifies that getProperty should substitute. +*/ +typedef struct { + int version; /* current (and only) version is 0 */ + JSClassAttributes attributes; + + const char* className; + JSClassRef parentClass; + + const JSStaticValue* staticValues; + const JSStaticFunction* staticFunctions; + + JSObjectInitializeCallback initialize; + JSObjectFinalizeCallback finalize; + JSObjectHasPropertyCallback hasProperty; + JSObjectGetPropertyCallback getProperty; + JSObjectSetPropertyCallback setProperty; + JSObjectDeletePropertyCallback deleteProperty; + JSObjectGetPropertyNamesCallback getPropertyNames; + JSObjectCallAsFunctionCallback callAsFunction; + JSObjectCallAsConstructorCallback callAsConstructor; + JSObjectHasInstanceCallback hasInstance; + JSObjectConvertToTypeCallback convertToType; +} JSClassDefinition; + +/*! +@const kJSClassDefinitionEmpty +@abstract A JSClassDefinition structure of the current version, filled with NULL pointers and having no attributes. +@discussion Use this constant as a convenience when creating class definitions. For example, to create a class definition with only a finalize method: + +JSClassDefinition definition = kJSClassDefinitionEmpty; +definition.finalize = Finalize; +*/ +JS_EXPORT extern const JSClassDefinition kJSClassDefinitionEmpty; + +/*! +@function +@abstract Creates a JavaScript class suitable for use with JSObjectMake. +@param definition A JSClassDefinition that defines the class. +@result A JSClass with the given definition. Ownership follows the Create Rule. +*/ +JS_EXPORT JSClassRef JSClassCreate(const JSClassDefinition* definition); + +/*! +@function +@abstract Retains a JavaScript class. +@param jsClass The JSClass to retain. +@result A JSClass that is the same as jsClass. +*/ +JS_EXPORT JSClassRef JSClassRetain(JSClassRef jsClass); + +/*! +@function +@abstract Releases a JavaScript class. +@param jsClass The JSClass to release. +*/ +JS_EXPORT void JSClassRelease(JSClassRef jsClass); + +/*! +@function +@abstract Creates a JavaScript object. +@param ctx The execution context to use. +@param jsClass The JSClass to assign to the object. Pass NULL to use the default object class. +@param data A void* to set as the object's private data. Pass NULL to specify no private data. +@result A JSObject with the given class and private data. +@discussion The default object class does not allocate storage for private data, so you must provide a non-NULL jsClass to JSObjectMake if you want your object to be able to store private data. + +data is set on the created object before the intialize methods in its class chain are called. This enables the initialize methods to retrieve and manipulate data through JSObjectGetPrivate. +*/ +JS_EXPORT JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data); + +/*! +@function +@abstract Convenience method for creating a JavaScript function with a given callback as its implementation. +@param ctx The execution context to use. +@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function. +@param callAsFunction The JSObjectCallAsFunctionCallback to invoke when the function is called. +@result A JSObject that is a function. The object's prototype will be the default function prototype. +*/ +JS_EXPORT JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction); + +/*! +@function +@abstract Convenience method for creating a JavaScript constructor. +@param ctx The execution context to use. +@param jsClass A JSClass that is the class your constructor will assign to the objects its constructs. jsClass will be used to set the constructor's .prototype property, and to evaluate 'instanceof' expressions. Pass NULL to use the default object class. +@param callAsConstructor A JSObjectCallAsConstructorCallback to invoke when your constructor is used in a 'new' expression. Pass NULL to use the default object constructor. +@result A JSObject that is a constructor. The object's prototype will be the default object prototype. +@discussion The default object constructor takes no arguments and constructs an object of class jsClass with no private data. +*/ +JS_EXPORT JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor); + +/*! + @function + @abstract Creates a JavaScript Array object. + @param ctx The execution context to use. + @param argumentCount An integer count of the number of arguments in arguments. + @param arguments A JSValue array of data to populate the Array with. Pass NULL if argumentCount is 0. + @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. + @result A JSObject that is an Array. + @discussion The behavior of this function does not exactly match the behavior of the built-in Array constructor. Specifically, if one argument + is supplied, this function returns an array with one element. + */ +JS_EXPORT JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0); + +/*! + @function + @abstract Creates a JavaScript Date object, as if by invoking the built-in Date constructor. + @param ctx The execution context to use. + @param argumentCount An integer count of the number of arguments in arguments. + @param arguments A JSValue array of arguments to pass to the Date Constructor. Pass NULL if argumentCount is 0. + @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. + @result A JSObject that is a Date. + */ +JS_EXPORT JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0); + +/*! + @function + @abstract Creates a JavaScript Error object, as if by invoking the built-in Error constructor. + @param ctx The execution context to use. + @param argumentCount An integer count of the number of arguments in arguments. + @param arguments A JSValue array of arguments to pass to the Error Constructor. Pass NULL if argumentCount is 0. + @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. + @result A JSObject that is a Error. + */ +JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0); + +/*! + @function + @abstract Creates a JavaScript RegExp object, as if by invoking the built-in RegExp constructor. + @param ctx The execution context to use. + @param argumentCount An integer count of the number of arguments in arguments. + @param arguments A JSValue array of arguments to pass to the RegExp Constructor. Pass NULL if argumentCount is 0. + @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. + @result A JSObject that is a RegExp. + */ +JS_EXPORT JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0); + +/*! +@function +@abstract Creates a function with a given script as its body. +@param ctx The execution context to use. +@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function. +@param parameterCount An integer count of the number of parameter names in parameterNames. +@param parameterNames A JSString array containing the names of the function's parameters. Pass NULL if parameterCount is 0. +@param body A JSString containing the script to use as the function's body. +@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. +@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1. +@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception. +@result A JSObject that is a function, or NULL if either body or parameterNames contains a syntax error. The object's prototype will be the default function prototype. +@discussion Use this method when you want to execute a script repeatedly, to avoid the cost of re-parsing the script before each execution. +*/ +JS_EXPORT JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); + +/*! +@function +@abstract Gets an object's prototype. +@param ctx The execution context to use. +@param object A JSObject whose prototype you want to get. +@result A JSValue that is the object's prototype. +*/ +JS_EXPORT JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object); + +/*! +@function +@abstract Sets an object's prototype. +@param ctx The execution context to use. +@param object The JSObject whose prototype you want to set. +@param value A JSValue to set as the object's prototype. +*/ +JS_EXPORT void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value); + +/*! +@function +@abstract Tests whether an object has a given property. +@param object The JSObject to test. +@param propertyName A JSString containing the property's name. +@result true if the object has a property whose name matches propertyName, otherwise false. +*/ +JS_EXPORT bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName); + +/*! +@function +@abstract Gets a property from an object. +@param ctx The execution context to use. +@param object The JSObject whose property you want to get. +@param propertyName A JSString containing the property's name. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The property's value if object has the property, otherwise the undefined value. +*/ +JS_EXPORT JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +/*! +@function +@abstract Sets a property on an object. +@param ctx The execution context to use. +@param object The JSObject whose property you want to set. +@param propertyName A JSString containing the property's name. +@param value A JSValue to use as the property's value. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@param attributes A logically ORed set of JSPropertyAttributes to give to the property. +*/ +JS_EXPORT void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception); + +/*! +@function +@abstract Deletes a property from an object. +@param ctx The execution context to use. +@param object The JSObject whose property you want to delete. +@param propertyName A JSString containing the property's name. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set). +*/ +JS_EXPORT bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +/*! +@function +@abstract Gets a property from an object by numeric index. +@param ctx The execution context to use. +@param object The JSObject whose property you want to get. +@param propertyIndex An integer value that is the property's name. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The property's value if object has the property, otherwise the undefined value. +@discussion Calling JSObjectGetPropertyAtIndex is equivalent to calling JSObjectGetProperty with a string containing propertyIndex, but JSObjectGetPropertyAtIndex provides optimized access to numeric properties. +*/ +JS_EXPORT JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception); + +/*! +@function +@abstract Sets a property on an object by numeric index. +@param ctx The execution context to use. +@param object The JSObject whose property you want to set. +@param propertyIndex The property's name as a number. +@param value A JSValue to use as the property's value. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@discussion Calling JSObjectSetPropertyAtIndex is equivalent to calling JSObjectSetProperty with a string containing propertyIndex, but JSObjectSetPropertyAtIndex provides optimized access to numeric properties. +*/ +JS_EXPORT void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception); + +/*! +@function +@abstract Gets an object's private data. +@param object A JSObject whose private data you want to get. +@result A void* that is the object's private data, if the object has private data, otherwise NULL. +*/ +JS_EXPORT void* JSObjectGetPrivate(JSObjectRef object); + +/*! +@function +@abstract Sets a pointer to private data on an object. +@param object The JSObject whose private data you want to set. +@param data A void* to set as the object's private data. +@result true if object can store private data, otherwise false. +@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data. +*/ +JS_EXPORT bool JSObjectSetPrivate(JSObjectRef object, void* data); + +/*! +@function +@abstract Tests whether an object can be called as a function. +@param ctx The execution context to use. +@param object The JSObject to test. +@result true if the object can be called as a function, otherwise false. +*/ +JS_EXPORT bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object); + +/*! +@function +@abstract Calls an object as a function. +@param ctx The execution context to use. +@param object The JSObject to call as a function. +@param thisObject The object to use as "this," or NULL to use the global object as "this." +@param argumentCount An integer count of the number of arguments in arguments. +@param arguments A JSValue array of arguments to pass to the function. Pass NULL if argumentCount is 0. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The JSValue that results from calling object as a function, or NULL if an exception is thrown or object is not a function. +*/ +JS_EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +/*! +@function +@abstract Tests whether an object can be called as a constructor. +@param ctx The execution context to use. +@param object The JSObject to test. +@result true if the object can be called as a constructor, otherwise false. +*/ +JS_EXPORT bool JSObjectIsConstructor(JSContextRef ctx, JSObjectRef object); + +/*! +@function +@abstract Calls an object as a constructor. +@param ctx The execution context to use. +@param object The JSObject to call as a constructor. +@param argumentCount An integer count of the number of arguments in arguments. +@param arguments A JSValue array of arguments to pass to the constructor. Pass NULL if argumentCount is 0. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The JSObject that results from calling object as a constructor, or NULL if an exception is thrown or object is not a constructor. +*/ +JS_EXPORT JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +/*! +@function +@abstract Gets the names of an object's enumerable properties. +@param ctx The execution context to use. +@param object The object whose property names you want to get. +@result A JSPropertyNameArray containing the names object's enumerable properties. Ownership follows the Create Rule. +*/ +JS_EXPORT JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object); + +/*! +@function +@abstract Retains a JavaScript property name array. +@param array The JSPropertyNameArray to retain. +@result A JSPropertyNameArray that is the same as array. +*/ +JS_EXPORT JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array); + +/*! +@function +@abstract Releases a JavaScript property name array. +@param array The JSPropetyNameArray to release. +*/ +JS_EXPORT void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array); + +/*! +@function +@abstract Gets a count of the number of items in a JavaScript property name array. +@param array The array from which to retrieve the count. +@result An integer count of the number of names in array. +*/ +JS_EXPORT size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array); + +/*! +@function +@abstract Gets a property name at a given index in a JavaScript property name array. +@param array The array from which to retrieve the property name. +@param index The index of the property name to retrieve. +@result A JSStringRef containing the property name. +*/ +JS_EXPORT JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index); + +/*! +@function +@abstract Adds a property name to a JavaScript property name accumulator. +@param accumulator The accumulator object to which to add the property name. +@param propertyName The property name to add. +*/ +JS_EXPORT void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef accumulator, JSStringRef propertyName); + +#ifdef __cplusplus +} +#endif + +#endif /* JSObjectRef_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JSStringRef.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JSStringRef.h new file mode 100644 index 0000000..aded736 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JSStringRef.h @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSStringRef_h +#define JSStringRef_h + +#include + +#ifndef __cplusplus +#include +#endif +#include /* for size_t */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(WIN32) && !defined(_WIN32) \ + && !((defined(__CC_ARM) || defined(__ARMCC__)) && !defined(__linux__)) /* RVCT */ +/*! +@typedef JSChar +@abstract A Unicode character. +*/ + typedef unsigned short JSChar; +#else + typedef wchar_t JSChar; +#endif + +/*! +@function +@abstract Creates a JavaScript string from a buffer of Unicode characters. +@param chars The buffer of Unicode characters to copy into the new JSString. +@param numChars The number of characters to copy from the buffer pointed to by chars. +@result A JSString containing chars. Ownership follows the Create Rule. +*/ +JS_EXPORT JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars); +/*! +@function +@abstract Creates a JavaScript string from a null-terminated UTF8 string. +@param string The null-terminated UTF8 string to copy into the new JSString. +@result A JSString containing string. Ownership follows the Create Rule. +*/ +JS_EXPORT JSStringRef JSStringCreateWithUTF8CString(const char* string); + +/*! +@function +@abstract Retains a JavaScript string. +@param string The JSString to retain. +@result A JSString that is the same as string. +*/ +JS_EXPORT JSStringRef JSStringRetain(JSStringRef string); +/*! +@function +@abstract Releases a JavaScript string. +@param string The JSString to release. +*/ +JS_EXPORT void JSStringRelease(JSStringRef string); + +/*! +@function +@abstract Returns the number of Unicode characters in a JavaScript string. +@param string The JSString whose length (in Unicode characters) you want to know. +@result The number of Unicode characters stored in string. +*/ +JS_EXPORT size_t JSStringGetLength(JSStringRef string); +/*! +@function +@abstract Returns a pointer to the Unicode character buffer that + serves as the backing store for a JavaScript string. +@param string The JSString whose backing store you want to access. +@result A pointer to the Unicode character buffer that serves as string's + backing store, which will be deallocated when string is deallocated. +*/ +JS_EXPORT const JSChar* JSStringGetCharactersPtr(JSStringRef string); + +/*! +@function +@abstract Returns the maximum number of bytes a JavaScript string will + take up if converted into a null-terminated UTF8 string. +@param string The JSString whose maximum converted size (in bytes) you + want to know. +@result The maximum number of bytes that could be required to convert string into a + null-terminated UTF8 string. The number of bytes that the conversion actually ends + up requiring could be less than this, but never more. +*/ +JS_EXPORT size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string); +/*! +@function +@abstract Converts a JavaScript string into a null-terminated UTF8 string, + and copies the result into an external byte buffer. +@param string The source JSString. +@param buffer The destination byte buffer into which to copy a null-terminated + UTF8 representation of string. On return, buffer contains a UTF8 string + representation of string. If bufferSize is too small, buffer will contain only + partial results. If buffer is not at least bufferSize bytes in size, + behavior is undefined. +@param bufferSize The size of the external buffer in bytes. +@result The number of bytes written into buffer (including the null-terminator byte). +*/ +JS_EXPORT size_t JSStringGetUTF8CString(JSStringRef string, char* buffer, size_t bufferSize); + +/*! +@function +@abstract Tests whether two JavaScript strings match. +@param a The first JSString to test. +@param b The second JSString to test. +@result true if the two strings match, otherwise false. +*/ +JS_EXPORT bool JSStringIsEqual(JSStringRef a, JSStringRef b); +/*! +@function +@abstract Tests whether a JavaScript string matches a null-terminated UTF8 string. +@param a The JSString to test. +@param b The null-terminated UTF8 string to test. +@result true if the two strings match, otherwise false. +*/ +JS_EXPORT bool JSStringIsEqualToUTF8CString(JSStringRef a, const char* b); + +#ifdef __cplusplus +} +#endif + +#endif /* JSStringRef_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JSValueRef.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JSValueRef.h new file mode 100644 index 0000000..97385c0 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JSValueRef.h @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSValueRef_h +#define JSValueRef_h + +#include +#include + +#ifndef __cplusplus +#include +#endif + +/*! +@enum JSType +@abstract A constant identifying the type of a JSValue. +@constant kJSTypeUndefined The unique undefined value. +@constant kJSTypeNull The unique null value. +@constant kJSTypeBoolean A primitive boolean value, one of true or false. +@constant kJSTypeNumber A primitive number value. +@constant kJSTypeString A primitive string value. +@constant kJSTypeObject An object value (meaning that this JSValueRef is a JSObjectRef). +*/ +typedef enum { + kJSTypeUndefined, + kJSTypeNull, + kJSTypeBoolean, + kJSTypeNumber, + kJSTypeString, + kJSTypeObject +} JSType; + +#ifdef __cplusplus +extern "C" { +#endif + +/*! +@function +@abstract Returns a JavaScript value's type. +@param ctx The execution context to use. +@param value The JSValue whose type you want to obtain. +@result A value of type JSType that identifies value's type. +*/ +JS_EXPORT JSType JSValueGetType(JSContextRef ctx, JSValueRef); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the undefined type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the undefined type, otherwise false. +*/ +JS_EXPORT bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the null type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the null type, otherwise false. +*/ +JS_EXPORT bool JSValueIsNull(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the boolean type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the boolean type, otherwise false. +*/ +JS_EXPORT bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the number type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the number type, otherwise false. +*/ +JS_EXPORT bool JSValueIsNumber(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the string type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the string type, otherwise false. +*/ +JS_EXPORT bool JSValueIsString(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value's type is the object type. +@param ctx The execution context to use. +@param value The JSValue to test. +@result true if value's type is the object type, otherwise false. +*/ +JS_EXPORT bool JSValueIsObject(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Tests whether a JavaScript value is an object with a given class in its class chain. +@param ctx The execution context to use. +@param value The JSValue to test. +@param jsClass The JSClass to test against. +@result true if value is an object and has jsClass in its class chain, otherwise false. +*/ +JS_EXPORT bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass); + +/* Comparing values */ + +/*! +@function +@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator. +@param ctx The execution context to use. +@param a The first value to test. +@param b The second value to test. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result true if the two values are equal, false if they are not equal or an exception is thrown. +*/ +JS_EXPORT bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception); + +/*! +@function +@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator. +@param ctx The execution context to use. +@param a The first value to test. +@param b The second value to test. +@result true if the two values are strict equal, otherwise false. +*/ +JS_EXPORT bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b); + +/*! +@function +@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator. +@param ctx The execution context to use. +@param value The JSValue to test. +@param constructor The constructor to test against. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false. +*/ +JS_EXPORT bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception); + +/* Creating values */ + +/*! +@function +@abstract Creates a JavaScript value of the undefined type. +@param ctx The execution context to use. +@result The unique undefined value. +*/ +JS_EXPORT JSValueRef JSValueMakeUndefined(JSContextRef ctx); + +/*! +@function +@abstract Creates a JavaScript value of the null type. +@param ctx The execution context to use. +@result The unique null value. +*/ +JS_EXPORT JSValueRef JSValueMakeNull(JSContextRef ctx); + +/*! +@function +@abstract Creates a JavaScript value of the boolean type. +@param ctx The execution context to use. +@param boolean The bool to assign to the newly created JSValue. +@result A JSValue of the boolean type, representing the value of boolean. +*/ +JS_EXPORT JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool boolean); + +/*! +@function +@abstract Creates a JavaScript value of the number type. +@param ctx The execution context to use. +@param number The double to assign to the newly created JSValue. +@result A JSValue of the number type, representing the value of number. +*/ +JS_EXPORT JSValueRef JSValueMakeNumber(JSContextRef ctx, double number); + +/*! +@function +@abstract Creates a JavaScript value of the string type. +@param ctx The execution context to use. +@param string The JSString to assign to the newly created JSValue. The + newly created JSValue retains string, and releases it upon garbage collection. +@result A JSValue of the string type, representing the value of string. +*/ +JS_EXPORT JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string); + +/* Converting to and from JSON formatted strings */ + +/*! + @function + @abstract Creates a JavaScript value from a JSON formatted string. + @param ctx The execution context to use. + @param string The JSString containing the JSON string to be parsed. + @result A JSValue containing the parsed value, or NULL if the input is invalid. + */ +JS_EXPORT JSValueRef JSValueMakeFromJSONString(JSContextRef ctx, JSStringRef string) CF_AVAILABLE(10_7, 7_0); + +/*! + @function + @abstract Creates a JavaScript string containing the JSON serialized representation of a JS value. + @param ctx The execution context to use. + @param value The value to serialize. + @param indent The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces. + @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. + @result A JSString with the result of serialization, or NULL if an exception is thrown. + */ +JS_EXPORT JSStringRef JSValueCreateJSONString(JSContextRef ctx, JSValueRef value, unsigned indent, JSValueRef* exception) CF_AVAILABLE(10_7, 7_0); + +/* Converting to primitive values */ + +/*! +@function +@abstract Converts a JavaScript value to boolean and returns the resulting boolean. +@param ctx The execution context to use. +@param value The JSValue to convert. +@result The boolean result of conversion. +*/ +JS_EXPORT bool JSValueToBoolean(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Converts a JavaScript value to number and returns the resulting number. +@param ctx The execution context to use. +@param value The JSValue to convert. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The numeric result of conversion, or NaN if an exception is thrown. +*/ +JS_EXPORT double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception); + +/*! +@function +@abstract Converts a JavaScript value to string and copies the result into a JavaScript string. +@param ctx The execution context to use. +@param value The JSValue to convert. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule. +*/ +JS_EXPORT JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception); + +/*! +@function +@abstract Converts a JavaScript value to object and returns the resulting object. +@param ctx The execution context to use. +@param value The JSValue to convert. +@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. +@result The JSObject result of conversion, or NULL if an exception is thrown. +*/ +JS_EXPORT JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception); + +/* Garbage collection */ +/*! +@function +@abstract Protects a JavaScript value from garbage collection. +@param ctx The execution context to use. +@param value The JSValue to protect. +@discussion Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + +A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection. +*/ +JS_EXPORT void JSValueProtect(JSContextRef ctx, JSValueRef value); + +/*! +@function +@abstract Unprotects a JavaScript value from garbage collection. +@param ctx The execution context to use. +@param value The JSValue to unprotect. +@discussion A value may be protected multiple times and must be unprotected an + equal number of times before becoming eligible for garbage collection. +*/ +JS_EXPORT void JSValueUnprotect(JSContextRef ctx, JSValueRef value); + +#ifdef __cplusplus +} +#endif + +#endif /* JSValueRef_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/JavaScript.h b/Sources/CJavaScriptCore/include/JavaScriptCore/JavaScript.h new file mode 100644 index 0000000..f8d92d8 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/JavaScript.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2006 Apple Inc. All rights reserved. + * Copyright (C) 2008 Alp Toker + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JavaScript_h +#define JavaScript_h + +#include +#include +#include +#include +#include + +#endif /* JavaScript_h */ diff --git a/Sources/CJavaScriptCore/include/JavaScriptCore/WebKitAvailability.h b/Sources/CJavaScriptCore/include/JavaScriptCore/WebKitAvailability.h new file mode 100644 index 0000000..6af6198 --- /dev/null +++ b/Sources/CJavaScriptCore/include/JavaScriptCore/WebKitAvailability.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2008, 2009, 2010, 2014 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __WebKitAvailability__ +#define __WebKitAvailability__ + +#if defined(__APPLE__) && !defined(BUILDING_GTK__) +#include +#include +#else +#define CF_AVAILABLE(_mac, _ios) +#endif + +#endif /* __WebKitAvailability__ */ From 57d931baa5e1969e8ebfb83c1ed5809e70a33263 Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Mon, 19 Feb 2018 16:35:54 +0000 Subject: [PATCH 03/47] Rename JavaScriptCore to JavaScript to support macOS --- Package.swift | 10 +++++----- Sources/{JavaScriptCore => JavaScript}/JSContext.swift | 5 +++++ Sources/{JavaScriptCore => JavaScript}/JSError.swift | 4 ++++ Sources/{JavaScriptCore => JavaScript}/JSValue.swift | 4 ++++ Sources/{JavaScriptCore => JavaScript}/shims.swift | 4 ++++ .../JSValueTests.swift | 2 +- .../JavaScriptTests.swift} | 2 +- .../XCTestManifests.swift | 0 Tests/LinuxMain.swift | 4 ++-- 9 files changed, 26 insertions(+), 9 deletions(-) rename Sources/{JavaScriptCore => JavaScript}/JSContext.swift (98%) rename Sources/{JavaScriptCore => JavaScript}/JSError.swift (93%) rename Sources/{JavaScriptCore => JavaScript}/JSValue.swift (98%) rename Sources/{JavaScriptCore => JavaScript}/shims.swift (98%) rename Tests/{JavaScriptCoreTests => JavaScriptTests}/JSValueTests.swift (96%) rename Tests/{JavaScriptCoreTests/JavaScriptCoreTests.swift => JavaScriptTests/JavaScriptTests.swift} (99%) rename Tests/{JavaScriptCoreTests => JavaScriptTests}/XCTestManifests.swift (100%) diff --git a/Package.swift b/Package.swift index 270201d..98ca2a5 100644 --- a/Package.swift +++ b/Package.swift @@ -15,8 +15,8 @@ let package = Package( name: "JavaScript", products: [ .library( - name: "JavaScriptCore", - targets: ["JavaScriptCore"]) + name: "JavaScript", + targets: ["JavaScript"]) ], dependencies: [ .package( @@ -28,10 +28,10 @@ let package = Package( name: "CJavaScriptCore", dependencies: []), .target( - name: "JavaScriptCore", + name: "JavaScript", dependencies: ["CJavaScriptCore"]), .testTarget( - name: "JavaScriptCoreTests", - dependencies: ["Test", "JavaScriptCore"]) + name: "JavaScriptTests", + dependencies: ["Test", "JavaScript"]) ] ) diff --git a/Sources/JavaScriptCore/JSContext.swift b/Sources/JavaScript/JSContext.swift similarity index 98% rename from Sources/JavaScriptCore/JSContext.swift rename to Sources/JavaScript/JSContext.swift index e60b4cf..304cea0 100644 --- a/Sources/JavaScriptCore/JSContext.swift +++ b/Sources/JavaScript/JSContext.swift @@ -8,7 +8,12 @@ * See CONTRIBUTORS.txt for the list of the project authors */ +#if os(Linux) import CJavaScriptCore +#else +import JavaScriptCore +#endif + import struct Foundation.URL public class JSContext { diff --git a/Sources/JavaScriptCore/JSError.swift b/Sources/JavaScript/JSError.swift similarity index 93% rename from Sources/JavaScriptCore/JSError.swift rename to Sources/JavaScript/JSError.swift index 58e44d2..540f91f 100644 --- a/Sources/JavaScriptCore/JSError.swift +++ b/Sources/JavaScript/JSError.swift @@ -8,7 +8,11 @@ * See CONTRIBUTORS.txt for the list of the project authors */ +#if os(Linux) import CJavaScriptCore +#else +import JavaScriptCore +#endif public struct JSError: Error, CustomStringConvertible { public var description: String diff --git a/Sources/JavaScriptCore/JSValue.swift b/Sources/JavaScript/JSValue.swift similarity index 98% rename from Sources/JavaScriptCore/JSValue.swift rename to Sources/JavaScript/JSValue.swift index 834f3b3..5325f1a 100644 --- a/Sources/JavaScriptCore/JSValue.swift +++ b/Sources/JavaScript/JSValue.swift @@ -8,7 +8,11 @@ * See CONTRIBUTORS.txt for the list of the project authors */ +#if os(Linux) import CJavaScriptCore +#else +import JavaScriptCore +#endif public class JSValue { let context: JSContextRef diff --git a/Sources/JavaScriptCore/shims.swift b/Sources/JavaScript/shims.swift similarity index 98% rename from Sources/JavaScriptCore/shims.swift rename to Sources/JavaScript/shims.swift index d6558b8..1942ef8 100644 --- a/Sources/JavaScriptCore/shims.swift +++ b/Sources/JavaScript/shims.swift @@ -8,7 +8,11 @@ * See CONTRIBUTORS.txt for the list of the project authors */ +#if os(Linux) import CJavaScriptCore +#else +import JavaScriptCore +#endif public func JSValueToStringCopy( _ ctx: JSContextRef, diff --git a/Tests/JavaScriptCoreTests/JSValueTests.swift b/Tests/JavaScriptTests/JSValueTests.swift similarity index 96% rename from Tests/JavaScriptCoreTests/JSValueTests.swift rename to Tests/JavaScriptTests/JSValueTests.swift index 0ba1956..835706b 100644 --- a/Tests/JavaScriptCoreTests/JSValueTests.swift +++ b/Tests/JavaScriptTests/JSValueTests.swift @@ -9,7 +9,7 @@ */ import Test -@testable import JavaScriptCore +@testable import JavaScript final class JSValueTests: TestCase { func testToInt() { diff --git a/Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift b/Tests/JavaScriptTests/JavaScriptTests.swift similarity index 99% rename from Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift rename to Tests/JavaScriptTests/JavaScriptTests.swift index ac780fb..23fb676 100644 --- a/Tests/JavaScriptCoreTests/JavaScriptCoreTests.swift +++ b/Tests/JavaScriptTests/JavaScriptTests.swift @@ -9,7 +9,7 @@ */ import Test -@testable import JavaScriptCore +@testable import JavaScript final class JavaScriptCoreTests: TestCase { func testEvaluate() { diff --git a/Tests/JavaScriptCoreTests/XCTestManifests.swift b/Tests/JavaScriptTests/XCTestManifests.swift similarity index 100% rename from Tests/JavaScriptCoreTests/XCTestManifests.swift rename to Tests/JavaScriptTests/XCTestManifests.swift diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 5d0b0ab..5363a11 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -1,8 +1,8 @@ import XCTest -import JavaScriptCoreTests +import JavaScriptTests var tests = [XCTestCaseEntry]() -tests += JavaScriptCoreTests.__allTests() +tests += JavaScriptTests.__allTests() XCTMain(tests) From f83a91ee511c704d9974f0fffe45464d5de09ea1 Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Tue, 20 Feb 2018 14:38:46 +0000 Subject: [PATCH 04/47] Initial arguments --- Sources/JavaScript/JSContext+closure.swift | 102 ++++++++++++++++++++ Sources/JavaScript/JSContext.swift | 56 ----------- Sources/JavaScript/JSValue.swift | 15 +++ Tests/JavaScriptTests/JavaScriptTests.swift | 37 ++++++- Tests/JavaScriptTests/XCTestManifests.swift | 2 + 5 files changed, 152 insertions(+), 60 deletions(-) create mode 100644 Sources/JavaScript/JSContext+closure.swift diff --git a/Sources/JavaScript/JSContext+closure.swift b/Sources/JavaScript/JSContext+closure.swift new file mode 100644 index 0000000..b514d7f --- /dev/null +++ b/Sources/JavaScript/JSContext+closure.swift @@ -0,0 +1,102 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +#if os(Linux) +import CJavaScriptCore +#else +import JavaScriptCore +#endif + +public enum ReturnValue { + case undefined + case null + case bool(Bool) + case number(Double) + case string(String) +} + +private var functions: [OpaquePointer: ([JSValue]) throws -> ReturnValue] = [:] + +extension JSContext { + public func createFunction( + name: String, + _ body: @escaping ([JSValue]) throws -> ReturnValue) throws + { + let function = try createFunction(name: name, callback: wrapper) + functions[function] = body + } + + public func createFunction( + name: String, + _ body: @escaping ([JSValue]) throws -> Void) throws + { + let function = try createFunction(name: name, callback: wrapper) + functions[function] = { arguments in + try body(arguments) + return .undefined + } + } +} + +extension JSContext { + public func createFunction( + name: String, + _ body: @escaping () throws -> ReturnValue) throws + { + return try createFunction(name: name) { _ in + return try body() + } + } + + public func createFunction( + name: String, + _ body: @escaping () throws -> Void) throws + { + try createFunction(name: name) { _ in + try body() + } + } +} + +func wrapper( + ctx: JSContextRef!, + function: JSObjectRef!, + thisObject: JSObjectRef!, + argumentCount: Int, + arguments: UnsafePointer?, + exception: UnsafeMutablePointer?) -> JSValueRef? +{ + guard let body = functions[function] else { + if let exception = exception { + let error = "swift error: unregistered function" + exception.pointee = JSValue(string: error, in: ctx).pointer + } + return nil + } + do { + let arguments = [JSValue]( + start: arguments, + count: argumentCount, + in: ctx) + let result = try body(arguments) + switch result { + case .undefined: return JSValueMakeUndefined(ctx) + case .null: return JSValueMakeNull(ctx) + case .bool(let value): return JSValueMakeBoolean(ctx, value) + case .number(let value): return JSValueMakeNumber(ctx, value) + case .string(let value): return JSValue(string: value, in: ctx).pointer + } + } catch { + if let exception = exception { + exception.pointee = JSValue(string: "\(error)", in: ctx).pointer + } + return nil + } +} diff --git a/Sources/JavaScript/JSContext.swift b/Sources/JavaScript/JSContext.swift index 304cea0..092ec5f 100644 --- a/Sources/JavaScript/JSContext.swift +++ b/Sources/JavaScript/JSContext.swift @@ -14,8 +14,6 @@ import CJavaScriptCore import JavaScriptCore #endif -import struct Foundation.URL - public class JSContext { let group: JSContextGroupRef let context: JSGlobalContextRef @@ -67,57 +65,3 @@ public class JSContext { return function! } } - -// MARK: register swift closure as javascript function - -public enum ReturnValue { - case undefined - case null - case bool(Bool) - case number(Double) - case string(String) -} - -var functions: [OpaquePointer: [OpaquePointer: () throws -> ReturnValue]] = [:] - -extension JSContext { - public func createFunction( - name: String, - _ body: @escaping () throws -> ReturnValue - ) throws { - let function = try createFunction(name: name, callback: wrapper) - functions[global, default: [:]][function] = body - } -} - -func wrapper( - ctx: JSContextRef!, - function: JSObjectRef!, - thisObject: JSObjectRef!, - argumentCount: Int, - arguments: UnsafePointer?, - exception: UnsafeMutablePointer? -) -> JSValueRef? { - guard let body = functions[thisObject]?[function] else { - if let exception = exception { - let error = "swift error: unregistered function" - exception.pointee = JSValue(string: error, in: thisObject).pointer - } - return nil - } - do { - let result = try body() - switch result { - case .undefined: return JSValueMakeUndefined(ctx) - case .null: return JSValueMakeNull(ctx) - case .bool(let value): return JSValueMakeBoolean(ctx, value) - case .number(let value): return JSValueMakeNumber(ctx, value) - case .string(let value): return JSValue(string: value, in: ctx).pointer - } - } catch { - if let exception = exception { - exception.pointee = JSValue(string: "\(error)", in: ctx).pointer - } - return nil - } -} diff --git a/Sources/JavaScript/JSValue.swift b/Sources/JavaScript/JSValue.swift index 5325f1a..2ec0006 100644 --- a/Sources/JavaScript/JSValue.swift +++ b/Sources/JavaScript/JSValue.swift @@ -113,6 +113,21 @@ extension JSValue { } } +extension Array where Element == JSValue { + init( + start: UnsafePointer?, + count: Int, + in context: JSObjectRef + ) { + var arguments = [JSValue]() + for i in 0.. ReturnValue in + captured = true + return .string("captured") + } + let result = try context.evaluate("testCapture()") + assertTrue(captured) + assertEqual("\(result)", "captured") + } catch { + fail(String(describing: error)) + } + } + + func testArguments() { + do { + let context = JSContext() + + var result = [String]() + try context.createFunction(name: "testArguments") { arguments in + result = try arguments.map(String.init) + } + try context.evaluate("testArguments('one', 'two')") + assertEqual(result, ["one", "two"]) + } catch { + fail(String(describing: error)) + } + } } diff --git a/Tests/JavaScriptTests/XCTestManifests.swift b/Tests/JavaScriptTests/XCTestManifests.swift index 8ba4bd3..878ca30 100644 --- a/Tests/JavaScriptTests/XCTestManifests.swift +++ b/Tests/JavaScriptTests/XCTestManifests.swift @@ -9,6 +9,8 @@ extension JSValueTests { extension JavaScriptCoreTests { static let __allTests = [ + ("testArguments", testArguments), + ("testCapture", testCapture), ("testClosure", testClosure), ("testEvaluate", testEvaluate), ("testException", testException), From 9df699870adc798ad9ef6090aae6cd9c29fced6a Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Fri, 23 Feb 2018 16:59:47 +0000 Subject: [PATCH 05/47] Release JSString --- Sources/JavaScript/JSValue.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/JavaScript/JSValue.swift b/Sources/JavaScript/JSValue.swift index 2ec0006..c1082dd 100644 --- a/Sources/JavaScript/JSValue.swift +++ b/Sources/JavaScript/JSValue.swift @@ -42,6 +42,7 @@ public class JSValue { self.context = context let bytes = [UInt16](string.utf16) let stringRef = JSStringCreateWithCharacters(bytes, bytes.count) + defer { JSStringRelease(stringRef) } self.pointer = JSValueMakeString(context, stringRef) } } From 472132f3c5574135b4d3a4165d4f1cd058d2fc2a Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Fri, 23 Feb 2018 17:43:53 +0000 Subject: [PATCH 06/47] Implement isObject & object properties --- Sources/JavaScript/JSValue.swift | 24 ++++++++++++++++++++++++ Tests/JavaScriptTests/JSValueTests.swift | 16 ++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/Sources/JavaScript/JSValue.swift b/Sources/JavaScript/JSValue.swift index c1082dd..ab60427 100644 --- a/Sources/JavaScript/JSValue.swift +++ b/Sources/JavaScript/JSValue.swift @@ -69,6 +69,26 @@ extension JSValue { } } +extension JSValue { + subscript(_ property: String) -> JSValue? { + guard isObject else { + return nil + } + let bytes = [UInt16](property.utf16) + let property = JSStringCreateWithCharacters(bytes, bytes.count) + defer { JSStringRelease(property) } + + var exception: JSValueRef? = nil + let result = JSObjectGetProperty(context, pointer, property, &exception) + + if exception != nil { + return nil + } + return JSValue(context: context, pointer: result!) + } +} + + extension JSValue { public var isNull: Bool { return JSValueIsNull(context, pointer) @@ -89,6 +109,10 @@ extension JSValue { public var isString: Bool { return JSValueIsString(context, pointer) } + + public var isObject: Bool { + return JSValueIsObject(context, pointer) + } } extension JSValue { diff --git a/Tests/JavaScriptTests/JSValueTests.swift b/Tests/JavaScriptTests/JSValueTests.swift index 835706b..77655bb 100644 --- a/Tests/JavaScriptTests/JSValueTests.swift +++ b/Tests/JavaScriptTests/JSValueTests.swift @@ -31,4 +31,20 @@ final class JSValueTests: TestCase { fail(String(describing: error)) } } + + func testProperty() { + do { + let context = JSContext() + let result = try context.evaluate(""" + (function(){ + return { property: 'test' } + })() + """) + + print(result) + assertEqual(try result["property"]?.toString(), "test") + } catch { + fail(String(describing: error)) + } + } } From 8c399ad00d3ce3b4c2eeaed56459fc9557a89fcb Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Fri, 23 Feb 2018 17:44:02 +0000 Subject: [PATCH 07/47] Fix JSError recursion in some cases --- Sources/JavaScript/JSError.swift | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Sources/JavaScript/JSError.swift b/Sources/JavaScript/JSError.swift index 540f91f..d36d60e 100644 --- a/Sources/JavaScript/JSError.swift +++ b/Sources/JavaScript/JSError.swift @@ -20,9 +20,17 @@ public struct JSError: Error, CustomStringConvertible { init(context: JSContextRef, pointer: JSValueRef) { let value = JSValue(context: context, pointer: pointer) do { - self.description = try value.toString() + guard value.isObject else { + description = "not an object" + return + } + guard let message = value["message"] else { + self.description = "failed to access error.message" + return + } + self.description = try message.toString() } catch { - self.description = "\(error)" + self.description = "failed to convert JSError" } } } From 41cd0192b1de8054fbed674ea58aeeecd5025ae5 Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Tue, 13 Mar 2018 03:36:52 +0000 Subject: [PATCH 08/47] Move JSC from JavaScript to JSCSwift target --- Package.swift | 9 +- Sources/JavaScript/JavaScript.swift | 49 +++++++ .../JSContext+closure.swift | 14 +- .../JSContext.swift | 0 .../JSError.swift | 0 .../JSValue.swift | 10 ++ .../shims.swift | 0 Tests/JavaScriptCoreTests/JSValueTests.swift | 127 ++++++++++++++++++ .../JavaScriptTests.swift | 33 +---- .../XCTestManifests.swift | 1 + Tests/JavaScriptTests/JSValueTests.swift | 50 ------- Tests/LinuxMain.swift | 4 +- 12 files changed, 202 insertions(+), 95 deletions(-) create mode 100644 Sources/JavaScript/JavaScript.swift rename Sources/{JavaScript => JavaScriptCoreSwift}/JSContext+closure.swift (88%) rename Sources/{JavaScript => JavaScriptCoreSwift}/JSContext.swift (100%) rename Sources/{JavaScript => JavaScriptCoreSwift}/JSError.swift (100%) rename Sources/{JavaScript => JavaScriptCoreSwift}/JSValue.swift (95%) rename Sources/{JavaScript => JavaScriptCoreSwift}/shims.swift (100%) create mode 100644 Tests/JavaScriptCoreTests/JSValueTests.swift rename Tests/{JavaScriptTests => JavaScriptCoreTests}/JavaScriptTests.swift (70%) rename Tests/{JavaScriptTests => JavaScriptCoreTests}/XCTestManifests.swift (94%) delete mode 100644 Tests/JavaScriptTests/JSValueTests.swift diff --git a/Package.swift b/Package.swift index 98ca2a5..b86e002 100644 --- a/Package.swift +++ b/Package.swift @@ -27,11 +27,14 @@ let package = Package( .target( name: "CJavaScriptCore", dependencies: []), + .target( + name: "JavaScriptCoreSwift", + dependencies: ["CJavaScriptCore", "JavaScript"]), .target( name: "JavaScript", - dependencies: ["CJavaScriptCore"]), + dependencies: []), .testTarget( - name: "JavaScriptTests", - dependencies: ["Test", "JavaScript"]) + name: "JavaScriptCoreTests", + dependencies: ["Test", "JavaScriptCoreSwift"]), ] ) diff --git a/Sources/JavaScript/JavaScript.swift b/Sources/JavaScript/JavaScript.swift new file mode 100644 index 0000000..297989c --- /dev/null +++ b/Sources/JavaScript/JavaScript.swift @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +public protocol JSEngine { + associatedtype JSRuntime: JavaScript.JSRuntime + static func createRuntime() throws -> JSRuntime +} + +public protocol JSRuntime { + associatedtype JSContext: JavaScript.JSContext + func createContext() -> JSContext +} + +public protocol JSContext { + associatedtype JSValue: JavaScript.JSValue + func evaluate(_ script: String) throws -> JSValue + +// func createValue(string: String) -> JSValue +// func createValue(number: Int) -> JSValue +// func createValue(number: Double) -> JSValue + +// func createFunction() +} + +public protocol JSValue { + func toString() throws -> String + + var isNull: Bool { get } + var isUndefined: Bool { get } + var isBool: Bool { get } + var isNumber: Bool { get } + var isString: Bool { get } + var isObject: Bool { get } +} + +public enum Value { + case undefined + case null + case bool(Bool) + case number(Double) + case string(String) +} diff --git a/Sources/JavaScript/JSContext+closure.swift b/Sources/JavaScriptCoreSwift/JSContext+closure.swift similarity index 88% rename from Sources/JavaScript/JSContext+closure.swift rename to Sources/JavaScriptCoreSwift/JSContext+closure.swift index b514d7f..d0f7cec 100644 --- a/Sources/JavaScript/JSContext+closure.swift +++ b/Sources/JavaScriptCoreSwift/JSContext+closure.swift @@ -14,20 +14,14 @@ import CJavaScriptCore import JavaScriptCore #endif -public enum ReturnValue { - case undefined - case null - case bool(Bool) - case number(Double) - case string(String) -} +@_exported import JavaScript -private var functions: [OpaquePointer: ([JSValue]) throws -> ReturnValue] = [:] +private var functions: [OpaquePointer: ([JSValue]) throws -> Value] = [:] extension JSContext { public func createFunction( name: String, - _ body: @escaping ([JSValue]) throws -> ReturnValue) throws + _ body: @escaping ([JSValue]) throws -> Value) throws { let function = try createFunction(name: name, callback: wrapper) functions[function] = body @@ -48,7 +42,7 @@ extension JSContext { extension JSContext { public func createFunction( name: String, - _ body: @escaping () throws -> ReturnValue) throws + _ body: @escaping () throws -> Value) throws { return try createFunction(name: name) { _ in return try body() diff --git a/Sources/JavaScript/JSContext.swift b/Sources/JavaScriptCoreSwift/JSContext.swift similarity index 100% rename from Sources/JavaScript/JSContext.swift rename to Sources/JavaScriptCoreSwift/JSContext.swift diff --git a/Sources/JavaScript/JSError.swift b/Sources/JavaScriptCoreSwift/JSError.swift similarity index 100% rename from Sources/JavaScript/JSError.swift rename to Sources/JavaScriptCoreSwift/JSError.swift diff --git a/Sources/JavaScript/JSValue.swift b/Sources/JavaScriptCoreSwift/JSValue.swift similarity index 95% rename from Sources/JavaScript/JSValue.swift rename to Sources/JavaScriptCoreSwift/JSValue.swift index ab60427..c14f75b 100644 --- a/Sources/JavaScript/JSValue.swift +++ b/Sources/JavaScriptCoreSwift/JSValue.swift @@ -14,6 +14,16 @@ import CJavaScriptCore import JavaScriptCore #endif +protocol JSValueInitializable { + init(from jsValue: JSValue) throws +} + +extension String: JSValueInitializable { + init(from jsValue: JSValue) throws { + self = try jsValue.toString() + } +} + public class JSValue { let context: JSContextRef let pointer: JSValueRef diff --git a/Sources/JavaScript/shims.swift b/Sources/JavaScriptCoreSwift/shims.swift similarity index 100% rename from Sources/JavaScript/shims.swift rename to Sources/JavaScriptCoreSwift/shims.swift diff --git a/Tests/JavaScriptCoreTests/JSValueTests.swift b/Tests/JavaScriptCoreTests/JSValueTests.swift new file mode 100644 index 0000000..12a1bad --- /dev/null +++ b/Tests/JavaScriptCoreTests/JSValueTests.swift @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +import Test +@testable import JavaScriptCoreSwift + +final class JSValueTests: TestCase { + func testIsUndefined() { + do { + let context = JSContext() + + let result = try context.evaluate("undefined") + assertTrue(result.isUndefined) + assertFalse(result.isNull) + assertFalse(result.isBool) + assertFalse(result.isNumber) + assertFalse(result.isString) + assertEqual(try result.toString(), "undefined") + } catch { + fail(String(describing: error)) + } + } + + func testIsNull() { + do { + let context = JSContext() + let result = try context.evaluate("null") + assertFalse(result.isUndefined) + assertTrue(result.isNull) + assertFalse(result.isBool) + assertFalse(result.isNumber) + assertFalse(result.isString) + assertEqual(try result.toString(), "null") + } catch { + fail(String(describing: error)) + } + } + + func testIsBool() { + do { + let context = JSContext() + let result = try context.evaluate("true") + assertFalse(result.isUndefined) + assertFalse(result.isNull) + assertTrue(result.isBool) + assertFalse(result.isNumber) + assertFalse(result.isString) + assertEqual(try result.toString(), "true") + assertEqual(result.toBool(), true) + } catch { + fail(String(describing: error)) + } + } + + func testIsNumber() { + do { + let context = JSContext() + let result = try context.evaluate("3.14") + assertFalse(result.isUndefined) + assertFalse(result.isNull) + assertFalse(result.isBool) + assertTrue(result.isNumber) + assertFalse(result.isString) + assertEqual(try result.toString(), "3.14") + assertEqual(try result.toDouble(), 3.14) + } catch { + fail(String(describing: error)) + } + } + + func testIsString() { + do { + let context = JSContext() + let result = try context.evaluate("'success'") + assertFalse(result.isUndefined) + assertFalse(result.isNull) + assertFalse(result.isBool) + assertFalse(result.isNumber) + assertTrue(result.isString) + assertEqual(try result.toString(), "success") + } catch { + fail(String(describing: error)) + } + } + + func testToInt() { + do { + let context = JSContext() + let result = try context.evaluate("40 + 2") + assertEqual(try result.toInt(), 42) + } catch { + fail(String(describing: error)) + } + } + + func testToString() { + do { + let context = JSContext() + let result = try context.evaluate("40 + 2") + assertEqual(try result.toString(), "42") + } catch { + fail(String(describing: error)) + } + } + + func testProperty() { + do { + let context = JSContext() + let result = try context.evaluate(""" + (function(){ + return { property: 'test' } + })() + """) + + assertEqual(try result["property"]?.toString(), "test") + } catch { + fail(String(describing: error)) + } + } +} diff --git a/Tests/JavaScriptTests/JavaScriptTests.swift b/Tests/JavaScriptCoreTests/JavaScriptTests.swift similarity index 70% rename from Tests/JavaScriptTests/JavaScriptTests.swift rename to Tests/JavaScriptCoreTests/JavaScriptTests.swift index b4cd665..b1577fd 100644 --- a/Tests/JavaScriptTests/JavaScriptTests.swift +++ b/Tests/JavaScriptCoreTests/JavaScriptTests.swift @@ -9,7 +9,7 @@ */ import Test -@testable import JavaScript +@testable import JavaScriptCoreSwift final class JavaScriptCoreTests: TestCase { func testEvaluate() { @@ -20,7 +20,7 @@ final class JavaScriptCoreTests: TestCase { func testException() { let context = JSContext() assertThrowsError(try context.evaluate("x()")) { error in - assertEqual("\(error)", "ReferenceError: Can't find variable: x") + assertEqual("\(error)", "Can't find variable: x") } } @@ -46,57 +46,30 @@ final class JavaScriptCoreTests: TestCase { } let undefinedResult = try context.evaluate("testUndefined()") assertTrue(undefinedResult.isUndefined) - assertFalse(undefinedResult.isNull) - assertFalse(undefinedResult.isBool) - assertFalse(undefinedResult.isNumber) - assertFalse(undefinedResult.isString) - assertEqual(try undefinedResult.toString(), "undefined") - try context.createFunction(name: "testNull") { return .null } let nullResult = try context.evaluate("testNull()") - assertFalse(nullResult.isUndefined) assertTrue(nullResult.isNull) - assertFalse(nullResult.isBool) - assertFalse(nullResult.isNumber) - assertFalse(nullResult.isString) - assertEqual(try nullResult.toString(), "null") - try context.createFunction(name: "testBool") { return .bool(true) } let boolResult = try context.evaluate("testBool()") - assertFalse(boolResult.isUndefined) - assertFalse(boolResult.isNull) assertTrue(boolResult.isBool) - assertFalse(boolResult.isNumber) - assertFalse(boolResult.isString) - assertEqual(boolResult.toBool(), true) try context.createFunction(name: "testNumber") { return .number(3.14) } let numberResult = try context.evaluate("testNumber()") - assertFalse(numberResult.isUndefined) - assertFalse(numberResult.isNull) - assertFalse(numberResult.isBool) assertTrue(numberResult.isNumber) - assertFalse(numberResult.isString) - assertEqual(try numberResult.toDouble(), 3.14) try context.createFunction(name: "testString") { return .string("success") } let stringResult = try context.evaluate("testString()") - assertFalse(stringResult.isUndefined) - assertFalse(stringResult.isNull) - assertFalse(stringResult.isBool) - assertFalse(stringResult.isNumber) assertTrue(stringResult.isString) - assertEqual(try stringResult.toString(), "success") } catch { fail(String(describing: error)) } @@ -108,7 +81,7 @@ final class JavaScriptCoreTests: TestCase { var captured = false try context.createFunction(name: "testCapture") - { (_) -> ReturnValue in + { (_) -> Value in captured = true return .string("captured") } diff --git a/Tests/JavaScriptTests/XCTestManifests.swift b/Tests/JavaScriptCoreTests/XCTestManifests.swift similarity index 94% rename from Tests/JavaScriptTests/XCTestManifests.swift rename to Tests/JavaScriptCoreTests/XCTestManifests.swift index 878ca30..9a1d262 100644 --- a/Tests/JavaScriptTests/XCTestManifests.swift +++ b/Tests/JavaScriptCoreTests/XCTestManifests.swift @@ -2,6 +2,7 @@ import XCTest extension JSValueTests { static let __allTests = [ + ("testProperty", testProperty), ("testToInt", testToInt), ("testToString", testToString), ] diff --git a/Tests/JavaScriptTests/JSValueTests.swift b/Tests/JavaScriptTests/JSValueTests.swift deleted file mode 100644 index 77655bb..0000000 --- a/Tests/JavaScriptTests/JSValueTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2017 Tris Foundation and the project authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License - * - * See LICENSE.txt in the project root for license information - * See CONTRIBUTORS.txt for the list of the project authors - */ - -import Test -@testable import JavaScript - -final class JSValueTests: TestCase { - func testToInt() { - do { - let context = JSContext() - let result = try context.evaluate("40 + 2") - assertEqual(try result.toInt(), 42) - } catch { - fail(String(describing: error)) - } - } - - func testToString() { - do { - let context = JSContext() - let result = try context.evaluate("40 + 2") - assertEqual(try result.toString(), "42") - } catch { - fail(String(describing: error)) - } - } - - func testProperty() { - do { - let context = JSContext() - let result = try context.evaluate(""" - (function(){ - return { property: 'test' } - })() - """) - - print(result) - assertEqual(try result["property"]?.toString(), "test") - } catch { - fail(String(describing: error)) - } - } -} diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 5363a11..5d0b0ab 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -1,8 +1,8 @@ import XCTest -import JavaScriptTests +import JavaScriptCoreTests var tests = [XCTestCaseEntry]() -tests += JavaScriptTests.__allTests() +tests += JavaScriptCoreTests.__allTests() XCTMain(tests) From 4e01bfae31d54fef8ebb208bec5c56601074cc87 Mon Sep 17 00:00:00 2001 From: Tony Freeman Date: Tue, 13 Mar 2018 03:43:42 +0000 Subject: [PATCH 09/47] Add V8 engine base --- Package.swift | 12 +- Sources/CV8/include/module.modulemap | 15 ++ Sources/CV8/include/wrappers.h | 50 +++++ Sources/CV8/wrappers.cpp | 176 ++++++++++++++++++ Sources/V8/JSContext.swift | 44 +++++ Sources/V8/JSEngine.swift | 19 ++ Sources/V8/JSRuntime.swift | 37 ++++ Sources/V8/JSValue.swift | 70 +++++++ .../JavaScriptCoreTests/XCTestManifests.swift | 5 + Tests/LinuxMain.swift | 2 + Tests/V8Tests/JSValueTests.swift | 112 +++++++++++ Tests/V8Tests/V8Tests.swift | 26 +++ 12 files changed, 567 insertions(+), 1 deletion(-) create mode 100644 Sources/CV8/include/module.modulemap create mode 100644 Sources/CV8/include/wrappers.h create mode 100644 Sources/CV8/wrappers.cpp create mode 100644 Sources/V8/JSContext.swift create mode 100644 Sources/V8/JSEngine.swift create mode 100644 Sources/V8/JSRuntime.swift create mode 100644 Sources/V8/JSValue.swift create mode 100644 Tests/V8Tests/JSValueTests.swift create mode 100644 Tests/V8Tests/V8Tests.swift diff --git a/Package.swift b/Package.swift index b86e002..76a62e8 100644 --- a/Package.swift +++ b/Package.swift @@ -27,14 +27,24 @@ let package = Package( .target( name: "CJavaScriptCore", dependencies: []), + .target( + name: "CV8", + dependencies: []), .target( name: "JavaScriptCoreSwift", dependencies: ["CJavaScriptCore", "JavaScript"]), + .target( + name: "V8", + dependencies: ["CV8", "JavaScript"]), .target( name: "JavaScript", dependencies: []), .testTarget( name: "JavaScriptCoreTests", dependencies: ["Test", "JavaScriptCoreSwift"]), - ] + .testTarget( + name: "V8Tests", + dependencies: ["Test", "V8"]), + ], + cxxLanguageStandard: .cxx11 ) diff --git a/Sources/CV8/include/module.modulemap b/Sources/CV8/include/module.modulemap new file mode 100644 index 0000000..f331385 --- /dev/null +++ b/Sources/CV8/include/module.modulemap @@ -0,0 +1,15 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +module CV8 [system] { + header "wrappers.h" + link "v8" + export * +} diff --git a/Sources/CV8/include/wrappers.h b/Sources/CV8/include/wrappers.h new file mode 100644 index 0000000..a9cf15d --- /dev/null +++ b/Sources/CV8/include/wrappers.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +#ifndef wrappers_h +#define wrappers_h + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + + void* initialize(); + void dispose(void* platform); + void* createIsolate(); + void disposeIsolate(void* isolate); + + void* createContext(void* isolate); + void disposeContext(void* context); + + void* evaluate(void* isolatePtr, void* contextPtr, const char* scriptPtr, void** exception); + void disposeValue(void* pointer); + + int getUtf8StringLength(void* isolatePtr, void* valuePtr); + void copyUtf8String(void* isolatePtr, void* valuePtr, void* buffer, int count); + + int64_t valueToInt(void* isolatePtr, void* valuePtr); + + bool isNull(void* isolatePtr, void* valuePtr); + bool isUndefined(void* isolatePtr, void* valuePtr); + bool isBoolean(void* isolatePtr, void* valuePtr); + bool isNumber(void* isolatePtr, void* valuePtr); + bool isString(void* isolatePtr, void* valuePtr); + bool isObject(void* isolatePtr, void* valuePtr); + + +#ifdef __cplusplus +} +#endif + +#endif /* wrappers_h */ diff --git a/Sources/CV8/wrappers.cpp b/Sources/CV8/wrappers.cpp new file mode 100644 index 0000000..571f28b --- /dev/null +++ b/Sources/CV8/wrappers.cpp @@ -0,0 +1,176 @@ +/* + * Copyright 2017 Tris Foundation and the project authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License + * + * See LICENSE.txt in the project root for license information + * See CONTRIBUTORS.txt for the list of the project authors + */ + +#include // malloc, free +#include // memset, memcpy +#include +#include + +using namespace v8; + +class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { +public: + virtual void *Allocate(size_t length){ + void *data = AllocateUninitialized(length); + return data == NULL ? data : memset(data, 0, length); + } + virtual void *AllocateUninitialized(size_t length) { return malloc(length); } + virtual void Free(void *data, size_t) { free(data); } +}; + +class GlobalValue { +public: + explicit GlobalValue(Isolate* isolate, Global* value): + isolate_locker(isolate), isolate_scope(isolate), handle_scope(isolate), + isolate(isolate), value(value) { + } + + explicit GlobalValue(void* isolate, void* value) + : GlobalValue(reinterpret_cast(isolate), reinterpret_cast*>(value)) { + } + + ~GlobalValue() { } + + V8_INLINE Local operator*() const { + return value->Get(isolate); + } + + V8_INLINE Local operator->() const { + return value->Get(isolate); + } + +private: + Locker isolate_locker; + Isolate::Scope isolate_scope; + HandleScope handle_scope; + + Isolate* isolate; + Global* value; + + // Prevent copying of GlobalValue objects. + GlobalValue(const GlobalValue&); + GlobalValue& operator=(const GlobalValue&); +}; + +extern "C" { + ArrayBufferAllocator bufferAllocator; + + const void* initialize() { + V8::InitializeICU(); + auto platform = platform::CreateDefaultPlatform(); + V8::InitializePlatform(platform); + V8::Initialize(); + return platform; + } + + void dispose(void* platform) { + V8::Dispose(); + V8::ShutdownPlatform(); + delete reinterpret_cast(platform);; + } + + const void* createIsolate() { + Isolate::CreateParams create_params; + create_params.array_buffer_allocator = &bufferAllocator; + return Isolate::New(create_params); + } + + void disposeIsolate(void* isolate) { + reinterpret_cast(isolate)->Dispose(); + } + + void* createContext(void* isolatePtr) { + auto isolate = reinterpret_cast(isolatePtr); + Locker isolateLocker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = Context::New(isolate); + return new Global(isolate, context); + } + + void disposeContext(void* context) { + delete reinterpret_cast*>(context); + } + + void* evaluate(void* isolatePtr, void* contextPtr, const char* scriptPtr, void** exception) { + auto isolate = reinterpret_cast(isolatePtr); + auto globalContext = reinterpret_cast*>(contextPtr); + + Locker isolateLocker(isolate); + TryCatch trycatch(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = globalContext->Get(isolate); + Context::Scope context_scope(context); + Local source = String::NewFromUtf8(isolate, scriptPtr); + Local