Oolite
Loading...
Searching...
No Matches
OOJavaScriptEnginePoc.m
Go to the documentation of this file.
1/*
2
3OOJavaScriptEngine.m (QuickJS-ng proof of concept)
4
5Copyright (C) 2007-2013 David Taylor and Jens Ayton.
6
7This program is free software; you can redistribute it and/or
8modify it under the terms of the GNU General Public License
9as published by the Free Software Foundation; either version 2
10of the License, or (at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with this program; if not, write to the Free Software
19Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20MA 02110-1301, USA.
21
22*/
23
24#import "OOJavaScriptEngine.h"
25
26// This minimal engine implements only what the harness uses of the full engine header.
27#pragma clang diagnostic ignored "-Wincomplete-implementation"
28#import "OOJSQuaternion.h"
29#import "OOJSScript.h"
30#import "OOJSVector.h"
31
32#include <time.h>
33#if OOLITE_WINDOWS
34#include <windows.h>
35#endif
36
37#define OOJS_RUNTIME_SIZE_MiB 256
38#define OOJS_TIME_LIMIT (1) // seconds
39
41JSContext* gOOJSMainThreadContext = NULL;
42
43static int InterruptHandler(OOJSInterruptHandlerArg* arg, void* opaque);
44static JSValue GlobalLog(OOJS_NATIVE_ARGS);
45
46static const JSCFunctionListEntry sGlobalMethods[] = {
47 JS_CFUNC_DEF("log", 1, GlobalLog),
48};
49
50//===========================================================================
51// JavaScript engine initialisation and shutdown
52//===========================================================================
53
54@implementation OOJavaScriptEngine
55
57{
58 if (sSharedEngine == nil)
59 sSharedEngine = [[self alloc] init];
60
61 return sSharedEngine;
62}
63
64- (id)init
65{
66 NSAssert(sSharedEngine == nil, @"Attempt to create multiple OOJavaScriptEngines.");
67
68 if (!(self = [super init]))
69 return nil;
70 sSharedEngine = self;
72
73 _runtime = JS_NewRuntime();
74 if (_runtime == NULL) {
75 OOLog(@"script.javaScript.init.error", @"%@", @"***** FATAL ERROR: failed to create JavaScript runtime.");
76 exit(1);
77 }
78
79 NSInteger jsRuntimeInMiB = [[NSUserDefaults standardUserDefaults] integerForKey:@"jsruntime-size-mib"];
80 if (jsRuntimeInMiB <= 0)
81 jsRuntimeInMiB = OOJS_RUNTIME_SIZE_MiB;
82 JS_SetMemoryLimit(_runtime, jsRuntimeInMiB * 1024L * 1024L);
83 JS_SetInterruptHandler(_runtime, InterruptHandler, NULL);
84#ifndef NDEBUG
85 JS_SetDumpFlags(_runtime, JS_DUMP_LEAKS);
86#endif
87
88 _context = JS_NewContext(_runtime);
90 if (_context == NULL) {
91 OOLog(@"script.javaScript.init.error", @"%@", @"***** FATAL ERROR: failed to create JavaScript context.");
92 exit(1);
93 }
94
95 _globalObject = JS_GetGlobalObject(_context);
96 JS_SetPropertyStr(_context, _globalObject, "global", JS_DupValue(_context, _globalObject));
97 JS_SetPropertyFunctionList(_context, _globalObject, sGlobalMethods, OOJS_COUNT(sGlobalMethods));
98
102
103 return self;
104}
105
106- (NSUInteger)shutDown
107{
108 if (_context == NULL)
109 return 0;
110
111 JS_FreeValue(_context, _globalObject);
112 _globalObject = JS_UNDEFINED;
113 JS_FreeContext(_context);
114 _context = NULL;
116
117 JS_RunGC(_runtime);
118 JSMemoryUsage usage;
119 JS_ComputeMemoryUsage(_runtime, &usage);
120 if (usage.obj_count != 0) {
121 /* JS_FreeRuntime() would assert. Dump what is left and abandon the
122 runtime instead, so the leak can be reported.
123 */
124 OOLog(@"script.javaScript.shutDown.leak", @"***** JavaScript runtime shut down with %lli objects still alive; something is holding a JSValue it does not own, or has not freed one it does.", (long long)usage.obj_count);
125 JS_DumpMemoryUsage(stdout, &usage, _runtime);
126 _runtime = NULL;
127 return (NSUInteger)usage.obj_count;
128 }
129
130 JS_FreeRuntime(_runtime);
131 _runtime = NULL;
132 return 0;
133}
134
135- (void)dealloc
136{
137 [self shutDown];
138 if (sSharedEngine == self)
140 [super dealloc];
141}
142
143- (JSContext*)context
144{
145 return _context;
146}
147
148- (JSValueConst)globalObject
149{
150 return _globalObject;
151}
152
153- (BOOL)callJSFunction:(JSValueConst)function
154 forObject:(JSValueConst)jsThis
155 argc:(int)argc
156 argv:(JSValueConst*)argv
157 result:(JSValue*)outResult
158{
159 NSParameterAssert(JS_IsFunction(_context, function));
160
162 JSValue result = JS_Call(_context, function, jsThis, argc, argv);
164
165 if (JS_IsException(result)) {
167 if (outResult != NULL)
168 *outResult = JS_UNDEFINED;
169 return NO;
170 }
171
172 if (outResult != NULL)
173 *outResult = result;
174 else
175 JS_FreeValue(_context, result);
176 return YES;
177}
178
180{
181 return _showErrorLocations;
182}
183
184- (void)setShowErrorLocations:(BOOL)value
185{
186 _showErrorLocations = !!value;
187}
188
189@end
190
191JSAtom OOJSIDFromString(NSString* string)
192{
193 // Interned for the life of the process, as in the full engine.
194 return JS_NewAtom(OOJSAcquireContext(), [string UTF8String]);
195}
196
197JSValue OOJSNativeFailure(JSContext* context)
198{
199 if (JS_HasException(context))
200 return JS_EXCEPTION;
201
202 JSValue error = JS_NewError(context);
203 JS_SetUncatchableError(context, error);
204 return JS_Throw(context, error);
205}
206
207NSString* OOJSWrapScriptSource(NSString* source)
208{
209 // A newline before the closing part is needed if the last line is a // comment.
210 NSString* lineEnd = [source hasSuffix:@"\n"] ? @"" : @"\n";
211 return [NSString stringWithFormat:@"with(this){(function(){%@%@}).call(this)}", source, lineEnd];
212}
213
214//===========================================================================
215// Global functions
216//===========================================================================
217
218// log([messageClass : String,] message : String, ...)
220{
222
223 NSString* message = nil;
224 NSString* messageClass = nil;
225
226 if (EXPECT_NOT(argc < 1)) {
228 }
229 if (argc < 2) {
230 messageClass = @"script.debug.message";
232 } else {
234 if (!OOLogWillDisplayMessagesInClass(messageClass)) {
235 // Do nothing (and short-circuit) if message class is filtered out.
237 }
238
239 NSMutableArray* parts = [NSMutableArray arrayWithCapacity:argc - 1];
240 for (int i = 1; i < argc; i++) {
241 [parts addObject:OOStringFromJSValueEvenIfNull(context, OOJS_ARGV[i])];
242 }
243 message = [parts componentsJoinedByString:@", "];
244 }
245
247 OOLog(messageClass, @"%@", message);
249
251
253}
254
255//===========================================================================
256// Time limiter
257//===========================================================================
258
259static unsigned sLimiterStartDepth;
261static double sLimiterStart;
262static double sLimiterPauseStart;
263static double sLimiterTimeLimit;
264
265static double MonotonicTime(void)
266{
267#if OOLITE_WINDOWS
268 static LARGE_INTEGER frequency;
269 LARGE_INTEGER counter;
270 if (frequency.QuadPart == 0)
271 QueryPerformanceFrequency(&frequency);
272 QueryPerformanceCounter(&counter);
273 return (double)counter.QuadPart / (double)frequency.QuadPart;
274#else
275 struct timespec now;
276 clock_gettime(CLOCK_MONOTONIC, &now);
277 return now.tv_sec + now.tv_nsec * 1e-9;
278#endif
279}
280
282{
283 if (sLimiterStartDepth++ == 0) {
284 if (limit <= 0.0)
285 limit = OOJS_TIME_LIMIT;
286 sLimiterTimeLimit = limit;
289 }
290}
291
293{
294 if (sLimiterStartDepth == 0) {
295 OOLog(@"bug.javaScript.limiterDepth", @"%@", @"Attempt to stop JavaScript time limiter while it is already fully stopped. This is an internal bug, please report it.");
296 return;
297 }
298
299 if (--sLimiterStartDepth == 0)
300 sLimiterTimeLimit = 0.0;
301}
302
304{
305 if (sLimiterPauseDepth++ == 0)
307}
308
314
315/* QuickJS polls this regularly while running JS code, so unlike the
316 SpiderMonkey operation callback no watchdog thread is needed. Returning
317 non-zero throws an uncatchable error, which unwinds all JS frames.
318*/
319static int InterruptHandler(OOJSInterruptHandlerArg* arg, void* opaque)
320{
322 return 0;
323
324 double elapsed = MonotonicTime() - sLimiterStart;
325 if (elapsed <= sLimiterTimeLimit)
326 return 0;
327
328 OOLogERR(@"script.javaScript.timeLimit", @"Script \"%@\" ran for %g seconds and has been terminated.", [[OOJSScript currentlyRunningScript] name], elapsed);
329 return 1;
330}
331
332//===========================================================================
333// Error reporting
334//===========================================================================
335
336/* QuickJS records locations only in the stack property, as lines of the form
337 " at name (file:line:column)" or " at file:line:column".
338 Extract the file and line of the innermost frame.
339*/
340static BOOL GetLocationFromStack(NSString* stack, NSString** outFile, unsigned* outLine)
341{
342 for (NSString* frame in [stack componentsSeparatedByString:@"\n"]) {
343 frame = [frame stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
344 if (![frame hasPrefix:@"at "])
345 continue;
346 frame = [frame substringFromIndex:3];
347
348 NSRange open = [frame rangeOfString:@"(" options:NSBackwardsSearch];
349 if (open.location != NSNotFound && [frame hasSuffix:@")"]) {
350 frame = [frame substringWithRange:NSMakeRange(open.location + 1, [frame length] - open.location - 2)];
351 }
352
353 NSArray* parts = [frame componentsSeparatedByString:@":"];
354 if ([parts count] < 3)
355 continue; // Native frame, e.g. "at log (native)".
356
357 NSUInteger count = [parts count];
358 *outFile = [[parts subarrayWithRange:NSMakeRange(0, count - 2)] componentsJoinedByString:@":"];
359 *outLine = (unsigned)[[parts objectAtIndex:count - 2] intValue];
360 return YES;
361 }
362 return NO;
363}
364
365static NSString* StackOfValue(JSContext* context, JSValueConst value)
366{
367 if (!JS_IsObject(value))
368 return nil;
369 JSValue stack = JS_GetPropertyStr(context, value, "stack");
370 NSString* result = OOStringFromJSValue(context, stack);
371 JS_FreeValue(context, stack);
372 return result;
373}
374
375static void LogProblem(NSString* severity, NSString* errorName, NSString* message, NSString* stack)
376{
377 NSString* messageClass = [NSString stringWithFormat:@"script.javaScript.%@.%@", severity, errorName];
378 NSString* highlight = [severity isEqualToString:@"warning"] ? @"-----" : @"*****";
379
380 if (!OOLogWillDisplayMessagesInClass(messageClass))
381 return;
382
383 NSString* activeScript = [[OOJSScript currentlyRunningScript] displayName];
384 if (activeScript == nil)
385 activeScript = @"<unidentified script>";
386 OOLog(messageClass, @"%@ JavaScript %@ (%@): %@", highlight, severity, activeScript, message);
387
388 NSString* file = nil;
389 unsigned line = 0;
390 if ([[OOJavaScriptEngine sharedEngine] showErrorLocations] && GetLocationFromStack(stack, &file, &line)) {
391 OOLog(messageClass, @" %@, line %u.", file, line);
392 }
393}
394
395void OOJSReportPendingException(JSContext* context)
396{
397 JSValue exception = JS_GetException(context);
398
399 // The time limiter has already logged a termination.
400 if (JS_IsUncatchableError(exception)) {
401 JS_FreeValue(context, exception);
402 return;
403 }
404
406
407 NSString* errorName = @"exception";
408 if (JS_IsError(exception)) {
409 JSValue name = JS_GetPropertyStr(context, exception, "name");
410 errorName = OOStringFromJSValue(context, name) ?: errorName;
411 JS_FreeValue(context, name);
412 }
413
414 LogProblem(@"exception", errorName, OOStringFromJSValueEvenIfNull(context, exception), StackOfValue(context, exception));
415
416 JS_FreeValue(context, exception);
418}
419
420static NSString* CallerPrefix(NSString* scriptClass, NSString* function)
421{
422 if (function == nil)
423 return @"";
424 if (scriptClass == nil)
425 return [function stringByAppendingString:@": "];
426 return [NSString stringWithFormat:@"%@.%@: ", scriptClass, function];
427}
428
429void OOJSReportError(JSContext* context, NSString* format, ...)
430{
431 va_list args;
432
433 va_start(args, format);
434 OOJSReportErrorWithArguments(context, format, args);
435 va_end(args);
436}
437
438void OOJSReportErrorForCaller(JSContext* context, NSString* scriptClass, NSString* function, NSString* format, ...)
439{
440 va_list args;
441 NSString* msg = nil;
442
443 @try {
444 va_start(args, format);
445 msg = [[NSString alloc] initWithFormat:format arguments:args];
446 va_end(args);
447
448 OOJSReportError(context, @"%@%@", CallerPrefix(scriptClass, function), msg);
449 }
450 @catch (id exception) {
451 // Squash any secondary errors during error handling.
452 }
453 [msg release];
454}
455
456void OOJSReportErrorWithArguments(JSContext* context, NSString* format, va_list args)
457{
458 NSString* msg = nil;
459
460 @try {
461 msg = [[NSString alloc] initWithFormat:format arguments:args];
462 JS_ThrowPlainError(context, "%s", [msg UTF8String]);
463 }
464 @catch (id exception) {
465 // Squash any secondary errors during error handling.
466 }
467 [msg release];
468}
469
470void OOJSReportWrappedException(JSContext* context, id exception)
471{
472 if (!JS_HasException(context)) {
473 if ([exception isKindOfClass:[NSException class]])
474 OOJSReportError(context, @"Native exception: %@", [exception reason]);
475 else
476 OOJSReportError(context, @"Unidentified native exception");
477 }
478 // Else, let the pending exception propagate.
479}
480
481void OOJSReportWarning(JSContext* context, NSString* format, ...)
482{
483 va_list args;
484
485 va_start(args, format);
486 OOJSReportWarningWithArguments(context, format, args);
487 va_end(args);
488}
489
490void OOJSReportWarningForCaller(JSContext* context, NSString* scriptClass, NSString* function, NSString* format, ...)
491{
492 va_list args;
493 NSString* msg = nil;
494
495 @try {
496 va_start(args, format);
497 msg = [[NSString alloc] initWithFormat:format arguments:args];
498 va_end(args);
499
500 OOJSReportWarning(context, @"%@%@", CallerPrefix(scriptClass, function), msg);
501 }
502 @catch (id exception) {
503 // Squash any secondary errors during error handling.
504 }
505 [msg release];
506}
507
508void OOJSReportWarningWithArguments(JSContext* context, NSString* format, va_list args)
509{
510 NSString* msg = nil;
511
512 @try {
513 msg = [[NSString alloc] initWithFormat:format arguments:args];
514
515 // A fresh Error object captures the current JS stack, giving the location.
516 JSValue error = JS_NewError(context);
517 LogProblem(@"warning", @"warning", msg, StackOfValue(context, error));
518 JS_FreeValue(context, error);
519 }
520 @catch (id exception) {
521 // Squash any secondary errors during error handling.
522 }
523 [msg release];
524}
525
526static NSString* PropertyNameForMagic(int magic, const JSCFunctionListEntry* list, size_t count)
527{
528 for (size_t i = 0; i < count; i++) {
529 if (list[i].def_type == JS_DEF_CGETSET_MAGIC && list[i].magic == magic)
530 return [NSString stringWithUTF8String:list[i].name];
531 }
532 return [NSString stringWithFormat:@"%i", magic];
533}
534
535void OOJSReportBadPropertySelector(JSContext* context, JSValueConst thisObj, int magic, const JSCFunctionListEntry* list, size_t count)
536{
537 NSString* propName = PropertyNameForMagic(magic, list, count);
538 NSString* className = OOJSClassNameOfValue(context, thisObj);
539
540 OOJSReportError(context, @"Invalid property identifier %@ for instance of %@.", propName, className);
541}
542
543void OOJSReportBadPropertyValue(JSContext* context, JSValueConst thisObj, int magic, const JSCFunctionListEntry* list, size_t count, JSValueConst value)
544{
545 NSString* propName = PropertyNameForMagic(magic, list, count);
546 NSString* className = OOJSClassNameOfValue(context, thisObj);
547 NSString* valueDesc = OOJSDescribeValue(context, value, YES);
548
549 OOJSReportError(context, @"Cannot set property %@ of instance of %@ to invalid value %@.", propName, className, valueDesc);
550}
551
552void OOJSReportBadArguments(JSContext* context, NSString* scriptClass, NSString* function, int argc, JSValueConst* argv, NSString* message, NSString* expectedArgsDescription)
553{
554 @try {
555 if (message == nil)
556 message = @"Invalid arguments";
557 message = [NSString stringWithFormat:@"%@ %@", message, [NSString stringWithJavaScriptParameters:argv count:argc inContext:context]];
558 if (expectedArgsDescription != nil)
559 message = [NSString stringWithFormat:@"%@ -- expected %@", message, expectedArgsDescription];
560
561 OOJSReportErrorForCaller(context, scriptClass, function, @"%@.", message);
562 }
563 @catch (id exception) {
564 // Squash any secondary errors during error handling.
565 }
566}
567
568BOOL OOJSArgumentListGetNumber(JSContext* context, NSString* scriptClass, NSString* function, int argc, JSValueConst* argv, double* outNumber, int* outConsumed)
569{
570 if (OOJSArgumentListGetNumberNoError(context, argc, argv, outNumber, outConsumed)) {
571 return YES;
572 } else {
573 OOJSReportBadArguments(context, scriptClass, function, argc, argv,
574 @"Expected number, got", NULL);
575 return NO;
576 }
577}
578
579BOOL OOJSArgumentListGetNumberNoError(JSContext* context, int argc, JSValueConst* argv, double* outNumber, int* outConsumed)
580{
581 double value;
582
583 NSCParameterAssert(context != NULL && (argv != NULL || argc == 0) && outNumber != NULL);
584
585 // Get value, if possible.
586 if (EXPECT_NOT(argc < 1 || JS_ToFloat64(context, &value, argv[0]) < 0 || isnan(value))) {
587 // ToNumber can throw (e.g. for a Symbol); this variant must not leave an exception pending.
588 if (JS_HasException(context))
589 JS_FreeValue(context, JS_GetException(context));
590 if (outConsumed != NULL)
591 *outConsumed = 0;
592 return NO;
593 }
594
595 // Success.
596 *outNumber = value;
597 if (outConsumed != NULL)
598 *outConsumed = 1;
599 return YES;
600}
601
602//===========================================================================
603// Value conversion
604//===========================================================================
605
606NSString* OOStringFromJSValueEvenIfNull(JSContext* context, JSValueConst value)
607{
608 size_t length;
609 const char* chars = JS_ToCStringLen(context, &length, value); // Calls the value's toString method if needed.
610 if (chars == NULL) {
611 JS_FreeValue(context, JS_GetException(context));
612 return nil;
613 }
614
615 NSString* result = [[[NSString alloc] initWithBytes:chars length:length encoding:NSUTF8StringEncoding] autorelease];
616 JS_FreeCString(context, chars);
617 return result;
618}
619
620NSString* OOStringFromJSValue(JSContext* context, JSValueConst value)
621{
622 if (EXPECT(!JS_IsNull(value) && !JS_IsUndefined(value))) {
623 return OOStringFromJSValueEvenIfNull(context, value);
624 }
625 return nil;
626}
627
628NSString* OOJSClassNameOfValue(JSContext* context, JSValueConst value)
629{
630 if (!JS_IsObject(value))
631 return @"primitive";
632
633 JSValue ctor = JS_GetPropertyStr(context, value, "constructor");
634 JSValue name = JS_IsObject(ctor) ? JS_GetPropertyStr(context, ctor, "name") : JS_UNDEFINED;
635 NSString* result = OOStringFromJSValue(context, name);
636 JS_FreeValue(context, name);
637 JS_FreeValue(context, ctor);
638 return result ?: @"Object";
639}
640
641static NSString* DescribeValue(JSContext* context, JSValueConst value, BOOL abbreviateObjects, BOOL recursing)
642{
643 if (JS_IsFunction(context, value)) {
644 JSValue nameVal = JS_GetPropertyStr(context, value, "name");
645 NSString* name = OOStringFromJSValue(context, nameVal);
646 JS_FreeValue(context, nameVal);
647 if ([name length] != 0)
648 return [NSString stringWithFormat:@"function %@", name];
649 else
650 return @"function";
651 }
652
653 NSString* result = nil;
654
655 if (JS_IsString(value)) {
656 enum { kMaxLength = 200 };
657
658 NSString* string = OOStringFromJSValueEvenIfNull(context, value);
659 NSUInteger length = [string length];
660 result = [string substringToIndex:MIN(length, (NSUInteger)kMaxLength)];
661 result = [NSString stringWithFormat:@"\"%@%@\"", [result escapedForJavaScriptLiteral], (length > kMaxLength) ? @"..." : @""];
662 } else if (JS_IsArray(value)) {
663 // Descibe up to four elements of an array.
664 int64_t count;
665 if (JS_GetLength(context, value, &count) == 0) {
666 if (!recursing) {
667 NSMutableString* arrayDesc = [NSMutableString stringWithString:@"["];
668 int64_t i, effectiveCount = MIN(count, (int64_t)4);
669 for (i = 0; i < effectiveCount; i++) {
670 JSValue item = JS_GetPropertyUint32(context, value, (uint32_t)i);
671 NSString* itemDesc = @"?";
672 if (!JS_IsException(item)) {
673 itemDesc = DescribeValue(context, item, YES /* always abbreviate objects in arrays */, YES);
674 }
675 JS_FreeValue(context, item);
676 if (i != 0)
677 [arrayDesc appendString:@", "];
678 [arrayDesc appendString:itemDesc];
679 }
680 if (effectiveCount != count) {
681 [arrayDesc appendFormat:@", ... <%lli items total>]", (long long)count];
682 } else {
683 [arrayDesc appendString:@"]"];
684 }
685
686 result = arrayDesc;
687 } else {
688 result = [NSString stringWithFormat:@"[<%lli items>]", (long long)count];
689 }
690 } else {
691 result = @"[...]";
692 }
693 }
694
695 if (result == nil) {
696 result = OOStringFromJSValueEvenIfNull(context, value);
697
698 if (abbreviateObjects && JS_IsObject(value) && [result isEqualToString:@"[object Object]"]) {
699 result = @"{...}";
700 }
701
702 if (result == nil)
703 result = @"?";
704 }
705
706 return result;
707}
708
709NSString* OOJSDescribeValue(JSContext* context, JSValueConst value, BOOL abbreviateObjects)
710{
711 return DescribeValue(context, value, abbreviateObjects, NO);
712}
713
714@implementation NSObject (OOJavaScript)
715
716- (JSValue)oo_jsValueInContext:(JSContext*)context
717{
718 return JS_UNDEFINED;
719}
720
721@end
722
723@implementation NSString (OOJavaScriptConversion)
724
725- (JSValue)oo_jsValueInContext:(JSContext*)context
726{
727 NSData* utf8 = [self dataUsingEncoding:NSUTF8StringEncoding];
728 return JS_NewStringLen(context, [utf8 bytes], [utf8 length]);
729}
730
731@end
732
733@implementation NSNumber (OOJavaScriptConversion)
734
735- (JSValue)oo_jsValueInContext:(JSContext*)context
736{
737 // As with SpiderMonkey, all NSNumbers (including booleans) become JS numbers.
738 return JS_NewNumber(context, [self doubleValue]);
739}
740
741@end
742
743@implementation NSNull (OOJavaScriptConversion)
744
745- (JSValue)oo_jsValueInContext:(JSContext*)context
746{
747 return JS_NULL;
748}
749
750@end
751
752@implementation NSString (OOJavaScriptExtensions)
753
754+ (NSString*)stringWithJavaScriptParameters:(JSValueConst*)params count:(int)count inContext:(JSContext*)context
755{
756 if (params == NULL && count != 0)
757 return nil;
758
759 int i;
760 NSMutableString* result = [NSMutableString stringWithString:@"("];
761
762 for (i = 0; i < count; ++i) {
763 if (i != 0)
764 [result appendString:@", "];
765 [result appendString:OOJSDescribeValue(context, params[i], NO)];
766 }
767
768 [result appendString:@")"];
769 return result;
770}
771
773{
774 NSMutableString* result = nil;
775 NSUInteger i, length;
776 unichar c;
777
778 length = [self length];
779 result = [NSMutableString stringWithCapacity:length];
780
781 // Not hugely efficient.
782 for (i = 0; i != length; ++i) {
783 c = [self characterAtIndex:i];
784 switch (c) {
785 case '\\':
786 [result appendString:@"\\\\"];
787 break;
788
789 case '\b':
790 [result appendString:@"\\b"];
791 break;
792
793 case '\f':
794 [result appendString:@"\\f"];
795 break;
796
797 case '\n':
798 [result appendString:@"\\n"];
799 break;
800
801 case '\r':
802 [result appendString:@"\\r"];
803 break;
804
805 case '\t':
806 [result appendString:@"\\t"];
807 break;
808
809 case '\v':
810 [result appendString:@"\\v"];
811 break;
812
813 case '\'':
814 [result appendString:@"\\\'"];
815 break;
816
817 case '\"':
818 [result appendString:@"\\\""];
819 break;
820
821 default:
822 [result appendString:[NSString stringWithCharacters:&c length:1]];
823 }
824 }
825
826 return result;
827}
828
829@end
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJS_END_FULL_NATIVE
#define OOJS_BEGIN_FULL_NATIVE(context)
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJSStartTimeLimiterWithTimeLimit(limit)
#define OOJS_TIME_LIMIT
static OOHighResTimeValue sLimiterPauseStart
static double sLimiterTimeLimit
static int sLimiterPauseDepth
static unsigned sLimiterStartDepth
static OOHighResTimeValue sLimiterStart
static JSBool GlobalLog(JSContext *context, uintN argc, jsval *vp)
Definition OOJSGlobal.m:230
static JSFunctionSpec sGlobalMethods[]
Definition OOJSGlobal.m:124
void InitOOJSQuaternion(JSContext *context, JSObject *global)
void InitOOJSScript(JSContext *context, JSObject *global)
Definition OOJSScript.m:614
void InitOOJSVector(JSContext *context, JSObject *global)
Definition OOJSVector.m:231
void OOJSPauseTimeLimiter(void)
void OOJSReportPendingException(JSContext *context)
void OOJSReportWarning(JSContext *context, NSString *format,...)
static NSString * CallerPrefix(NSString *scriptClass, NSString *function)
NSString * OOJSClassNameOfValue(JSContext *context, JSValueConst value)
void OOJSReportWrappedException(JSContext *context, id exception)
void OOJSReportWarningWithArguments(JSContext *context, NSString *format, va_list args)
JSValue OOJSNativeFailure(JSContext *context)
static double MonotonicTime(void)
void OOJSReportBadPropertySelector(JSContext *context, JSValueConst thisObj, int magic, const JSCFunctionListEntry *list, size_t count)
void OOJSReportWarningForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
void OOJSReportErrorForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
static NSString * StackOfValue(JSContext *context, JSValueConst value)
static void LogProblem(NSString *severity, NSString *errorName, NSString *message, NSString *stack)
void OOJSReportError(JSContext *context, NSString *format,...)
BOOL OOJSArgumentListGetNumberNoError(JSContext *context, int argc, JSValueConst *argv, double *outNumber, int *outConsumed)
static NSString * DescribeValue(JSContext *context, JSValueConst value, BOOL abbreviateObjects, BOOL recursing)
static NSString * PropertyNameForMagic(int magic, const JSCFunctionListEntry *list, size_t count)
static int InterruptHandler(OOJSInterruptHandlerArg *arg, void *opaque)
BOOL OOJSArgumentListGetNumber(JSContext *context, NSString *scriptClass, NSString *function, int argc, JSValueConst *argv, double *outNumber, int *outConsumed)
void OOJSReportBadPropertyValue(JSContext *context, JSValueConst thisObj, int magic, const JSCFunctionListEntry *list, size_t count, JSValueConst value)
NSString * OOJSWrapScriptSource(NSString *source)
void OOJSReportErrorWithArguments(JSContext *context, NSString *format, va_list args)
JSAtom OOJSIDFromString(NSString *string)
void OOJSResumeTimeLimiter(void)
NSString * OOStringFromJSValueEvenIfNull(JSContext *context, JSValueConst value)
static BOOL GetLocationFromStack(NSString *stack, NSString **outFile, unsigned *outLine)
static JSValue GlobalLog(OOJS_NATIVE_ARGS)
void OOJSStopTimeLimiter(void)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, int argc, JSValueConst *argv, NSString *message, NSString *expectedArgsDescription)
NSString * OOJSDescribeValue(JSContext *context, JSValueConst value, BOOL abbreviateObjects)
NSString * OOStringFromJSValue(JSContext *context, JSValueConst value)
OOINLINE JSContext * OOJSAcquireContext(void)
#define OOJS_ARGV
#define OOJS_RETURN_VOID
static OOJavaScriptEngine * sSharedEngine
JSContext * gOOJSMainThreadContext
#define OOJS_RUNTIME_SIZE_MiB
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define MIN(A, B)
Definition OOMaths.h:91
unsigned count
return nil
double OOTimeDelta
Definition OOTypes.h:193
void OOJSReportPendingException(JSContext *context)
#define OOJSStartTimeLimiter()
void OOJSStopTimeLimiter(void)
JSRuntime OOJSInterruptHandlerArg
#define OOJS_NATIVE_ARGS
#define OOJS_COUNT(array)
static int InterruptHandler(OOJSInterruptHandlerArg *arg, void *opaque)
NSString * displayName()
Definition OOJSScript.m:118
OOJSScript * currentlyRunningScript()
Definition OOJSScript.m:101
OOJavaScriptEngine * sharedEngine()