feat(smart-app): implement complete mobile app MVP

- App.tsx: full navigation (Auth stack + Main tabs with 5 screens)
- Auth: LoginScreen, RegisterScreen, ForgotPasswordScreen
- HomeScreen: dashboard with IoT metrics, weather widget, alerts, quick actions, sensors
- MapScreen: interactive map with layer toggles (6 layers)
- MarketplaceScreen: categories (6), products (5), search
- ChatScreen: AI chat with quick prompts (4), bot responses
- ProfileScreen: user info, stats, menu (9 items), logout
- AlertsScreen: alert list with severity, acknowledge
- SensorsScreen: sensor list with type filters (6 types), search
- ZonesScreen: zone cards with stats
- SettingsScreen: language picker (FR/EN/ES/DE), privacy, about
- Stores: iotStore (sensors, zones, alerts), notificationStore, uiStore + i18n
- Hooks: useSensors, useAlerts, useNotifications, useLocation
- Components: Card, Button, LoadingSpinner, ErrorBoundary, Header
- Services: iotService, notificationService (with axios API client)
- Utils: formatters (temp, AQI, noise, dates), validators (email, password, IBAN)
- Theme: colors.ts with full design system (Blue Ocean palette)
- Ditto: fixed MongoDB connection, new JWT secrets, official gateway image
This commit is contained in:
Eric FELIXINE
2026-06-01 18:00:35 -04:00
parent 08ca495bde
commit e30ae8ed09
35578 changed files with 3703534 additions and 43 deletions

View File

@@ -0,0 +1,113 @@
/*
* Copyright (C) 2013, 2016 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 APICallbackFunction_h
#define APICallbackFunction_h
#include "APICast.h"
#include "Error.h"
#include "JSCallbackConstructor.h"
#include "JSLock.h"
#include <wtf/Vector.h>
namespace JSC {
struct APICallbackFunction {
template <typename T> static EncodedJSValue JSC_HOST_CALL call(ExecState*);
template <typename T> static EncodedJSValue JSC_HOST_CALL construct(ExecState*);
};
template <typename T>
EncodedJSValue JSC_HOST_CALL APICallbackFunction::call(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(exec->jsCallee());
JSObjectRef thisObjRef = toRef(jsCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode)));
int argumentCount = static_cast<int>(exec->argumentCount());
Vector<JSValueRef, 16> arguments;
arguments.reserveInitialCapacity(argumentCount);
for (int i = 0; i < argumentCount; i++)
arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
JSValueRef exception = 0;
JSValueRef result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = jsCast<T*>(toJS(functionRef))->functionCallback()(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
// result must be a valid JSValue.
if (!result)
return JSValue::encode(jsUndefined());
return JSValue::encode(toJS(exec, result));
}
template <typename T>
EncodedJSValue JSC_HOST_CALL APICallbackFunction::construct(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* constructor = exec->jsCallee();
JSContextRef ctx = toRef(exec);
JSObjectRef constructorRef = toRef(constructor);
JSObjectCallAsConstructorCallback callback = jsCast<T*>(constructor)->constructCallback();
if (callback) {
size_t argumentCount = exec->argumentCount();
Vector<JSValueRef, 16> arguments;
arguments.reserveInitialCapacity(argumentCount);
for (size_t i = 0; i < argumentCount; ++i)
arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
JSValueRef exception = 0;
JSObjectRef result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = callback(ctx, constructorRef, argumentCount, arguments.data(), &exception);
}
if (exception) {
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(toJS(exec, exception));
}
// result must be a valid JSValue.
if (!result)
return throwVMTypeError(exec, scope);
return JSValue::encode(toJS(result));
}
return JSValue::encode(toJS(JSObjectMake(ctx, jsCast<JSCallbackConstructor*>(constructor)->classRef(), 0)));
}
} // namespace JSC
#endif // APICallbackFunction_h

View File

@@ -0,0 +1,182 @@
/*
* Copyright (C) 2006-2019 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 APICast_h
#define APICast_h
#include "JSAPIValueWrapper.h"
#include "JSCJSValue.h"
#include "JSCJSValueInlines.h"
#include "JSGlobalObject.h"
#include "HeapCellInlines.h"
namespace JSC {
class ExecState;
class PropertyNameArray;
class VM;
class JSObject;
class JSValue;
}
typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
typedef const struct OpaqueJSContext* JSContextRef;
typedef struct OpaqueJSContext* JSGlobalContextRef;
typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
typedef const struct OpaqueJSValue* JSValueRef;
typedef struct OpaqueJSValue* JSObjectRef;
/* Opaque typing convenience methods */
inline JSC::ExecState* toJS(JSContextRef c)
{
ASSERT(c);
return reinterpret_cast<JSC::ExecState*>(const_cast<OpaqueJSContext*>(c));
}
inline JSC::ExecState* toJS(JSGlobalContextRef c)
{
ASSERT(c);
return reinterpret_cast<JSC::ExecState*>(c);
}
inline JSC::JSGlobalObject* toJSGlobalObject(JSGlobalContextRef context)
{
return toJS(context)->lexicalGlobalObject();
}
inline JSC::JSValue toJS(JSC::ExecState* exec, JSValueRef v)
{
ASSERT_UNUSED(exec, exec);
#if !CPU(ADDRESS64)
JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
if (!jsCell)
return JSC::jsNull();
JSC::JSValue result;
if (jsCell->isAPIValueWrapper())
result = JSC::jsCast<JSC::JSAPIValueWrapper*>(jsCell)->value();
else
result = jsCell;
#else
JSC::JSValue result = bitwise_cast<JSC::JSValue>(v);
#endif
if (!result)
return JSC::jsNull();
if (result.isCell())
RELEASE_ASSERT(result.asCell()->methodTable(exec->vm()));
return result;
}
inline JSC::JSValue toJSForGC(JSC::ExecState* exec, JSValueRef v)
{
ASSERT_UNUSED(exec, exec);
#if !CPU(ADDRESS64)
JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
if (!jsCell)
return JSC::JSValue();
JSC::JSValue result = jsCell;
#else
JSC::JSValue result = bitwise_cast<JSC::JSValue>(v);
#endif
if (result && result.isCell())
RELEASE_ASSERT(result.asCell()->methodTable(exec->vm()));
return result;
}
// Used in JSObjectGetPrivate as that may be called during finalization
inline JSC::JSObject* uncheckedToJS(JSObjectRef o)
{
return reinterpret_cast<JSC::JSObject*>(o);
}
inline JSC::JSObject* toJS(JSObjectRef o)
{
JSC::JSObject* object = uncheckedToJS(o);
if (object)
RELEASE_ASSERT(object->methodTable(object->vm()));
return object;
}
inline JSC::PropertyNameArray* toJS(JSPropertyNameAccumulatorRef a)
{
return reinterpret_cast<JSC::PropertyNameArray*>(a);
}
inline JSC::VM* toJS(JSContextGroupRef g)
{
return reinterpret_cast<JSC::VM*>(const_cast<OpaqueJSContextGroup*>(g));
}
inline JSValueRef toRef(JSC::VM& vm, JSC::JSValue v)
{
ASSERT(vm.currentThreadIsHoldingAPILock());
#if !CPU(ADDRESS64)
if (!v)
return 0;
if (!v.isCell())
return reinterpret_cast<JSValueRef>(JSC::JSAPIValueWrapper::create(vm, v));
return reinterpret_cast<JSValueRef>(v.asCell());
#else
UNUSED_PARAM(vm);
return bitwise_cast<JSValueRef>(v);
#endif
}
inline JSValueRef toRef(JSC::ExecState* exec, JSC::JSValue v)
{
return toRef(exec->vm(), v);
}
inline JSObjectRef toRef(JSC::JSObject* o)
{
return reinterpret_cast<JSObjectRef>(o);
}
inline JSObjectRef toRef(const JSC::JSObject* o)
{
return reinterpret_cast<JSObjectRef>(const_cast<JSC::JSObject*>(o));
}
inline JSContextRef toRef(JSC::ExecState* e)
{
return reinterpret_cast<JSContextRef>(e);
}
inline JSGlobalContextRef toGlobalRef(JSC::ExecState* e)
{
ASSERT(e == e->lexicalGlobalObject()->globalExec());
return reinterpret_cast<JSGlobalContextRef>(e);
}
inline JSPropertyNameAccumulatorRef toRef(JSC::PropertyNameArray* l)
{
return reinterpret_cast<JSPropertyNameAccumulatorRef>(l);
}
inline JSContextGroupRef toRef(JSC::VM* g)
{
return reinterpret_cast<JSContextGroupRef>(g);
}
#endif // APICast_h

View File

@@ -0,0 +1,65 @@
/*
* Copyright (C) 2016 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 APIUtils_h
#define APIUtils_h
#include "CatchScope.h"
#include "Exception.h"
#include "JSCJSValue.h"
#include "JSGlobalObjectInspectorController.h"
#include "JSValueRef.h"
enum class ExceptionStatus {
DidThrow,
DidNotThrow
};
inline ExceptionStatus handleExceptionIfNeeded(JSC::CatchScope& scope, JSC::ExecState* exec, JSValueRef* returnedExceptionRef)
{
if (UNLIKELY(scope.exception())) {
JSC::Exception* exception = scope.exception();
if (returnedExceptionRef)
*returnedExceptionRef = toRef(exec, exception->value());
scope.clearException();
#if ENABLE(REMOTE_INSPECTOR)
scope.vm().vmEntryGlobalObject(exec)->inspectorController().reportAPIException(exec, exception);
#endif
return ExceptionStatus::DidThrow;
}
return ExceptionStatus::DidNotThrow;
}
inline void setException(JSC::ExecState* exec, JSValueRef* returnedExceptionRef, JSC::JSValue exception)
{
if (returnedExceptionRef)
*returnedExceptionRef = toRef(exec, exception);
#if ENABLE(REMOTE_INSPECTOR)
JSC::VM& vm = exec->vm();
vm.vmEntryGlobalObject(exec)->inspectorController().reportAPIException(exec, JSC::Exception::create(vm, exception));
#endif
}
#endif /* APIUtils_h */

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2019 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.
*/
#pragma once
#include "JSGlobalObject.h"
OBJC_CLASS JSScript;
namespace JSC {
class JSAPIGlobalObject : public JSGlobalObject {
public:
using Base = JSGlobalObject;
DECLARE_EXPORT_INFO;
static const GlobalObjectMethodTable s_globalObjectMethodTable;
static JSAPIGlobalObject* create(VM& vm, Structure* structure)
{
auto* object = new (NotNull, allocateCell<JSAPIGlobalObject>(vm.heap)) JSAPIGlobalObject(vm, structure);
object->finishCreation(vm);
return object;
}
static Structure* createStructure(VM& vm, JSValue prototype)
{
auto* result = Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
result->setTransitionWatchpointIsLikelyToBeFired(true);
return result;
}
static JSInternalPromise* moduleLoaderImportModule(JSGlobalObject*, ExecState*, JSModuleLoader*, JSString* moduleNameValue, JSValue parameters, const SourceOrigin&);
static Identifier moduleLoaderResolve(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue keyValue, JSValue referrerValue, JSValue);
static JSInternalPromise* moduleLoaderFetch(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue, JSValue);
static JSObject* moduleLoaderCreateImportMetaProperties(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSModuleRecord*, JSValue);
static JSValue moduleLoaderEvaluate(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue, JSValue);
JSValue loadAndEvaluateJSScriptModule(const JSLockHolder&, JSScript *);
private:
JSAPIGlobalObject(VM& vm, Structure* structure)
: Base(vm, structure, &s_globalObjectMethodTable)
{ }
};
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003-2019 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#pragma once
#include "CallFrame.h"
#include "JSCJSValue.h"
#include "JSCast.h"
#include "Structure.h"
namespace JSC {
class JSAPIValueWrapper final : public JSCell {
friend JSValue jsAPIValueWrapper(ExecState*, JSValue);
public:
typedef JSCell Base;
static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
JSValue value() const { return m_value.get(); }
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
return Structure::create(vm, globalObject, prototype, TypeInfo(APIValueWrapperType, OverridesGetPropertyNames), info());
}
DECLARE_EXPORT_INFO;
static JSAPIValueWrapper* create(VM& vm, JSValue value)
{
JSAPIValueWrapper* wrapper = new (NotNull, allocateCell<JSAPIValueWrapper>(vm.heap)) JSAPIValueWrapper(vm);
wrapper->finishCreation(vm, value);
return wrapper;
}
protected:
void finishCreation(VM& vm, JSValue value)
{
Base::finishCreation(vm);
m_value.set(vm, this, value);
ASSERT(!value.isCell());
}
private:
JSAPIValueWrapper(VM& vm)
: JSCell(vm, vm.apiWrapperStructure.get())
{
}
WriteBarrier<Unknown> m_value;
};
} // namespace JSC

View File

@@ -0,0 +1,57 @@
/*
* Copyright (C) 2013-2019 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSAPIWrapperObject_h
#define JSAPIWrapperObject_h
#include "JSBase.h"
#include "JSDestructibleObject.h"
#if JSC_OBJC_API_ENABLED || defined(JSC_GLIB_API_ENABLED)
namespace JSC {
class JSAPIWrapperObject : public JSDestructibleObject {
public:
typedef JSDestructibleObject Base;
void finishCreation(VM&);
static void visitChildren(JSCell*, JSC::SlotVisitor&);
void* wrappedObject() { return m_wrappedObject; }
void setWrappedObject(void*);
protected:
JSAPIWrapperObject(VM&, Structure*);
private:
void* m_wrappedObject { nullptr };
};
} // namespace JSC
#endif // JSC_OBJC_API_ENABLED || defined(JSC_GLIB_API_ENABLED)
#endif // JSAPIWrapperObject_h

View File

@@ -0,0 +1,155 @@
/*
* Copyright (C) 2006 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 JSBase_h
#define JSBase_h
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#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;
/*! @typedef JSTypedArrayBytesDeallocator A function used to deallocate bytes passed to a Typed Array constructor. The function should take two arguments. The first is a pointer to the bytes that were originally passed to the Typed Array constructor. The second is a pointer to additional information desired at the time the bytes are to be freed. */
typedef void (*JSTypedArrayBytesDeallocator)(void* bytes, void* deallocatorContext);
/* 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;
/* Clang's __has_declspec_attribute emulation */
/* https://clang.llvm.org/docs/LanguageExtensions.html#has-declspec-attribute */
#ifndef __has_declspec_attribute
#define __has_declspec_attribute(x) 0
#endif
/* JavaScript symbol exports */
/* These rules should stay the same as in WebKit/Shared/API/c/WKDeclarationSpecifiers.h */
#undef JS_EXPORT
#if defined(JS_NO_EXPORT)
#define JS_EXPORT
#elif defined(WIN32) || defined(_WIN32) || defined(__CC_ARM) || defined(__ARMCC__) || (__has_declspec_attribute(dllimport) && __has_declspec_attribute(dllexport))
#if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore)
#define JS_EXPORT __declspec(dllexport)
#else
#define JS_EXPORT __declspec(dllimport)
#endif
#elif defined(__GNUC__)
#define JS_EXPORT __attribute__((visibility("default")))
#else /* !defined(JS_NO_EXPORT) */
#define JS_EXPORT
#endif /* defined(JS_NO_EXPORT) */
#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 used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
@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. NOTE: This is duplicated in VM.h. */
#if !defined(JSC_OBJC_API_ENABLED)
#if (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)))
#define JSC_OBJC_API_ENABLED 1
#else
#define JSC_OBJC_API_ENABLED 0
#endif
#endif
#endif /* JSBase_h */

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2019 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.
*/
#pragma once
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
namespace JSC {
class JSLockHolder;
class ExecState;
class SourceCode;
}
extern "C" JSValueRef JSEvaluateScriptInternal(const JSC::JSLockHolder&, JSC::ExecState*, JSContextRef, JSObjectRef thisObject, const JSC::SourceCode&, JSValueRef* exception);

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2008 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 JSBasePrivate_h
#define JSBasePrivate_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Reports an object's non-GC memory payload to the garbage collector.
@param ctx The execution context to use.
@param size The payload's size, in bytes.
@discussion Use this function to notify the garbage collector that a GC object
owns a large non-GC memory region. Calling this function will encourage the
garbage collector to collect soon, hoping to reclaim that large non-GC memory
region.
*/
JS_EXPORT void JSReportExtraMemoryCost(JSContextRef ctx, size_t size) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
JS_EXPORT void JSDisableGCTimer(void);
#ifdef __cplusplus
}
#endif
#endif /* JSBasePrivate_h */

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2013 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 JSCTestRunnerUtils_h
#define JSCTestRunnerUtils_h
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSValueRef.h>
namespace JSC {
JS_EXPORT_PRIVATE JSValueRef failNextNewCodeBlock(JSContextRef);
JS_EXPORT_PRIVATE JSValueRef numberOfDFGCompiles(JSContextRef, JSValueRef theFunction);
JS_EXPORT_PRIVATE JSValueRef setNeverInline(JSContextRef, JSValueRef theFunction);
JS_EXPORT_PRIVATE JSValueRef setNeverOptimize(JSContextRef, JSValueRef theFunction);
} // namespace JSC
#endif // JSCTestRunnerUtils_h

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2006, 2008 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 JSCallbackConstructor_h
#define JSCallbackConstructor_h
#include "JSDestructibleObject.h"
#include "JSObjectRef.h"
namespace JSC {
class JSCallbackConstructor final : public JSDestructibleObject {
public:
typedef JSDestructibleObject Base;
static const unsigned StructureFlags = Base::StructureFlags | ImplementsHasInstance | ImplementsDefaultHasInstance;
static JSCallbackConstructor* create(ExecState* exec, JSGlobalObject* globalObject, Structure* structure, JSClassRef classRef, JSObjectCallAsConstructorCallback callback)
{
VM& vm = exec->vm();
JSCallbackConstructor* constructor = new (NotNull, allocateCell<JSCallbackConstructor>(vm.heap)) JSCallbackConstructor(globalObject, structure, classRef, callback);
constructor->finishCreation(globalObject, classRef);
return constructor;
}
~JSCallbackConstructor();
static void destroy(JSCell*);
JSClassRef classRef() const { return m_class; }
JSObjectCallAsConstructorCallback callback() const { return m_callback; }
DECLARE_INFO;
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
{
return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info());
}
protected:
JSCallbackConstructor(JSGlobalObject*, Structure*, JSClassRef, JSObjectCallAsConstructorCallback);
void finishCreation(JSGlobalObject*, JSClassRef);
private:
friend struct APICallbackFunction;
static ConstructType getConstructData(JSCell*, ConstructData&);
JSObjectCallAsConstructorCallback constructCallback() { return m_callback; }
JSClassRef m_class;
JSObjectCallAsConstructorCallback m_callback;
};
} // namespace JSC
#endif // JSCallbackConstructor_h

