Skip to content

Commit e06bf09

Browse files
author
Gavin Barraclough
committed
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:flags: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. Canonical link: https://commits.webkit.org/124088@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@138604 268f45cc-cd09-0410-ab3c-d52691b4dbfc
1 parent 6f51332 commit e06bf09

31 files changed

Lines changed: 5170 additions & 4 deletions
Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
/*
2+
* Copyright (C) 2013 Apple Inc. All rights reserved.
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions
6+
* are met:
7+
* 1. Redistributions of source code must retain the above copyright
8+
* notice, this list of conditions and the following disclaimer.
9+
* 2. Redistributions in binary form must reproduce the above copyright
10+
* notice, this list of conditions and the following disclaimer in the
11+
* documentation and/or other materials provided with the distribution.
12+
*
13+
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14+
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16+
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17+
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18+
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19+
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20+
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21+
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24+
*/
25+
26+
#if JS_OBJC_API_ENABLED
27+
28+
@class JSContext;
29+
30+
// A JSValue is a reference to a value within the JavaScript object space of a
31+
// JSVirtualMachine. All instances of JSValue originate from a JSContext, and
32+
// hold a weak reference to this JSContext. Where an instance method is invoked
33+
// upon a JSValue, and this returns another JSValue, the returned JSValue will
34+
// originate from the same JSContext as the JSValue on which the method was
35+
// invoked.
36+
//
37+
// The JSContext is used to manage the life-cycle of the refereced JavaScript
38+
// value within the virtual machine. So long as the JSContext is being retained
39+
// the JSValue will continue to keep the referencd value within the JavaScript
40+
// virtual machine alive. When the JSContext associated with a JSValue is
41+
// deallocated the weak context property of the JSValue will become nil. After
42+
// this occurs the value within the JavaScript virtual machine is no longer
43+
// being maintained by this JSValue, and the JSValue instance may no longer by
44+
// used as a reference to this value. For any method invoked on instance of
45+
// JSValue with a nil context, the method will return a nil/zero/false result.
46+
//
47+
// For all methods taking arguments of type id, arguments will be converted
48+
// into a JavaScript value according to the conversion specified below.
49+
// All JavaScript values are associated with a particular JSVirtualMachine
50+
// (the associated JSVirtualMachine is avaible indirectly via the context
51+
// property). An instance of JSValue may only be passed as an argument to
52+
// methods on instances of JSValue and JSContext that belong to the same
53+
// JSVirtualMachine - passing a JSValue to a method on an object originating
54+
// from a different JSVirtualMachine will result in an Objective-C exception
55+
// being raised.
56+
//
57+
// Conversion between Objective-C and JavaScript types.
58+
//
59+
// When converting between JavaScript values and Objective-C objects a copy is
60+
// performed. Values of types listed below are copied to the corresponding
61+
// types on conversion in each direction. For NSDictionaries, entries in the
62+
// dictionary that are keyed by strings are copied onto a JavaScript object.
63+
// For dictionaries and arrays, conversion is recursive, with the same object
64+
// conversion being applied to all entries in the collection.
65+
//
66+
// Objective-C type | JavaScript type
67+
// --------------------+---------------------
68+
// nil | undefined
69+
// NSNull | null
70+
// NSString | string
71+
// NSNumber | number, boolean
72+
// NSDictionary | Object object
73+
// NSArray | Array object
74+
// NSDate | Date object
75+
// NSBlock * | Function object *
76+
// id ** | Wrapper object **
77+
// Class *** | Constructor object ***
78+
//
79+
// * Instances of NSBlock with supported arguments types will be presented to
80+
// JavaScript as a callable Function object. For more information on supported
81+
// argument types see JSExport.h. If a JavaScript Function originating from an
82+
// Objective-C block is converted back to an Objective-C object the block will
83+
// be returned. All other JavaScript functions will be converted in the same
84+
// manner as a JavaScript object of type Object.
85+
//
86+
// ** For Objective-C instances that do not derive from the set of types listed
87+
// above, a wrapper object to provide a retaining handle to the Objective-C
88+
// instance from JavaScript. For more information on these wrapper objects, see
89+
// JSExport.h. When a JavaScript wrapper object is converted back to Objective-C
90+
// the Objective-C instance being retained by the wrapper is returned.
91+
//
92+
// *** For Objective-C Class objects a constructor object containing exported
93+
// class methods will be returned. See JSExport.h sor more information on
94+
// constructor objects.
95+
NS_CLASS_AVAILABLE(10_9, NA)
96+
@interface JSValue : NSObject
97+
98+
// Create a JSValue by converting an Objective-C object.
99+
+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;
100+
// Create a JavaScript value from an Objective-C primitive type.
101+
+ (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context;
102+
+ (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context;
103+
+ (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context;
104+
+ (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context;
105+
// Create a JavaScript value in this context.
106+
+ (JSValue *)valueWithNewObjectInContext:(JSContext *)context;
107+
+ (JSValue *)valueWithNewArrayInContext:(JSContext *)context;
108+
+ (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context;
109+
+ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context;
110+
+ (JSValue *)valueWithNullInContext:(JSContext *)context;
111+
+ (JSValue *)valueWithUndefinedInContext:(JSContext *)context;
112+
113+
// Convert this value to a corresponding Objective-C object, according to the
114+
// conversion specified above.
115+
- (id)toObject;
116+
// Convert this value to a corresponding Objective-C object, if the result is
117+
// not of the specified class then nil will be returned.
118+
- (id)toObjectOfClass:(Class)cls;
119+
// The value is copied to a boolean according to the conversion specified by the
120+
// JavaScript language.
121+
- (BOOL)toBool;
122+
// The value is copied to a number according to the conversion specified by the
123+
// JavaScript language.
124+
- (double)toDouble;
125+
// The value is copied to an integer according to the conversion specified by
126+
// the JavaScript language.
127+
- (int32_t)toInt32;
128+
// The value is copied to an integer according to the conversion specified by
129+
// the JavaScript language.
130+
- (uint32_t)toUInt32;
131+
// If the value is a boolean, a NSNumber value of @YES or @NO will be returned.
132+
// For all other types the value will be copied to a number according to the
133+
// conversion specified by the JavaScript language.
134+
- (NSNumber *)toNumber;
135+
// The value is copied to a string according to the conversion specified by the
136+
// JavaScript language.
137+
- (NSString *)toString;
138+
// The value is converted to a number representing a time interval since 1970,
139+
// and a new NSDate instance is returned.
140+
- (NSDate *)toDate;
141+
// If the value is null or undefined then nil is returned.
142+
// If the value is not an object then a JavaScript TypeError will be thrown.
143+
// The property "length" is read from the object, converted to an unsigned
144+
// integer, and an NSArray of this size is allocated. Properties corresponding
145+
// to indicies within the array bounds will be copied to the array, with
146+
// Objective-C objects converted to equivalent JSValues as specified.
147+
- (NSArray *)toArray;
148+
// If the value is null or undefined then nil is returned.
149+
// If the value is not an object then a JavaScript TypeError will be thrown.
150+
// All enumerable properties of the object are copied to the dictionary, with
151+
// Objective-C objects converted to equivalent JSValues as specified.
152+
- (NSDictionary *)toDictionary;
153+
154+
// Access a property from the value. This method will return the JavaScript value
155+
// 'undefined' if the property does not exist.
156+
- (JSValue *)valueForProperty:(NSString *)property;
157+
// Set a property on the value.
158+
- (void)setValue:(id)value forProperty:(NSString *)property;
159+
// Delete a property from the value, returns YES if deletion is successful.
160+
- (BOOL)deleteProperty:(NSString *)property;
161+
// Returns YES if property is present on the value.
162+
// This method has the same function as the JavaScript operator "in".
163+
- (BOOL)hasProperty:(NSString *)property;
164+
// This method may be used to create a data or accessor property on an object;
165+
// this method operates in accordance with the Object.defineProperty method in
166+
// the JavaScript langauage.
167+
- (void)defineProperty:(NSString *)property descriptor:(id)descriptor;
168+
169+
// Access an indexed property from the value. This method will return the
170+
// JavaScript value 'undefined' if no property exists at that index.
171+
- (JSValue *)valueAtIndex:(NSUInteger)index;
172+
// Set an indexed property on the value.
173+
- (void)setValue:(id)value atIndex:(NSUInteger)index;
174+
175+
// All JavaScript values are precisely one of these types.
176+
- (BOOL)isUndefined;
177+
- (BOOL)isNull;
178+
- (BOOL)isBoolean;
179+
- (BOOL)isNumber;
180+
- (BOOL)isString;
181+
- (BOOL)isObject;
182+
183+
// This method has the same function as the JavaScript operator "===".
184+
- (BOOL)isEqualToObject:(id)value;
185+
// This method has the same function as the JavaScript operator "==".
186+
- (BOOL)isEqualWithTypeCoercionToObject:(id)value;
187+
// This method has the same function as the JavaScript operator "instanceof".
188+
- (BOOL)isInstanceOf:(id)value;
189+
190+
// Call this value as a function passing the specified "this" value and arguments.
191+
- (JSValue *)callWithArguments:(NSArray *)arguments;
192+
// Call this value as a constructor passing the specified arguments.
193+
- (JSValue *)constructWithArguments:(NSArray *)arguments;
194+
// Access the property named "method" from this value; call the value resulting
195+
// from the property access as a function, passing this value as the "this"
196+
// value, and the specified agruments.
197+
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;
198+
199+
// The JSContext that this value originates from.
200+
@property(readonly, weak) JSContext *context;
201+
202+
@end
203+
204+
// Objective-C methods exported to JavaScript may have argument and/or return
205+
// values of struct types if the struct if conversion to and from the struct
206+
// is supported by JSValue. Support is provided for any types where JSValue
207+
// contains both a class method "valueWith<Type>:inContext:", and and instance
208+
// method "to<Type>" - where the string "<Type>" in these selector names match,
209+
// with the first argument to the former being of the same struct type as the
210+
// return type of the latter.
211+
// Support is provided for structs of type CGPoint, NSRange, CGRect and CGSize.
212+
@interface JSValue(StructSupport)
213+
214+
// This method returns a newly allocated JavaScript object containing properties
215+
// named "x" and "y", with values from the CGPoint.
216+
+ (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context;
217+
// This method returns a newly allocated JavaScript object containing properties
218+
// named "location" and "length", with values from the NSRange.
219+
+ (JSValue *)valueWithRange:(NSRange)range inContext:(JSContext *)context;
220+
// This method returns a newly allocated JavaScript object containing properties
221+
// named "x", "y", "width", and "height", with values from the CGRect.
222+
+ (JSValue *)valueWithRect:(CGRect)rect inContext:(JSContext *)context;
223+
// This method returns a newly allocated JavaScript object containing properties
224+
// named "width" and "height", with values from the CGSize.
225+
+ (JSValue *)valueWithSize:(CGSize)size inContext:(JSContext *)context;
226+
227+
// Convert a value to type CGPoint by reading properties named "x" and "y" from
228+
// this value, and converting the results to double.
229+
- (CGPoint)toPoint;
230+
// Convert a value to type NSRange by accessing properties named "location" and
231+
// "length" from this value converting the results to double.
232+
- (NSRange)toRange;
233+
// Convert a value to type CGRect by reading properties named "x", "y", "width",
234+
// and "height" from this value, and converting the results to double.
235+
- (CGRect)toRect;
236+
// Convert a value to type CGRange by accessing properties named "width" and
237+
// "height" from this value converting the results to double.
238+
- (CGSize)toSize;
239+
240+
@end
241+
242+
// Instances of JSValue implement the following methods in order to enable
243+
// support for subscript access by key and index, for example:
244+
//
245+
// JSValue *objectA, *objectB;
246+
// JSValue *v1 = object[@"X"]; // Get value for property "X" from 'object'.
247+
// JSValue *v2 = object[42]; // Get value for index 42 from 'object'.
248+
// object[@"Y"] = v1; // Assign 'v1' to property "Y" of 'object'.
249+
// object[101] = v2; // Assign 'v2' to index 101 of 'object'.
250+
//
251+
// An object key passed as a subscript will be converted to a JavaScipt value,
252+
// and then the value converted to a string used as a property name.
253+
@interface JSValue(SubscriptSupport)
254+
255+
- (JSValue *)objectForKeyedSubscript:(id)key;
256+
- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index;
257+
- (void)setObject:(id)object forKeyedSubscript:(id <NSCopying>)key;
258+
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index;
259+
260+
@end
261+
262+
#ifdef __cplusplus
263+
extern "C" {
264+
#endif
265+
266+
// These keys may assist in creating a property descriptor for use with the
267+
// defineProperty method on JSValue.
268+
// Property descriptors must fit one of three descriptions:
269+
// Data Descriptor:
270+
// - A descriptor containing one or both of the keys "value" and "writable",
271+
// and optionally containing one or both of the keys "enumerable" and
272+
// "configurable". A data descriptor may not contain either the "get" or
273+
// "set" key.
274+
// A data descriptor may be used to create or modify the attributes of a
275+
// data property on an object (replacing any existing accessor property).
276+
// Accessor Descriptor:
277+
// - A descriptor containing one or both of the keys "get" and "set", and
278+
// optionally containing one or both of the keys "enumerable" and
279+
// "configurable". An accessor descriptor may not contain either the "value"
280+
// or "writable" key.
281+
// An accessor descriptor may be used to create or modify the attributes of
282+
// an accessor property on an object (replacing any existing data property).
283+
// Generic Descriptor:
284+
// - A descriptor containing one or both of the keys "enumerable" and
285+
// "configurable". A generic descriptor may not contain any of the keys
286+
// "value", " writable", "get", or "set".
287+
// A generic descriptor may be used to modify the attributes of an existing
288+
// data or accessor property, or to create a new data property.
289+
JS_EXPORT extern NSString * const JSPropertyDescriptorWritableKey;
290+
JS_EXPORT extern NSString * const JSPropertyDescriptorEnumerableKey;
291+
JS_EXPORT extern NSString * const JSPropertyDescriptorConfigurableKey;
292+
JS_EXPORT extern NSString * const JSPropertyDescriptorValueKey;
293+
JS_EXPORT extern NSString * const JSPropertyDescriptorGetKey;
294+
JS_EXPORT extern NSString * const JSPropertyDescriptorSetKey;
295+
296+
#ifdef __cplusplus
297+
} // extern "C"
298+
#endif
299+
300+
#endif
301+

‎Source/JavaScriptCore/API/JSBase.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
#include <stdbool.h>
3131
#endif
3232

33+
#ifdef __OBJC__
34+
#import <Foundation/Foundation.h>
35+
#endif
36+
3337
/* JavaScript engine interface */
3438

3539
/*! @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);
135139
}
136140
#endif
137141

142+
/* Enable the Objective-C API for platforms with a modern runtime. */
143+
#undef JS_OBJC_API_ENABLED
144+
#define JS_OBJC_API_ENABLED (defined(__OBJC__) && defined(__clang__) && defined(__APPLE__) && (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1090) && !defined(__i386__))
145+
138146
#endif /* JSBase_h */
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright (C) 2013 Apple Inc. All rights reserved.
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions
6+
* are met:
7+
* 1. Redistributions of source code must retain the above copyright
8+
* notice, this list of conditions and the following disclaimer.
9+
* 2. Redistributions in binary form must reproduce the above copyright
10+
* notice, this list of conditions and the following disclaimer in the
11+
* documentation and/or other materials provided with the distribution.
12+
*
13+
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14+
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16+
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17+
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18+
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19+
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20+
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21+
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24+
*/
25+
26+
#import <JavaScriptCore/JavaScriptCore.h>
27+
#import <wtf/RetainPtr.h>
28+
29+
#if JS_OBJC_API_ENABLED
30+
31+
@interface JSBlockAdaptor : NSObject
32+
33+
- (id)initWithBlockSignatureFromProtocol:(const char *)signature;
34+
- (id)blockFromValue:(JSValueRef)argument inContext:(JSContext *)context withException:(JSValueRef *)exception;
35+
36+
@end
37+
38+
#endif

0 commit comments

Comments
 (0)