25#ifndef OO_CACHE_JS_SCRIPTS
26#define OO_CACHE_JS_SCRIPTS 1
37#if OO_CACHE_JS_SCRIPTS
58static BOOL
RunScriptWithName(JSContext* context, NSString* path, JSValueConst
object, NSString** outErrorMessage);
64#if OO_CACHE_JS_SCRIPTS
66static void CacheCompiledScript(JSContext* context, NSString* path, NSData* source, JSValueConst compiled);
70 .class_name =
"Script",
79@interface OOJSScript (OOPrivate)
81- (NSString*)scriptNameFromPath:(NSString*)path;
82- (NSDictionary*)defaultPropertiesFromPath:(NSString*)path;
83- (void)checkForTickle:(JSContext*)context;
89+ (id)scriptWithPath:(NSString*)path properties:(NSDictionary*)properties
91 return [[[
self alloc] initWithPath:path properties:properties] autorelease];
94- (id)initWithPath:(NSString*)path properties:(NSDictionary*)properties
96 JSContext* context = NULL;
97 NSString* problem =
nil;
103 problem =
@"allocation failure";
107 if (JS_HasException(context)) {
108 JS_FreeValue(context, JS_GetException(context));
109 OOLogERR(
@"script.javaScript.load.waitingException",
@"Prior to loading script %@, there was a pending JavaScript exception, which has been cleared. This is an internal error, please report it.", path);
116 JS_FreeValue(context, JS_GetException(context));
118 problem =
@"allocation failure";
139 if ([key isKindOfClass:[NSString
class]]) {
152 if (!problem && properties !=
nil) {
155 if ([key isKindOfClass:[NSString
class]]) {
168 JSAtom nameID =
OOJSID(
"name");
173 OOLog(
@"script.javaScript.willLoad",
@"About to load JavaScript %@", path);
178 problem =
@"could not run script";
207 OOLog(
@"script.javaScript.load.failed",
@"***** Error loading JavaScript script %@ -- %@", path, problem);
208 if (context != NULL && JS_HasException(context))
217 selector:@selector(javaScriptEngineWillReset:)
218 name:kOOJavaScriptEngineWillResetNotification
227 [[NSNotificationCenter defaultCenter] removeObserver:
self
228 name:kOOJavaScriptEngineWillResetNotification
236 if (JS_IsObject(_jsSelf)) {
241 [(id)JS_GetAnyOpaque(_jsSelf, &ignored) release];
242 JS_SetOpaque(_jsSelf, NULL);
243 JS_FreeValue(context, _jsSelf);
244 _jsSelf = JS_UNDEFINED;
249 [weakSelf weakRefDrop];
254- (NSString*)oo_jsClassName
259- (NSString*)descriptionComponents
261 if (JS_IsObject(_jsSelf))
262 return [
super descriptionComponents];
264 return @"invalid script";
267- (void)javaScriptEngineWillReset:(NSNotification*)notification
270 if (JS_IsObject(_jsSelf)) {
272 _jsSelf = JS_UNDEFINED;
276+ (OOJSScript*)currentlyRunningScript
285 NSMutableArray* result =
nil;
296 return [weakSelf retain];
299- (void)weakRefDied:(OOWeakReference*)weakRef
301 if (weakRef == weakSelf)
308 name = [[
self propertyNamed:@"name"] copy];
310 return [
self scriptNameFromPath:filePath];
314- (NSString*)scriptDescription
324- (void)runWithTarget:(Entity*)target
328- (BOOL)callMethod:(JSAtom)methodID
329 inContext:(JSContext*)context
330 withArguments:(JSValueConst*)argv
332 result:(JSValue*)outResult
334 NSParameterAssert(
name != NULL && (argv != NULL || argc == 0) && context != NULL);
335 if (outResult != NULL)
336 *outResult = JS_UNDEFINED;
342 JSValue method = JS_GetProperty(context,
_jsSelf, methodID);
348 if (
EXPECT(!JS_IsUndefined(method))) {
350 if (JS_HasException(context)) {
351 OOLog(
@"script.internalBug",
@"Exception pending on context before calling method in %s, clearing. This is an internal error, please report it.", __PRETTY_FUNCTION__);
352 JS_FreeValue(context, JS_GetException(context));
368 JSValue result = JS_Call(context, method,
_jsSelf, argc, argv);
371 if (JS_IsException(result)) {
376 if (outResult != NULL)
379 JS_FreeValue(context, result);
390 JS_FreeValue(context, method);
394- (id)propertyWithID:(JSAtom)propID inContext:(JSContext*)context
396 NSParameterAssert(context != NULL);
400 JSValue jsValue = JS_GetProperty(context,
_jsSelf, propID);
401 if (JS_IsException(jsValue)) {
402 JS_FreeValue(context, JS_GetException(context));
407 JS_FreeValue(context, jsValue);
411- (BOOL)setProperty:(
id)value withID:(JSAtom)propID inContext:(JSContext*)context
413 NSParameterAssert(context != NULL);
421- (BOOL)defineProperty:(
id)value withID:(JSAtom)propID inContext:(JSContext*)context
423 NSParameterAssert(context != NULL);
431- (id)propertyNamed:(NSString*)propName
445- (BOOL)setProperty:(
id)value named:(NSString*)propName
447 if (value ==
nil || propName ==
nil)
459- (BOOL)defineProperty:(
id)value named:(NSString*)propName
461 if (value ==
nil || propName ==
nil)
473- (JSValue)oo_jsValueInContext:(JSContext*)context
475 if (!JS_IsObject(_jsSelf))
477 return JS_DupValue(context, _jsSelf);
484 element = malloc(
sizeof *element);
506@implementation OOJSScript (OOPrivate)
522- (NSString*)scriptNameFromPath:(NSString*)path
524 NSString* lastComponent =
nil;
525 NSString* truncatedPath =
nil;
526 NSString* theName =
nil;
529 theName = [
NSString stringWithFormat:@"%p",
self];
531 lastComponent = [
path lastPathComponent];
532 if (![lastComponent hasPrefix:
@"script."])
533 theName = lastComponent;
535 truncatedPath = [
path stringByDeletingLastPathComponent];
536 if (NSOrderedSame == [[truncatedPath lastPathComponent] caseInsensitiveCompare:
@"Config"]) {
537 truncatedPath = [
truncatedPath stringByDeletingLastPathComponent];
539 if (NSOrderedSame == [[truncatedPath pathExtension] caseInsensitiveCompare:
@"oxp"]) {
540 truncatedPath = [
truncatedPath stringByDeletingPathExtension];
544 theName = lastComponent;
548 if (0 == [theName length])
551 return StrippedName([theName stringByAppendingString:
@".anon-script"]);
554- (NSDictionary*)defaultPropertiesFromPath:(NSString*)path
557 NSString* manifestPath = [[[
path stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"manifest.plist"];
564 [
properties setObject:[
manifest oo_stringForKey:kOOManifestVersion] forKey:@"version"];
568 [
properties setObject:[
manifest oo_stringForKey:kOOManifestIdentifier] forKey:kLocalManifestProperty];
574 [
properties setObject:[
manifest oo_stringForKey:kOOManifestLicense] forKey:@"license"];
585- (void)checkForTickle:(JSContext*)context
587 JSValue tickle = JS_GetPropertyStr(context, _jsSelf,
"tickle");
588 if (JS_IsException(tickle)) {
589 JS_FreeValue(context, JS_GetException(context));
590 }
else if (!JS_IsUndefined(tickle)) {
591 OOJSReportWarning(context,
@"Script %@ appears to use the tickle() event handler, which is no longer supported.", [
self name]);
593 JS_FreeValue(context, tickle);
598@implementation OOScript (JavaScriptEvents)
600- (BOOL)callMethod:(JSAtom)methodID
601 inContext:(JSContext*)context
602 withArguments:(JSValueConst*)argv
604 result:(JSValue*)outResult
606 if (outResult != NULL)
607 *outResult = JS_UNDEFINED;
616 OOJSInitClass(context, global,
sScriptClassID, JS_UNDEFINED,
OOJSUnconstructableConstruct, 0, NULL, 0,
sScriptMethods,
OOJS_COUNT(
sScriptMethods), NULL, 0);
624 [array addObject:stack->current];
642 [held getValue:&compiled];
643 JS_FreeValue(context, compiled);
652static BOOL
RunScriptWithName(JSContext* context, NSString* path, JSValueConst
object, NSString** outErrorMessage)
654 NSCParameterAssert(outErrorMessage != NULL);
655 *outErrorMessage =
nil;
658 NSValue* held = [sCompiledScripts objectForKey:path];
660 [held getValue:&compiled];
661 compiled = JS_DupValue(context, compiled);
664 if (JS_IsException(compiled))
669 JSValue kept = JS_DupValue(context, compiled);
670 [sCompiledScripts setObject:[NSValue valueWithBytes:&kept objCType:@encode(JSValue)] forKey:path];
675 JSValue
function = JS_EvalFunction(context, compiled);
676 if (JS_IsException(
function)) {
679 result = JS_Call(context,
function,
object, 0, NULL);
680 JS_FreeValue(context,
function);
684 if (JS_IsException(result)) {
686 *outErrorMessage =
@"could not run script";
690 JS_FreeValue(context, result);
697 NSString* fileContents = [NSString stringWithContentsOfUnicodeFile:path];
698 if (fileContents ==
nil) {
699 *outErrorMessage =
@"could not load file";
703#ifdef OO_DEBUG_MONITOR_ENABLED
708 if ([fileContents rangeOfString:
@"\"use strict\
";"].location == NSNotFound && [fileContents rangeOfString:
@"'use strict';"].location == NSNotFound) {
713 fileContents = [@"\"use strict\";\n" stringByAppendingString:fileContents];
724 OOLog(
@"script.javaScript.load.modern",
@"Script %@ uses modern scoping.", path);
725 NSString* lineEnd = [fileContents hasSuffix:@"\n"] ?
@"" :
@"\n";
726 fileContents = [NSString stringWithFormat:@"(function(){%@%@})", fileContents, lineEnd];
728 fileContents = [NSString stringWithFormat:@"(function(){%@})", OOJSWrapScriptSource(RewriteLegacyConst(context, fileContents))];
737 NSString* wrapped = fileContents;
738 NSData* source = [wrapped dataUsingEncoding:NSUTF8StringEncoding];
740 JSValue compiled = JS_UNDEFINED;
741#if OO_CACHE_JS_SCRIPTS
745 if (JS_IsUndefined(compiled)) {
746 NSMutableData* terminated = [NSMutableData dataWithData:source];
747 [terminated appendBytes:"" length:1];
749 compiled = JS_Eval(context, [terminated bytes], [source length], [path UTF8String], JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
750 if (JS_IsException(compiled)) {
752 *outErrorMessage =
@"compilation failed";
755#if OO_CACHE_JS_SCRIPTS
763#if OO_CACHE_JS_SCRIPTS
783 const uint8_t* bytes = [source bytes];
784 NSUInteger length = [source length];
785 uint64_t hash = 0xcbf29ce484222325ULL;
786 for (NSUInteger i = 0; i < length; i++) {
788 hash *= 0x100000001b3ULL;
790 return [NSString stringWithFormat:@"%016llx:%lu", (unsigned long long)hash, (unsigned long)length];
797 if (![entry isKindOfClass:[NSDictionary
class]])
800 NSData* bytecode = [entry objectForKey:kCompiledScriptKeyBytecode];
801 if (![bytecode isKindOfClass:[NSData
class]]
803 || ![[entry oo_stringForKey:
kCompiledScriptKeyEngine] isEqualToString:[NSString stringWithUTF8String:JS_GetVersion()]]
805 OOLog(
@"script.javaScript.cache.stale",
@"Compiled script cache entry for %@ is out of date.", path);
810 JSValue compiled = JS_ReadObject(context, [bytecode bytes], [bytecode length], JS_READ_OBJ_BYTECODE);
811 if (JS_IsException(compiled)) {
812 JS_FreeValue(context, JS_GetException(context));
813 OOLog(
@"script.javaScript.cache.readFailed",
@"Could not read compiled script cache entry for %@; compiling instead.", path);
817 OOLog(
@"script.javaScript.cache.load",
@"Loaded compiled script %@ from cache.", path);
824 uint8_t* bytes = JS_WriteObject(context, &length, compiled, JS_WRITE_OBJ_BYTECODE);
826 if (JS_HasException(context))
827 JS_FreeValue(context, JS_GetException(context));
831 NSData* bytecode = [NSData dataWithBytes:bytes length:length];
832 js_free(context, bytes);
834 NSDictionary* entry = [NSDictionary dictionaryWithObjectsAndKeys:
835 bytecode, kCompiledScriptKeyBytecode,
836 SourceHash(source), kCompiledScriptKeyHash,
837 [NSString stringWithUTF8String:JS_GetVersion()], kCompiledScriptKeyEngine,
838 [NSNumber numberWithUnsignedInt:kCompiledScriptFormat], kCompiledScriptKeyFormat,
842 OOLog(
@"script.javaScript.cache.store",
@"Cached compiled script %@.", path);
851 NSUInteger length = [source length];
853 if (length > 0 && [source characterAtIndex:0] == 0xFEFF)
859 while (skipped && i < length) {
861 unichar c = [source characterAtIndex:i];
862 if (c ==
' ' || c ==
'\t' || c ==
'\r' || c ==
'\n' || c == 0xA0 || c == 0xFEFF) {
865 }
else if (c ==
'/' && i + 1 < length && [source characterAtIndex:i + 1] ==
'/') {
866 while (i < length && [source characterAtIndex:i] !=
'\n')
869 }
else if (c ==
'/' && i + 1 < length && [source characterAtIndex:i + 1] ==
'*') {
870 NSRange end = [source rangeOfString:@"*/" options:0 range:NSMakeRange(i + 2, length - i - 2)];
871 if (end.location == NSNotFound)
873 i = end.location + 2;
881 unichar quote = [source characterAtIndex:i];
882 if (quote !=
'"' && quote !=
'\'')
884 NSUInteger start = ++i;
886 while (i < length && [source characterAtIndex:i] != quote) {
887 unichar c = [source characterAtIndex:i];
898 NSString* directive = [source substringWithRange:NSMakeRange(start, i - start)];
903 unichar c = [source characterAtIndex:i];
906 }
else if (c ==
'/' && i + 1 < length && [source characterAtIndex:i + 1] ==
'/') {
907 while (i < length && [source characterAtIndex:i] !=
'\n')
910 }
else if (c !=
' ' && c !=
'\t' && c !=
'\r') {
915 if (i < length && [source characterAtIndex:i] ==
';')
917 else if (!lineBreak && i < length && [source characterAtIndex:i] !=
'}')
920 if (!escaped && [directive isEqualToString:
@"use oolite modern"])
937 static NSMutableDictionary* sRewritten =
nil;
939 if ([source rangeOfString:
@"const"].location == NSNotFound)
942 NSString* cached = [sRewritten objectForKey:source];
947 NSString* result = source;
949 if (JS_IsFunction(context, rewriter)) {
951 JSValue rewritten = JS_Call(context, rewriter, JS_UNDEFINED, 1, (JSValueConst*)&argument);
952 if (JS_IsException(rewritten)) {
956 if (sRewritten ==
nil)
957 sRewritten = [[NSMutableDictionary alloc] init];
958 [sRewritten setObject:result forKey:source];
960 JS_FreeValue(context, rewritten);
961 JS_FreeValue(context, argument);
969 static NSCharacterSet* invalidSet =
nil;
970 if (invalidSet ==
nil)
971 invalidSet = [[NSCharacterSet characterSetWithCharactersInString:@"_ \t\n\r\v"] retain];
973 return [string stringByTrimmingCharactersInSet:invalidSet];
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
#define foreachkey(VAR, DICT)
id OOConsumeReference(id OO_NS_CONSUMED value)
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiter()
#define kOOJSLongTimeLimit
#define OOJSStartTimeLimiterWithTimeLimit(limit)
void InitOOJSScript(JSContext *context, JSObject *global)
static NSString *const kLocalManifestProperty
static NSString * StrippedName(NSString *string)
static RunningStack * sRunningStack
static JSFunctionSpec sScriptMethods[]
static JSClass sScriptClass
static void AddStackToArrayReversed(NSMutableArray *array, RunningStack *stack)
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
void OOJSReportWarning(JSContext *context, NSString *format,...)
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)
NSString * OOStringFromJSID(jsid propID)
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
#define OOJS_PROP_READONLY
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
OOINLINE void OOJSRelinquishContext(JSContext *context)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
#define OOLogERR(class, format,...)
#define OOLogOutdentIf(class)
#define OOLog(class, format,...)
#define OOLogIndentIf(class)
static NSString *const kOOManifestLicense
static NSString *const kOOManifestIdentifier
static NSString *const kOOManifestVersion
static NSString *const kOOManifestAuthor
NSDictionary * OODictionaryFromFile(NSString *path)
void OOJSScriptDestroyCompiledScripts(JSContext *context)
static NSMutableDictionary * sCompiledScripts
static void CacheCompiledScript(JSContext *context, NSString *path, NSData *source, JSValueConst compiled)
static NSString * StrippedName(NSString *string)
static BOOL RunScriptWithName(JSContext *context, NSString *path, JSValueConst object, NSString **outErrorMessage)
static NSString *const kCompiledScriptKeyHash
static NSString *const kCompiledScriptCache
static NSString * SourceHash(NSData *source)
static NSString *const kCompiledScriptKeyEngine
static JSValue CachedCompiledScript(JSContext *context, NSString *path, NSData *source)
static BOOL HasModernScopeDirective(NSString *source)
static JSValue CompileScriptWithName(JSContext *context, NSString *path, NSString **outErrorMessage)
static NSString * RewriteLegacyConst(JSContext *context, NSString *source)
static NSString *const kCompiledScriptKeyFormat
static JSClassID sScriptClassID
static NSString *const kCompiledScriptKeyBytecode
JSValueConst OOJSLegacyConstRewriter(void)
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
JSValueConst OOJSInitClass(JSContext *context, JSValueConst global, JSClassID classID, JSValueConst parentPrototype, JSCFunction *constructor, int constructorArgCount, const JSCFunctionListEntry *properties, size_t propertyCount, const JSCFunctionListEntry *methods, size_t methodCount, const JSCFunctionListEntry *staticMethods, size_t staticMethodCount)
#define OOJS_COUNT(array)
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
OOCacheManager * sharedCache()
BOOL defineProperty:named:(id value,[named] NSString *name)
BOOL setProperty:named:(id value,[named] NSString *name)
BOOL defineProperty:withID:inContext:(id value,[withID] jsid propID,[inContext] JSContext *context)
id propertyWithID:inContext:(jsid propID,[inContext] JSContext *context)
NSString * scriptNameFromPath:(NSString *path)
BOOL setProperty:withID:inContext:(id value,[withID] jsid propID,[inContext] JSContext *context)
void checkForTickle:(JSContext *context)
NSDictionary * defaultPropertiesFromPath:(NSString *path)
OOJavaScriptEngine * sharedEngine()
id weakRefWithObject:(id< OOWeakReferenceSupport > object)