View File

@@ -0,0 +1,67 @@
/*
* Copyright (C) 2006-2019 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 JSCallbackFunction_h
#define JSCallbackFunction_h
#include "InternalFunction.h"
#include "JSObjectRef.h"
namespace JSC {
class JSCallbackFunction final : public InternalFunction {
friend struct APICallbackFunction;
public:
typedef InternalFunction Base;
template<typename CellType, SubspaceAccess mode>
static IsoSubspace* subspaceFor(VM& vm)
{
return vm.callbackFunctionSpace<mode>();
}
static JSCallbackFunction* create(VM&, JSGlobalObject*, JSObjectCallAsFunctionCallback, const String& name);
DECLARE_INFO;
// InternalFunction mish-mashes constructor and function behavior -- we should
// refactor the code so this override isn't necessary
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
{
return Structure::create(vm, globalObject, proto, TypeInfo(InternalFunctionType, StructureFlags), info());
}
private:
JSCallbackFunction(VM&, Structure*, JSObjectCallAsFunctionCallback);
void finishCreation(VM&, const String& name);
JSObjectCallAsFunctionCallback functionCallback() { return m_callback; }
JSObjectCallAsFunctionCallback m_callback { nullptr };
};
} // namespace JSC
#endif // JSCallbackFunction_h

View File

@@ -0,0 +1,237 @@
/*
* Copyright (C) 2006-2019 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* 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 JSCallbackObject_h
#define JSCallbackObject_h
#include "JSObjectRef.h"
#include "JSValueRef.h"
#include "JSObject.h"
namespace JSC {
struct JSCallbackObjectData {
WTF_MAKE_FAST_ALLOCATED;
public:
JSCallbackObjectData(void* privateData, JSClassRef jsClass)
: privateData(privateData)
, jsClass(jsClass)
{
JSClassRetain(jsClass);
}
~JSCallbackObjectData()
{
JSClassRelease(jsClass);
}
JSValue getPrivateProperty(const Identifier& propertyName) const
{
if (!m_privateProperties)
return JSValue();
return m_privateProperties->getPrivateProperty(propertyName);
}
void setPrivateProperty(VM& vm, JSCell* owner, const Identifier& propertyName, JSValue value)
{
if (!m_privateProperties)
m_privateProperties = makeUnique<JSPrivatePropertyMap>();
m_privateProperties->setPrivateProperty(vm, owner, propertyName, value);
}
void deletePrivateProperty(const Identifier& propertyName)
{
if (!m_privateProperties)
return;
m_privateProperties->deletePrivateProperty(propertyName);
}
void visitChildren(SlotVisitor& visitor)
{
JSPrivatePropertyMap* properties = m_privateProperties.get();
if (!properties)
return;
properties->visitChildren(visitor);
}
void* privateData;
JSClassRef jsClass;
struct JSPrivatePropertyMap {
WTF_MAKE_FAST_ALLOCATED;
public:
JSValue getPrivateProperty(const Identifier& propertyName) const
{
PrivatePropertyMap::const_iterator location = m_propertyMap.find(propertyName.impl());
if (location == m_propertyMap.end())
return JSValue();
return location->value.get();
}
void setPrivateProperty(VM& vm, JSCell* owner, const Identifier& propertyName, JSValue value)
{
LockHolder locker(m_lock);
WriteBarrier<Unknown> empty;
m_propertyMap.add(propertyName.impl(), empty).iterator->value.set(vm, owner, value);
}
void deletePrivateProperty(const Identifier& propertyName)
{
LockHolder locker(m_lock);
m_propertyMap.remove(propertyName.impl());
}
void visitChildren(SlotVisitor& visitor)
{
LockHolder locker(m_lock);
for (auto& pair : m_propertyMap) {
if (pair.value)
visitor.append(pair.value);
}
}
private:
typedef HashMap<RefPtr<UniquedStringImpl>, WriteBarrier<Unknown>, IdentifierRepHash> PrivatePropertyMap;
PrivatePropertyMap m_propertyMap;
Lock m_lock;
};
std::unique_ptr<JSPrivatePropertyMap> m_privateProperties;
};
template <class Parent>
class JSCallbackObject final : public Parent {
protected:
JSCallbackObject(ExecState*, Structure*, JSClassRef, void* data);
JSCallbackObject(VM&, JSClassRef, Structure*);
void finishCreation(ExecState*);
void finishCreation(VM&);
public:
typedef Parent Base;
static const unsigned StructureFlags = Base::StructureFlags | ProhibitsPropertyCaching | OverridesGetOwnPropertySlot | InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | ImplementsHasInstance | OverridesGetPropertyNames | OverridesGetCallData;
static_assert(!(StructureFlags & ImplementsDefaultHasInstance), "using customHasInstance");
~JSCallbackObject();
static JSCallbackObject* create(ExecState* exec, JSGlobalObject* globalObject, Structure* structure, JSClassRef classRef, void* data)
{
VM& vm = exec->vm();
ASSERT_UNUSED(globalObject, !structure->globalObject() || structure->globalObject() == globalObject);
JSCallbackObject* callbackObject = new (NotNull, allocateCell<JSCallbackObject>(vm.heap)) JSCallbackObject(exec, structure, classRef, data);
callbackObject->finishCreation(exec);
return callbackObject;
}
static JSCallbackObject<Parent>* create(VM&, JSClassRef, Structure*);
static const bool needsDestruction;
static void destroy(JSCell* cell)
{
static_cast<JSCallbackObject*>(cell)->JSCallbackObject::~JSCallbackObject();
}
void setPrivate(void* data);
void* getPrivate();
// FIXME: We should fix the warnings for extern-template in JSObject template classes: https://bugs.webkit.org/show_bug.cgi?id=161979
IGNORE_CLANG_WARNINGS_BEGIN("undefined-var-template")
DECLARE_INFO;
IGNORE_CLANG_WARNINGS_END
JSClassRef classRef() const { return m_callbackObjectData->jsClass; }
bool inherits(JSClassRef) const;
static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
JSValue getPrivateProperty(const Identifier& propertyName) const
{
return m_callbackObjectData->getPrivateProperty(propertyName);
}
void setPrivateProperty(VM& vm, const Identifier& propertyName, JSValue value)
{
m_callbackObjectData->setPrivateProperty(vm, this, propertyName, value);
}
void deletePrivateProperty(const Identifier& propertyName)
{
m_callbackObjectData->deletePrivateProperty(propertyName);
}
using Parent::methodTable;
private:
static String className(const JSObject*, VM&);
static String toStringName(const JSObject*, ExecState*);
static JSValue defaultValue(const JSObject*, ExecState*, PreferredPrimitiveType);
static bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&);
static bool getOwnPropertySlotByIndex(JSObject*, ExecState*, unsigned propertyName, PropertySlot&);
static bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);
static bool putByIndex(JSCell*, ExecState*, unsigned, JSValue, bool shouldThrow);
static bool deleteProperty(JSCell*, ExecState*, PropertyName);
static bool deletePropertyByIndex(JSCell*, ExecState*, unsigned);
static bool customHasInstance(JSObject*, ExecState*, JSValue);
static void getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
static ConstructType getConstructData(JSCell*, ConstructData&);
static CallType getCallData(JSCell*, CallData&);
static void visitChildren(JSCell* cell, SlotVisitor& visitor)
{
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
ASSERT_GC_OBJECT_INHERITS((static_cast<Parent*>(thisObject)), JSCallbackObject<Parent>::info());
Parent::visitChildren(thisObject, visitor);
thisObject->m_callbackObjectData->visitChildren(visitor);
}
void init(ExecState*);
static JSCallbackObject* asCallbackObject(JSValue);
static JSCallbackObject* asCallbackObject(EncodedJSValue);
static EncodedJSValue JSC_HOST_CALL call(ExecState*);
static EncodedJSValue JSC_HOST_CALL construct(ExecState*);
JSValue getStaticValue(ExecState*, PropertyName);
static EncodedJSValue staticFunctionGetter(ExecState*, EncodedJSValue, PropertyName);
static EncodedJSValue callbackGetter(ExecState*, EncodedJSValue, PropertyName);
std::unique_ptr<JSCallbackObjectData> m_callbackObjectData;
const ClassInfo* m_classInfo { nullptr };
};
} // namespace JSC
// include the actual template class implementation
#include "JSCallbackObjectFunctions.h"
#endif // JSCallbackObject_h

View File

@@ -0,0 +1,714 @@
/*
* Copyright (C) 2006-2019 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* 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.
*/
#include "APICast.h"
#include "Error.h"
#include "ExceptionHelpers.h"
#include "JSCallbackFunction.h"
#include "JSClassRef.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "JSLock.h"
#include "JSObjectRef.h"
#include "JSString.h"
#include "OpaqueJSString.h"
#include "PropertyNameArray.h"
#include <wtf/Vector.h>
namespace JSC {
template <class Parent>
inline JSCallbackObject<Parent>* JSCallbackObject<Parent>::asCallbackObject(JSValue value)
{
ASSERT(asObject(value)->inherits(value.getObject()->vm(), info()));
return jsCast<JSCallbackObject*>(asObject(value));
}
template <class Parent>
inline JSCallbackObject<Parent>* JSCallbackObject<Parent>::asCallbackObject(EncodedJSValue encodedValue)
{
JSValue value = JSValue::decode(encodedValue);
ASSERT(asObject(value)->inherits(value.getObject()->vm(), info()));
return jsCast<JSCallbackObject*>(asObject(value));
}
template <class Parent>
JSCallbackObject<Parent>::JSCallbackObject(ExecState* exec, Structure* structure, JSClassRef jsClass, void* data)
: Parent(exec->vm(), structure)
, m_callbackObjectData(makeUnique<JSCallbackObjectData>(data, jsClass))
{
}
// Global object constructor.
// FIXME: Move this into a separate JSGlobalCallbackObject class derived from this one.
template <class Parent>
JSCallbackObject<Parent>::JSCallbackObject(VM& vm, JSClassRef jsClass, Structure* structure)
: Parent(vm, structure)
, m_callbackObjectData(makeUnique<JSCallbackObjectData>(nullptr, jsClass))
{
}
template <class Parent>
JSCallbackObject<Parent>::~JSCallbackObject()
{
VM& vm = this->HeapCell::vm();
vm.currentlyDestructingCallbackObject = this;
ASSERT(m_classInfo);
vm.currentlyDestructingCallbackObjectClassInfo = m_classInfo;
JSObjectRef thisRef = toRef(static_cast<JSObject*>(this));
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectFinalizeCallback finalize = jsClass->finalize)
finalize(thisRef);
}
vm.currentlyDestructingCallbackObject = nullptr;
vm.currentlyDestructingCallbackObjectClassInfo = nullptr;
}
template <class Parent>
void JSCallbackObject<Parent>::finishCreation(ExecState* exec)
{
VM& vm = exec->vm();
Base::finishCreation(vm);
ASSERT(Parent::inherits(vm, info()));
init(exec);
}
// This is just for Global object, so we can assume that Base::finishCreation is JSGlobalObject::finishCreation.
template <class Parent>
void JSCallbackObject<Parent>::finishCreation(VM& vm)
{
ASSERT(Parent::inherits(vm, info()));
ASSERT(Parent::isGlobalObject());
Base::finishCreation(vm);
init(jsCast<JSGlobalObject*>(this)->globalExec());
}
template <class Parent>
void JSCallbackObject<Parent>::init(ExecState* exec)
{
ASSERT(exec);
Vector<JSObjectInitializeCallback, 16> initRoutines;
JSClassRef jsClass = classRef();
do {
if (JSObjectInitializeCallback initialize = jsClass->initialize)
initRoutines.append(initialize);
} while ((jsClass = jsClass->parentClass));
// initialize from base to derived
for (int i = static_cast<int>(initRoutines.size()) - 1; i >= 0; i--) {
JSLock::DropAllLocks dropAllLocks(exec);
JSObjectInitializeCallback initialize = initRoutines[i];
initialize(toRef(exec), toRef(this));
}
m_classInfo = this->classInfo();
}
template <class Parent>
String JSCallbackObject<Parent>::className(const JSObject* object, VM& vm)
{
const JSCallbackObject* thisObject = jsCast<const JSCallbackObject*>(object);
String thisClassName = thisObject->classRef()->className();
if (!thisClassName.isEmpty())
return thisClassName;
return Parent::className(object, vm);
}
template <class Parent>
String JSCallbackObject<Parent>::toStringName(const JSObject* object, ExecState* exec)
{
VM& vm = exec->vm();
const ClassInfo* info = object->classInfo(vm);
ASSERT(info);
return info->methodTable.className(object, vm);
}
template <class Parent>
bool JSCallbackObject<Parent>::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
RefPtr<OpaqueJSString> propertyNameRef;
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
// optional optimization to bypass getProperty in cases when we only need to know if the property exists
if (JSObjectHasPropertyCallback hasProperty = jsClass->hasProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(name);
JSLock::DropAllLocks dropAllLocks(exec);
if (hasProperty(ctx, thisRef, propertyNameRef.get())) {
slot.setCustom(thisObject, PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum, callbackGetter);
return true;
}
} else if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(name);
JSValueRef exception = 0;
JSValueRef value;
{
JSLock::DropAllLocks dropAllLocks(exec);
value = getProperty(ctx, thisRef, propertyNameRef.get(), &exception);
}
if (exception) {
throwException(exec, scope, toJS(exec, exception));
slot.setValue(thisObject, PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum, jsUndefined());
return true;
}
if (value) {
slot.setValue(thisObject, PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum, toJS(exec, value));
return true;
}
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (staticValues->contains(name)) {
JSValue value = thisObject->getStaticValue(exec, propertyName);
if (value) {
slot.setValue(thisObject, PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum, value);
return true;
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (staticFunctions->contains(name)) {
slot.setCustom(thisObject, PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum, staticFunctionGetter);
return true;
}
}
}
}
return Parent::getOwnPropertySlot(thisObject, exec, propertyName, slot);
}
template <class Parent>
bool JSCallbackObject<Parent>::getOwnPropertySlotByIndex(JSObject* object, ExecState* exec, unsigned propertyName, PropertySlot& slot)
{
VM& vm = exec->vm();
return object->methodTable(vm)->getOwnPropertySlot(object, exec, Identifier::from(vm, propertyName), slot);
}
template <class Parent>
JSValue JSCallbackObject<Parent>::defaultValue(const JSObject* object, ExecState* exec, PreferredPrimitiveType hint)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
const JSCallbackObject* thisObject = jsCast<const JSCallbackObject*>(object);
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
::JSType jsHint = hint == PreferString ? kJSTypeString : kJSTypeNumber;
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectConvertToTypeCallback convertToType = jsClass->convertToType) {
JSValueRef exception = 0;
JSValueRef result = convertToType(ctx, thisRef, jsHint, &exception);
if (exception) {
throwException(exec, scope, toJS(exec, exception));
return jsUndefined();
}
if (result)
return toJS(exec, result);
}
}
return Parent::defaultValue(object, exec, hint);
}
template <class Parent>
bool JSCallbackObject<Parent>::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
RefPtr<OpaqueJSString> propertyNameRef;
JSValueRef valueRef = toRef(exec, value);
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectSetPropertyCallback setProperty = jsClass->setProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(name);
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(name)) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
if (JSObjectSetPropertyCallback setProperty = entry->setProperty) {
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = setProperty(ctx, thisRef, entry->propertyNameRef.get(), valueRef, &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
PropertySlot getSlot(thisObject, PropertySlot::InternalMethodType::VMInquiry);
if (Parent::getOwnPropertySlot(thisObject, exec, propertyName, getSlot))
return Parent::put(thisObject, exec, propertyName, value, slot);
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
return thisObject->JSCallbackObject<Parent>::putDirect(vm, propertyName, value); // put as override property
}
}
}
}
return Parent::put(thisObject, exec, propertyName, value, slot);
}
template <class Parent>
bool JSCallbackObject<Parent>::putByIndex(JSCell* cell, ExecState* exec, unsigned propertyIndex, JSValue value, bool shouldThrow)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
RefPtr<OpaqueJSString> propertyNameRef;
JSValueRef valueRef = toRef(exec, value);
Identifier propertyName = Identifier::from(vm, propertyIndex);
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectSetPropertyCallback setProperty = jsClass->setProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(propertyName.impl());
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(propertyName.impl())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
if (JSObjectSetPropertyCallback setProperty = entry->setProperty) {
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = setProperty(ctx, thisRef, entry->propertyNameRef.get(), valueRef, &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.impl())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
break;
}
}
}
return Parent::putByIndex(thisObject, exec, propertyIndex, value, shouldThrow);
}
template <class Parent>
bool JSCallbackObject<Parent>::deleteProperty(JSCell* cell, ExecState* exec, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
RefPtr<OpaqueJSString> propertyNameRef;
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectDeletePropertyCallback deleteProperty = jsClass->deleteProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(name);
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = deleteProperty(ctx, thisRef, propertyNameRef.get(), &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return true;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(name)) {
if (entry->attributes & kJSPropertyAttributeDontDelete)
return false;
return true;
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
if (entry->attributes & kJSPropertyAttributeDontDelete)
return false;
return true;
}
}
}
}
return Parent::deleteProperty(thisObject, exec, propertyName);
}
template <class Parent>
bool JSCallbackObject<Parent>::deletePropertyByIndex(JSCell* cell, ExecState* exec, unsigned propertyName)
{
VM& vm = exec->vm();
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
return thisObject->methodTable(vm)->deleteProperty(thisObject, exec, Identifier::from(vm, propertyName));
}
template <class Parent>
ConstructType JSCallbackObject<Parent>::getConstructData(JSCell* cell, ConstructData& constructData)
{
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (jsClass->callAsConstructor) {
constructData.native.function = construct;
return ConstructType::Host;
}
}
return ConstructType::None;
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::construct(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* constructor = exec->jsCallee();
JSContextRef execRef = toRef(exec);
JSObjectRef constructorRef = toRef(constructor);
for (JSClassRef jsClass = jsCast<JSCallbackObject<Parent>*>(constructor)->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectCallAsConstructorCallback callAsConstructor = jsClass->callAsConstructor) {
size_t argumentCount = exec->argumentCount();
Vector<JSValueRef, 16> arguments;
arguments.reserveInitialCapacity(argumentCount);
for (size_t i = 0; i < argumentCount; ++i)
arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
JSValueRef exception = 0;
JSObject* result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = toJS(callAsConstructor(execRef, constructorRef, argumentCount, arguments.data(), &exception));
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(result);
}
}
RELEASE_ASSERT_NOT_REACHED(); // getConstructData should prevent us from reaching here
return JSValue::encode(JSValue());
}
template <class Parent>
bool JSCallbackObject<Parent>::customHasInstance(JSObject* object, ExecState* exec, JSValue value)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
JSContextRef execRef = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectHasInstanceCallback hasInstance = jsClass->hasInstance) {
JSValueRef valueRef = toRef(exec, value);
JSValueRef exception = 0;
bool result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = hasInstance(execRef, thisRef, valueRef, &exception);
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
return result;
}
}
return false;
}
template <class Parent>
CallType JSCallbackObject<Parent>::getCallData(JSCell* cell, CallData& callData)
{
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (jsClass->callAsFunction) {
callData.native.function = call;
return CallType::Host;
}
}
return CallType::None;
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::call(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(exec->jsCallee());
JSObjectRef thisObjRef = toRef(jsCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode)));
for (JSClassRef jsClass = jsCast<JSCallbackObject<Parent>*>(toJS(functionRef))->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectCallAsFunctionCallback callAsFunction = jsClass->callAsFunction) {
size_t argumentCount = exec->argumentCount();
Vector<JSValueRef, 16> arguments;
arguments.reserveInitialCapacity(argumentCount);
for (size_t i = 0; i < argumentCount; ++i)
arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
JSValueRef exception = 0;
JSValue result;
{
JSLock::DropAllLocks dropAllLocks(exec);
result = toJS(exec, callAsFunction(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception));
}
if (exception)
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(result);
}
}
RELEASE_ASSERT_NOT_REACHED(); // getCallData should prevent us from reaching here
return JSValue::encode(JSValue());
}
template <class Parent>
void JSCallbackObject<Parent>::getOwnNonIndexPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
VM& vm = exec->vm();
JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
JSContextRef execRef = toRef(exec);
JSObjectRef thisRef = toRef(thisObject);
for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectGetPropertyNamesCallback getPropertyNames = jsClass->getPropertyNames) {
JSLock::DropAllLocks dropAllLocks(exec);
getPropertyNames(execRef, thisRef, toRef(&propertyNames));
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
typedef OpaqueJSClassStaticValuesTable::const_iterator iterator;
iterator end = staticValues->end();
for (iterator it = staticValues->begin(); it != end; ++it) {
StringImpl* name = it->key.get();
StaticValueEntry* entry = it->value.get();
if (entry->getProperty && (!(entry->attributes & kJSPropertyAttributeDontEnum) || mode.includeDontEnumProperties())) {
ASSERT(!name->isSymbol());
propertyNames.add(Identifier::fromString(vm, String(name)));
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
typedef OpaqueJSClassStaticFunctionsTable::const_iterator iterator;
iterator end = staticFunctions->end();
for (iterator it = staticFunctions->begin(); it != end; ++it) {
StringImpl* name = it->key.get();
StaticFunctionEntry* entry = it->value.get();
if (!(entry->attributes & kJSPropertyAttributeDontEnum) || mode.includeDontEnumProperties()) {
ASSERT(!name->isSymbol());
propertyNames.add(Identifier::fromString(vm, String(name)));
}
}
}
}
Parent::getOwnNonIndexPropertyNames(thisObject, exec, propertyNames, mode);
}
template <class Parent>
void JSCallbackObject<Parent>::setPrivate(void* data)
{
m_callbackObjectData->privateData = data;
}
template <class Parent>
void* JSCallbackObject<Parent>::getPrivate()
{
return m_callbackObjectData->privateData;
}
template <class Parent>
bool JSCallbackObject<Parent>::inherits(JSClassRef c) const
{
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (jsClass == c)
return true;
}
return false;
}
template <class Parent>
JSValue JSCallbackObject<Parent>::getStaticValue(ExecState* exec, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObjectRef thisRef = toRef(this);
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(name)) {
if (JSObjectGetPropertyCallback getProperty = entry->getProperty) {
JSValueRef exception = 0;
JSValueRef value;
{
JSLock::DropAllLocks dropAllLocks(exec);
value = getProperty(toRef(exec), thisRef, entry->propertyNameRef.get(), &exception);
}
if (exception) {
throwException(exec, scope, toJS(exec, exception));
return jsUndefined();
}
if (value)
return toJS(exec, value);
}
}
}
}
}
return JSValue();
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::staticFunctionGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObj = asCallbackObject(thisValue);
// Check for cached or override property.
PropertySlot slot2(thisObj, PropertySlot::InternalMethodType::VMInquiry);
if (Parent::getOwnPropertySlot(thisObj, exec, propertyName, slot2))
return JSValue::encode(slot2.getValue(exec, propertyName));
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
if (JSObjectCallAsFunctionCallback callAsFunction = entry->callAsFunction) {
JSObject* o = JSCallbackFunction::create(vm, thisObj->globalObject(vm), callAsFunction, name);
thisObj->putDirect(vm, propertyName, o, entry->attributes);
return JSValue::encode(o);
}
}
}
}
}
return JSValue::encode(throwException(exec, scope, createReferenceError(exec, "Static function property defined with NULL callAsFunction callback."_s)));
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::callbackGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObj = asCallbackObject(thisValue);
JSObjectRef thisRef = toRef(thisObj);
RefPtr<OpaqueJSString> propertyNameRef;
if (StringImpl* name = propertyName.uid()) {
for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::tryCreate(name);
JSValueRef exception = 0;
JSValueRef value;
{
JSLock::DropAllLocks dropAllLocks(exec);
value = getProperty(toRef(exec), thisRef, propertyNameRef.get(), &exception);
}
if (exception) {
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(jsUndefined());
}
if (value)
return JSValue::encode(toJS(exec, value));
}
}
}
return JSValue::encode(throwException(exec, scope, createReferenceError(exec, "hasProperty callback returned true for a property that doesn't exist."_s)));
}
} // namespace JSC

