Oolite
Loading...
Searching...
No Matches
OOJSFunction.m
Go to the documentation of this file.
1/*
2
3OOJSFunction.m
4
5
6JavaScript support for Oolite
7Copyright (C) 2007-2013 David Taylor and Jens Ayton.
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
26#import "OOJSFunction.h"
28#import "OOJSScript.h"
29
30@implementation OOJSFunction
31
32- (id)initWithFunction:(JSValueConst)function context:(JSContext*)context
33{
34 NSParameterAssert(context != NULL);
35
36 if (!JS_IsFunction(context, function)) {
37 [self release];
38 return nil;
39 }
40
41 if ((self = [super init])) {
42 _function = JS_DupValue(context, function);
43
44 // QuickJS has no JS_GetFunctionId(); use the function's name property.
45 JSValue nameValue = JS_GetPropertyStr(context, function, "name");
46 if (JS_IsException(nameValue)) {
47 JS_FreeValue(context, JS_GetException(context));
48 } else {
49 NSString* name = OOStringFromJSValue(context, nameValue);
50 if ([name length] != 0)
51 _name = [name retain];
52 }
53 JS_FreeValue(context, nameValue);
54
55 [[NSNotificationCenter defaultCenter] addObserver:self
56 selector:@selector(deleteJSValue)
57 name:kOOJavaScriptEngineWillResetNotification
59 }
60
61 return self;
62}
63
64- (id)initWithName:(NSString*)name
65 scope:(JSValueConst)scope
66 code:(NSString*)code
67 argumentCount:(NSUInteger)argCount
68 argumentNames:(const char**)argNames
69 fileName:(NSString*)fileName
70 lineNumber:(NSUInteger)lineNumber
71 context:(JSContext*)context
72{
73 BOOL OK = YES;
74 BOOL releaseContext = NO;
75 JSValue function = JS_UNDEFINED;
76
77 if (context == NULL) {
78 context = OOJSAcquireContext();
79 releaseContext = YES;
80 }
81
82 /* SpiderMonkey's JS_CompileUCFunction() could compile the function in an
83 arbitrary scope object. QuickJS has no equivalent, so the function is
84 always compiled in the global scope. (The only caller passed NULL,
85 meaning the global object, anyway.)
86 */
87 (void)scope;
88
89 if (code == nil || (argCount > 0 && argNames == NULL))
90 OK = NO;
91
92 if (OK) {
93 assert(argCount < INT_MAX && lineNumber < INT_MAX);
94
95 /* QuickJS has no API to compile a function from a body and argument
96 names, so evaluate a function expression. The wrapper is kept on
97 the first line so that line numbers in the body are unchanged.
98 */
99 NSMutableString* source = [NSMutableString stringWithString:@"(function("];
100 NSUInteger i;
101 for (i = 0; i < argCount; i++) {
102 if (i != 0)
103 [source appendString:@","];
104 [source appendString:[NSString stringWithUTF8String:argNames[i]]];
105 }
106 [source appendFormat:@"){%@\n})", code];
107
108 NSData* utf8 = [source dataUsingEncoding:NSUTF8StringEncoding];
109 NSMutableData* buffer = [NSMutableData dataWithData:utf8];
110 [buffer appendBytes:"" length:1]; // JS_Eval2() requires a NUL-terminated buffer.
111
112 JSEvalOptions options = {
113 .version = JS_EVAL_OPTIONS_VERSION,
114 .eval_flags = JS_EVAL_TYPE_GLOBAL,
115 .filename = [fileName UTF8String] ?: "<anonymous>",
116 .line_num = (int)lineNumber
117 };
118 function = JS_Eval2(context, [buffer bytes], [utf8 length], &options);
119 if (JS_IsException(function)) {
121 function = JS_UNDEFINED;
122 OK = NO;
123 } else if (!JS_IsFunction(context, function)) {
124 OK = NO;
125 }
126 }
127
128 if (OK && name != nil) {
129 // Function expression names are read-only but configurable; redefine it.
130 JS_DefinePropertyValueStr(context, function, "name", [name oo_jsValueInContext:context], JS_PROP_CONFIGURABLE);
131 }
132
133 if (OK) {
134 self = [self initWithFunction:function context:context];
135 } else {
136 DESTROY(self);
137 }
138 JS_FreeValue(context, function);
139
140 if (releaseContext)
141 OOJSRelinquishContext(context);
142
143 return self;
144}
145
146- (void)deleteJSValue
147{
148 // _function is zero-filled (not an object) if never set.
149 if (JS_IsObject(_function)) {
150 JSContext* context = OOJSAcquireContext();
151 JS_FreeValue(context, _function);
152 OOJSRelinquishContext(context);
153
154 _function = JS_NULL;
155 [[NSNotificationCenter defaultCenter] removeObserver:self
156 name:kOOJavaScriptEngineWillResetNotification
158 }
159}
160
161- (void)dealloc
162{
163 [self deleteJSValue];
164 DESTROY(_name);
165
166 [super dealloc];
167}
168
169- (NSString*)descriptionComponents
170{
171 NSString* name = [self name];
172 if (name == nil)
173 name = @"<anonymous>";
174 return [NSString stringWithFormat:@"%@()", name];
175}
176
177- (NSString*)name
178{
179 return _name;
180}
181
182- (BOOL)isValid
183{
184 // _function is zero-filled (the integer 0) until set, and JS_NULL after reset.
185 return JS_IsObject(_function);
186}
187
188- (JSValueConst)function
189{
190 return [self isValid] ? _function : JS_NULL;
191}
192
194{
195 if (EXPECT([self isValid])) {
196 return JS_DupValue(OOJSAcquireContext(), _function);
197 } else {
198 return JS_NULL;
199 }
200}
201
202- (BOOL)evaluateWithContext:(JSContext*)context
203 scope:(JSValueConst)jsThis
204 argc:(int)argc
205 argv:(JSValueConst*)argv
206 result:(JSValue*)result
207{
208 NSParameterAssert(result != NULL);
209
210 if (EXPECT_NOT(![self isValid])) {
211 *result = JS_UNDEFINED;
212 return NO;
213 }
214
215 // As with JS_CallFunction(), a missing this means the global object.
216 JSValue global = JS_UNDEFINED;
217 if (!JS_IsObject(jsThis)) {
218 global = JS_GetGlobalObject(context);
219 jsThis = global;
220 }
221
224 JSValue rval = JS_Call(context, _function, jsThis, argc, argv);
226 [OOJSScript popScript:nil];
227
228 JS_FreeValue(context, global);
229
230 if (JS_IsException(rval)) {
231 *result = JS_UNDEFINED;
232 return NO;
233 }
234 *result = rval;
235 return YES;
236}
237
238// Semi-raw evaluation shared by convenience methods below. *result is owned on success; exceptions are reported.
239- (BOOL)evaluateWithContext:(JSContext*)context
240 scope:(id)jsThis
241 arguments:(NSArray*)arguments
242 result:(JSValue*)result
243{
244 NSUInteger i, argc = [arguments count];
245 assert(argc < INT_MAX);
246 JSValue argv[argc + 1]; // + 1 avoids a zero-length array.
247
248 for (i = 0; i < argc; i++) {
249 argv[i] = [[arguments objectAtIndex:i] oo_jsValueInContext:context];
250 }
251
252 JSValue scopeObj = JS_UNDEFINED;
253 BOOL OK = YES;
254 if (jsThis != nil) {
255 JSValue thisValue = [jsThis oo_jsValueInContext:context];
256 // As with JS_ValueToObject(), null and undefined give no object (the global object is used).
257 if (!JS_IsNull(thisValue) && !JS_IsUndefined(thisValue)) {
258 scopeObj = JS_ToObject(context, thisValue);
259 if (JS_IsException(scopeObj)) {
260 scopeObj = JS_UNDEFINED;
261 OK = NO;
262 }
263 }
264 JS_FreeValue(context, thisValue);
265 }
266 if (OK)
267 OK = [self evaluateWithContext:context
268 scope:scopeObj
269 argc:(int)argc
270 argv:argv
271 result:result];
272 if (!OK) {
273 /* SpiderMonkey reported uncaught exceptions automatically when
274 control returned from JS; QuickJS leaves them pending.
275 */
276 if (JS_HasException(context))
278 *result = JS_UNDEFINED;
279 }
280
281 JS_FreeValue(context, scopeObj);
282 for (i = 0; i < argc; i++) {
283 JS_FreeValue(context, argv[i]);
284 }
285
286 return OK;
287}
288
289- (id)evaluateWithContext:(JSContext*)context
290 scope:(id)jsThis
291 arguments:(NSArray*)arguments
292{
293 JSValue result;
294 BOOL OK = [self evaluateWithContext:context
295 scope:jsThis
296 arguments:arguments
297 result:&result];
298 if (!OK)
299 return nil;
300
301 id object = OOJSNativeObjectFromJSValue(context, result);
302 JS_FreeValue(context, result);
303 return object;
304}
305
306- (BOOL)evaluatePredicateWithContext:(JSContext*)context
307 scope:(id)jsThis
308 arguments:(NSArray*)arguments
309{
310 JSValue result;
311 BOOL OK = [self evaluateWithContext:context
312 scope:jsThis
313 arguments:arguments
314 result:&result];
315 int retval = NO;
316 if (OK) {
317 retval = JS_ToBool(context, result);
318 JS_FreeValue(context, result);
319 if (retval < 0) {
321 OK = NO;
322 }
323 }
324 return OK && retval;
325}
326
327@end
#define DESTROY(x)
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiter()
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
OOINLINE void OOJSRelinquishContext(JSContext *context)
return nil
NSString * descriptionComponents()
id initWithFunction:context:(JSFunction *function,[context] JSContext *context)
JSFunction * function()
NSString * _name
JSFunction * _function
jsval functionValue()
BOOL evaluateWithContext:scope:arguments:result:(JSContext *context, [scope] id jsThis, [arguments] NSArray *arguments, [result] jsval *result)
BOOL evaluateWithContext:scope:argc:argv:result:(JSContext *context,[scope] JSObject *jsThis,[argc] uintN argc,[argv] jsval *argv,[result] jsval *result)
NSString * name()
void pushScript:(OOJSScript *script)
Definition OOJSScript.m:480
void popScript:(OOJSScript *script)
Definition OOJSScript.m:493
OOJavaScriptEngine * sharedEngine()
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque