80#define OOJSENGINE_JSVERSION JSVERSION_ECMA_5
84#define JIT_OPTIONS JSOPTION_JIT | JSOPTION_METHODJIT | JSOPTION_PROFILING
86#define OOJSENGINE_CONTEXT_OPTIONS JSOPTION_VAROBJFIX | JSOPTION_RELIMIT | JSOPTION_ANONFUNFIX | JIT_OPTIONS
88#define OOJS_STACK_SIZE 8192
89#define OOJS_RUNTIME_SIZE_MiB 256
99#if OOJSENGINE_MONITOR_SUPPORT
101@interface OOJavaScriptEngine (OOMonitorSupportInternal)
103- (void)sendMonitorError:(JSErrorReport*)errorReport
104 withMessage:(NSString*)message
105 inContext:(JSContext*)context;
107- (void)sendMonitorLogMessage:(NSString*)message
108 withMessageClass:(NSString*)messageClass
109 inContext:(JSContext*)context;
115@interface OOJavaScriptEngine (Private)
125static void ReportJSError(JSContext* context,
const char* message, JSErrorReport* report);
135static void ReportJSError(JSContext* context,
const char* message, JSErrorReport* report)
137 NSString* severity =
@"error";
138 NSString* messageText =
nil;
139 NSString* lineBuf =
nil;
140 NSString* messageClass =
nil;
141 NSString* highlight =
@"*****";
142 NSString* activeScript =
nil;
149 jschar empty[1] = { 0 };
150 JSErrorReport blankReport = {
151 .filename =
"<unspecified file>",
158 report = &blankReport;
159 if (
EXPECT_NOT(message == NULL || *message ==
'\0'))
160 message =
"<unspecified error>";
163 if (report->flags & JSREPORT_EXCEPTION)
164 severity =
@"exception";
165 else if (report->flags & JSREPORT_WARNING) {
166 severity =
@"warning";
167 highlight =
@"-----";
171 messageText = [NSString stringWithUTF8String:message];
174 lineBuf = [NSString stringWithUTF16String:report->uclinebuf];
175 while ([lineBuf hasSuffix:
@"\n"] || [lineBuf hasSuffix:
@"\r"])
176 lineBuf = [lineBuf substringToIndex:[lineBuf length] - 1];
180 NSString* errorNumberStr = [NSString stringWithFormat:@"%u", report->errorNumber];
181 NSString* errorName = [errorNames oo_stringForKey:errorNumberStr];
182 if (errorName ==
nil)
183 errorName = errorNumberStr;
186 messageClass = [NSString stringWithFormat:@"script.javaScript.%@.%@", severity, errorName];
193 activeScript = [[thisScript weakRefUnderlyingObject] displayName];
194 [thisScript release];
196 if (activeScript ==
nil)
197 activeScript =
@"<unidentified script>";
198 OOLog(messageClass,
@"%@ JavaScript %@ (%@): %@", highlight, severity, activeScript, messageText);
202 if ([lineBuf length] != 0) {
203 OOLog(messageClass,
@" %s, line %d: %@", report->filename, report->lineno, lineBuf);
205 OOLog(messageClass,
@" %s, line %d.", report->filename, report->lineno);
209#ifdef OO_DEBUG_MONITOR_ENABLED
211 if (report->flags & JSREPORT_WARNING)
212 dump = [jsEng dumpStackForWarnings];
214 dump = [jsEng dumpStackForErrors];
219#if OOJSENGINE_MONITOR_SUPPORT
220 JSExceptionState* exState = JS_SaveExceptionState(context);
222 withMessage:messageText
224 JS_RestoreExceptionState(context, exState);
235@implementation OOJavaScriptEngine
237+ (OOJavaScriptEngine*)sharedEngine
245- (void)runMissionCallback
252 NSAssert(
sSharedEngine ==
nil,
@"Attempt to create multiple OOJavaScriptEngines.");
254 if (!(
self = [super
init]))
258 JS_SetCStringsAreUTF8();
261#ifdef OO_DEBUG_MONITOR_ENABLED
267 [
self setDumpStackForErrors:[
defaults boolForKey:@"dump-stack-for-errors"]];
268 [
self setDumpStackForWarnings:[
defaults boolForKey:@"dump-stack-for-warnings"]];
271 assert(
sizeof(jschar) ==
sizeof(unichar));
274 uint32_t jsRuntimeInMiB = [
defaults oo_intForKey:@"jsruntime-size-mib" defaultValue:OOJS_RUNTIME_SIZE_MiB];
275 _runtime = JS_NewRuntime(jsRuntimeInMiB * 1024L * 1024L);
279 OOLog(
@"script.javaScript.init.error",
@"***** FATAL ERROR: failed to create JavaScript runtime with size %uMiB.", jsRuntimeInMiB);
293 NSAssert(
gOOJSMainThreadContext == NULL,
@"-[OOJavaScriptEngine createMainThreadContext] called while the main thread context exists.");
300 OOLog(
@"script.javaScript.init.error",
@"%@",
@"***** FATAL ERROR: failed to create JavaScript context.");
310 uint8_t gcZeal = [[
NSUserDefaults standardUserDefaults] oo_unsignedCharForKey:@"js-gc-zeal"];
313 OOLog(
@"script.javaScript.debug.gcZeal",
@"Setting JavaScript garbage collector zeal to %u.", gcZeal);
326 OOLog(
@"script.javaScript.init.error",
@"%@",
@"***** FATAL ERROR: failed to look up standard JavaScript classes.");
375 OOLog(
@"script.javaScript.init.success",
@"%@",
@"Set up JavaScript context.");
384 _globalObject = NULL;
389 _booleanClass = NULL;
397 _globalObject = NULL;
411 static int counter = 3;
412 if (counter-- == 0) {
414 OOLog(
@"script.javascript.init.error",
@"%@",
@"JavaScript processes still pending. Can't reset JavaScript engine.");
419 OOLog(
@"script.javascript.init",
@"%@",
@"JavaScript reset successful.");
428 OOLog(
@"script.javascript.init.error",
@"%@",
@"JavaScript processes still pending. Can't reset JavaScript engine.");
431 OOLog(
@"script.javascript.init",
@"%@",
@"JavaScript reset successful.");
436 [[NSNotificationCenter defaultCenter] postNotificationName:kOOJavaScriptEngineWillResetNotification object:
self];
439 [
self destroyMainThreadContext];
440 [
self createMainThreadContext];
443 [[NSNotificationCenter defaultCenter] postNotificationName:kOOJavaScriptEngineDidResetNotification object:
self];
446 [
self garbageCollectionOpportunity:YES];
462- (JSObject*)globalObject
464 return _globalObject;
467- (BOOL)callJSFunction:(jsval)function
468 forObject:(JSObject*)jsThis
471 result:(jsval*)outResult
473 JSContext* context = NULL;
481 result = JS_CallFunctionValue(context, jsThis,
function, argc, argv, outResult);
484 JS_ReportPendingException(context);
490- (void)removeGCObjectRoot:(JSObject**)rootPtr
493 JS_RemoveObjectRoot(
context, rootPtr);
497- (void)removeGCValueRoot:(jsval*)rootPtr
500 JS_RemoveValueRoot(
context, rootPtr);
504- (void)garbageCollectionOpportunity:(BOOL)force
515- (BOOL)showErrorLocations
517 return _showErrorLocations;
520- (void)setShowErrorLocations:(BOOL)value
522 _showErrorLocations = !!value;
552 JSObject* templateObject = NULL;
588#ifdef OO_DEBUG_MONITOR_ENABLED
589static JSTrapStatus DebuggerHook(JSContext* context, JSScript* script, jsbytecode* pc, jsval* rval,
void* closure)
593 OOLog(
@"script.javaScript.debugger",
@"debugger invoked during %@:", [[
OOJSScript currentlyRunningScript] displayName]);
598 return JSTRAP_CONTINUE;
601- (BOOL)dumpStackForErrors
603 return _dumpStackForErrors;
606- (void)setDumpStackForErrors:(BOOL)value
608 _dumpStackForErrors = !!value;
611- (BOOL)dumpStackForWarnings
613 return _dumpStackForWarnings;
616- (void)setDumpStackForWarnings:(BOOL)value
618 _dumpStackForWarnings = !!value;
621- (void)enableDebuggerStatement
623 JS_SetDebuggerHandler(_runtime, DebuggerHook,
self);
629#if OOJSENGINE_MONITOR_SUPPORT
631@implementation OOJavaScriptEngine (OOMonitorSupport)
633- (void)setMonitor:(
id<OOJavaScriptEngineMonitor>)inMonitor
635 [_monitor autorelease];
636 _monitor = [inMonitor retain];
641@implementation OOJavaScriptEngine (OOMonitorSupportInternal)
643- (void)sendMonitorError:(JSErrorReport*)errorReport
644 withMessage:(NSString*)message
645 inContext:(JSContext*)theContext
647 if ([_monitor respondsToSelector:
@selector(jsEngine:context:error:stackSkip:showingLocation:withMessage:)]) {
648 [_monitor jsEngine:
self context:theContext error:errorReport stackSkip:sErrorHandlerStackSkip showingLocation:[
self showErrorLocations] withMessage:message];
652- (void)sendMonitorLogMessage:(NSString*)message
653 withMessageClass:(NSString*)messageClass
654 inContext:(JSContext*)theContext
656 if ([_monitor respondsToSelector:
@selector(jsEngine:context:logMessage:ofClass:)]) {
657 [_monitor jsEngine:
self context:theContext logMessage:message ofClass:messageClass];
665#if OOLITE_DEBUG || defined(OO_DEBUG_MONITOR_ENABLED)
667static void DumpVariable(JSContext* context, JSPropertyDesc* prop)
673 kInterestingFlags = ~(JSPD_ENUMERATE | JSPD_PERMANENT | JSPD_VARIABLE | JSPD_ARGUMENT)
676 NSString* flagStr =
@"";
677 if ((prop->flags & kInterestingFlags) != 0) {
678 NSMutableArray* flags = [NSMutableArray array];
679 if (prop->flags & JSPD_READONLY)
680 [flags addObject:@"read-only"];
681 if (prop->flags & JSPD_ALIAS)
682 [flags addObject:[NSString stringWithFormat:@"alias (%@)", OOJSDescribeValue(context, prop->alias, YES)]];
683 if (prop->flags & JSPD_EXCEPTION)
684 [flags addObject:@"exception"];
685 if (prop->flags & JSPD_ERROR)
686 [flags addObject:@"error"];
688 flagStr = [NSString stringWithFormat:@" [%@]", [flags componentsJoinedByString:@", "]];
691 OOLog(
@"script.javaScript.stackTrace",
@" %@: %@%@", name, value, flagStr);
696 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
699 JSStackFrame* frame = NULL;
703 while (JS_FrameIterator(context, &frame) != NULL) {
704 JSScript* script = JS_GetFrameScript(context, frame);
705 NSString* desc =
nil;
706 JSPropertyDescArray properties = { 0, NULL };
707 BOOL gotProperties = NO;
711 if (!JS_IsScriptFrame(context, frame)) {
720 if (script != NULL) {
722 JSObject* scope = JS_GetFrameScopeChain(context, frame);
725 gotProperties = JS_GetPropertyDescArray(context, scope, &properties);
727 NSString* funcDesc =
nil;
728 JSFunction*
function = JS_GetFrameFunction(context, frame);
729 if (
function != NULL) {
730 JSString* funcName = JS_GetFunctionId(
function);
731 if (funcName != NULL) {
733 if (!JS_IsConstructorFrame(context, frame)) {
734 funcDesc = [funcDesc stringByAppendingString:@"()"];
736 funcDesc = [NSString stringWithFormat:@"new %@()", funcDesc];
740 funcDesc =
@"<anonymous function>";
743 funcDesc =
@"<not a function frame>";
746 desc = [NSString stringWithFormat:@"(%@) %@", location, funcDesc];
747 }
else if (JS_IsDebuggerFrame(context, frame)) {
748 desc =
@"<debugger frame>";
750 desc =
@"<Oolite native>";
753 OOLog(
@"script.javaScript.stackTrace",
@"%2u %@", idx - 1, desc);
757 if (JS_GetFrameThis(context, frame, &
this)) {
758 static BOOL haveThis = NO;
759 static jsval thisAtom;
761 thisAtom = STRING_TO_JSVAL(JS_InternString(context,
"this"));
764 JSPropertyDesc thisDesc = { .id = thisAtom, .value =
this };
765 DumpVariable(context, &thisDesc);
770 for (i = 0; i < properties.length; i++) {
771 JSPropertyDesc* prop = &properties.array[i];
772 if (prop->flags & JSPD_ARGUMENT)
773 DumpVariable(context, prop);
777 for (i = 0; i < properties.length; i++) {
778 JSPropertyDesc* prop = &properties.array[i];
779 if (prop->flags & JSPD_VARIABLE)
780 DumpVariable(context, prop);
784 for (i = 0; i < properties.length; i++) {
785 JSPropertyDesc* prop = &properties.array[i];
786 if (!(prop->flags & (JSPD_ARGUMENT | JSPD_VARIABLE)))
787 DumpVariable(context, prop);
790 JS_PutPropertyDescArray(context, &properties);
794 @catch (NSException* exception) {
795 OOLog(
kOOLogException,
@"Exception during JavaScript stack trace: %@:%@", [exception name], [exception reason]);
801static const char* sConsoleScriptName;
802static NSUInteger sConsoleEvalLineNo;
804static void GetLocationNameAndLine(JSContext* context, JSStackFrame* stackFrame,
const char** name, NSUInteger* line)
806 NSCParameterAssert(context != NULL && stackFrame != NULL && name != NULL && line != NULL);
811 JSScript* script = JS_GetFrameScript(context, stackFrame);
812 if (script != NULL) {
813 *name = JS_GetScriptFilename(context, script);
815 jsbytecode* PC = JS_GetFramePC(context, stackFrame);
816 *line = JS_PCToLineNumber(context, script, PC);
818 }
else if (JS_IsDebuggerFrame(context, stackFrame)) {
819 *name =
"<debugger frame>";
825 NSCParameterAssert(context != NULL && stackFrame != NULL);
827 const char* fileName;
829 GetLocationNameAndLine(context, stackFrame, &fileName, &lineNo);
830 if (fileName == NULL)
834 if (fileName == sConsoleScriptName && lineNo >= sConsoleEvalLineNo)
835 return @"<console input>";
838 NSString* fileNameObj = [NSString stringWithUTF8String:fileName];
839 if (fileNameObj ==
nil)
840 fileNameObj = [NSString stringWithCString:fileName encoding:NSISOLatin1StringEncoding];
841 if (fileNameObj ==
nil)
844 NSString* shortFileName = [fileNameObj lastPathComponent];
845 if (![[shortFileName lowercaseString] isEqualToString:
@"script.js"])
846 fileNameObj = shortFileName;
848 return [NSString stringWithFormat:@"%@:%zu", fileNameObj, lineNo];
853 GetLocationNameAndLine(context, stackFrame, &sConsoleScriptName, &sConsoleEvalLineNo);
859 NSCParameterAssert(name != NULL && name[0] !=
'\0' && idCache != NULL);
863 JSString*
string = JS_InternString(context, name);
865 [NSException raise:NSGenericException format:@"Failed to initialize JS ID cache for \"%s\".", name];
868 *idCache = INTERNED_STRING_TO_JSID(
string);
880 enum { kStackBufSize = 1024 };
881 unichar stackBuf[kStackBufSize];
883 size_t length = [string length];
884 if (length < kStackBufSize) {
887 buffer = malloc(
sizeof(unichar) * length);
891 [string getCharacters:buffer];
893 JSString* jsString = JS_InternUCStringN(context, buffer, length);
900 if (
EXPECT(jsString != NULL))
901 return INTERNED_STRING_TO_JSID(jsString);
911 NSString* result =
nil;
912 if (JS_IdToValue(context, propID, &value)) {
921static NSString*
CallerPrefix(NSString* scriptClass, NSString*
function)
925 if (scriptClass ==
nil)
926 return [function stringByAppendingString:@": "];
927 return [NSString stringWithFormat:@"%@.%@: ", scriptClass, function];
934 va_start(args, format);
945 va_start(args, format);
946 msg = [[NSString alloc] initWithFormat:format arguments:args];
951 @catch (
id exception) {
964 msg = [[NSString alloc] initWithFormat:format arguments:args];
965 JS_ReportError(context,
"%s", [msg UTF8String]);
967 @catch (
id exception) {
975 if (!JS_IsExceptionPending(context)) {
976 if ([exception isKindOfClass:[NSException
class]])
988 OOLog(
@"fatal.unreachable",
@"Supposedly unreachable statement reached in %s (%@:%u) -- terminating.",
function,
OOLogAbbreviatedFileName(file), line);
998 va_start(args, format);
1006 NSString* msg =
nil;
1009 va_start(args, format);
1010 msg = [[NSString alloc] initWithFormat:format arguments:args];
1015 @catch (
id exception) {
1023 NSString* msg =
nil;
1026 msg = [[NSString alloc] initWithFormat:format arguments:args];
1027 JS_ReportWarning(context,
"%s", [msg UTF8String]);
1029 @catch (
id exception) {
1038 const char* className =
OOJSGetClass(context, thisObj)->name;
1040 OOJSReportError(context,
@"Invalid property identifier %@ for instance of %s.", propName, className);
1046 const char* className =
OOJSGetClass(context, thisObj)->name;
1049 OOJSReportError(context,
@"Cannot set property %@ of instance of %s to invalid value %@.", propName, className, valueDesc);
1052void OOJSReportBadArguments(JSContext* context, NSString* scriptClass, NSString*
function, uintN argc, jsval* argv, NSString* message, NSString* expectedArgsDescription)
1056 message =
@"Invalid arguments";
1057 message = [NSString stringWithFormat:@"%@ %@", message, [NSString stringWithJavaScriptParameters:argv count:argc inContext:context]];
1058 if (expectedArgsDescription !=
nil)
1059 message = [NSString stringWithFormat:@"%@ -- expected %@", message, expectedArgsDescription];
1063 @catch (
id exception) {
1073BOOL
OOJSArgumentListGetNumber(JSContext* context, NSString* scriptClass, NSString*
function, uintN argc, jsval* argv,
double* outNumber, uintN* outConsumed)
1079 @"Expected number, got", NULL);
1090 NSCParameterAssert(context != NULL && (argv != NULL || argc == 0) && outNumber != NULL);
1093 if (
EXPECT_NOT(!JS_ValueToNumber(context, argv[0], &value) || isnan(value))) {
1094 if (outConsumed != NULL)
1101 if (outConsumed != NULL)
1112 JSObject* result = NULL;
1118 NSUInteger fullCount = [array count];
1123 uint32_t i,
count = (int32_t)fullCount;
1125 result = JS_NewArrayObject(context, 0, NULL);
1126 if (result != NULL) {
1127 for (i = 0; i !=
count; ++i) {
1128 jsval value = [[array objectAtIndex:i] oo_jsValueInContext:context];
1129 BOOL OK = JS_SetElement(context, result, i, &value);
1142 return (JSObject*)result;
1151 JSObject*
object = NULL;
1158 if (!JS_EnterLocalRootScope(context))
1162 if (
object == NULL) {
1163 *value = JSVAL_VOID;
1166 *value = OBJECT_TO_JSVAL(
object);
1169 JS_LeaveLocalRootScopeWithResult(context, *value);
1183 JSObject* result = NULL;
1189 if (dictionary ==
nil)
1193 result = JS_NewObject(context, NULL, NULL, NULL);
1194 if (result != NULL) {
1197 if ([key isKindOfClass:[NSString
class]] && [key length] != 0) {
1199 value = [[dictionary objectForKey:key] oo_jsValueInContext:context];
1201#if __GNUC__ > 4 || __GNUC_MINOR__ > 6
1202 value = [[dictionary objectForKey:key] oo_jsValueInContext:context];
1207 id tmp = [dictionary objectForKey:key];
1208 if ([tmp respondsToSelector:
@selector(weakRefUnderlyingObject)]) {
1209 tmp = [tmp weakRefUnderlyingObject];
1211 value = [tmp oo_jsValueInContext:context];
1214 if (!JSVAL_IS_VOID(value)) {
1219 }
else if ([key isKindOfClass:[NSNumber
class]]) {
1220 index = [key intValue];
1222 value = [[dictionary objectForKey:key] oo_jsValueInContext:context];
1223 if (!JSVAL_IS_VOID(value)) {
1224 OK = JS_SetElement(context, (JSObject*)result, index, &value);
1236 @catch (
id exception) {
1244 return (JSObject*)result;
1253 JSObject*
object = NULL;
1260 if (!JS_EnterLocalRootScope(context))
1264 if (
object == NULL) {
1265 *value = JSVAL_VOID;
1268 *value = OBJECT_TO_JSVAL(
object);
1271 JS_LeaveLocalRootScopeWithResult(context, *value);
1277@implementation NSObject (OOJavaScriptConversion)
1279- (jsval)oo_jsValueInContext:(JSContext*)context
1291 return [
self oo_jsDescriptionWithClassName:[
self oo_jsClassName]];
1294- (NSString*)oo_jsDescriptionWithClassName:(NSString*)className
1298 NSString* components =
nil;
1299 NSString* description =
nil;
1301 components = [
self descriptionComponents];
1302 if (className ==
nil)
1303 className = [[
self class] description];
1305 if (components !=
nil) {
1306 description = [
NSString stringWithFormat:@"[%@ %@]", className, components];
1308 description = [
NSString stringWithFormat:@"[object %@]", className];
1316- (void)oo_clearJSSelf:(JSObject*)selfVal
1325 JSObject* result = NULL;
1326 if (JS_ValueToObject(context, value, &result))
1331@implementation OOJSValue
1333+ (id)valueWithJSValue:(jsval)value inContext:(JSContext*)context
1337 return [[[
self alloc] initWithJSValue:value inContext:context] autorelease];
1342+ (id)valueWithJSObject:(JSObject*)object inContext:(JSContext*)context
1346 return [[[
self alloc] initWithJSObject:object inContext:context] autorelease];
1351- (id)initWithJSValue:(jsval)value inContext:(JSContext*)context
1355 self = [
super init];
1358 if (context == NULL) {
1364 if (!JSVAL_IS_VOID(_val)) {
1365 JS_AddNamedValueRoot(context, &_val,
"OOJSValue");
1367 [[NSNotificationCenter defaultCenter] addObserver:
self
1368 selector:@selector(deleteJSValue)
1369 name:kOOJavaScriptEngineWillResetNotification
1381- (id)initWithJSObject:(JSObject*)object inContext:(JSContext*)context
1388 if (!JSVAL_IS_VOID(
_val)) {
1390 JS_RemoveValueRoot(context, &
_val);
1395 name:kOOJavaScriptEngineWillResetNotification
1406- (jsval)oo_jsValueInContext:(JSContext*)context
1415 NSCParameterAssert(
string != NULL && strCache != NULL && inited != NULL && !*inited);
1419 JSString* jsString = JS_InternString(context,
string);
1421 [NSException raise:NSGenericException format:@"Failed to initialize JavaScript string literal cache for \"%@\".", [[NSString stringWithUTF8String:string] escapedForJavaScriptLiteral]];
1424 *strCache = STRING_TO_JSVAL(jsString);
1438 const jschar* chars = JS_GetStringCharsAndLength(context,
string, &length);
1440 if (
EXPECT(chars != NULL)) {
1441 return [NSString stringWithCharacters:chars length:length];
1455 JSString*
string = JS_ValueToString(context, value);
1465 if (
EXPECT(!JSVAL_IS_NULL(value) && !JSVAL_IS_VOID(value))) {
1475 if (JSID_IS_STRING(propID)) {
1477 }
else if (JSID_IS_INT(propID) && propertySpec != NULL) {
1478 int tinyid = JSID_TO_INT(propID);
1480 while (propertySpec->name != NULL) {
1481 if (propertySpec->tinyid == tinyid)
1482 return [NSString stringWithUTF8String:propertySpec->name];
1488 if (!JS_IdToValue(context, propID, &value))
1493static NSString*
DescribeValue(JSContext* context, jsval value, BOOL abbreviateObjects, BOOL recursing)
1500 JSString* name = JS_GetFunctionId(JS_ValueToFunction(context, value));
1502 return [NSString stringWithFormat:@"function %@", OOStringFromJSString(context, name)];
1507 NSString* result =
nil;
1508 JSClass*
class = NULL;
1511 if (JSVAL_IS_OBJECT(value) && !JSVAL_IS_NULL(value)) {
1516 if (
class == [jsEng stringClass]) {
1517 value = STRING_TO_JSVAL(JS_ValueToString(context, value));
1520 if (JSVAL_IS_STRING(value)) {
1521 enum { kMaxLength = 200 };
1523 JSString*
string = JSVAL_TO_STRING(value);
1525 const jschar* chars = JS_GetStringCharsAndLength(context,
string, &length);
1527 result = [NSString stringWithCharacters:chars length:MIN(length, (size_t)kMaxLength)];
1528 result = [NSString stringWithFormat:@"\"%@%@\"", [result escapedForJavaScriptLiteral], (length > kMaxLength) ? @"..." : @""];
1529 }
else if (
class == [jsEng arrayClass]) {
1532 JSObject* obj = JSVAL_TO_OBJECT(value);
1533 if (JS_GetArrayLength(context, obj, &
count)) {
1535 NSMutableString* arrayDesc = [NSMutableString stringWithString:@"["];
1536 jsuint i, effectiveCount =
MIN(
count, (jsuint)4);
1537 for (i = 0; i < effectiveCount; i++) {
1539 NSString* itemDesc =
@"?";
1540 if (JS_GetElement(context, obj, i, &item)) {
1544 [arrayDesc appendString:@", "];
1545 [arrayDesc appendString:itemDesc];
1547 if (effectiveCount !=
count) {
1548 [arrayDesc appendFormat:@", ... <%u items total>]", count];
1550 [arrayDesc appendString:@"]"];
1555 result = [NSString stringWithFormat:@"[<%u items>]", count];
1562 if (result ==
nil) {
1565 if (abbreviateObjects &&
class == [jsEng objectClass] && [result isEqualToString:
@"[object Object]"]) {
1580 return DescribeValue(context, value, abbreviateObjects, NO);
1583@implementation NSString (OOJavaScriptExtensions)
1585+ (NSString*)stringWithJavaScriptParameters:(jsval*)params count:(uintN)count inContext:(JSContext*)context
1589 if (params == NULL &&
count != 0)
1593 NSMutableString* result = [NSMutableString stringWithString:@"("];
1595 for (i = 0; i <
count; ++i) {
1597 [result appendString:
@", "];
1598 [result appendString:OOJSDescribeValue(context, params[i], NO)];
1601 [result appendString:@")"];
1607- (jsval)oo_jsValueInContext:(JSContext*)context
1611 size_t length = [
self length];
1612 unichar* buffer = NULL;
1613 JSString*
string = NULL;
1616 jsval result = JS_GetEmptyStringValue(context);
1619 buffer = malloc(length *
sizeof *buffer);
1623 [
self getCharacters:buffer];
1625 string = JS_NewUCStringCopyN(context, buffer, length);
1628 return STRING_TO_JSVAL(
string);
1634+ (NSString*)concatenationOfStringsFromJavaScriptValues:(jsval*)values count:(
size_t)count separator:(NSString*)separator inContext:(JSContext*)context
1639 NSMutableString* result =
nil;
1640 NSString* element =
nil;
1647 for (i = 0; i !=
count; ++i) {
1650 result = [[element mutableCopy] autorelease];
1652 if (separator !=
nil)
1653 [result appendString:separator];
1654 [result appendString:element];
1663- (NSString*)escapedForJavaScriptLiteral
1667 NSMutableString* result =
nil;
1668 NSUInteger i, length;
1670 NSAutoreleasePool* pool =
nil;
1672 length = [
self length];
1673 result = [NSMutableString stringWithCapacity:length];
1676 pool = [[NSAutoreleasePool alloc] init];
1677 for (i = 0; i != length; ++i) {
1678 c = [
self characterAtIndex:i];
1681 [result appendString:@"\\\\"];
1685 [result appendString:@"\\b"];
1689 [result appendString:@"\\f"];
1693 [result appendString:@"\\n"];
1697 [result appendString:@"\\r"];
1701 [result appendString:@"\\t"];
1705 [result appendString:@"\\v"];
1709 [result appendString:@"\\\'"];
1713 [result appendString:@"\\\""];
1717 [result appendString:[NSString stringWithCharacters:&c length:1]];
1733@implementation NSArray (OOJavaScriptConversion)
1735- (jsval)oo_jsValueInContext:(JSContext*)context
1737 jsval value = JSVAL_VOID;
1744@implementation OONativeVector (OOJavaScriptConversion)
1746- (jsval)oo_jsValueInContext:(JSContext*)context
1748 jsval value = JSVAL_VOID;
1755@implementation NSDictionary (OOJavaScriptConversion)
1757- (jsval)oo_jsValueInContext:(JSContext*)context
1759 jsval value = JSVAL_VOID;
1766@implementation NSNumber (OOJavaScriptConversion)
1768- (jsval)oo_jsValueInContext:(JSContext*)context
1774 long long longLongValue;
1776 isFloat = [
self oo_isFloatingPointNumber];
1778 longLongValue = [
self longLongValue];
1779 if (longLongValue < (
long long)JSVAL_INT_MIN || (
long long)JSVAL_INT_MAX < longLongValue) {
1786 if (!JS_NewNumberValue(context, [
self doubleValue], &result))
1787 result = JSVAL_VOID;
1789 result = INT_TO_JSVAL((int32_t)longLongValue);
1804@implementation NSNull (OOJavaScriptConversion)
1806- (jsval)oo_jsValueInContext:(JSContext*)context
1817 JSFunction*
function = JS_ValueToFunction(context, JS_CALLEE(context, vp));
1820 OOJSReportError(context,
@"%@ cannot be used as a constructor.", name);
1830 id object = JS_GetPrivate(context,
this);
1831 if (
object !=
nil) {
1832 [[object weakRefUnderlyingObject] oo_clearJSSelf:this];
1834 JS_SetPrivate(context,
this,
nil);
1845 NSString* description =
nil;
1846 JSClass* jsClass = NULL;
1849 if (
object !=
nil) {
1850 description = [object oo_jsDescription];
1851 if (description ==
nil)
1852 description = [object description];
1854 if (description ==
nil) {
1856 if (jsClass != NULL) {
1857 description = [NSString stringWithFormat:@"[object %@]", [NSString stringWithUTF8String:jsClass->name]];
1860 if (description ==
nil)
1861 description =
@"[object]";
1874 jsval rval = JSVAL_VOID;
1877 NSCParameterAssert(entity !=
nil && param != NULL);
1878 NSCParameterAssert(param->context != NULL &&
JS_IsInRequest(param->context));
1888 BOOL success = JS_CallFunctionValue(param->context, param->jsThis, param->function, 1, args, &rval);
1893 if (!JS_ValueToBoolean(param->context, rval, &result))
1895 if (JS_IsExceptionPending(param->context)) {
1896 JS_ReportPendingException(param->context);
1897 param->errorFlag = YES;
1900 param->errorFlag = YES;
1921 if (![entity isVisibleToScripts])
1923 if ([entity isShip]) {
1924 if ([entity isSubEntity])
1926 if ([entity status] == STATUS_COCKPIT_DISPLAY)
1929 }
else if ([entity isPlanet]) {
1930 switch ([(OOPlanetEntity*)entity planetType]) {
1951 return ([entity isVisibleToScripts] && [entity isShip] && [entity status] == STATUS_COCKPIT_DISPLAY && ![entity isSubEntity]);
1958 NSCParameterAssert(subclass != NULL && superclass != NULL);
1961 sRegisteredSubClasses = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks, NSNonOwnedPointerMapValueCallBacks, 0);
1964 NSCAssert(NSMapGet(
sRegisteredSubClasses, subclass) == NULL,
@"A JS class cannot be registered as a subclass of multiple classes.");
1977 NSCParameterAssert(putativeSubclass != NULL && superclass != NULL);
1978 NSCAssert(
sRegisteredSubClasses != NULL,
@"OOJSIsSubclass() called before any subclasses registered (disallowed for hot path efficiency).");
1981 if (putativeSubclass == superclass)
1985 }
while (putativeSubclass != NULL);
1992 Class requiredObjCClass,
const char* name,
1998 NSCParameterAssert(requiredObjCClass != Nil);
1999 NSCParameterAssert(context != NULL &&
object != NULL && requiredJSClass != NULL && outObject != NULL);
2021 NSCAssert(actualClass->flags & JSCLASS_HAS_PRIVATE,
@"Native object accessor requires JS class with private storage.");
2024 *outObject = [(id)JS_GetPrivate(context, object) weakRefUnderlyingObject];
2028 if (
EXPECT_NOT(*outObject !=
nil && ![*outObject isKindOfClass:requiredObjCClass])) {
2029 OOJSReportError(context,
@"Native method expected %@ from %s and got correct JS type but incorrect native object %@", requiredObjCClass, requiredJSClass->name, *outObject);
2043 JSObject*
object = NULL;
2044 if (
EXPECT_NOT(!JS_ValueToObject(context, value, &
object) ||
object == NULL)) {
2056 JSIdArray* ids = NULL;
2058 NSMutableDictionary* result =
nil;
2059 jsval value = JSVAL_VOID;
2063 ids = JS_Enumerate(context,
object);
2068 result = [NSMutableDictionary dictionaryWithCapacity:ids->length];
2069 for (i = 0; i != ids->length; ++i) {
2070 jsid thisID = ids->vector[i];
2072 if (JSID_IS_STRING(thisID)) {
2074 }
else if (JSID_IS_INT(thisID)) {
2080 objKey = [NSNumber numberWithInt:JSID_TO_INT(thisID)];
2086 if (objKey !=
nil && !JS_LookupPropertyById(context,
object, thisID, &value))
2089 if (objKey !=
nil && !JSVAL_IS_VOID(value)) {
2091 if (objValue !=
nil) {
2092 [result setObject:objValue forKey:objKey];
2097 JS_DestroyIdArray(context, ids);
2107 JSObject* tableObject = NULL;
2110 NSMutableDictionary* result =
nil;
2111 jsval value = JSVAL_VOID;
2115 if (
EXPECT_NOT(JSVAL_IS_NULL(tableValue) || !JS_ValueToObject(context, tableValue, &tableObject))) {
2119 ids = JS_Enumerate(context, tableObject);
2124 result = [NSMutableDictionary dictionaryWithCapacity:ids->length];
2125 for (i = 0; i != ids->length; ++i) {
2126 jsid thisID = ids->vector[i];
2128 if (JSID_IS_STRING(thisID)) {
2135 if (objKey !=
nil && !JS_LookupPropertyById(context, tableObject, thisID, &value))
2138 if (objKey !=
nil && !JSVAL_IS_VOID(value)) {
2141 if (objValue !=
nil) {
2142 [result setObject:objValue forKey:objKey];
2147 JS_DestroyIdArray(context, ids);
2159 if (JSVAL_IS_NULL(value) || JSVAL_IS_VOID(value))
2162 if (JSVAL_IS_INT(value)) {
2163 return [NSNumber numberWithInt:JSVAL_TO_INT(value)];
2165 if (JSVAL_IS_DOUBLE(value)) {
2166 return [NSNumber numberWithDouble:JSVAL_TO_DOUBLE(value)];
2168 if (JSVAL_IS_BOOLEAN(value)) {
2169 return [NSNumber numberWithBool:JSVAL_TO_BOOLEAN(value)];
2171 if (JSVAL_IS_STRING(value)) {
2174 if (JSVAL_IS_OBJECT(value)) {
2186 NSValue* wrappedClass =
nil;
2187 NSValue* wrappedConverter =
nil;
2189 JSClass*
class = NULL;
2191 if (tableObject == NULL)
2195 wrappedClass = [NSValue valueWithPointer:class];
2196 if (wrappedClass !=
nil)
2198 if (wrappedConverter !=
nil) {
2199 converter = [wrappedConverter pointerValue];
2200 return converter(context, tableObject);
2210 if (![result isKindOfClass:requiredClass])
2218 if (![result isKindOfClass:requiredClass])
2231 result = JS_GetPrivate(context,
object);
2232 return [result weakRefUnderlyingObject];
2237 NSValue* wrappedClass =
nil;
2238 NSValue* wrappedConverter =
nil;
2240 if (theClass == NULL)
2245 wrappedClass = [NSValue valueWithPointer:theClass];
2246 if (converter != NULL) {
2247 wrappedConverter = [NSValue valueWithPointer:converter];
2248 [sObjectConverters setObject:wrappedConverter forKey:wrappedClass];
2250 [sObjectConverters removeObjectForKey:wrappedClass];
2263 jsval value = JSVAL_VOID;
2265 NSArray* result =
nil;
2268 if (!JS_IsArrayObject(context, array))
2270 if (!JS_GetArrayLength(context, array, &
count))
2274 return [NSArray array];
2276 values = calloc(
count,
sizeof *values);
2280 for (i = 0; i !=
count; ++i) {
2282 if (!JS_GetElement(context, array, i, &value))
2287 object = [NSNull null];
2291 result = [NSArray arrayWithObjects:values count:count];
2304 if (JS_ValueToNumber(context, OBJECT_TO_JSVAL(
object), &value)) {
2305 return [NSNumber numberWithDouble:value];
2318 if (JS_ValueToNumber(context, OBJECT_TO_JSVAL(
object), &value)) {
2319 return [NSNumber numberWithBool:(value != 0)];
void OOConstToJSStringDestroy(void)
void OOConstToJSStringInit(JSContext *context)
#define foreachkey(VAR, DICT)
void InitOOJSClock(JSContext *context, JSObject *global)
void InitOOJSDock(JSContext *context, JSObject *global)
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_PROFILE_ENTER
#define OOJS_PROFILE_EXIT_JSVAL
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiter()
void OOJSTimeManagementInit(OOJavaScriptEngine *engine, JSRuntime *runtime)
void InitOOJSEntity(JSContext *context, JSObject *global)
void InitOOJSEquipmentInfo(JSContext *context, JSObject *global)
void InitOOJSExhaustPlume(JSContext *context, JSObject *global)
void InitOOJSFlasher(JSContext *context, JSObject *global)
void InitOOJSFont(JSContext *context, JSObject *global)
void InitOOJSFrameCallbacks(JSContext *context, JSObject *global)
void OOJSFrameCallbacksRemoveAll(void)
void CreateOOJSGlobal(JSContext *context, JSObject **outGlobal)
void SetUpOOJSGlobal(JSContext *context, JSObject *global)
void InitOOJSManifest(JSContext *context, JSObject *global)
void InitOOJSMissionVariables(JSContext *context, JSObject *global)
void MissionRunCallback(void)
void InitOOJSMission(JSContext *context, JSObject *global)
void InitOOJSOolite(JSContext *context, JSObject *global)
void InitOOJSPlanet(JSContext *context, JSObject *global)
void InitOOJSPlayerShip(JSContext *context, JSObject *global)
void InitOOJSPlayer(JSContext *context, JSObject *global)
void InitOOJSQuaternion(JSContext *context, JSObject *global)
void InitOOJSScript(JSContext *context, JSObject *global)
void InitOOJSShipGroup(JSContext *context, JSObject *global)
void InitOOJSShip(JSContext *context, JSObject *global)
void InitOOJSSoundSource(JSContext *context, JSObject *global)
void InitOOJSSound(JSContext *context, JSObject *global)
void InitOOJSSpecialFunctions(JSContext *context, JSObject *global)
void InitOOJSStation(JSContext *context, JSObject *global)
void InitOOJSSun(JSContext *context, JSObject *global)
void InitOOJSSystemInfo(JSContext *context, JSObject *global)
void InitOOJSSystem(JSContext *context, JSObject *global)
void InitOOJSTimer(JSContext *context, JSObject *global)
void InitOOJSVector(JSContext *context, JSObject *global)
BOOL VectorToJSValue(JSContext *context, Vector vector, jsval *outValue) NONNULL_FUNC
void InitOOJSVisualEffect(JSContext *context, JSObject *global)
void InitOOJSWaypoint(JSContext *context, JSObject *global)
void InitOOJSWorldScripts(JSContext *context, JSObject *global)
void InitOOJSWormhole(JSContext *context, JSObject *global)
void OOJSPauseTimeLimiter(void)
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
jsid OOJSIDFromString(NSString *string)
BOOL JSEntityIsDemoShipPredicate(Entity *entity, void *parameter)
BOOL OOJSArgumentListGetNumberNoError(JSContext *context, uintN argc, jsval *argv, double *outNumber, uintN *outConsumed)
void OOJSReportWarning(JSContext *context, NSString *format,...)
#define OOJSMarkConsoleEvalLocation(cx, frame)
BOOL OOJSArgumentListGetNumber(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, double *outNumber, uintN *outConsumed)
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)
BOOL OOJSObjectGetterImplPRIVATE(JSContext *context, JSObject *object, JSClass *requiredJSClass, Class requiredObjCClass, const char *name, id *outObject)
BOOL JSEntityIsJavaScriptSearchablePredicate(Entity *entity, void *parameter)
NSString *const kOOJavaScriptEngineWillResetNotification
void OOJSReportWarningWithArguments(JSContext *context, NSString *format, va_list args)
NSString *const kOOJavaScriptEngineDidResetNotification
NSString * OOStringFromJSPropertyIDAndSpec(JSContext *context, jsid propID, JSPropertySpec *propertySpec)
#define JS_IsInRequest(context)
NSString * OOStringFromJSID(jsid propID)
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
void OOJSSetWarningOrErrorStackSkip(unsigned skip)
BOOL JSFunctionPredicate(Entity *entity, void *parameter)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
#define OOJSDumpStack(cx)
#define OOJS_RETURN_OBJECT(o)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
NSDictionary * OOJSDictionaryFromJSValue(JSContext *context, jsval value)
void OOJSReportWarningForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
void OOJSReportErrorForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
NSDictionary * OOJSDictionaryFromJSObject(JSContext *context, JSObject *object)
id OOJSNativeObjectOfClassFromJSValue(JSContext *context, jsval value, Class requiredClass)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
void OOJSRegisterSubclass(JSClass *subclass, JSClass *superclass)
JSObject * OOJSObjectFromNativeObject(JSContext *context, id object)
OOINLINE JSContext * OOJSAcquireContext(void)
NSString * OOJSDescribeValue(JSContext *context, jsval value, BOOL abbreviateObjects)
#define OOJSDescribeLocation(cx, frame)
void OOJSReportError(JSContext *context, NSString *format,...)
#define JS_BeginRequest(context)
NSString * OOStringFromJSValueEvenIfNull(JSContext *context, jsval value)
OOINLINE void OOJSRelinquishContext(JSContext *context)
id(* OOJSClassConverterCallback)(JSContext *context, JSObject *object)
void OOJSReportBadPropertyValue(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec, jsval value)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
#define JS_EndRequest(context)
NSDictionary * OOJSDictionaryFromStringTable(JSContext *context, jsval value)
void OOJSReportErrorWithArguments(JSContext *context, NSString *format, va_list args)
void OOJSResumeTimeLimiter(void)
BOOL JSEntityIsJavaScriptVisiblePredicate(Entity *entity, void *parameter)
BOOL OOJSIsSubclass(JSClass *putativeSubclass, JSClass *superclass)
NSString * OOStringFromJSString(JSContext *context, JSString *string)
OOINLINE JSClass * OOJSGetClass(JSContext *cx, JSObject *obj) ALWAYS_INLINE_FUNC
void OOJSStrLiteralCachePRIVATE(const char *string, jsval *strCache, BOOL *inited)
id OOJSNativeObjectOfClassFromJSObject(JSContext *context, JSObject *object, Class requiredClass)
static id JSNumberConverter(JSContext *context, JSObject *object)
static NSString * CallerPrefix(NSString *scriptClass, NSString *function)
static id JSStringConverter(JSContext *context, JSObject *object)
void OOJSReportWrappedException(JSContext *context, id exception)
#define OOJSENGINE_JSVERSION
static OOJavaScriptEngine * sSharedEngine
static id JSArrayConverter(JSContext *context, JSObject *object)
static void ReportJSError(JSContext *context, const char *message, JSErrorReport *report)
#define OOJSENGINE_CONTEXT_OPTIONS
void OOJSUnreachable(const char *function, const char *file, unsigned line)
static NSMapTable * sRegisteredSubClasses
static NSString * DescribeValue(JSContext *context, jsval value, BOOL abbreviateObjects, BOOL recursing)
static void UnregisterSubclasses(void)
static id JSBooleanConverter(JSContext *context, JSObject *object)
static JSObject * JSArrayFromNSArray(JSContext *context, NSArray *array)
static JSObject * JSObjectFromNSDictionary(JSContext *context, NSDictionary *dictionary)
JSContext * gOOJSMainThreadContext
static NSMutableDictionary * sObjectConverters
static BOOL JSNewNSArrayValue(JSContext *context, NSArray *array, jsval *value)
static unsigned sErrorHandlerStackSkip
static BOOL JSNewNSDictionaryValue(JSContext *context, NSDictionary *dictionary, jsval *value)
static void UnregisterObjectConverters(void)
void OOJSInitJSIDCachePRIVATE(const char *name, jsid *idCache)
NSString *const kOOLogException
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
#define OOLog(class, format,...)
NSString * OOLogAbbreviatedFileName(const char *inName)
@ STELLAR_TYPE_ATMOSPHERE
@ STELLAR_TYPE_NORMAL_PLANET
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_ENTER_NAMED(NAME)
#define OOJS_PROFILE_ENTER
static id JSArrayConverter(JSContext *context, JSValueConst array)
static id JSNumberConverter(JSContext *context, JSValueConst object)
NSDictionary * OOJSDictionaryFromJSObject(JSContext *context, JSValueConst object)
JSContext * gOOJSMainThreadContext
static id JSStringConverter(JSContext *context, JSValueConst object)
static id JSBooleanConverter(JSContext *context, JSValueConst object)
NSString * oo_jsClassName()
NSString * oo_jsDescription()
NSString * oo_jsClassName()
NSString * oo_jsClassName()
void registerStandardObjectConverters()
void createMainThreadContext()
void destroyMainThreadContext()
BOOL lookUpStandardClassPointers()
BOOL isVisibleToScripts()
jsval oo_jsValueInContext:(JSContext *context)
OOJSScript * currentlyRunningScript()
id initWithJSValue:inContext:(jsval value,[inContext] JSContext *context)
void destroyMainThreadContext()
BOOL showErrorLocations()
void createMainThreadContext()
OOJavaScriptEngine * sharedEngine()
void registerStandardObjectConverters()
id jsScriptFromFileNamed:properties:(NSString *fileName,[properties] NSDictionary *properties)
NSDictionary * dictionaryFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)