View File

@@ -0,0 +1,130 @@
/*
* Copyright (C) 2006 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 JSClassRef_h
#define JSClassRef_h
#include "OpaqueJSString.h"
#include "Protect.h"
#include "Weak.h"
#include <JavaScriptCore/JSObjectRef.h>
#include <wtf/HashMap.h>
#include <wtf/text/WTFString.h>
struct StaticValueEntry {
WTF_MAKE_FAST_ALLOCATED;
public:
StaticValueEntry(JSObjectGetPropertyCallback _getProperty, JSObjectSetPropertyCallback _setProperty, JSPropertyAttributes _attributes, String& propertyName)
: getProperty(_getProperty)
, setProperty(_setProperty)
, attributes(_attributes)
, propertyNameRef(OpaqueJSString::tryCreate(propertyName))
{
}
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSPropertyAttributes attributes;
RefPtr<OpaqueJSString> propertyNameRef;
};
struct StaticFunctionEntry {
WTF_MAKE_FAST_ALLOCATED;
public:
StaticFunctionEntry(JSObjectCallAsFunctionCallback _callAsFunction, JSPropertyAttributes _attributes)
: callAsFunction(_callAsFunction), attributes(_attributes)
{
}
JSObjectCallAsFunctionCallback callAsFunction;
JSPropertyAttributes attributes;
};
typedef HashMap<RefPtr<StringImpl>, std::unique_ptr<StaticValueEntry>> OpaqueJSClassStaticValuesTable;
typedef HashMap<RefPtr<StringImpl>, std::unique_ptr<StaticFunctionEntry>> OpaqueJSClassStaticFunctionsTable;
struct OpaqueJSClass;
// An OpaqueJSClass (JSClass) is created without a context, so it can be used with any context, even across context groups.
// This structure holds data members that vary across context groups.
struct OpaqueJSClassContextData {
WTF_MAKE_NONCOPYABLE(OpaqueJSClassContextData); WTF_MAKE_FAST_ALLOCATED;
public:
OpaqueJSClassContextData(JSC::VM&, OpaqueJSClass*);
// It is necessary to keep OpaqueJSClass alive because of the following rare scenario:
// 1. A class is created and used, so its context data is stored in VM hash map.
// 2. The class is released, and when all JS objects that use it are collected, OpaqueJSClass
// is deleted (that's the part prevented by this RefPtr).
// 3. Another class is created at the same address.
// 4. When it is used, the old context data is found in VM and used.
RefPtr<OpaqueJSClass> m_class;
std::unique_ptr<OpaqueJSClassStaticValuesTable> staticValues;
std::unique_ptr<OpaqueJSClassStaticFunctionsTable> staticFunctions;
JSC::Weak<JSC::JSObject> cachedPrototype;
};
struct OpaqueJSClass : public ThreadSafeRefCounted<OpaqueJSClass> {
static Ref<OpaqueJSClass> create(const JSClassDefinition*);
static Ref<OpaqueJSClass> createNoAutomaticPrototype(const JSClassDefinition*);
JS_EXPORT_PRIVATE ~OpaqueJSClass();
String className();
OpaqueJSClassStaticValuesTable* staticValues(JSC::ExecState*);
OpaqueJSClassStaticFunctionsTable* staticFunctions(JSC::ExecState*);
JSC::JSObject* prototype(JSC::ExecState*);
OpaqueJSClass* parentClass;
OpaqueJSClass* prototypeClass;
JSObjectInitializeCallback initialize;
JSObjectFinalizeCallback finalize;
JSObjectHasPropertyCallback hasProperty;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSObjectDeletePropertyCallback deleteProperty;
JSObjectGetPropertyNamesCallback getPropertyNames;
JSObjectCallAsFunctionCallback callAsFunction;
JSObjectCallAsConstructorCallback callAsConstructor;
JSObjectHasInstanceCallback hasInstance;
JSObjectConvertToTypeCallback convertToType;
private:
friend struct OpaqueJSClassContextData;
OpaqueJSClass();
OpaqueJSClass(const OpaqueJSClass&);
OpaqueJSClass(const JSClassDefinition*, OpaqueJSClass* protoClass);
OpaqueJSClassContextData& contextData(JSC::ExecState*);
// Strings in these data members should not be put into any AtomStringTable.
String m_className;
std::unique_ptr<OpaqueJSClassStaticValuesTable> m_staticValues;
std::unique_ptr<OpaqueJSClassStaticFunctionsTable> m_staticFunctions;
};
#endif // JSClassRef_h

View File

@@ -0,0 +1,238 @@
/*
* Copyright (C) 2013-2019 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 JSContext_h
#define JSContext_h
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/WebKitAvailability.h>
#if JSC_OBJC_API_ENABLED
@class JSScript, JSVirtualMachine, JSValue, JSContext;
/*!
@interface
@discussion A JSContext is a JavaScript execution environment. All
JavaScript execution takes place within a context, and all JavaScript values
are tied to a context.
*/
JSC_CLASS_AVAILABLE(macos(10.9), ios(7.0))
@interface JSContext : NSObject
/*!
@methodgroup Creating New JSContexts
*/
/*!
@method
@abstract Create a JSContext.
@result The new context.
*/
- (instancetype)init;
/*!
@method
@abstract Create a JSContext in the specified virtual machine.
@param virtualMachine The JSVirtualMachine in which the context will be created.
@result The new context.
*/
- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine;
/*!
@methodgroup Evaluating Scripts
*/
/*!
@method
@abstract Evaluate a string of JavaScript code.
@param script A string containing the JavaScript code to evaluate.
@result The last value generated by the script.
*/
- (JSValue *)evaluateScript:(NSString *)script;
/*!
@method
@abstract Evaluate a string of JavaScript code, with a URL for the script's source file.
@param script A string containing the JavaScript code to evaluate.
@param sourceURL A URL for the script's source file. Used by debuggers and when reporting exceptions. This parameter is informative only: it does not change the behavior of the script.
@result The last value generated by the script.
*/
- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@methodgroup Callback Accessors
*/
/*!
@method
@abstract Get the JSContext that is currently executing.
@discussion This method may be called from within an Objective-C block or method invoked
as a callback from JavaScript to retrieve the callback's context. Outside of
a callback from JavaScript this method will return nil.
@result The currently executing JSContext or nil if there isn't one.
*/
+ (JSContext *)currentContext;
/*!
@method
@abstract Get the JavaScript function that is currently executing.
@discussion This method may be called from within an Objective-C block or method invoked
as a callback from JavaScript to retrieve the callback's context. Outside of
a callback from JavaScript this method will return nil.
@result The currently executing JavaScript function or nil if there isn't one.
*/
+ (JSValue *)currentCallee JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@method
@abstract Get the <code>this</code> value of the currently executing method.
@discussion This method may be called from within an Objective-C block or method invoked
as a callback from JavaScript to retrieve the callback's this value. Outside
of a callback from JavaScript this method will return nil.
@result The current <code>this</code> value or nil if there isn't one.
*/
+ (JSValue *)currentThis;
/*!
@method
@abstract Get the arguments to the current callback.
@discussion This method may be called from within an Objective-C block or method invoked
as a callback from JavaScript to retrieve the callback's arguments, objects
in the returned array are instances of JSValue. Outside of a callback from
JavaScript this method will return nil.
@result An NSArray of the arguments nil if there is no current callback.
*/
+ (NSArray *)currentArguments;
/*!
@functiongroup Global Properties
*/
/*!
@property
@abstract Get the global object of the context.
@discussion This method retrieves the global object of the JavaScript execution context.
Instances of JSContext originating from WebKit will return a reference to the
WindowProxy object.
@result The global object.
*/
@property (readonly, strong) JSValue *globalObject;
/*!
@property
@discussion The <code>exception</code> property may be used to throw an exception to JavaScript.
Before a callback is made from JavaScript to an Objective-C block or method,
the prior value of the exception property will be preserved and the property
will be set to nil. After the callback has completed the new value of the
exception property will be read, and prior value restored. If the new value
of exception is not nil, the callback will result in that value being thrown.
This property may also be used to check for uncaught exceptions arising from
API function calls (since the default behaviour of <code>exceptionHandler</code> is to
assign an uncaught exception to this property).
*/
@property (strong) JSValue *exception;
/*!
@property
@discussion If a call to an API function results in an uncaught JavaScript exception, the
<code>exceptionHandler</code> block will be invoked. The default implementation for the
exception handler will store the exception to the exception property on
context. As a consequence the default behaviour is for uncaught exceptions
occurring within a callback from JavaScript to be rethrown upon return.
Setting this value to nil will cause all exceptions occurring
within a callback from JavaScript to be silently caught.
*/
@property (copy) void(^exceptionHandler)(JSContext *context, JSValue *exception);
/*!
@property
@discussion All instances of JSContext are associated with a JSVirtualMachine.
*/
@property (readonly, strong) JSVirtualMachine *virtualMachine;
/*!
@property
@discussion Name of the JSContext. Exposed when remote debugging the context.
*/
@property (copy) NSString *name JSC_API_AVAILABLE(macos(10.10), ios(8.0));
@end
/*!
@category
@discussion Instances of JSContext implement the following methods in order to enable
support for subscript access by key and index, for example:
@textblock
JSContext *context;
JSValue *v = context[@"X"]; // Get value for "X" from the global object.
context[@"Y"] = v; // Assign 'v' to "Y" on the global object.
@/textblock
An object key passed as a subscript will be converted to a JavaScript value,
and then the value converted to a string used to resolve a property of the
global object.
*/
@interface JSContext (SubscriptSupport)
/*!
@method
@abstract Get a particular property on the global object.
@result The JSValue for the global object's property.
*/
- (JSValue *)objectForKeyedSubscript:(id)key;
/*!
@method
@abstract Set a particular property on the global object.
*/
- (void)setObject:(id)object forKeyedSubscript:(NSObject <NSCopying> *)key;
@end
/*!
@category
@discussion These functions are for bridging between the C API and the Objective-C API.
*/
@interface JSContext (JSContextRefSupport)
/*!
@method
@abstract Create a JSContext, wrapping its C API counterpart.
@result The JSContext equivalent of the provided JSGlobalContextRef.
*/
+ (JSContext *)contextWithJSGlobalContextRef:(JSGlobalContextRef)jsGlobalContextRef;
/*!
@property
@abstract Get the C API counterpart wrapped by a JSContext.
@result The C API equivalent of this JSContext.
*/
@property (readonly) JSGlobalContextRef JSGlobalContextRef;
@end
#endif
#endif // JSContext_h

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2013-2019 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.
*/
#import <JavaScriptCore/JavaScriptCore.h>
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JSContextPrivate.h>
struct CallbackData {
CallbackData* next;
JSContext *context;
JSValue *preservedException;
JSValueRef calleeValue;
JSValueRef thisValue;
size_t argumentCount;
const JSValueRef *arguments;
NSArray *currentArguments;
};
@class JSWrapperMap;
@interface JSContext(Internal)
- (void)notifyException:(JSValueRef)exception;
- (JSValue *)valueFromNotifyException:(JSValueRef)exception;
- (BOOL)boolFromNotifyException:(JSValueRef)exception;
- (void)beginCallbackWithData:(CallbackData *)callbackData calleeValue:(JSValueRef)calleeValue thisValue:(JSValueRef)thisValue argumentCount:(size_t)argumentCount arguments:(const JSValueRef *)arguments;
- (void)endCallbackWithData:(CallbackData *)callbackData;
- (JSWrapperMap *)wrapperMap;
- (JSValue *)wrapperForObjCObject:(id)object;
- (JSValue *)wrapperForJSObject:(JSValueRef)value;
@end
#endif

