Permalink
Browse files

Objective-C API for JavaScriptCore

https://bugs.webkit.org/show_bug.cgi?id=105889

Reviewed by Filip Pizlo.

../JavaScriptCore: 

For a detailed description of the API implemented here, see:
    JSContext.h
    APIJSValue.h
    JSVirtualMachine.h
    JSExport.h
Still to do -
    (1) Shoud rename APIJSValue.h -> JSValue.h (but we'll have to rename JSValue.h first).
    (2) Numerous FIXMEs, all with separate bugs filed.

* API/APIJSValue.h: Added.
    - this Objective-C class is used to reference a JavaScript object.
* API/JSBase.h:
    - added JS_OBJC_API_ENABLED macro to control ObjC API support.
* API/JSBlockAdaptor.h: Added.
    - this Objective-C class is used in creating a special NSBlock proxying a JavaScript function.
* API/JSBlockAdaptor.mm: Added.
(BlockArgument):
(BlockArgument::~BlockArgument):
(BlockArgumentBoolean):
(BlockArgumentBoolean::get):
(BlockArgumentNumeric):
(BlockArgumentNumeric::get):
(BlockArgumentId):
(BlockArgumentId::get):
(BlockArgumentStruct):
(BlockArgumentStruct::BlockArgumentStruct):
(BlockArgumentStruct::~BlockArgumentStruct):
(BlockArgumentStruct::get):
    - decoded arguent type information of a JSBlockAdaptor.
(BlockArgumentTypeDelegate):
(BlockArgumentTypeDelegate::typeInteger):
(BlockArgumentTypeDelegate::typeDouble):
(BlockArgumentTypeDelegate::typeBool):
(BlockArgumentTypeDelegate::typeVoid):
(BlockArgumentTypeDelegate::typeId):
(BlockArgumentTypeDelegate::typeOfClass):
(BlockArgumentTypeDelegate::typeBlock):
(BlockArgumentTypeDelegate::typeStruct):
    - delegate for use in conjunction with parseObjCType.
(BlockResult):
(BlockResult::~BlockResult):
(BlockResultVoid):
(BlockResultVoid::set):
(BlockResultInteger):
(BlockResultInteger::set):
(BlockResultDouble):
(BlockResultDouble::set):
(BlockResultBoolean):
(BlockResultBoolean::set):
(BlockResultStruct):
(BlockResultStruct::BlockResultStruct):
(BlockResultStruct::~BlockResultStruct):
(BlockResultStruct::set):
    - decoded result type information of a JSBlockAdaptor.
(buildBlockSignature):
    - partial step in constructing a signature with stack offset information from one without.
(-[JSBlockAdaptor initWithBlockSignatureFromProtocol:]):
    - constructor.
(-[JSBlockAdaptor blockMatchesSignature:]):
    - check whether signature strings match, where only one contains stack frame offsets.
(-[JSBlockAdaptor blockFromValue:inContext:withException:]):
    - use the adaptor to create a special forwarding block.
* API/JSCallbackObjectFunctions.h:
(JSC::::inherits):
    - add missing braces to multiline for statement.
* API/JSContext.h: Added.
    - this Objective-C class is used to reference a JavaScript context.
* API/JSContext.mm: Added.
(-[JSContext init]):
    - constructor.
(-[JSContext initWithVirtualMachine:]):
    - construct in a given VM (JSGlobalData).
(-[JSContext evaluateScript:]):
(-[JSContext globalObject]):
    - evaluate a script, global object accessor.
(+[JSContext currentContext]):
(+[JSContext currentThis]):
(+[JSContext currentArguments]):
    - These methods obtain context, this, arguments from within a callback.
(-[JSContext virtualMachine]):
    - implementation for .virtualMachine property.
(-[JSContext objectForKeyedSubscript:]):
(-[JSContext setObject:forKeyedSubscript:]):
    - support for subscript property access.
(contextInternalContext):
    - internal accessor to m_context.
(-[JSContext dealloc]):
    - desctructor.
(-[JSContext notifyException:]):
(-[JSContext valueFromNotifyException:]):
(-[JSContext boolFromNotifyException:]):
    - internal method to record an exception was thrown.
(-[JSContext beginCallbackWithData:thisValue:argumentCount:arguments:]):
(-[JSContext endCallbackWithData:]):
    - internal methods to push/pop a callback record.
(-[JSContext protect:]):
(-[JSContext unprotect:]):
    - internal methods to add a value to a protect set (used to protect the internal property of JSValue).
(-[JSContext wrapperForObject:]):
    - internal method to create a wrapper object.
(WeakContextRef::WeakContextRef):
(WeakContextRef::~WeakContextRef):
(WeakContextRef::get):
(WeakContextRef::set):
    - Helper class to implement a weak reference to a JSContext.
* API/JSContextInternal.h: Added.
(CallbackData):
(WeakContextRef):
    - see API/JSContext.mm for description of internal methods.
* API/JSExport.h: Added.
    - Provides JSExport protocol & JSExportAs macro.
* API/JSValue.mm: Added.
(+[JSValue valueWithObject:inContext:]):
(+[JSValue valueWithBool:inContext:]):
(+[JSValue valueWithDouble:inContext:]):
(+[JSValue valueWithInt32:inContext:]):
(+[JSValue valueWithUInt32:inContext:]):
(+[JSValue valueWithNewObjectInContext:]):
(+[JSValue valueWithNewArrayInContext:]):
(+[JSValue valueWithNewRegularExpressionFromPattern🎏inContext:]):
(+[JSValue valueWithNewErrorFromMessage:inContext:]):
(+[JSValue valueWithNullInContext:]):
(+[JSValue valueWithUndefinedInContext:]):
    - Constructors.
(-[JSValue toObject]):
(-[JSValue toObjectOfClass:]):
(-[JSValue toBool]):
(-[JSValue toDouble]):
(-[JSValue toInt32]):
(-[JSValue toUInt32]):
(-[JSValue toNumber]):
(-[JSValue toString]):
(-[JSValue toDate]):
(-[JSValue toArray]):
(-[JSValue toDictionary]):
    - Conversion to Objective-C types.
(-[JSValue valueForProperty:]):
(-[JSValue setValue:forProperty:]):
(-[JSValue deleteProperty:]):
(-[JSValue hasProperty:]):
(-[JSValue defineProperty:descriptor:]):
    - Property access by property name.
(-[JSValue valueAtIndex:]):
(-[JSValue setValue:atIndex:]):
    - Property access by index.
(-[JSValue isUndefined]):
(-[JSValue isNull]):
(-[JSValue isBoolean]):
(-[JSValue isNumber]):
(-[JSValue isString]):
(-[JSValue isObject]):
    - Test JavaScript type.
(-[JSValue isEqualToObject:]):
(-[JSValue isEqualWithTypeCoercionToObject:]):
(-[JSValue isInstanceOf:]):
    - ===, ==, instanceof operators.
(-[JSValue callWithArguments:]):
(-[JSValue constructWithArguments:]):
(-[JSValue invokeMethod:withArguments:]):
    - Call & construct.
(-[JSValue context]):
    - implementation for .context property.
(-[JSValue toPoint]):
(-[JSValue toRange]):
(-[JSValue toRect]):
(-[JSValue toSize]):
(+[JSValue valueWithPoint:inContext:]):
(+[JSValue valueWithRange:inContext:]):
(+[JSValue valueWithRect:inContext:]):
(+[JSValue valueWithSize:inContext:]):
    - Support for NS struct types.
(-[JSValue objectForKeyedSubscript:]):
(-[JSValue objectAtIndexedSubscript:]):
(-[JSValue setObject:forKeyedSubscript:]):
(-[JSValue setObject:atIndexedSubscript:]):
    - support for subscript property access.
(isDate):
(isArray):
    - internal helper functions to check for instances of JS Date, Array types.
(JSContainerConvertor):
(Task):
(JSContainerConvertor::JSContainerConvertor):
(JSContainerConvertor::isWorkListEmpty):
(JSContainerConvertor::convert):
(JSContainerConvertor::add):
(JSContainerConvertor::take):
    - helper class for tracking state while converting to Array/Dictionary objects.
(valueToObjectWithoutCopy):
(containerValueToObject):
(valueToObject):
(valueToNumber):
(valueToString):
(valueToDate):
(valueToArray):
(valueToDictionary):
    - function for converting JavaScript values to Objective-C objects.
(ObjcContainerConvertor):
(ObjcContainerConvertor::ObjcContainerConvertor):
(ObjcContainerConvertor::isWorkListEmpty):
(ObjcContainerConvertor::convert):
(ObjcContainerConvertor::add):
(ObjcContainerConvertor::take):
    - helper class for tracking state while converting to Array/Dictionary values.
(objectToValueWithoutCopy):
(objectToValue):
(valueInternalValue):
    - function for converting Objective-C objects to JavaScript values.
(+[JSValue valueWithValue:inContext:]):
(-[JSValue initWithValue:inContext:]):
    - internal constructors.
(StructTagHandler):
(getStructTagHandler):
(+[JSValue selectorForStructToValue:]):
(+[JSValue selectorForValueToStruct:]):
    - methods to tracking struct types that support conversion to/from JSValue.
(-[JSValue dealloc]):
    - destructor.
(-[JSValue description]):
    - Objective-C to-NSString conversion.
(typeToValueInvocationFor):
(valueToTypeInvocationFor):
    - create invocation objects for conversion to/from JSValue.
* API/JSValueInternal.h: Added.
    - see API/JSValue.mm for description of internal methods.
* API/JSVirtualMachine.h: Added.
    - this Objective-C class is used to reference a JavaScript virtual machine (JSGlobalData).
* API/JSVirtualMachine.mm: Added.
(-[JSVirtualMachine init]):
(-[JSVirtualMachine dealloc]):
    - constructor & destructor.
(getGroupFromVirtualMachine):
    - internal accessor for m_group property.
* API/JSVirtualMachineInternal.h: Added.
    - see API/JSVirtualMachine.mm for description of internal methods.
* API/JSWrapperMap.h: Added.
* API/JSWrapperMap.mm: Added.
(wrapperClass):
    - singleton root for detction (& unwrapping) of wrapper objects.
(selectorToPropertyName):
    - default selector to property name conversion.
(createObjectWithCustomBrand):
    - creates a JSObject with a custom NativeBrand (class name).
(createRenameMap):
    - parse @optional properties of a JSExport protocol.
(putNonEnumerable):
    - property put with enumerable=false.
(copyMethodsToObject):
    - iterate methods in a protocol; add functions to a JSObject.
(parsePropertyAttributes):
    - examine protocol property metadata.
(makeSetterName):
    - "foo" -> "setFoo"
(copyPrototypeProperties):
    - create properties on a Protocol object reflecting the instance methods & properties of a protocol.
(-[JSObjCClassInfo initWithContext:forClass:superClassInfo:]):
(-[JSObjCClassInfo dealloc]):
(-[JSObjCClassInfo wrapperForObject:]):
(-[JSObjCClassInfo constructor]):
    - cache the Protocol/Constructor objects for an Objective-C type.
(-[JSWrapperMap initWithContext:]):
(-[JSWrapperMap dealloc]):
    - constructor & desctructor.
(-[JSWrapperMap classInfoForClass:]):
    - maps Class -> JSObjCClassInfo.
(-[JSWrapperMap wrapperForObject:]):
    - cretae or retrieve a cached wrapper value for an object.
(tryUnwrapObjcObject):
    - check whether a value is a wrapper object; unwrap if so.
* API/JavaScriptCore.h:
    - Added includes for new API headers.
* API/ObjCCallbackFunction.h: Added.
    - this class is used to wrap Objective-C instance methods, class methods & blocks as JSFunction objects.
* API/ObjCCallbackFunction.mm: Added.
(CallbackArgument):
(CallbackArgument::~CallbackArgument):
(CallbackArgumentBoolean):
(CallbackArgumentBoolean::set):
(CallbackArgumentInteger):
(CallbackArgumentInteger::set):
(CallbackArgumentDouble):
(CallbackArgumentDouble::set):
(CallbackArgumentJSValue):
(CallbackArgumentJSValue::set):
(CallbackArgumentId):
(CallbackArgumentId::set):
(CallbackArgumentOfClass):
(CallbackArgumentOfClass::CallbackArgumentOfClass):
(CallbackArgumentOfClass::~CallbackArgumentOfClass):
(CallbackArgumentOfClass::set):
(CallbackArgumentNSNumber):
(CallbackArgumentNSNumber::set):
(CallbackArgumentNSString):
(CallbackArgumentNSString::set):
(CallbackArgumentNSDate):
(CallbackArgumentNSDate::set):
(CallbackArgumentNSArray):
(CallbackArgumentNSArray::set):
(CallbackArgumentNSDictionary):
(CallbackArgumentNSDictionary::set):
(CallbackArgumentStruct):
(CallbackArgumentStruct::CallbackArgumentStruct):
(CallbackArgumentStruct::~CallbackArgumentStruct):
(CallbackArgumentStruct::set):
(CallbackArgumentBlockCallback):
(CallbackArgumentBlockCallback::CallbackArgumentBlockCallback):
(CallbackArgumentBlockCallback::~CallbackArgumentBlockCallback):
(CallbackArgumentBlockCallback::set):
    - decoded arguent type information of a ObjCCallbackFunction.
(ArgumentTypeDelegate):
(ArgumentTypeDelegate::typeInteger):
(ArgumentTypeDelegate::typeDouble):
(ArgumentTypeDelegate::typeBool):
(ArgumentTypeDelegate::typeVoid):
(ArgumentTypeDelegate::typeId):
(ArgumentTypeDelegate::typeOfClass):
(ArgumentTypeDelegate::typeBlock):
(ArgumentTypeDelegate::typeStruct):
    - delegate for use in conjunction with parseObjCType.
(CallbackResult):
(CallbackResult::~CallbackResult):
(CallbackResultVoid):
(CallbackResultVoid::get):
(CallbackResultId):
(CallbackResultId::get):
(CallbackResultNumeric):
(CallbackResultNumeric::get):
(CallbackResultBoolean):
(CallbackResultBoolean::get):
(CallbackResultStruct):
(CallbackResultStruct::CallbackResultStruct):
(CallbackResultStruct::~CallbackResultStruct):
(CallbackResultStruct::get):
    - decoded result type information of a ObjCCallbackFunction.
(ResultTypeDelegate):
(ResultTypeDelegate::typeInteger):
(ResultTypeDelegate::typeDouble):
(ResultTypeDelegate::typeBool):
(ResultTypeDelegate::typeVoid):
(ResultTypeDelegate::typeId):
(ResultTypeDelegate::typeOfClass):
(ResultTypeDelegate::typeBlock):
(ResultTypeDelegate::typeStruct):
    - delegate for use in conjunction with parseObjCType.
(ObjCCallbackFunction):
(ObjCCallbackFunction::ObjCCallbackFunction):
(ObjCCallbackFunction::~ObjCCallbackFunction):
    - constructor & destructor.
(ObjCCallbackFunction::context):
    - accessor.
(ObjCCallbackFunction::wrappedBlock):
    - attemmpt to unwrap a block object.
(objCCallbackFunctionFinalize):
(objCCallbackFunctionCallAsFunction):
(objCCallbackFunctionClass):
    - JSClassRef used to represent ObjCCallbackFunction objects.
(ObjCCallbackFunction::call):
(blockSignatureContainsClass):
    - helper function to determine if we're running on a recent Clang.
(skipNumber):
    - helper used in parsing signature strings.
(objCCallbackFunctionForInvocation):
(objCCallbackFunctionForMethod):
(objCCallbackFunctionForBlock):
    - functions to try to create ObjCCallbackFunction instances for methods/blocks.
(tryUnwrapBlock):
    - attemmpt to unwrap a block object.
* API/ObjcRuntimeExtras.h: Added.
(protocolImplementsProtocol):
(forEachProtocolImplementingProtocol):
(forEachMethodInClass):
(forEachMethodInProtocol):
(forEachPropertyInProtocol):
    - functions used in reflecting on Objective-C types.
(skipPair):
    - parsing helper used by parseObjCType, scans for matching parentheses.
(StringRange):
(StringRange::StringRange):
(StringRange::~StringRange):
(StringRange::operator const char*):
(StringRange::get):
    - Helper class - create a c string copy of a range of an existing string.
(parseObjCType):
    - function to parse Objective-C type strings, makes callbacks to a deleagte.
* API/tests/testapi.c:
(main):
    - added call to testObjectiveCAPI (in testapi.m).
* API/tests/testapi.m: Added.
(+[ParentObject parentTest]):
(+[TestObject testObject]):
(+[TestObject classTest]):
(-[TestObject getString]):
(-[TestObject testArgumentTypesWithInt:double:boolean:string:number:array:dictionary:]):
(-[TestObject callback:]):
(-[TextXYZ test:]):
    - test object, used in various test vases.
(checkResult):
    - helper function.
(blockSignatureContainsClass):
    - helper function to determine if we're running on a recent Clang.
(testObjectiveCAPI):
    - new test cases.
* JavaScriptCore.xcodeproj/project.pbxproj:
    - added new files.
* runtime/JSGlobalData.cpp:
(JSC::JSGlobalData::JSGlobalData):
* runtime/JSGlobalData.h:
(JSGlobalData):
    - added m_apiData - provide convenient storage for use by the API.
* runtime/JSGlobalObject.cpp:
(JSC::JSGlobalObject::JSGlobalObject):
* runtime/JSGlobalObject.h:
(JSGlobalObject):
    - added m_apiData - provide convenient storage for use by the API.

../WTF: 

* wtf/WTFThreadData.cpp:
(WTF::WTFThreadData::WTFThreadData):
* wtf/WTFThreadData.h:
(WTFThreadData):
    - Added m_apiData - provide convenient storage for use by the API.



git-svn-id: http://svn.webkit.org/repository/webkit/trunk@138604 268f45cc-cd09-0410-ab3c-d52691b4dbfc
  • Loading branch information...
barraclough@apple.com
barraclough@apple.com committed Jan 2, 2013
1 parent 3e7471a commit fc3818879aa31b219fb99880378ef947bbc1acc1
Showing with 5,170 additions and 4 deletions.
  1. +301 −0 Source/JavaScriptCore/API/APIJSValue.h
  2. +8 −0 Source/JavaScriptCore/API/JSBase.h
  3. +38 −0 Source/JavaScriptCore/API/JSBlockAdaptor.h
  4. +428 −0 Source/JavaScriptCore/API/JSBlockAdaptor.mm
  5. +2 −2 Source/JavaScriptCore/API/JSCallbackObjectFunctions.h
  6. +116 −0 Source/JavaScriptCore/API/JSContext.h
  7. +262 −0 Source/JavaScriptCore/API/JSContext.mm
  8. +73 −0 Source/JavaScriptCore/API/JSContextInternal.h
  9. +127 −0 Source/JavaScriptCore/API/JSExport.h
  10. +1,167 −0 Source/JavaScriptCore/API/JSValue.mm
  11. +54 −0 Source/JavaScriptCore/API/JSValueInternal.h
  12. +41 −0 Source/JavaScriptCore/API/JSVirtualMachine.h
  13. +66 −0 Source/JavaScriptCore/API/JSVirtualMachine.mm
  14. +37 −0 Source/JavaScriptCore/API/JSVirtualMachineInternal.h
  15. +45 −0 Source/JavaScriptCore/API/JSWrapperMap.h
  16. +463 −0 Source/JavaScriptCore/API/JSWrapperMap.mm
  17. +9 −0 Source/JavaScriptCore/API/JavaScriptCore.h
  18. +35 −0 Source/JavaScriptCore/API/ObjCCallbackFunction.h
  19. +677 −0 Source/JavaScriptCore/API/ObjCCallbackFunction.mm
  20. +219 −0 Source/JavaScriptCore/API/ObjcRuntimeExtras.h
  21. +9 −1 Source/JavaScriptCore/API/tests/testapi.c
  22. +477 −0 Source/JavaScriptCore/API/tests/testapi.m
  23. +421 −0 Source/JavaScriptCore/ChangeLog
  24. +72 −0 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj
  25. +1 −0 Source/JavaScriptCore/runtime/JSGlobalData.cpp
  26. +2 −0 Source/JavaScriptCore/runtime/JSGlobalData.h
  27. +1 −0 Source/JavaScriptCore/runtime/JSGlobalObject.cpp
  28. +2 −0 Source/JavaScriptCore/runtime/JSGlobalObject.h
  29. +13 −0 Source/WTF/ChangeLog
  30. +2 −1 Source/WTF/wtf/WTFThreadData.cpp
  31. +2 −0 Source/WTF/wtf/WTFThreadData.h
@@ -0,0 +1,301 @@
/*
* 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.
*/
#if JS_OBJC_API_ENABLED
@class JSContext;
// A JSValue is a reference to a value within the JavaScript object space of a
// JSVirtualMachine. All instances of JSValue originate from a JSContext, and
// hold a weak reference to this JSContext. Where an instance method is invoked
// upon a JSValue, and this returns another JSValue, the returned JSValue will
// originate from the same JSContext as the JSValue on which the method was
// invoked.
//
// The JSContext is used to manage the life-cycle of the refereced JavaScript
// value within the virtual machine. So long as the JSContext is being retained
// the JSValue will continue to keep the referencd value within the JavaScript
// virtual machine alive. When the JSContext associated with a JSValue is
// deallocated the weak context property of the JSValue will become nil. After
// this occurs the value within the JavaScript virtual machine is no longer
// being maintained by this JSValue, and the JSValue instance may no longer by
// used as a reference to this value. For any method invoked on instance of
// JSValue with a nil context, the method will return a nil/zero/false result.
//
// For all methods taking arguments of type id, arguments will be converted
// into a JavaScript value according to the conversion specified below.
// All JavaScript values are associated with a particular JSVirtualMachine
// (the associated JSVirtualMachine is avaible indirectly via the context
// property). An instance of JSValue may only be passed as an argument to
// methods on instances of JSValue and JSContext that belong to the same
// JSVirtualMachine - passing a JSValue to a method on an object originating
// from a different JSVirtualMachine will result in an Objective-C exception
// being raised.
//
// Conversion between Objective-C and JavaScript types.
//
// 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.
//
// Objective-C type | JavaScript type
// --------------------+---------------------
// nil | undefined
// NSNull | null
// NSString | string
// NSNumber | number, boolean
// NSDictionary | Object object
// NSArray | Array object
// NSDate | Date object
// NSBlock * | Function object *
// id ** | Wrapper object **
// Class *** | Constructor object ***
//
// * 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.
//
// ** 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.
//
// *** For Objective-C Class objects a constructor object containing exported
// class methods will be returned. See JSExport.h sor more information on
// constructor objects.
NS_CLASS_AVAILABLE(10_9, NA)
@interface JSValue : NSObject
// Create a JSValue by converting an Objective-C object.
+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;
// Create a JavaScript value from an Objective-C primitive type.
+ (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context;
+ (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context;
+ (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context;
+ (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context;
// Create a JavaScript value in this context.
+ (JSValue *)valueWithNewObjectInContext:(JSContext *)context;
+ (JSValue *)valueWithNewArrayInContext:(JSContext *)context;
+ (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context;
+ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context;
+ (JSValue *)valueWithNullInContext:(JSContext *)context;
+ (JSValue *)valueWithUndefinedInContext:(JSContext *)context;
// Convert this value to a corresponding Objective-C object, according to the
// conversion specified above.
- (id)toObject;
// Convert this value to a corresponding Objective-C object, if the result is
// not of the specified class then nil will be returned.
- (id)toObjectOfClass:(Class)cls;
// The value is copied to a boolean according to the conversion specified by the
// JavaScript language.
- (BOOL)toBool;
// The value is copied to a number according to the conversion specified by the
// JavaScript language.
- (double)toDouble;
// The value is copied to an integer according to the conversion specified by
// the JavaScript language.
- (int32_t)toInt32;
// The value is copied to an integer according to the conversion specified by
// the JavaScript language.
- (uint32_t)toUInt32;
// If the value is a boolean, a NSNumber value of @YES or @NO will be returned.
// For all other types the value will be copied to a number according to the
// conversion specified by the JavaScript language.
- (NSNumber *)toNumber;
// The value is copied to a string according to the conversion specified by the
// JavaScript language.
- (NSString *)toString;
// The value is converted to a number representing a time interval since 1970,
// and a new NSDate instance is returned.
- (NSDate *)toDate;
// If the value is null or undefined then nil is returned.
// If the value is not an object then a JavaScript TypeError will be thrown.
// The property "length" 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
// Objective-C objects converted to equivalent JSValues as specified.
- (NSArray *)toArray;
// If the value is null or undefined then nil 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
// Objective-C objects converted to equivalent JSValues as specified.
- (NSDictionary *)toDictionary;
// Access a property from the value. This method will return the JavaScript value
// 'undefined' if the property does not exist.
- (JSValue *)valueForProperty:(NSString *)property;
// Set a property on the value.
- (void)setValue:(id)value forProperty:(NSString *)property;
// Delete a property from the value, returns YES if deletion is successful.
- (BOOL)deleteProperty:(NSString *)property;
// Returns YES if property is present on the value.
// This method has the same function as the JavaScript operator "in".
- (BOOL)hasProperty:(NSString *)property;
// 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 langauage.
- (void)defineProperty:(NSString *)property descriptor:(id)descriptor;
// Access an indexed property from the value. This method will return the
// JavaScript value 'undefined' if no property exists at that index.
- (JSValue *)valueAtIndex:(NSUInteger)index;
// Set an indexed property on the value.
- (void)setValue:(id)value atIndex:(NSUInteger)index;
// All JavaScript values are precisely one of these types.
- (BOOL)isUndefined;
- (BOOL)isNull;
- (BOOL)isBoolean;
- (BOOL)isNumber;
- (BOOL)isString;
- (BOOL)isObject;
// This method has the same function as the JavaScript operator "===".
- (BOOL)isEqualToObject:(id)value;
// This method has the same function as the JavaScript operator "==".
- (BOOL)isEqualWithTypeCoercionToObject:(id)value;
// This method has the same function as the JavaScript operator "instanceof".
- (BOOL)isInstanceOf:(id)value;
// Call this value as a function passing the specified "this" value and arguments.
- (JSValue *)callWithArguments:(NSArray *)arguments;
// Call this value as a constructor passing the specified arguments.
- (JSValue *)constructWithArguments:(NSArray *)arguments;
// Access the property named "method" from this value; call the value resulting
// from the property access as a function, passing this value as the "this"
// value, and the specified agruments.
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;
// The JSContext that this value originates from.
@property(readonly, weak) JSContext *context;
@end
// Objective-C methods exported to JavaScript may have argument and/or return
// values of struct types if the struct if conversion to and from the struct
// is supported by JSValue. Support is provided for any types where JSValue
// contains both a class method "valueWith<Type>:inContext:", and and instance
// method "to<Type>" - where the string "<Type>" 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)
// This method returns a newly allocated JavaScript object containing properties
// named "x" and "y", with values from the CGPoint.
+ (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context;
// This method returns a newly allocated JavaScript object containing properties
// named "location" and "length", with values from the NSRange.
+ (JSValue *)valueWithRange:(NSRange)range inContext:(JSContext *)context;
// This method returns a newly allocated JavaScript object containing properties
// named "x", "y", "width", and "height", with values from the CGRect.
+ (JSValue *)valueWithRect:(CGRect)rect inContext:(JSContext *)context;
// This method returns a newly allocated JavaScript object containing properties
// named "width" and "height", with values from the CGSize.
+ (JSValue *)valueWithSize:(CGSize)size inContext:(JSContext *)context;
// Convert a value to type CGPoint by reading properties named "x" and "y" from
// this value, and converting the results to double.
- (CGPoint)toPoint;
// Convert a value to type NSRange by accessing properties named "location" and
// "length" from this value converting the results to double.
- (NSRange)toRange;
// Convert a value to type CGRect by reading properties named "x", "y", "width",
// and "height" from this value, and converting the results to double.
- (CGRect)toRect;
// Convert a value to type CGRange by accessing properties named "width" and
// "height" from this value converting the results to double.
- (CGSize)toSize;
@end
// Instances of JSValue implement the following methods in order to enable
// support for subscript access by key and index, for example:
//
// 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'.
//
// An object key passed as a subscript will be converted to a JavaScipt value,
// and then the value converted to a string used as a property name.
@interface JSValue(SubscriptSupport)
- (JSValue *)objectForKeyedSubscript:(id)key;
- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index;
- (void)setObject:(id)object forKeyedSubscript:(id <NSCopying>)key;
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index;
@end
#ifdef __cplusplus
extern "C" {
#endif
// 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 "value" and "writable",
// and optionally containing one or both of the keys "enumerable" and
// "configurable". A data descriptor may not contain either the "get" or
// "set" 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 "get" and "set", and
// optionally containing one or both of the keys "enumerable" and
// "configurable". An accessor descriptor may not contain either the "value"
// or "writable" 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 "enumerable" and
// "configurable". A generic descriptor may not contain any of the keys
// "value", " writable", "get", or "set".
// A generic descriptor may be used to modify the attributes of an existing
// data or accessor property, or to create a new data property.
JS_EXPORT extern NSString * const JSPropertyDescriptorWritableKey;
JS_EXPORT extern NSString * const JSPropertyDescriptorEnumerableKey;
JS_EXPORT extern NSString * const JSPropertyDescriptorConfigurableKey;
JS_EXPORT extern NSString * const JSPropertyDescriptorValueKey;
JS_EXPORT extern NSString * const JSPropertyDescriptorGetKey;
JS_EXPORT extern NSString * const JSPropertyDescriptorSetKey;
#ifdef __cplusplus
} // extern "C"
#endif
#endif
@@ -30,6 +30,10 @@
#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. */
@@ -135,4 +139,8 @@ JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
}
#endif
/* Enable the Objective-C API for platforms with a modern runtime. */
#undef JS_OBJC_API_ENABLED
#define JS_OBJC_API_ENABLED (defined(__OBJC__) && defined(__clang__) && defined(__APPLE__) && (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1090) && !defined(__i386__))
#endif /* JSBase_h */
@@ -0,0 +1,38 @@
/*
* 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 <wtf/RetainPtr.h>
#if JS_OBJC_API_ENABLED
@interface JSBlockAdaptor : NSObject
- (id)initWithBlockSignatureFromProtocol:(const char *)signature;
- (id)blockFromValue:(JSValueRef)argument inContext:(JSContext *)context withException:(JSValueRef *)exception;
@end
#endif
Oops, something went wrong.

0 comments on commit fc38188

Please sign in to comment.