View File

@@ -0,0 +1,113 @@
/*
* Copyright (C) 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 JSContextPrivate_h
#define JSContextPrivate_h
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JSContext.h>
@protocol JSModuleLoaderDelegate <NSObject>
@required
/*! @abstract Provides source code for any JS module that is actively imported.
@param context The context for which the module is being requested.
@param identifier The resolved identifier for the requested module.
@param resolve A JS function to call with the desired script for identifier.
@param reject A JS function to call when identifier cannot be fetched.
@discussion Currently, identifier will always be an absolute file URL computed from specifier of the requested module relative to the URL of the requesting script. If the requesting script does not have a URL and the module specifier is not an absolute path the module loader will fail to load the module.
The first argument to resolve sholud always be a JSScript, otherwise the module loader will reject the module.
Once an identifier has been resolved or rejected in a given context it will never be requested again. If a script is successfully evaluated it will not be re-evaluated on any subsequent import.
The VM will retain all evaluated modules for the lifetime of the context.
*/
- (void)context:(JSContext *)context fetchModuleForIdentifier:(JSValue *)identifier withResolveHandler:(JSValue *)resolve andRejectHandler:(JSValue *)reject;
@optional
/*! @abstract This is called before the module with "key" is evaluated.
@param key The module key for the module that is about to be evaluated.
*/
- (void)willEvaluateModule:(NSURL *)key;
/*! @abstract This is called after the module with "key" is evaluated.
@param key The module key for the module that was just evaluated.
*/
- (void)didEvaluateModule:(NSURL *)key;
@end
@interface JSContext(Private)
/*!
@property
@discussion Remote inspection setting of the JSContext. Default value is YES.
*/
@property (setter=_setRemoteInspectionEnabled:) BOOL _remoteInspectionEnabled JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@property
@discussion Set whether or not the native call stack is included when reporting exceptions. Default value is YES.
*/
@property (setter=_setIncludesNativeCallStackWhenReportingExceptions:) BOOL _includesNativeCallStackWhenReportingExceptions JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@property
@discussion Set the run loop the Web Inspector debugger should use when evaluating JavaScript in the JSContext.
*/
@property (setter=_setDebuggerRunLoop:) CFRunLoopRef _debuggerRunLoop JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*! @abstract The delegate the context will use when trying to load a module. Note, this delegate will be ignored for contexts returned by UIWebView. */
@property (nonatomic, weak) id <JSModuleLoaderDelegate> moduleLoaderDelegate JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Run a JSScript.
@param script the JSScript to evaluate.
@discussion If the provided JSScript was created with kJSScriptTypeProgram, the script will run synchronously and return the result of evaluation.
Otherwise, if the script was created with kJSScriptTypeModule, the module will be run asynchronously and will return a promise resolved when the module and any transitive dependencies are loaded. The module loader will treat the script as if it had been returned from a delegate call to moduleLoaderDelegate. This mirrors the JavaScript dynamic import operation.
*/
// FIXME: Before making this public need to fix: https://bugs.webkit.org/show_bug.cgi?id=199714
- (JSValue *)evaluateJSScript:(JSScript *)script JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Get the identifiers of the modules a JSScript depends on in this context.
@param script the JSScript to determine the dependencies of.
@result An Array containing all the identifiers of modules script depends on.
@discussion If the provided JSScript was not created with kJSScriptTypeModule, an exception will be thrown. Also, if the script has not already been evaluated in this context an error will be throw.
*/
- (JSValue *)dependencyIdentifiersForModuleJSScript:(JSScript *)script JSC_API_AVAILABLE(macos(10.15), ios(13.0));
@end
#endif
#endif // JSContextInternal_h

View File

@@ -0,0 +1,163 @@
/*
* Copyright (C) 2006 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 JSContextRef_h
#define JSContextRef_h
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#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.
A JSContextGroup may need to run deferred tasks on a run loop, such as garbage collection
or resolving WebAssembly compilations. By default, calling JSContextGroupCreate will use
the run loop of the thread it was called on. Currently, there is no API to change a
JSContextGroup's run loop once it has been created.
@result The created JSContextGroup.
*/
JS_EXPORT JSContextGroupRef JSContextGroupCreate(void) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Releases a JavaScript context group.
@param group The JSContextGroup to release.
*/
JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.5), ios(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) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.7), ios(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) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@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) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
#ifdef __cplusplus
}
#endif
#endif /* JSContextRef_h */

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 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 JSContextRefInspectorSupport_h
#define JSContextRefInspectorSupport_h
#ifndef __cplusplus
#error Requires C++ Support.
#endif
#include <JavaScriptCore/JSContextRefPrivate.h>
namespace Inspector {
class AugmentableInspectorController;
}
extern "C" {
JS_EXPORT Inspector::AugmentableInspectorController* JSGlobalContextGetAugmentableInspectorController(JSGlobalContextRef);
}
#endif // JSContextRefInspectorSupport_h

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 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 JSContextRefInternal_h
#define JSContextRefInternal_h
#include "JSContextRefPrivate.h"
#if USE(CF)
#include <CoreFoundation/CFRunLoop.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if USE(CF)
/*!
@function
@abstract Gets the run loop used by the Web Inspector debugger when evaluating JavaScript in this context.
@param ctx The JSGlobalContext whose setting you want to get.
*/
JS_EXPORT CFRunLoopRef JSGlobalContextGetDebuggerRunLoop(JSGlobalContextRef ctx) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Sets the run loop used by the Web Inspector debugger when evaluating JavaScript in this context.
@param ctx The JSGlobalContext that you want to change.
@param runLoop The new value of the setting for the context.
*/
JS_EXPORT void JSGlobalContextSetDebuggerRunLoop(JSGlobalContextRef ctx, CFRunLoopRef runLoop) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
#endif
#ifdef __cplusplus
}
#endif
#endif // JSContextRefInternal_h

View File

@@ -0,0 +1,145 @@
/*
* Copyright (C) 2009 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 JSContextRefPrivate_h
#define JSContextRefPrivate_h
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Gets a Backtrace for the existing context
@param ctx The JSContext whose backtrace you want to get
@result A string containing the backtrace
*/
JS_EXPORT JSStringRef JSContextCreateBacktrace(JSContextRef ctx, unsigned maxStackSize) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@typedef JSShouldTerminateCallback
@abstract The callback invoked when script execution has exceeded the allowed
time limit previously specified via JSContextGroupSetExecutionTimeLimit.
@param ctx The execution context to use.
@param context User specified context data previously passed to
JSContextGroupSetExecutionTimeLimit.
@discussion If you named your function Callback, you would declare it like this:
bool Callback(JSContextRef ctx, void* context);
If you return true, the timed out script will terminate.
If you return false, the script will run for another period of the allowed
time limit specified via JSContextGroupSetExecutionTimeLimit.
Within this callback function, you may call JSContextGroupSetExecutionTimeLimit
to set a new time limit, or JSContextGroupClearExecutionTimeLimit to cancel the
timeout.
*/
typedef bool
(*JSShouldTerminateCallback) (JSContextRef ctx, void* context);
/*!
@function
@abstract Sets the script execution time limit.
@param group The JavaScript context group that this time limit applies to.
@param limit The time limit of allowed script execution time in seconds.
@param callback The callback function that will be invoked when the time limit
has been reached. This will give you a chance to decide if you want to
terminate the script or not. If you pass a NULL callback, the script will be
terminated unconditionally when the time limit has been reached.
@param context User data that you can provide to be passed back to you
in your callback.
In order to guarantee that the execution time limit will take effect, you will
need to call JSContextGroupSetExecutionTimeLimit before you start executing
any scripts.
*/
JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef group, double limit, JSShouldTerminateCallback callback, void* context) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Clears the script execution time limit.
@param group The JavaScript context group that the time limit is cleared on.
*/
JS_EXPORT void JSContextGroupClearExecutionTimeLimit(JSContextGroupRef group) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Gets a whether or not remote inspection is enabled on the context.
@param ctx The JSGlobalContext whose setting you want to get.
@result The value of the setting, true if remote inspection is enabled, otherwise false.
@discussion Remote inspection is true by default.
*/
JS_EXPORT bool JSGlobalContextGetRemoteInspectionEnabled(JSGlobalContextRef ctx) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Sets the remote inspection setting for a context.
@param ctx The JSGlobalContext that you want to change.
@param enabled The new remote inspection enabled setting for the context.
*/
JS_EXPORT void JSGlobalContextSetRemoteInspectionEnabled(JSGlobalContextRef ctx, bool enabled) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Gets the include native call stack when reporting exceptions setting for a context.
@param ctx The JSGlobalContext whose setting you want to get.
@result The value of the setting, true if remote inspection is enabled, otherwise false.
@discussion This setting is true by default.
*/
JS_EXPORT bool JSGlobalContextGetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Sets the include native call stack when reporting exceptions setting for a context.
@param ctx The JSGlobalContext that you want to change.
@param includesNativeCallStack The new value of the setting for the context.
*/
JS_EXPORT void JSGlobalContextSetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx, bool includesNativeCallStack) JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@function
@abstract Sets the unhandled promise rejection callback for a context.
@discussion Similar to window.addEventListener('unhandledrejection'), but for contexts not associated with a web view.
@param ctx The JSGlobalContext to set the callback on.
@param function The callback function to set, which receives the promise and rejection reason as arguments.
@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.
*/
JS_EXPORT void JSGlobalContextSetUnhandledRejectionCallback(JSGlobalContextRef ctx, JSObjectRef function, JSValueRef* exception) JSC_API_AVAILABLE(macos(JSC_MAC_TBA), ios(JSC_IOS_TBA));
#ifdef __cplusplus
}
#endif
#endif /* JSContextRefPrivate_h */

View File

@@ -0,0 +1,146 @@
/*
* Copyright (C) 2013 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.
*/
#import <JavaScriptCore/JavaScriptCore.h>
#if JSC_OBJC_API_ENABLED
/*!
@protocol
@abstract JSExport provides a declarative way to export Objective-C objects and
classes -- including properties, instance methods, class methods, and
initializers -- to JavaScript.
@discussion When an Objective-C object is exported to JavaScript, a JavaScript
wrapper object is created.
In JavaScript, inheritance works via a chain of prototype objects.
For each Objective-C class in each JSContext, an object appropriate for use
as a prototype will be provided. For the class NSObject the prototype
will be the Object prototype. For all other Objective-C
classes a prototype will be created. The prototype for a given
Objective-C class will have its internal [Prototype] property set to point to
the prototype created for the Objective-C class's superclass. As such the
prototype chain for a JavaScript wrapper object will reflect the wrapped
Objective-C type's inheritance hierarchy.
JavaScriptCore also produces a constructor for each Objective-C class. The
constructor has a property named 'prototype' that references the prototype,
and the prototype has a property named 'constructor' that references the
constructor.
By default JavaScriptCore does not export any methods or properties from an
Objective-C class to JavaScript; however methods and properties may be exported
explicitly using JSExport. For each protocol that a class conforms to, if the
protocol incorporates the protocol JSExport, JavaScriptCore exports the methods
and properties in that protocol to JavaScript
For each exported instance method JavaScriptCore will assign a corresponding
JavaScript function to the prototype. For each exported Objective-C property
JavaScriptCore will assign a corresponding JavaScript accessor to the prototype.
For each exported class method JavaScriptCore will assign a corresponding
JavaScript function to the constructor. For example:
<pre>
@textblock
@protocol MyClassJavaScriptMethods <JSExport>
- (void)foo;
@end
@interface MyClass : NSObject <MyClassJavaScriptMethods>
- (void)foo;
- (void)bar;
@end
@/textblock
</pre>
Data properties that are created on the prototype or constructor objects have
the attributes: <code>writable:true</code>, <code>enumerable:false</code>, <code>configurable:true</code>.
Accessor properties have the attributes: <code>enumerable:false</code> and <code>configurable:true</code>.
If an instance of <code>MyClass</code> is converted to a JavaScript value, the resulting
wrapper object will (via its prototype) export the method <code>foo</code> to JavaScript,
since the class conforms to the <code>MyClassJavaScriptMethods</code> protocol, and this
protocol incorporates <code>JSExport</code>. <code>bar</code> will not be exported.
JSExport supports properties, arguments, and return values of the following types:
Primitive numbers: signed values up to 32-bits convert using JSValue's
valueWithInt32/toInt32. Unsigned values up to 32-bits convert using JSValue's
valueWithUInt32/toUInt32. All other numeric values convert using JSValue's
valueWithDouble/toDouble.
BOOL: values convert using JSValue's valueWithBool/toBool.
id: values convert using JSValue's valueWithObject/toObject.
Objective-C instance pointers: Pointers convert using JSValue's
valueWithObjectOfClass/toObject.
C structs: C structs for CGPoint, NSRange, CGRect, and CGSize convert using
JSValue's appropriate methods. Other C structs are not supported.
Blocks: Blocks convert using JSValue's valueWithObject/toObject.
All objects that conform to JSExport convert to JavaScript wrapper objects,
even if they subclass classes that would otherwise behave differently. For
example, if a subclass of NSString conforms to JSExport, it converts to
JavaScript as a wrapper object rather than a JavaScript string.
*/
@protocol JSExport
@end
/*!
@define
@abstract Rename a selector when it's exported to JavaScript.
@discussion When a selector that takes one or more arguments is converted to a JavaScript
property name, by default a property name will be generated by performing the
following conversion:
- All colons are removed from the selector
- Any lowercase letter that had followed a colon will be capitalized.
Under the default conversion a selector <code>doFoo:withBar:</code> will be exported as
<code>doFooWithBar</code>. The default conversion may be overridden using the JSExportAs
macro, for example to export a method <code>doFoo:withBar:</code> as <code>doFoo</code>:
<pre>
@textblock
@protocol MyClassJavaScriptMethods <JSExport>
JSExportAs(doFoo,
- (void)doFoo:(id)foo withBar:(id)bar
);
@end
@/textblock
</pre>
Note that the JSExport macro may only be applied to a selector that takes one
or more argument.
*/
#define JSExportAs(PropertyName, Selector) \
@optional Selector __JS_EXPORT_AS__##PropertyName:(id)argument; @required Selector
#endif

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2017 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 JSHeapFinalizerPrivate_h
#define JSHeapFinalizerPrivate_h
#include <JavaScriptCore/JSContextRef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*JSHeapFinalizer)(JSContextGroupRef, void *userData);
JS_EXPORT void JSContextGroupAddHeapFinalizer(JSContextGroupRef, JSHeapFinalizer, void *userData);
JS_EXPORT void JSContextGroupRemoveHeapFinalizer(JSContextGroupRef, JSHeapFinalizer, void *userData);
#ifdef __cplusplus
}
#endif
#endif // JSHeapFinalizerPrivate_h

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2013 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSManagedValue_h
#define JSManagedValue_h
#import <JavaScriptCore/JSBase.h>
#import <JavaScriptCore/WebKitAvailability.h>
#if JSC_OBJC_API_ENABLED
@class JSValue;
@class JSContext;
/*!
@interface
@discussion JSManagedValue represents a "conditionally retained" JSValue.
"Conditionally retained" means that as long as the JSManagedValue's
JSValue is reachable through the JavaScript object graph,
or through the Objective-C object graph reported to the JSVirtualMachine using
addManagedReference:withOwner:, the corresponding JSValue will
be retained. However, if neither graph reaches the JSManagedValue, the
corresponding JSValue will be released and set to nil.
The primary use for a JSManagedValue is to store a JSValue in an Objective-C
or Swift object that is exported to JavaScript. It is incorrect to store a JSValue
in an object that is exported to JavaScript, since doing so creates a retain cycle.
*/
NS_CLASS_AVAILABLE(10_9, 7_0)
@interface JSManagedValue : NSObject
/*!
@method
@abstract Create a JSManagedValue from a JSValue.
@result The new JSManagedValue.
*/
+ (JSManagedValue *)managedValueWithValue:(JSValue *)value;
+ (JSManagedValue *)managedValueWithValue:(JSValue *)value andOwner:(id)owner JSC_API_AVAILABLE(macos(10.10), ios(8.0));
/*!
@method
@abstract Create a JSManagedValue.
@result The new JSManagedValue.
*/
- (instancetype)initWithValue:(JSValue *)value;
/*!
@property
@abstract Get the JSValue from the JSManagedValue.
@result The corresponding JSValue for this JSManagedValue or
nil if the JSValue has been collected.
*/
@property (readonly, strong) JSValue *value;
@end
#endif // JSC_OBJC_API_ENABLED
#endif // JSManagedValue_h

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2013 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSManagedValueInternal_h
#define JSManagedValueInternal_h
#import <JavaScriptCore/JSBase.h>
#if JSC_OBJC_API_ENABLED
@interface JSManagedValue(Internal)
- (void)didAddOwner:(id)owner;
- (void)didRemoveOwner:(id)owner;
@end
#endif // JSC_OBJC_API_ENABLED
#endif // JSManagedValueInternal_h

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2017 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 JSMarkingConstraintPrivate_h
#define JSMarkingConstraintPrivate_h
#include <JavaScriptCore/JSContextRef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
struct JSMarker;
typedef struct JSMarker JSMarker;
typedef JSMarker *JSMarkerRef;
struct JSMarker {
bool (*IsMarked)(JSMarkerRef, JSObjectRef);
void (*Mark)(JSMarkerRef, JSObjectRef);
};
typedef void (*JSMarkingConstraint)(JSMarkerRef, void *userData);
JS_EXPORT void JSContextGroupAddMarkingConstraint(JSContextGroupRef, JSMarkingConstraint, void *userData);
#ifdef __cplusplus
}
#endif
#endif // JSMarkingConstraintPrivate_h

View File

@@ -0,0 +1,753 @@
/*
* Copyright (C) 2006-2019 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 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 JSObjectRef_h
#define JSObjectRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* 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 propertyNames 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) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.6), ios(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 an Error.
*/
JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) JSC_API_AVAILABLE(macos(10.6), ios(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) JSC_API_AVAILABLE(macos(10.6), ios(7.0));
/*!
@function
@abstract Creates a JavaScript promise object by invoking the provided executor.
@param ctx The execution context to use.
@param resolve A pointer to a JSObjectRef in which to store the resolve function for the new promise. Pass NULL if you do not care to store the resolve callback.
@param reject A pointer to a JSObjectRef in which to store the reject function for the new promise. Pass NULL if you do not care to store the reject callback.
@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 promise or NULL if an exception occurred.
*/
JS_EXPORT JSObjectRef JSObjectMakeDeferredPromise(JSContextRef ctx, JSObjectRef* resolve, JSObjectRef* reject, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.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 JSValueRef to use as the property's value.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
@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.
*/
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 Tests whether an object has a given property using a JSValueRef as the property key.
@param object The JSObject to test.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@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 object has a property whose name matches propertyKey, otherwise false.
@discussion This function is the same as performing "propertyKey in object" from JavaScript.
*/
JS_EXPORT bool JSObjectHasPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Gets a property from an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@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 key, otherwise the undefined value.
@discussion This function is the same as performing "object[propertyKey]" from JavaScript.
*/
JS_EXPORT JSValueRef JSObjectGetPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Sets a property on an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@param value A JSValueRef to use as the property's value.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
@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 This function is the same as performing "object[propertyKey] = value" from JavaScript.
*/
JS_EXPORT void JSObjectSetPropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@function
@abstract Deletes a property from an object using a JSValueRef as the property key.
@param ctx The execution context to use.
@param object The JSObject whose property you want to delete.
@param propertyKey A JSValueRef containing the property key to use when looking up the property.
@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).
@discussion This function is the same as performing "delete object[propertyKey]" from JavaScript.
*/
JS_EXPORT bool JSObjectDeletePropertyForKey(JSContextRef ctx, JSObjectRef object, JSValueRef propertyKey, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@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 */

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) 2010-2019 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSObjectRefPrivate_h
#define JSObjectRefPrivate_h
#include <JavaScriptCore/JSObjectRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Sets a private property on an object. This private property cannot be accessed from within JavaScript.
@param ctx The execution context to use.
@param object The JSObject whose private 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. This may be NULL.
@result true if object can store private data, otherwise false.
@discussion This API allows you to store JS values directly an object in a way that will be ensure that they are kept alive without exposing them to JavaScript code and without introducing the reference cycles that may occur when using JSValueProtect.
The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private properties.
*/
JS_EXPORT bool JSObjectSetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value);
/*!
@function
@abstract Gets a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to get.
@param propertyName A JSString containing the property's name.
@result The property's value if object has the property, otherwise NULL.
*/
JS_EXPORT JSValueRef JSObjectGetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Deletes a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to delete.
@param propertyName A JSString containing the property's name.
@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 JSObjectDeletePrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
JS_EXPORT JSObjectRef JSObjectGetProxyTarget(JSObjectRef);
JS_EXPORT JSGlobalContextRef JSObjectGetGlobalContext(JSObjectRef object);
#ifdef __cplusplus
}
#endif
#endif // JSObjectRefPrivate_h

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2015 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 JSRemoteInspector_h
#define JSRemoteInspector_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#if defined(WIN32) || defined(_WIN32)
typedef int JSProcessID;
#else
#include <unistd.h>
typedef pid_t JSProcessID;
#endif
#ifdef __cplusplus
extern "C" {
#endif
JS_EXPORT void JSRemoteInspectorDisableAutoStart(void) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
JS_EXPORT void JSRemoteInspectorStart(void) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
JS_EXPORT void JSRemoteInspectorSetParentProcessInformation(JSProcessID, const uint8_t* auditData, size_t auditLength) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
JS_EXPORT void JSRemoteInspectorSetLogToSystemConsole(bool) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
JS_EXPORT bool JSRemoteInspectorGetInspectionEnabledByDefault(void) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
JS_EXPORT void JSRemoteInspectorSetInspectionEnabledByDefault(bool) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
#ifdef __cplusplus
}
#endif
#endif /* JSRemoteInspector_h */

View File

@@ -0,0 +1,183 @@
/*
* Copyright (C) 2005-2018 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.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 OR ITS 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.
*/
#pragma once
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <algorithm>
inline void JSRetain(JSStringRef string) { JSStringRetain(string); }
inline void JSRelease(JSStringRef string) { JSStringRelease(string); }
inline void JSRetain(JSGlobalContextRef context) { JSGlobalContextRetain(context); }
inline void JSRelease(JSGlobalContextRef context) { JSGlobalContextRelease(context); }
enum AdoptTag { Adopt };
template<typename T> class JSRetainPtr {
public:
JSRetainPtr() = default;
JSRetainPtr(T ptr) : m_ptr(ptr) { if (ptr) JSRetain(ptr); }
JSRetainPtr(const JSRetainPtr&);
JSRetainPtr(JSRetainPtr&&);
~JSRetainPtr();
T get() const { return m_ptr; }
void clear();
T leakRef() WARN_UNUSED_RETURN;
T operator->() const { return m_ptr; }
bool operator!() const { return !m_ptr; }
explicit operator bool() const { return m_ptr; }
JSRetainPtr& operator=(const JSRetainPtr&);
JSRetainPtr& operator=(JSRetainPtr&&);
JSRetainPtr& operator=(T);
void swap(JSRetainPtr&);
friend JSRetainPtr<JSStringRef> adopt(JSStringRef);
friend JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef);
// FIXME: Make this private once Apple's internal code is updated to not rely on it.
// https://bugs.webkit.org/show_bug.cgi?id=189644
JSRetainPtr(AdoptTag, T);
private:
T m_ptr { nullptr };
};
JSRetainPtr<JSStringRef> adopt(JSStringRef);
JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef);
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(AdoptTag, T ptr)
: m_ptr(ptr)
{
}
inline JSRetainPtr<JSStringRef> adopt(JSStringRef o)
{
return JSRetainPtr<JSStringRef>(Adopt, o);
}
inline JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef o)
{
return JSRetainPtr<JSGlobalContextRef>(Adopt, o);
}
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr& o)
: m_ptr(o.m_ptr)
{
if (m_ptr)
JSRetain(m_ptr);
}
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(JSRetainPtr&& o)
: m_ptr(o.leakRef())
{
}
template<typename T> inline JSRetainPtr<T>::~JSRetainPtr()
{
if (m_ptr)
JSRelease(m_ptr);
}
template<typename T> inline void JSRetainPtr<T>::clear()
{
if (T ptr = leakRef())
JSRelease(ptr);
}
template<typename T> inline T JSRetainPtr<T>::leakRef()
{
return std::exchange(m_ptr, nullptr);
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<T>& o)
{
return operator=(o.get());
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(JSRetainPtr&& o)
{
if (T ptr = std::exchange(m_ptr, o.leakRef()))
JSRelease(ptr);
return *this;
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(T optr)
{
if (optr)
JSRetain(optr);
if (T ptr = std::exchange(m_ptr, optr))
JSRelease(ptr);
return *this;
}
template<typename T> inline void JSRetainPtr<T>::swap(JSRetainPtr<T>& o)
{
std::swap(m_ptr, o.m_ptr);
}
template<typename T> inline void swap(JSRetainPtr<T>& a, JSRetainPtr<T>& b)
{
a.swap(b);
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() == b.get();
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, U* b)
{
return a.get() == b;
}
template<typename T, typename U> inline bool operator==(T* a, const JSRetainPtr<U>& b)
{
return a == b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() != b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, U* b)
{
return a.get() != b;
}
template<typename T, typename U> inline bool operator!=(T* a, const JSRetainPtr<U>& b)
{
return a != b.get();
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2019 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.
*/
#import <JavaScriptCore/JSValue.h>
#if JSC_OBJC_API_ENABLED
NS_ASSUME_NONNULL_BEGIN
@class JSVirtualMachine;
/*!
@enum JSScriptType
@abstract A constant identifying the execution type of a JSScript.
@constant kJSScriptTypeProgram The type of a normal JavaScript program.
@constant kJSScriptTypeModule The type of a module JavaScript program.
*/
typedef NS_ENUM(NSInteger, JSScriptType) {
kJSScriptTypeProgram,
kJSScriptTypeModule,
};
JSC_CLASS_AVAILABLE(macos(10.15), ios(13.0))
@interface JSScript : NSObject
/*!
@method
@abstract Create a JSScript for the specified virtual machine.
@param type The type of JavaScript source.
@param source The source code to use when the script is evaluated by the JS vm.
@param sourceURL The source URL to associate with this script. For modules, this is the module identifier.
@param cachePath A URL containing the path where the VM should cache for future execution. On creation, we use this path to load the cached bytecode off disk. If the cached bytecode at this location is stale, you should delete that file before calling this constructor.
@param vm The JSVirtualMachine the script can be evaluated in.
@param error A description of why the script could not be created if the result is nil.
@result The new script.
@discussion The file at cachePath should not be externally modified for the lifecycle of vm.
*/
+ (nullable instancetype)scriptOfType:(JSScriptType)type withSource:(NSString *)source andSourceURL:(NSURL *)sourceURL andBytecodeCache:(nullable NSURL *)cachePath inVirtualMachine:(JSVirtualMachine *)vm error:(out NSError * _Nullable * _Nullable)error;
/*!
@method
@abstract Create a JSScript for the specified virtual machine with a path to a codesigning and bytecode caching.
@param type The type of JavaScript source.
@param filePath A URL containing the path to a JS source code file on disk.
@param sourceURL The source URL to associate with this script. For modules, this is the module identifier.
@param cachePath A URL containing the path where the VM should cache for future execution. On creation, we use this path to load the cached bytecode off disk. If the cached bytecode at this location is stale, you should delete that file before calling this constructor.
@param vm The JSVirtualMachine the script can be evaluated in.
@param error A description of why the script could not be created if the result is nil.
@result The new script.
@discussion The files at filePath and cachePath should not be externally modified for the lifecycle of vm. This method will file back the memory for the source.
If the file at filePath is not ascii this method will return nil.
*/
+ (nullable instancetype)scriptOfType:(JSScriptType)type memoryMappedFromASCIIFile:(NSURL *)filePath withSourceURL:(NSURL *)sourceURL andBytecodeCache:(nullable NSURL *)cachePath inVirtualMachine:(JSVirtualMachine *)vm error:(out NSError * _Nullable * _Nullable)error;
/*!
@method
@abstract Cache the bytecode for this JSScript to disk at the path passed in during creation.
@param error A description of why the script could not be cached if the result is FALSE.
*/
- (BOOL)cacheBytecodeWithError:(out NSError * _Nullable * _Nullable)error;
/*!
@method
@abstract Returns true when evaluating this JSScript will use the bytecode cache. Returns false otherwise.
*/
- (BOOL)isUsingBytecodeCache;
/*!
@method
@abstract Returns the JSScriptType of this JSScript.
*/
- (JSScriptType)type;
/*!
@method
@abstract Returns the sourceURL of this JSScript.
*/
- (NSURL *)sourceURL;
@end
NS_ASSUME_NONNULL_END
#endif // JSC_OBJC_API_ENABLED

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2019 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.
*/
#pragma once
#import "JSScript.h"
#import "SourceCode.h"
#import <wtf/RefPtr.h>
#if JSC_OBJC_API_ENABLED
NS_ASSUME_NONNULL_BEGIN
namespace JSC {
class CachedBytecode;
class Identifier;
class JSSourceCode;
};
namespace WTF {
class String;
};
@interface JSScript(Internal)
- (instancetype)init;
- (unsigned)hash;
- (const WTF::String&)source;
- (RefPtr<JSC::CachedBytecode>)cachedBytecode;
- (JSC::JSSourceCode*)jsSourceCode;
- (JSC::SourceCode)sourceCode;
- (BOOL)writeCache:(String&)error;
@end
NS_ASSUME_NONNULL_END
#endif // JSC_OBJC_API_ENABLED

View File

@@ -0,0 +1,99 @@
/*
* Copyright (C) 2012 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSScriptRefPrivate_h
#define JSScriptRefPrivate_h
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSValueRef.h>
/*! @typedef JSScriptRef A JavaScript script reference. */
typedef struct OpaqueJSScript* JSScriptRef;
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Creates a script reference from an ascii string, without copying or taking ownership of the string
@param contextGroup The context group the script is to be used in.
@param url The source url to be reported in errors and 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 source The source string. This is required to be pure ASCII and to never be deallocated.
@param length The length of the source string.
@param errorMessage A pointer to a JSStringRef in which to store the parse error message if the source is not valid. Pass NULL if you do not care to store an error message.
@param errorLine A pointer to an int in which to store the line number of a parser error. Pass NULL if you do not care to store an error line.
@result A JSScriptRef for the provided source, or NULL if any non-ASCII character is found in source or if the source is not a valid JavaScript program. Ownership follows the Create Rule.
@discussion Use this function to create a reusable script reference with a constant
buffer as the backing string. The source string must outlive the global context.
*/
JS_EXPORT JSScriptRef JSScriptCreateReferencingImmortalASCIIText(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, const char* source, size_t length, JSStringRef* errorMessage, int* errorLine);
/*!
@function
@abstract Creates a script reference from a string
@param contextGroup The context group the script is to be used in.
@param url The source url to be reported in errors and 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 source The source string.
@param errorMessage A pointer to a JSStringRef in which to store the parse error message if the source is not valid. Pass NULL if you do not care to store an error message.
@param errorLine A pointer to an int in which to store the line number of a parser error. Pass NULL if you do not care to store an error line.
@result A JSScriptRef for the provided source, or NULL is the source is not a valid JavaScript program. Ownership follows the Create Rule.
*/
JS_EXPORT JSScriptRef JSScriptCreateFromString(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, JSStringRef source, JSStringRef* errorMessage, int* errorLine);
/*!
@function
@abstract Retains a JavaScript script.
@param script The script to retain.
*/
JS_EXPORT void JSScriptRetain(JSScriptRef script);
/*!
@function
@abstract Releases a JavaScript script.
@param script The script to release.
*/
JS_EXPORT void JSScriptRelease(JSScriptRef script);
/*!
@function
@abstract Evaluates a JavaScript script.
@param ctx The execution context to use.
@param script The JSScript to evaluate.
@param thisValue The value to use as "this" when evaluating the script.
@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 JSScriptEvaluate(JSContextRef ctx, JSScriptRef script, JSValueRef thisValue, JSValueRef* exception);
#ifdef __cplusplus
}
#endif
#endif /* JSScriptRefPrivate_h */

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2019 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.
*/
#if JSC_OBJC_API_ENABLED
#import "SourceProvider.h"
@class JSScript;
class JSScriptSourceProvider : public JSC::SourceProvider {
public:
template<typename... Args>
static Ref<JSScriptSourceProvider> create(JSScript *script, Args&&... args)
{
return adoptRef(*new JSScriptSourceProvider(script, std::forward<Args>(args)...));
}
unsigned hash() const override;
StringView source() const override;
RefPtr<JSC::CachedBytecode> cachedBytecode() const override;
private:
template<typename... Args>
JSScriptSourceProvider(JSScript *script, Args&&... args)
: SourceProvider(std::forward<Args>(args)...)
, m_script(script)
{ }
RetainPtr<JSScript> m_script;
};
#endif // JSC_OBJC_API_ENABLED

View File

@@ -0,0 +1,148 @@
/*
* Copyright (C) 2006 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 JSStringRef_h
#define JSStringRef_h
#include <JavaScriptCore/JSValueRef.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(_NATIVE_WCHAR_T_DEFINED) /* MSVC */ \
&& (!defined(__WCHAR_MAX__) || (__WCHAR_MAX__ > 0xffffU)) /* ISO C/C++ */ \
&& (!defined(WCHAR_MAX) || (WCHAR_MAX > 0xffffU)) /* RVCT */
/*!
@typedef JSChar
@abstract A UTF-16 code unit. One, or a sequence of two, can encode any Unicode
character. As with all scalar types, endianness depends on the underlying
architecture.
*/
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 */

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2007 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.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 OR ITS 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 JSStringRefBSTR_h
#define JSStringRefBSTR_h
#include "JSBase.h"
#include <windows.h>
#ifdef __cplusplus
extern "C" {
#endif
/* COM convenience methods */
/*!
@function
@abstract Creates a JavaScript string from a BSTR.
@param string The BSTR to copy into the new JSString.
@result A JSString containing string. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithBSTR(const BSTR string);
/*!
@function
@abstract Creates a BSTR from a JavaScript string.
@param string The JSString to copy into the new BSTR.
@result A BSTR containing string. Ownership follows the Create Rule.
*/
JS_EXPORT BSTR JSStringCopyBSTR(const JSStringRef string);
#ifdef __cplusplus
}
#endif
#endif /* JSStringRefBSTR_h */

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2006, 2007 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 JSStringRefCF_h
#define JSStringRefCF_h
#include "JSBase.h"
#include <CoreFoundation/CoreFoundation.h>
#ifdef __cplusplus
extern "C" {
#endif
/* CFString convenience methods */
/*!
@function
@abstract Creates a JavaScript string from a CFString.
@discussion This function is optimized to take advantage of cases when
CFStringGetCharactersPtr returns a valid pointer.
@param string The CFString to copy into the new JSString.
@result A JSString containing string. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithCFString(CFStringRef string);
/*!
@function
@abstract Creates a CFString from a JavaScript string.
@param alloc The alloc parameter to pass to CFStringCreate.
@param string The JSString to copy into the new CFString.
@result A CFString containing string. Ownership follows the Create Rule.
*/
JS_EXPORT CFStringRef JSStringCopyCFString(CFAllocatorRef alloc, JSStringRef string) CF_RETURNS_RETAINED;
#ifdef __cplusplus
}
#endif
#endif /* JSStringRefCF_h */

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2013 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 JSStringRefPrivate_h
#define JSStringRefPrivate_h
#include <JavaScriptCore/JSStringRef.h>
#ifdef __cplusplus
extern "C" {
#endif
JS_EXPORT JSStringRef JSStringCreateWithCharactersNoCopy(const JSChar* chars, size_t numChars);
#ifdef __cplusplus
}
#endif
#endif /* JSStringRefPrivate_h */

View File

@@ -0,0 +1,180 @@
/*
* Copyright (C) 2015 Dominic Szablewski (dominic@phoboslab.org)
* Copyright (C) 2015-2016 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 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 JSTypedArray_h
#define JSTypedArray_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
// ------------- Typed Array functions --------------
/*!
@function
@abstract Creates a JavaScript Typed Array object with the given number of elements.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param length The number of elements to be in the new Typed Array.
@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 JSObjectRef that is a Typed Array with all elements set to zero or NULL if there was an error.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArray(JSContextRef ctx, JSTypedArrayType arrayType, size_t length, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing pointer.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the JSTypedArrayData object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@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 JSObjectRef Typed Array whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, JSTypedArrayType arrayType, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@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 JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBuffer(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object with the given offset and length.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param byteOffset The byte offset for the created Typed Array. byteOffset should aligned with the element size of arrayType.
@param length The number of elements to include in the Typed Array.
@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 JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBufferAndOffset(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, size_t byteOffset, size_t length, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns a temporary pointer to the backing store of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose backing store pointer to return.
@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 pointer to the raw data buffer that serves as object's backing store or NULL if object is not a Typed Array object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetTypedArrayBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose length to return.
@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 length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the byte length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte length to return.
@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 byte length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the byte offset of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte offset to return.
@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 byte offset of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteOffset(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the JavaScript Array Buffer object that is used as the backing of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The JSObjectRef whose Typed Array type data pointer to obtain.
@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 JSObjectRef with a JSTypedArrayType of kJSTypedArrayTypeArrayBuffer or NULL if object is not a Typed Array.
*/
JS_EXPORT JSObjectRef JSObjectGetTypedArrayBuffer(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
// ------------- Array Buffer functions -------------
/*!
@function
@abstract Creates a JavaScript Array Buffer object from an existing pointer.
@param ctx The execution context to use.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the Typed Array data object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@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 JSObjectRef Array Buffer whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeArrayBufferWithBytesNoCopy(JSContextRef ctx, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns a pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
@param object The Array Buffer object whose internal backing store pointer to return.
@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 pointer to the raw data buffer that serves as object's backing store or NULL if object is not an Array Buffer object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetArrayBufferBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/*!
@function
@abstract Returns the number of bytes in a JavaScript data object.
@param ctx The execution context to use.
@param object The JS Arary Buffer object whose length in bytes to return.
@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 number of bytes stored in the data object.
*/
JS_EXPORT size_t JSObjectGetArrayBufferByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
#ifdef __cplusplus
}
#endif
#endif /* JSTypedArray_h */

View File

@@ -0,0 +1,730 @@
/*
* Copyright (C) 2013-2019 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 JSValue_h
#define JSValue_h
#if JSC_OBJC_API_ENABLED
#import <CoreGraphics/CGGeometry.h>
@class JSContext;
/*!
@interface
@discussion A JSValue is a reference to a JavaScript value. Every JSValue
originates from a JSContext and holds a strong reference to it.
When a JSValue instance method creates a new JSValue, the new value
originates from the same JSContext.
All JSValues values also originate from a JSVirtualMachine
(available indirectly via the context property). It is an error to pass a
JSValue to a method or property of a JSValue or JSContext originating from a
different JSVirtualMachine. Doing so will raise an Objective-C exception.
*/
NS_CLASS_AVAILABLE(10_9, 7_0)
@interface JSValue : NSObject
/*!
@property
@abstract The JSContext that this value originates from.
*/
@property (readonly, strong) JSContext *context;
/*!
@methodgroup Creating JavaScript Values
*/
/*!
@method
@abstract Create a JSValue by converting an Objective-C object.
@discussion The resulting JSValue retains the provided Objective-C object.
@param value The Objective-C object to be converted.
@result The new JSValue.
*/
+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;
/*!
@method
@abstract Create a JavaScript value from a BOOL primitive.
@param context The JSContext in which the resulting JSValue will be created.
@result The new JSValue representing the equivalent boolean value.
*/
+ (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context;
/*!
@method
@abstract Create a JavaScript value from a double primitive.
@param context The JSContext in which the resulting JSValue will be created.
@result The new JSValue representing the equivalent boolean value.
*/
+ (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context;
/*!
@method
@abstract Create a JavaScript value from an <code>int32_t</code> primitive.
@param context The JSContext in which the resulting JSValue will be created.
@result The new JSValue representing the equivalent boolean value.
*/
+ (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context;
/*!
@method
@abstract Create a JavaScript value from a <code>uint32_t</code> primitive.
@param context The JSContext in which the resulting JSValue will be created.
@result The new JSValue representing the equivalent boolean value.
*/
+ (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context;
/*!
@method
@abstract Create a new, empty JavaScript object.
@param context The JSContext in which the resulting object will be created.
@result The new JavaScript object.
*/
+ (JSValue *)valueWithNewObjectInContext:(JSContext *)context;
/*!
@method
@abstract Create a new, empty JavaScript array.
@param context The JSContext in which the resulting array will be created.
@result The new JavaScript array.
*/
+ (JSValue *)valueWithNewArrayInContext:(JSContext *)context;
/*!
@method
@abstract Create a new JavaScript regular expression object.
@param pattern The regular expression pattern.
@param flags The regular expression flags.
@param context The JSContext in which the resulting regular expression object will be created.
@result The new JavaScript regular expression object.
*/
+ (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context;
/*!
@method
@abstract Create a new JavaScript error object.
@param message The error message.
@param context The JSContext in which the resulting error object will be created.
@result The new JavaScript error object.
*/
+ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context;
/*!
@method
@abstract Create a new promise object using the provided executor callback.
@param callback A callback block invoked while the promise object is being initialized. The resolve and reject parameters are functions that can be called to notify any pending reactions about the state of the new promise object.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing a new promise JavaScript object.
@discussion This method is equivalent to calling the Promise constructor in JavaScript. the resolve and reject callbacks each normally take a single value, which they forward to all relevent pending reactions. While inside the executor callback context will act as if it were in any other callback, except calleeFunction will be <code>nil</code>. This also means means the new promise object may be accessed via <code>[context thisValue]</code>.
*/
+ (JSValue *)valueWithNewPromiseInContext:(JSContext *)context fromExecutor:(void (^)(JSValue *resolve, JSValue *reject))callback JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Create a new resolved promise object with the provided value.
@param result The result value to be passed to any reactions.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing a new promise JavaScript object.
@discussion This method is equivalent to calling <code>[JSValue valueWithNewPromiseFromExecutor:^(JSValue *resolve, JSValue *reject) { [resolve callWithArguments:@[result]]; } inContext:context]</code>
*/
+ (JSValue *)valueWithNewPromiseResolvedWithResult:(id)result inContext:(JSContext *)context JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Create a new rejected promise object with the provided value.
@param reason The result value to be passed to any reactions.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing a new promise JavaScript object.
@discussion This method is equivalent to calling <code>[JSValue valueWithNewPromiseFromExecutor:^(JSValue *resolve, JSValue *reject) { [reject callWithArguments:@[reason]]; } inContext:context]</code>
*/
+ (JSValue *)valueWithNewPromiseRejectedWithReason:(id)reason inContext:(JSContext *)context JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Create a new, unique, symbol object.
@param description The description of the symbol object being created.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing a unique JavaScript value with type symbol.
*/
+ (JSValue *)valueWithNewSymbolFromDescription:(NSString *)description inContext:(JSContext *)context JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Create the JavaScript value <code>null</code>.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing the JavaScript value <code>null</code>.
*/
+ (JSValue *)valueWithNullInContext:(JSContext *)context;
/*!
@method
@abstract Create the JavaScript value <code>undefined</code>.
@param context The JSContext to which the resulting JSValue belongs.
@result The JSValue representing the JavaScript value <code>undefined</code>.
*/
+ (JSValue *)valueWithUndefinedInContext:(JSContext *)context;
/*!
@methodgroup Converting to Objective-C Types
@discussion When converting between JavaScript values and Objective-C objects a copy is
performed. Values of types listed below are copied to the corresponding
types on conversion in each direction. For NSDictionaries, entries in the
dictionary that are keyed by strings are copied onto a JavaScript object.
For dictionaries and arrays, conversion is recursive, with the same object
conversion being applied to all entries in the collection.
<pre>
@textblock
Objective-C type | JavaScript type
--------------------+---------------------
nil | undefined
NSNull | null
NSString | string
NSNumber | number, boolean
NSDictionary | Object object
NSArray | Array object
NSDate | Date object
NSBlock (1) | Function object (1)
id (2) | Wrapper object (2)
Class (3) | Constructor object (3)
@/textblock
</pre>
(1) Instances of NSBlock with supported arguments types will be presented to
JavaScript as a callable Function object. For more information on supported
argument types see JSExport.h. If a JavaScript Function originating from an
Objective-C block is converted back to an Objective-C object the block will
be returned. All other JavaScript functions will be converted in the same
manner as a JavaScript object of type Object.
(2) For Objective-C instances that do not derive from the set of types listed
above, a wrapper object to provide a retaining handle to the Objective-C
instance from JavaScript. For more information on these wrapper objects, see
JSExport.h. When a JavaScript wrapper object is converted back to Objective-C
the Objective-C instance being retained by the wrapper is returned.
(3) For Objective-C Class objects a constructor object containing exported
class methods will be returned. See JSExport.h for more information on
constructor objects.
For all methods taking arguments of type id, arguments will be converted
into a JavaScript value according to the above conversion.
*/
/*!
@method
@abstract Convert this JSValue to an Objective-C object.
@discussion The JSValue is converted to an Objective-C object according
to the conversion rules specified above.
@result The Objective-C representation of this JSValue.
*/
- (id)toObject;
/*!
@method
@abstract Convert a JSValue to an Objective-C object of a specific class.
@discussion The JSValue is converted to an Objective-C object of the specified Class.
If the result is not of the specified Class then <code>nil</code> will be returned.
@result An Objective-C object of the specified Class or <code>nil</code>.
*/
- (id)toObjectOfClass:(Class)expectedClass;
/*!
@method
@abstract Convert a JSValue to a boolean.
@discussion The JSValue is converted to a boolean according to the rules specified
by the JavaScript language.
@result The boolean result of the conversion.
*/
- (BOOL)toBool;
/*!
@method
@abstract Convert a JSValue to a double.
@discussion The JSValue is converted to a number according to the rules specified
by the JavaScript language.
@result The double result of the conversion.
*/
- (double)toDouble;
/*!
@method
@abstract Convert a JSValue to an <code>int32_t</code>.
@discussion The JSValue is converted to an integer according to the rules specified
by the JavaScript language.
@result The <code>int32_t</code> result of the conversion.
*/
- (int32_t)toInt32;
/*!
@method
@abstract Convert a JSValue to a <code>uint32_t</code>.
@discussion The JSValue is converted to an integer according to the rules specified
by the JavaScript language.
@result The <code>uint32_t</code> result of the conversion.
*/
- (uint32_t)toUInt32;
/*!
@method
@abstract Convert a JSValue to a NSNumber.
@discussion If the JSValue represents a boolean, a NSNumber value of YES or NO
will be returned. For all other types the value will be converted to a number according
to the rules specified by the JavaScript language.
@result The NSNumber result of the conversion.
*/
- (NSNumber *)toNumber;
/*!
@method
@abstract Convert a JSValue to a NSString.
@discussion The JSValue is converted to a string according to the rules specified
by the JavaScript language.
@result The NSString containing the result of the conversion.
*/
- (NSString *)toString;
/*!
@method
@abstract Convert a JSValue to a NSDate.
@discussion The value is converted to a number representing a time interval
since 1970 which is then used to create a new NSDate instance.
@result The NSDate created using the converted time interval.
*/
- (NSDate *)toDate;
/*!
@method
@abstract Convert a JSValue to a NSArray.
@discussion If the value is <code>null</code> or <code>undefined</code> then <code>nil</code> is returned.
If the value is not an object then a JavaScript TypeError will be thrown.
The property <code>length</code> is read from the object, converted to an unsigned
integer, and an NSArray of this size is allocated. Properties corresponding
to indicies within the array bounds will be copied to the array, with
JSValues converted to equivalent Objective-C objects as specified.
@result The NSArray containing the recursively converted contents of the
converted JavaScript array.
*/
- (NSArray *)toArray;
/*!
@method
@abstract Convert a JSValue to a NSDictionary.
@discussion If the value is <code>null</code> or <code>undefined</code> then <code>nil</code> is returned.
If the value is not an object then a JavaScript TypeError will be thrown.
All enumerable properties of the object are copied to the dictionary, with
JSValues converted to equivalent Objective-C objects as specified.
@result The NSDictionary containing the recursively converted contents of
the converted JavaScript object.
*/
- (NSDictionary *)toDictionary;
/*!
@functiongroup Checking JavaScript Types
*/
/*!
@property
@abstract Check if a JSValue corresponds to the JavaScript value <code>undefined</code>.
*/
@property (readonly) BOOL isUndefined;
/*!
@property
@abstract Check if a JSValue corresponds to the JavaScript value <code>null</code>.
*/
@property (readonly) BOOL isNull;
/*!
@property
@abstract Check if a JSValue is a boolean.
*/
@property (readonly) BOOL isBoolean;
/*!
@property
@abstract Check if a JSValue is a number.
@discussion In JavaScript, there is no differentiation between types of numbers.
Semantically all numbers behave like doubles except in special cases like bit
operations.
*/
@property (readonly) BOOL isNumber;
/*!
@property
@abstract Check if a JSValue is a string.
*/
@property (readonly) BOOL isString;
/*!
@property
@abstract Check if a JSValue is an object.
*/
@property (readonly) BOOL isObject;
/*!
@property
@abstract Check if a JSValue is an array.
*/
@property (readonly) BOOL isArray JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@property
@abstract Check if a JSValue is a date.
*/
@property (readonly) BOOL isDate JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@property
@abstract Check if a JSValue is a symbol.
*/
@property (readonly) BOOL isSymbol JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@method
@abstract Compare two JSValues using JavaScript's <code>===</code> operator.
*/
- (BOOL)isEqualToObject:(id)value;
/*!
@method
@abstract Compare two JSValues using JavaScript's <code>==</code> operator.
*/
- (BOOL)isEqualWithTypeCoercionToObject:(id)value;
/*!
@method
@abstract Check if a JSValue is an instance of another object.
@discussion This method has the same function as the JavaScript operator <code>instanceof</code>.
If an object other than a JSValue is passed, it will first be converted according to
the aforementioned rules.
*/
- (BOOL)isInstanceOf:(id)value;
/*!
@methodgroup Calling Functions and Constructors
*/
/*!
@method
@abstract Invoke a JSValue as a function.
@discussion In JavaScript, if a function doesn't explicitly return a value then it
implicitly returns the JavaScript value <code>undefined</code>.
@param arguments The arguments to pass to the function.
@result The return value of the function call.
*/
- (JSValue *)callWithArguments:(NSArray *)arguments;
/*!
@method
@abstract Invoke a JSValue as a constructor.
@discussion This is equivalent to using the <code>new</code> syntax in JavaScript.
@param arguments The arguments to pass to the constructor.
@result The return value of the constructor call.
*/
- (JSValue *)constructWithArguments:(NSArray *)arguments;
/*!
@method
@abstract Invoke a method on a JSValue.
@discussion Accesses the property named <code>method</code> from this value and
calls the resulting value as a function, passing this JSValue as the <code>this</code>
value along with the specified arguments.
@param method The name of the method to be invoked.
@param arguments The arguments to pass to the method.
@result The return value of the method call.
*/
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;
@end
/*!
@category
@discussion Objective-C methods exported to JavaScript may have argument and/or return
values of struct types, provided that conversion to and from the struct is
supported by JSValue. Support is provided for any types where JSValue
contains both a class method <code>valueWith<Type>:inContext:</code>, and and instance
method <code>to<Type></code>- where the string <code><Type></code> in these selector names match,
with the first argument to the former being of the same struct type as the
return type of the latter.
Support is provided for structs of type CGPoint, NSRange, CGRect and CGSize.
*/
@interface JSValue (StructSupport)
/*!
@method
@abstract Create a JSValue from a CGPoint.
@result A newly allocated JavaScript object containing properties
named <code>x</code> and <code>y</code>, with values from the CGPoint.
*/
+ (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context;
/*!
@method
@abstract Create a JSValue from a NSRange.
@result A newly allocated JavaScript object containing properties
named <code>location</code> and <code>length</code>, with values from the NSRange.
*/
+ (JSValue *)valueWithRange:(NSRange)range inContext:(JSContext *)context;
/*!
@method
@abstract
Create a JSValue from a CGRect.
@result A newly allocated JavaScript object containing properties
named <code>x</code>, <code>y</code>, <code>width</code>, and <code>height</code>, with values from the CGRect.
*/
+ (JSValue *)valueWithRect:(CGRect)rect inContext:(JSContext *)context;
/*!
@method
@abstract Create a JSValue from a CGSize.
@result A newly allocated JavaScript object containing properties
named <code>width</code> and <code>height</code>, with values from the CGSize.
*/
+ (JSValue *)valueWithSize:(CGSize)size inContext:(JSContext *)context;
/*!
@method
@abstract Convert a JSValue to a CGPoint.
@discussion Reads the properties named <code>x</code> and <code>y</code> from
this JSValue, and converts the results to double.
@result The new CGPoint.
*/
- (CGPoint)toPoint;
/*!
@method
@abstract Convert a JSValue to an NSRange.
@discussion Reads the properties named <code>location</code> and
<code>length</code> from this JSValue and converts the results to double.
@result The new NSRange.
*/
- (NSRange)toRange;
/*!
@method
@abstract Convert a JSValue to a CGRect.
@discussion Reads the properties named <code>x</code>, <code>y</code>,
<code>width</code>, and <code>height</code> from this JSValue and converts the results to double.
@result The new CGRect.
*/
- (CGRect)toRect;
/*!
@method
@abstract Convert a JSValue to a CGSize.
@discussion Reads the properties named <code>width</code> and
<code>height</code> from this JSValue and converts the results to double.
@result The new CGSize.
*/
- (CGSize)toSize;
@end
/*!
@category
@discussion These methods enable querying properties on a JSValue.
*/
@interface JSValue (PropertyAccess)
#if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500) || (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000)
typedef NSString *JSValueProperty;
#else
typedef id JSValueProperty;
#endif
/*!
@method
@abstract Access a property of a JSValue.
@result The JSValue for the requested property or the JSValue <code>undefined</code>
if the property does not exist.
@discussion Corresponds to the JavaScript operation <code>object[property]</code>. Starting with macOS 10.15 and iOS 13, 'property' can be any 'id' and will be converted to a JSValue using the conversion rules of <code>valueWithObject:inContext:</code>. Prior to macOS 10.15 and iOS 13, 'property' was expected to be an NSString *.
*/
- (JSValue *)valueForProperty:(JSValueProperty)property;
/*!
@method
@abstract Set a property on a JSValue.
@discussion Corresponds to the JavaScript operation <code>object[property] = value</code>. Starting with macOS 10.15 and iOS 13, 'property' can be any 'id' and will be converted to a JSValue using the conversion rules of <code>valueWithObject:inContext:</code>. Prior to macOS 10.15 and iOS 13, 'property' was expected to be an NSString *.
*/
- (void)setValue:(id)value forProperty:(JSValueProperty)property;
/*!
@method
@abstract Delete a property from a JSValue.
@result YES if deletion is successful, NO otherwise.
@discussion Corresponds to the JavaScript operation <code>delete object[property]</code>. Starting with macOS 10.15 and iOS 13, 'property' can be any 'id' and will be converted to a JSValue using the conversion rules of <code>valueWithObject:inContext:</code>. Prior to macOS 10.15 and iOS 13, 'property' was expected to be an NSString *.
*/
- (BOOL)deleteProperty:(JSValueProperty)property;
/*!
@method
@abstract Check if a JSValue has a property.
@discussion This method has the same function as the JavaScript operator <code>in</code>.
@result Returns YES if property is present on the value.
@discussion Corresponds to the JavaScript operation <code>property in object</code>. Starting with macOS 10.15 and iOS 13, 'property' can be any 'id' and will be converted to a JSValue using the conversion rules of <code>valueWithObject:inContext:</code>. Prior to macOS 10.15 and iOS 13, 'property' was expected to be an NSString *.
*/
- (BOOL)hasProperty:(JSValueProperty)property;
/*!
@method
@abstract Define properties with custom descriptors on JSValues.
@discussion This method may be used to create a data or accessor property on an object.
This method operates in accordance with the Object.defineProperty method in the JavaScript language. Starting with macOS 10.15 and iOS 13, 'property' can be any 'id' and will be converted to a JSValue using the conversion rules of <code>valueWithObject:inContext:</code>. Prior to macOS 10.15 and iOS 13, 'property' was expected to be an NSString *.
*/
- (void)defineProperty:(JSValueProperty)property descriptor:(id)descriptor;
/*!
@method
@abstract Access an indexed (numerical) property on a JSValue.
@result The JSValue for the property at the specified index.
Returns the JavaScript value <code>undefined</code> if no property exists at that index.
*/
- (JSValue *)valueAtIndex:(NSUInteger)index;
/*!
@method
@abstract Set an indexed (numerical) property on a JSValue.
@discussion For JSValues that are JavaScript arrays, indices greater than
UINT_MAX - 1 will not affect the length of the array.
*/
- (void)setValue:(id)value atIndex:(NSUInteger)index;
@end
/*!
@category
@discussion Instances of JSValue implement the following methods in order to enable
support for subscript access by key and index, for example:
@textblock
JSValue *objectA, *objectB;
JSValue *v1 = object[@"X"]; // Get value for property "X" from 'object'.
JSValue *v2 = object[42]; // Get value for index 42 from 'object'.
object[@"Y"] = v1; // Assign 'v1' to property "Y" of 'object'.
object[101] = v2; // Assign 'v2' to index 101 of 'object'.
@/textblock
An object key passed as a subscript will be converted to a JavaScript value,
and then the value using the same rules as <code>valueWithObject:inContext:</code>. In macOS
10.14 and iOS 12 and below, the <code>key</code> argument of
<code>setObject:object forKeyedSubscript:key</code> was restricted to an
<code>NSObject <NSCopying> *</code> but that restriction was never used internally.
*/
@interface JSValue (SubscriptSupport)
- (JSValue *)objectForKeyedSubscript:(id)key;
- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index;
- (void)setObject:(id)object forKeyedSubscript:(id)key;
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index;
@end
/*!
@category
@discussion These functions are for bridging between the C API and the Objective-C API.
*/
@interface JSValue (JSValueRefSupport)
/*!
@method
@abstract Creates a JSValue, wrapping its C API counterpart.
@result The Objective-C API equivalent of the specified JSValueRef.
*/
+ (JSValue *)valueWithJSValueRef:(JSValueRef)value inContext:(JSContext *)context;
/*!
@property
@abstract Returns the C API counterpart wrapped by a JSContext.
@result The C API equivalent of this JSValue.
*/
@property (readonly) JSValueRef JSValueRef;
@end
#ifdef __cplusplus
extern "C" {
#endif
/*!
@group Property Descriptor Constants
@discussion These keys may assist in creating a property descriptor for use with the
defineProperty method on JSValue.
Property descriptors must fit one of three descriptions:
Data Descriptor:
- A descriptor containing one or both of the keys <code>value</code> and <code>writable</code>,
and optionally containing one or both of the keys <code>enumerable</code> and
<code>configurable</code>. A data descriptor may not contain either the <code>get</code> or
<code>set</code> key.
A data descriptor may be used to create or modify the attributes of a
data property on an object (replacing any existing accessor property).
Accessor Descriptor:
- A descriptor containing one or both of the keys <code>get</code> and <code>set</code>, and
optionally containing one or both of the keys <code>enumerable</code> and
<code>configurable</code>. An accessor descriptor may not contain either the <code>value</code>
or <code>writable</code> key.
An accessor descriptor may be used to create or modify the attributes of
an accessor property on an object (replacing any existing data property).
Generic Descriptor:
- A descriptor containing one or both of the keys <code>enumerable</code> and
<code>configurable</code>. A generic descriptor may not contain any of the keys
<code>value</code>, <code>writable</code>, <code>get</code>, or <code>set</code>.
A generic descriptor may be used to modify the attributes of an existing
data or accessor property, or to create a new data property.
*/
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorWritableKey;
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorEnumerableKey;
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorConfigurableKey;
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorValueKey;
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorGetKey;
/*!
@const
*/
JS_EXPORT extern NSString * const JSPropertyDescriptorSetKey;
#ifdef __cplusplus
} // extern "C"
#endif
#endif
#endif // JSValue_h

View File

@@ -0,0 +1,57 @@
/*
* Copyright (C) 2013-2019 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 JSValueInternal_h
#define JSValueInternal_h
#import <JavaScriptCore/JSValuePrivate.h>
#if JSC_OBJC_API_ENABLED
@interface JSValue(Internal)
JSValueRef valueInternalValue(JSValue *);
- (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context;
JSValueRef objectToValue(JSContext *, id);
id valueToObject(JSContext *, JSValueRef);
id valueToNumber(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
id valueToString(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
id valueToDate(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
id valueToArray(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
id valueToDictionary(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+ (SEL)selectorForStructToValue:(const char *)structTag;
+ (SEL)selectorForValueToStruct:(const char *)structTag;
@end
NSInvocation *typeToValueInvocationFor(const char* encodedType);
NSInvocation *valueToTypeInvocationFor(const char* encodedType);
#endif
#endif // JSValueInternal_h

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2018-2019 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.
*/
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JavaScriptCore.h>
@interface JSValue(JSPrivate)
// Currently empty. May be used again in the future.
@end
#endif // JSC_OBJC_API_ENABLED

View File

@@ -0,0 +1,380 @@
/*
* Copyright (C) 2006-2019 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 JSValueRef_h
#define JSValueRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#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).
@constant kJSTypeSymbol A primitive symbol value.
*/
typedef enum {
kJSTypeUndefined,
kJSTypeNull,
kJSTypeBoolean,
kJSTypeNumber,
kJSTypeString,
kJSTypeObject,
kJSTypeSymbol JSC_API_AVAILABLE(macos(10.15), ios(13.0))
} JSType;
/*!
@enum JSTypedArrayType
@abstract A constant identifying the Typed Array type of a JSObjectRef.
@constant kJSTypedArrayTypeInt8Array Int8Array
@constant kJSTypedArrayTypeInt16Array Int16Array
@constant kJSTypedArrayTypeInt32Array Int32Array
@constant kJSTypedArrayTypeUint8Array Uint8Array
@constant kJSTypedArrayTypeUint8ClampedArray Uint8ClampedArray
@constant kJSTypedArrayTypeUint16Array Uint16Array
@constant kJSTypedArrayTypeUint32Array Uint32Array
@constant kJSTypedArrayTypeFloat32Array Float32Array
@constant kJSTypedArrayTypeFloat64Array Float64Array
@constant kJSTypedArrayTypeArrayBuffer ArrayBuffer
@constant kJSTypedArrayTypeNone Not a Typed Array
*/
typedef enum {
kJSTypedArrayTypeInt8Array,
kJSTypedArrayTypeInt16Array,
kJSTypedArrayTypeInt32Array,
kJSTypedArrayTypeUint8Array,
kJSTypedArrayTypeUint8ClampedArray,
kJSTypedArrayTypeUint16Array,
kJSTypedArrayTypeUint32Array,
kJSTypedArrayTypeFloat32Array,
kJSTypedArrayTypeFloat64Array,
kJSTypedArrayTypeArrayBuffer,
kJSTypedArrayTypeNone,
} JSTypedArrayType JSC_API_AVAILABLE(macos(10.12), ios(10.0));
#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 value);
/*!
@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 symbol type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the symbol type, otherwise false.
*/
JS_EXPORT bool JSValueIsSymbol(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/*!
@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);
/*!
@function
@abstract Tests whether a JavaScript value is an array.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is an array, otherwise false.
*/
JS_EXPORT bool JSValueIsArray(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@function
@abstract Tests whether a JavaScript value is a date.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is a date, otherwise false.
*/
JS_EXPORT bool JSValueIsDate(JSContextRef ctx, JSValueRef value) JSC_API_AVAILABLE(macos(10.11), ios(9.0));
/*!
@function
@abstract Returns a JavaScript value's Typed Array type.
@param ctx The execution context to use.
@param value The JSValue whose Typed Array type to return.
@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 value of type JSTypedArrayType that identifies value's Typed Array type, or kJSTypedArrayTypeNone if the value is not a Typed Array object.
*/
JS_EXPORT JSTypedArrayType JSValueGetTypedArrayType(JSContextRef ctx, JSValueRef value, JSValueRef* exception) JSC_API_AVAILABLE(macos(10.12), ios(10.0));
/* 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);
/*!
@function
@abstract Creates a JavaScript value of the symbol type.
@param ctx The execution context to use.
@param description A description of the newly created symbol value.
@result A unique JSValue of the symbol type, whose description matches the one provided.
*/
JS_EXPORT JSValueRef JSValueMakeSymbol(JSContextRef ctx, JSStringRef description) JSC_API_AVAILABLE(macos(10.15), ios(13.0));
/* 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) JSC_API_AVAILABLE(macos(10.7), ios(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) JSC_API_AVAILABLE(macos(10.7), ios(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 */

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2013 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.
*/
#import <JavaScriptCore/JavaScriptCore.h>
#if JSC_OBJC_API_ENABLED
/*!
@interface
@discussion An instance of JSVirtualMachine represents a single JavaScript "object space"
or set of execution resources. Thread safety is supported by locking the
virtual machine, with concurrent JavaScript execution supported by allocating
separate instances of JSVirtualMachine.
A virtual machine may need to run deferred tasks on a run loop, such as garbage collection
or resolving WebAssembly compilations. By default, a virtual machine will use the run loop
of the thread it was initialized on. Currently, there is no API to change a
JSVirtualMachine's run loop once it has been initialized.
*/
NS_CLASS_AVAILABLE(10_9, 7_0)
@interface JSVirtualMachine : NSObject
/*!
@methodgroup Creating New Virtual Machines
*/
/*!
@method
@abstract Create a new JSVirtualMachine.
*/
- (instancetype)init;
/*!
@methodgroup Memory Management
*/
/*!
@method
@abstract Notify the JSVirtualMachine of an external object relationship.
@discussion Allows clients of JSVirtualMachine to make the JavaScript runtime aware of
arbitrary external Objective-C object graphs. The runtime can then use
this information to retain any JavaScript values that are referenced
from somewhere in said object graph.
For correct behavior clients must make their external object graphs
reachable from within the JavaScript runtime. If an Objective-C object is
reachable from within the JavaScript runtime, all managed references
transitively reachable from it as recorded using
-addManagedReference:withOwner: will be scanned by the garbage collector.
@param object The object that the owner points to.
@param owner The object that owns the pointed to object.
*/
- (void)addManagedReference:(id)object withOwner:(id)owner;
/*!
@method
@abstract Notify the JSVirtualMachine that a previous object relationship no longer exists.
@discussion The JavaScript runtime will continue to scan any references that were
reported to it by -addManagedReference:withOwner: until those references are removed.
@param object The object that was formerly owned.
@param owner The former owner.
*/
- (void)removeManagedReference:(id)object withOwner:(id)owner;
@end
#endif

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2013, 2017 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 JSVirtualMachineInternal_h
#define JSVirtualMachineInternal_h
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JavaScriptCore.h>
namespace JSC {
class VM;
class SlotVisitor;
}
#if defined(__OBJC__)
@class NSMapTable;
@interface JSVirtualMachine(Internal)
JSContextGroupRef getGroupFromVirtualMachine(JSVirtualMachine *);
+ (JSVirtualMachine *)virtualMachineWithContextGroupRef:(JSContextGroupRef)group;
- (JSContext *)contextForGlobalContextRef:(JSGlobalContextRef)globalContext;
- (void)addContext:(JSContext *)wrapper forGlobalContextRef:(JSGlobalContextRef)globalContext;
- (JSC::VM&)vm;
- (BOOL)isWebThreadAware;
@end
#endif // defined(__OBJC__)
void scanExternalObjectGraph(JSC::VM&, JSC::SlotVisitor&, void* root);
void scanExternalRememberedSet(JSC::VM&, JSC::SlotVisitor&);
#endif // JSC_OBJC_API_ENABLED
#endif // JSVirtualMachineInternal_h

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2018 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.
*/
#include "JSExportMacros.h"
#include <JavaScriptCore/JavaScript.h>
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JSVirtualMachine.h>
@interface JSVirtualMachine(JSPrivate)
/*!
@method
@discussion Shrinks the memory footprint of the VM by deleting various internal caches,
running synchronous garbage collection, and releasing memory back to the OS. Note: this
API waits until no JavaScript is running on the stack before it frees any memory. It's
best to call this API when no JavaScript is running on the stack for this reason. However, if
you do call this API when JavaScript is running on the stack, the API will wait until all JavaScript
on the stack finishes running to free memory back to the OS. Therefore, calling this
API may not synchronously free memory.
*/
- (void)shrinkFootprintWhenIdle JSC_API_AVAILABLE(macos(10.14), ios(12.0));
#if ENABLE(DFG_JIT)
/*!
@method
@abstract Set the number of threads to be used by the DFG JIT compiler.
@discussion If called after the VM has been initialized, it will terminate
threads until it meets the new limit or create new threads accordingly if the
new limit is higher than the previous limit. If called before initialization,
the Options value for the number of DFG threads will be updated to ensure the
DFG compiler already starts with the up-to-date limit.
@param numberOfThreads The number of threads the DFG compiler should use going forward
@result The previous number of threads being used by the DFG compiler
*/
+ (NSUInteger)setNumberOfDFGCompilerThreads:(NSUInteger)numberOfThreads JSC_API_AVAILABLE(macos(10.14), ios(12.0));
/*!
@method
@abstract Set the number of threads to be used by the FTL JIT compiler.
@discussion If called after the VM has been initialized, it will terminate
threads until it meets the new limit or create new threads accordingly if the
new limit is higher than the previous limit. If called before initialization,
the Options value for the number of FTL threads will be updated to ensure the
FTL compiler already starts with the up-to-date limit.
@param numberOfThreads The number of threads the FTL compiler should use going forward
@result The previous number of threads being used by the FTL compiler
*/
+ (NSUInteger)setNumberOfFTLCompilerThreads:(NSUInteger)numberOfThreads JSC_API_AVAILABLE(macos(10.14), ios(12.0));
/*!
@method
@abstract Allows embedders of JSC to specify that JSC should crash the process if a VM is created when unexpected.
@param shouldCrash Sets process-wide state that indicates whether VM creation should crash or not.
*/
+ (void)setCrashOnVMCreation:(BOOL)shouldCrash;
#endif // ENABLE(DFG_JIT)
@end
#endif // JSC_OBJC_API_ENABLED

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2010 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSWeakObjectMapRefInternal_h
#define JSWeakObjectMapRefInternal_h
#include "WeakGCMap.h"
#include <wtf/RefCounted.h>
namespace JSC {
class JSObject;
}
typedef void (*JSWeakMapDestroyedCallback)(struct OpaqueJSWeakObjectMap*, void*);
typedef JSC::WeakGCMap<void*, JSC::JSObject> WeakMapType;
struct OpaqueJSWeakObjectMap : public RefCounted<OpaqueJSWeakObjectMap> {
public:
static Ref<OpaqueJSWeakObjectMap> create(JSC::VM& vm, void* data, JSWeakMapDestroyedCallback callback)
{
return adoptRef(*new OpaqueJSWeakObjectMap(vm, data, callback));
}
WeakMapType& map() { return m_map; }
~OpaqueJSWeakObjectMap()
{
m_callback(this, m_data);
}
private:
OpaqueJSWeakObjectMap(JSC::VM& vm, void* data, JSWeakMapDestroyedCallback callback)
: m_map(vm)
, m_data(data)
, m_callback(callback)
{
}
WeakMapType m_map;
void* m_data;
JSWeakMapDestroyedCallback m_callback;
};
#endif // JSWeakObjectMapInternal_h

View File

@@ -0,0 +1,92 @@
/*
* Copyright (C) 2010 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. AND ITS CONTRIBUTORS ``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 ITS 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 JSWeakObjectMapRefPrivate_h
#define JSWeakObjectMapRefPrivate_h
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*! @typedef JSWeakObjectMapRef A weak map for storing JSObjectRefs */
typedef struct OpaqueJSWeakObjectMap* JSWeakObjectMapRef;
/*!
@typedef JSWeakMapDestroyedCallback
@abstract The callback invoked when a JSWeakObjectMapRef is being destroyed.
@param map The map that is being destroyed.
@param data The private data (if any) that was associated with the map instance.
*/
typedef void (*JSWeakMapDestroyedCallback)(JSWeakObjectMapRef map, void* data);
/*!
@function
@abstract Creates a weak value map that can be used to reference user defined objects without preventing them from being collected.
@param ctx The execution context to use.
@param data A void* to set as the map's private data. Pass NULL to specify no private data.
@param destructor A function to call when the weak map is destroyed.
@result A JSWeakObjectMapRef bound to the given context, data and destructor.
@discussion The JSWeakObjectMapRef can be used as a storage mechanism to hold custom JS objects without forcing those objects to
remain live as JSValueProtect would.
*/
JS_EXPORT JSWeakObjectMapRef JSWeakObjectMapCreate(JSContextRef ctx, void* data, JSWeakMapDestroyedCallback destructor);
/*!
@function
@abstract Associates a JSObjectRef with the given key in a JSWeakObjectMap.
@param ctx The execution context to use.
@param map The map to operate on.
@param key The key to associate a weak reference with.
@param object The user defined object to associate with the key.
*/
JS_EXPORT void JSWeakObjectMapSet(JSContextRef ctx, JSWeakObjectMapRef map, void* key, JSObjectRef object);
/*!
@function
@abstract Retrieves the JSObjectRef associated with a key.
@param ctx The execution context to use.
@param map The map to query.
@param key The key to search for.
@result Either the live object associated with the provided key, or NULL.
*/
JS_EXPORT JSObjectRef JSWeakObjectMapGet(JSContextRef ctx, JSWeakObjectMapRef map, void* key);
/*!
@function
@abstract Removes the entry for the given key if the key is present, otherwise it has no effect.
@param ctx The execution context to use.
@param map The map to use.
@param key The key to remove.
*/
JS_EXPORT void JSWeakObjectMapRemove(JSContextRef ctx, JSWeakObjectMapRef map, void* key);
#ifdef __cplusplus
}
#endif
#endif // JSWeakObjectMapPrivate_h

View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2017 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 JSWeakPrivate_h
#define JSWeakPrivate_h
#include <JavaScriptCore/JSObjectRef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef const struct OpaqueJSWeak* JSWeakRef;
JS_EXPORT JSWeakRef JSWeakCreate(JSContextGroupRef, JSObjectRef);
JS_EXPORT void JSWeakRetain(JSContextGroupRef, JSWeakRef);
JS_EXPORT void JSWeakRelease(JSContextGroupRef, JSWeakRef);
JS_EXPORT JSObjectRef JSWeakGetObject(JSWeakRef);
#ifdef __cplusplus
}
#endif
#endif // JSWeakPrivate_h

View File

@@ -0,0 +1,95 @@
/*
* Copyright (C) 2013, 2016 Apple Inc. All rights reserved.
* Copyright (C) 2018 Igalia S.L.
*
* 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.
*/
#pragma once
#include "JSCJSValue.h"
#include "Weak.h"
namespace JSC {
class JSObject;
class JSString;
class WeakHandleOwner;
class JSWeakValue {
public:
JSWeakValue() = default;
~JSWeakValue();
void clear();
bool isClear() const;
bool isSet() const { return m_tag != WeakTypeTag::NotSet; }
bool isPrimitive() const { return m_tag == WeakTypeTag::Primitive; }
bool isObject() const { return m_tag == WeakTypeTag::Object; }
bool isString() const { return m_tag == WeakTypeTag::String; }
void setPrimitive(JSValue);
void setObject(JSObject*, WeakHandleOwner&, void* context);
void setString(JSString*, WeakHandleOwner&, void* context);
JSObject* object() const
{
ASSERT(isObject());
return m_value.object.get();
}
JSValue primitive() const
{
ASSERT(isPrimitive());
return m_value.primitive;
}
JSString* string() const
{
ASSERT(isString());
return m_value.string.get();
}
private:
enum class WeakTypeTag { NotSet, Primitive, Object, String };
WeakTypeTag m_tag { WeakTypeTag::NotSet };
union WeakValueUnion {
WeakValueUnion()
: primitive(JSValue())
{
}
~WeakValueUnion()
{
ASSERT(!primitive);
}
JSValue primitive;
Weak<JSObject> object;
Weak<JSString> string;
} m_value;
};
} // namespace JSC

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2013 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.
*/
#import <JavaScriptCore/JavaScriptCore.h>
#import <JSValueInternal.h>
#import <objc/objc-runtime.h>
#if JSC_OBJC_API_ENABLED
@interface JSWrapperMap : NSObject
- (instancetype)initWithGlobalContextRef:(JSGlobalContextRef)context;
- (JSValue *)jsWrapperForObject:(id)object inContext:(JSContext *)context;
- (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value inContext:(JSContext *)context;
@end
id tryUnwrapObjcObject(JSGlobalContextRef, JSValueRef);
bool supportsInitMethodConstructors();
Protocol *getJSExportProtocol();
Class getNSBlockClass();
#endif

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2008 Alp Toker <alp@atoker.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 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 JavaScript_h
#define JavaScript_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSTypedArray.h>
#include <JavaScriptCore/JSValueRef.h>
#endif /* JavaScript_h */

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2006, 2008 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 JavaScriptCore_h
#define JavaScriptCore_h
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSStringRefCF.h>
#if defined(__OBJC__) && JSC_OBJC_API_ENABLED
#import "JSContext.h"
#import "JSValue.h"
#import "JSManagedValue.h"
#import "JSVirtualMachine.h"
#import "JSExport.h"
#endif
#endif /* JavaScriptCore_h */

View File

@@ -0,0 +1,86 @@
/*
* Copyright (C) 2013, 2016 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 ObjCCallbackFunction_h
#define ObjCCallbackFunction_h
#include <JavaScriptCore/JSBase.h>
#if JSC_OBJC_API_ENABLED
#import <JavaScriptCore/JSCallbackFunction.h>
#if defined(__OBJC__)
JSObjectRef objCCallbackFunctionForMethod(JSContext *, Class, Protocol *, BOOL isInstanceMethod, SEL, const char* types);
JSObjectRef objCCallbackFunctionForBlock(JSContext *, id);
JSObjectRef objCCallbackFunctionForInit(JSContext *, Class, Protocol *, SEL, const char* types);
id tryUnwrapConstructor(JSC::VM*, JSObjectRef);
#endif
namespace JSC {
class ObjCCallbackFunctionImpl;
class ObjCCallbackFunction : public InternalFunction {
friend struct APICallbackFunction;
public:
typedef InternalFunction Base;
template<typename CellType, SubspaceAccess mode>
static IsoSubspace* subspaceFor(VM& vm)
{
return vm.objCCallbackFunctionSpace<mode>();
}
static ObjCCallbackFunction* create(VM&, JSGlobalObject*, const String& name, std::unique_ptr<ObjCCallbackFunctionImpl>);
static void destroy(JSCell*);
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
ASSERT(globalObject);
return Structure::create(vm, globalObject, prototype, TypeInfo(InternalFunctionType, StructureFlags), info());
}
DECLARE_EXPORT_INFO;
ObjCCallbackFunctionImpl* impl() const { return m_impl.get(); }
protected:
ObjCCallbackFunction(VM&, Structure*, JSObjectCallAsFunctionCallback, JSObjectCallAsConstructorCallback, std::unique_ptr<ObjCCallbackFunctionImpl>);
private:
JSObjectCallAsFunctionCallback functionCallback() { return m_functionCallback; }
JSObjectCallAsConstructorCallback constructCallback() { return m_constructCallback; }
JSObjectCallAsFunctionCallback m_functionCallback;
JSObjectCallAsConstructorCallback m_constructCallback;
std::unique_ptr<ObjCCallbackFunctionImpl> m_impl;
};
} // namespace JSC
#endif
#endif // ObjCCallbackFunction_h

View File

@@ -0,0 +1,250 @@
/*
* Copyright (C) 2013, 2017 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.
*/
#import <memory>
#import <objc/Protocol.h>
#import <objc/runtime.h>
#import <wtf/HashSet.h>
#import <wtf/SystemFree.h>
#import <wtf/Vector.h>
#import <wtf/text/CString.h>
template<typename T, typename U>
inline std::unique_ptr<T, WTF::SystemFree<T>> adoptSystem(U value)
{
return std::unique_ptr<T, WTF::SystemFree<T>>(value);
}
inline bool protocolImplementsProtocol(Protocol *candidate, Protocol *target)
{
unsigned protocolProtocolsCount;
auto protocolProtocols = adoptSystem<__unsafe_unretained Protocol*[]>(protocol_copyProtocolList(candidate, &protocolProtocolsCount));
for (unsigned i = 0; i < protocolProtocolsCount; ++i) {
if (protocol_isEqual(protocolProtocols[i], target))
return true;
}
return false;
}
inline void forEachProtocolImplementingProtocol(Class cls, Protocol *target, void (^callback)(Protocol *, bool& stop))
{
ASSERT(cls);
ASSERT(target);
Vector<Protocol*> worklist;
HashSet<void*> visited;
// Initially fill the worklist with the Class's protocols.
{
unsigned protocolsCount;
auto protocols = adoptSystem<__unsafe_unretained Protocol*[]>(class_copyProtocolList(cls, &protocolsCount));
worklist.append(protocols.get(), protocolsCount);
}
bool stop = false;
while (!worklist.isEmpty()) {
Protocol *protocol = worklist.last();
worklist.removeLast();
// Are we encountering this Protocol for the first time?
if (!visited.add((__bridge void*)protocol).isNewEntry)
continue;
// If it implements the protocol, make the callback.
if (protocolImplementsProtocol(protocol, target)) {
callback(protocol, stop);
if (stop)
break;
}
// Add incorporated protocols to the worklist.
{
unsigned protocolsCount;
auto protocols = adoptSystem<__unsafe_unretained Protocol*[]>(protocol_copyProtocolList(protocol, &protocolsCount));
worklist.append(protocols.get(), protocolsCount);
}
}
}
inline void forEachMethodInClass(Class cls, void (^callback)(Method))
{
unsigned count;
auto methods = adoptSystem<Method[]>(class_copyMethodList(cls, &count));
for (unsigned i = 0; i < count; ++i)
callback(methods[i]);
}
inline void forEachMethodInProtocol(Protocol *protocol, BOOL isRequiredMethod, BOOL isInstanceMethod, void (^callback)(SEL, const char*))
{
unsigned count;
auto methods = adoptSystem<objc_method_description[]>(protocol_copyMethodDescriptionList(protocol, isRequiredMethod, isInstanceMethod, &count));
for (unsigned i = 0; i < count; ++i)
callback(methods[i].name, methods[i].types);
}
inline void forEachPropertyInProtocol(Protocol *protocol, void (^callback)(objc_property_t))
{
unsigned count;
auto properties = adoptSystem<objc_property_t[]>(protocol_copyPropertyList(protocol, &count));
for (unsigned i = 0; i < count; ++i)
callback(properties[i]);
}
template<char open, char close>
void skipPair(const char*& position)
{
size_t count = 1;
do {
char c = *position++;
if (!c)
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Malformed type encoding" userInfo:nil];
if (c == open)
++count;
else if (c == close)
--count;
} while (count);
}
class StringRange {
WTF_MAKE_NONCOPYABLE(StringRange);
public:
StringRange(const char* begin, const char* end)
: m_string(begin, end - begin)
{ }
operator const char*() const { return m_string.data(); }
const char* get() const { return m_string.data(); }
private:
CString m_string;
};
class StructBuffer {
WTF_MAKE_NONCOPYABLE(StructBuffer);
public:
StructBuffer(const char* encodedType)
{
NSUInteger size, alignment;
NSGetSizeAndAlignment(encodedType, &size, &alignment);
m_buffer = fastAlignedMalloc(alignment, size);
}
~StructBuffer() { fastAlignedFree(m_buffer); }
operator void*() const { return m_buffer; }
private:
void* m_buffer;
};
template<typename DelegateType>
typename DelegateType::ResultType parseObjCType(const char*& position)
{
ASSERT(*position);
switch (*position++) {
case 'c':
return DelegateType::template typeInteger<char>();
case 'i':
return DelegateType::template typeInteger<int>();
case 's':
return DelegateType::template typeInteger<short>();
case 'l':
return DelegateType::template typeInteger<long>();
case 'q':
return DelegateType::template typeDouble<long long>();
case 'C':
return DelegateType::template typeInteger<unsigned char>();
case 'I':
return DelegateType::template typeInteger<unsigned>();
case 'S':
return DelegateType::template typeInteger<unsigned short>();
case 'L':
return DelegateType::template typeInteger<unsigned long>();
case 'Q':
return DelegateType::template typeDouble<unsigned long long>();
case 'f':
return DelegateType::template typeDouble<float>();
case 'd':
return DelegateType::template typeDouble<double>();
case 'B':
return DelegateType::typeBool();
case 'v':
return DelegateType::typeVoid();
case '@': { // An object (whether statically typed or typed id)
if (position[0] == '?' && position[1] == '<') {
position += 2;
const char* begin = position;
skipPair<'<','>'>(position);
return DelegateType::typeBlock(begin, position - 1);
}
if (*position == '"') {
const char* begin = position + 1;
const char* protocolPosition = strchr(begin, '<');
const char* endOfType = strchr(begin, '"');
position = endOfType + 1;
// There's no protocol involved in this type, so just handle the class name.
if (!protocolPosition || protocolPosition > endOfType)
return DelegateType::typeOfClass(begin, endOfType);
// We skipped the class name and went straight to the protocol, so this is an id type.
if (begin == protocolPosition)
return DelegateType::typeId();
// We have a class name with a protocol. For now, ignore the protocol.
return DelegateType::typeOfClass(begin, protocolPosition);
}
return DelegateType::typeId();
}
case '{': { // {name=type...} A structure
const char* begin = position - 1;
skipPair<'{','}'>(position);
return DelegateType::typeStruct(begin, position);
}
// NOT supporting C strings, arrays, pointers, unions, bitfields, function pointers.
case '*': // A character string (char *)
case '[': // [array type] An array
case '(': // (name=type...) A union
case 'b': // bnum A bit field of num bits
case '^': // ^type A pointer to type
case '?': // An unknown type (among other things, this code is used for function pointers)
// NOT supporting Objective-C Class, SEL
case '#': // A class object (Class)
case ':': // A method selector (SEL)
default:
return nil;
}
}
extern "C" {
// Forward declare some Objective-C runtime internal methods that are not API.
const char *_protocol_getMethodTypeEncoding(Protocol *, SEL, BOOL isRequiredMethod, BOOL isInstanceMethod);
id objc_initWeak(id *, id);
void objc_destroyWeak(id *);
bool _Block_has_signature(void *);
const char * _Block_signature(void *);
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (C) 2008 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 OpaqueJSString_h
#define OpaqueJSString_h
#include <atomic>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/text/WTFString.h>
namespace JSC {
class Identifier;
class VM;
}
struct OpaqueJSString : public ThreadSafeRefCounted<OpaqueJSString> {
static Ref<OpaqueJSString> create()
{
return adoptRef(*new OpaqueJSString);
}
static Ref<OpaqueJSString> create(const LChar* characters, unsigned length)
{
return adoptRef(*new OpaqueJSString(characters, length));
}
static Ref<OpaqueJSString> create(const UChar* characters, unsigned length)
{
return adoptRef(*new OpaqueJSString(characters, length));
}
JS_EXPORT_PRIVATE static RefPtr<OpaqueJSString> tryCreate(const String&);
JS_EXPORT_PRIVATE static RefPtr<OpaqueJSString> tryCreate(String&&);
JS_EXPORT_PRIVATE ~OpaqueJSString();
bool is8Bit() { return m_string.is8Bit(); }
const LChar* characters8() { return m_string.characters8(); }
const UChar* characters16() { return m_string.characters16(); }
unsigned length() { return m_string.length(); }
const UChar* characters();
JS_EXPORT_PRIVATE String string() const;
JSC::Identifier identifier(JSC::VM*) const;
static bool equal(const OpaqueJSString*, const OpaqueJSString*);
private:
friend class WTF::ThreadSafeRefCounted<OpaqueJSString>;
OpaqueJSString()
: m_characters(nullptr)
{
}
OpaqueJSString(const String& string)
: m_string(string.isolatedCopy())
, m_characters(m_string.impl() && m_string.is8Bit() ? nullptr : const_cast<UChar*>(m_string.characters16()))
{
}
explicit OpaqueJSString(String&& string)
: m_string(WTFMove(string))
, m_characters(m_string.impl() && m_string.is8Bit() ? nullptr : const_cast<UChar*>(m_string.characters16()))
{
}
OpaqueJSString(const LChar* characters, unsigned length)
: m_string(characters, length)
, m_characters(nullptr)
{
}
OpaqueJSString(const UChar* characters, unsigned length)
: m_string(characters, length)
, m_characters(m_string.impl() && m_string.is8Bit() ? nullptr : const_cast<UChar*>(m_string.characters16()))
{
}
String m_string;
// This will be initialized on demand when characters() is called if the string needs up-conversion.
std::atomic<UChar*> m_characters;
};
#endif

View File

@@ -0,0 +1,43 @@
/*
* 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__)
#include <AvailabilityMacros.h>
#include <CoreFoundation/CoreFoundation.h>
#if defined(BUILDING_GTK__)
#undef JSC_API_AVAILABLE
#define JSC_API_AVAILABLE(...)
#endif
#else
#define JSC_API_AVAILABLE(...)
#endif
#endif /* __WebKitAvailability__ */