Oolite
Loading...
Searching...
No Matches
OOJavaScriptEngine.h
Go to the documentation of this file.
1/*
2
3OOJavaScriptEngine.h (QuickJS-ng)
4
5JavaScript support for Oolite, ported from SpiderMonkey 1.8.5 to QuickJS-ng.
6See https://github.com/OoliteProject/oolite/issues/580.
7
8Copyright (C) 2007-2013 David Taylor and Jens Ayton.
9
10This program is free software; you can redistribute it and/or
11modify it under the terms of the GNU General Public License
12as published by the Free Software Foundation; either version 2
13of the License, or (at your option) any later version.
14
15This program is distributed in the hope that it will be useful,
16but WITHOUT ANY WARRANTY; without even the implied warranty of
17MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18GNU General Public License for more details.
19
20You should have received a copy of the GNU General Public License
21along with this program; if not, write to the Free Software
22Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23MA 02110-1301, USA.
24
25*/
26
27/* REFERENCE OWNERSHIP CONVENTIONS
28
29 SpiderMonkey values were traced by the garbage collector and never freed
30 explicitly. QuickJS values are reference counted, so every JSValue is
31 either owned (the holder must eventually JS_FreeValue() it, or hand it
32 on) or borrowed (JSValueConst; the holder must not free it).
33
34 1. Parameters typed JSValueConst are borrowed. Native callbacks never free
35 their this value or arguments.
36 2. JSValues returned from functions, and JSValues stored through out
37 parameters (e.g. VectorToJSValue(context, v, &outValue)), are owned by
38 the caller. This includes -oo_jsValueInContext:,
39 OOJSValueFromNativeObject() and OOJSSTR(). On failure the out
40 parameter is left as JS_UNDEFINED and need not be freed.
41 3. OOJS_RETURN(v) and friends transfer ownership of v to QuickJS.
42 4. A native object that keeps a JSValue (the old JS_Add*Root pattern) owns
43 a reference and must free it when done, and on
44 kOOJavaScriptEngineWillResetNotification. If the JS object can reach
45 back to the native object strongly, the reference must also be
46 reported from the class gc_mark hook so the cycle collector can see
47 it. Back references from JS to native objects use weak references,
48 as before.
49 5. Errors: a native that fails throws (OOJSReport*Error) and returns
50 JS_EXCEPTION. Code calling into JS from Objective-C reports a pending
51 exception with OOJSReportPendingException().
52 6. Property IDs (JSAtom) from OOJSID() and OOJSIDFromString() are
53 interned for the life of the process and are never freed.
54
55 There is one runtime for the life of the process. -reset replaces the
56 context (and so the global object and all prototypes), but class IDs and
57 atoms survive.
58*/
59
60#pragma once
61
62#import "OOFoundation.h"
63#import "OOTypes.h"
64#include <quickjs.h>
65
66#if !OOJS_POC_HARNESS
67#import "PlayerEntity.h"
69#import "Universe.h"
70#endif
71
72#define OOJS_QUICKJS 1
73
74/* quickjs-ng 0.18.0 passes the context rather than the runtime to the
75 interrupt handler.
76*/
77#if QJS_VERSION_MAJOR > 0 || QJS_VERSION_MINOR >= 18
78typedef JSContext OOJSInterruptHandlerArg;
79#else
80typedef JSRuntime OOJSInterruptHandlerArg;
81#endif
82
83#define OOJSENGINE_MONITOR_SUPPORT OO_DEBUG_MONITOR_ENABLED
84
85/* Profiling of native functions (the debug console's profile(), getProfile()
86 and trace()), as in SpiderMonkey builds without MOZ_TRACE_JSCALLS: time
87 is attributed to natives bracketed by OOJS_NATIVE_ENTER/EXIT or
88 OOJS_PROFILE_ENTER/EXIT, and everything else counts as JavaScript time.
89*/
90#define OOJS_PROFILE (OOLITE_DEBUG && !OOJS_POC_HARNESS)
91
92// Number of entries in a JSCFunctionListEntry (or other) array.
93#define OOJS_COUNT(array) (sizeof(array) / sizeof *(array))
94
95#import "OOJSPropID.h"
96
97@class Entity;
98@protocol OOJavaScriptEngineMonitor;
99
100@interface OOJavaScriptEngine : NSObject {
101@private
102 JSRuntime* _runtime;
103 JSContext* _context;
106
107#ifdef OO_DEBUG_MONITOR_ENABLED
108 BOOL _dumpStackForErrors;
109 BOOL _dumpStackForWarnings;
110#endif
111#if OOJSENGINE_MONITOR_SUPPORT
112 id<OOJavaScriptEngineMonitor> _monitor;
113#endif
114}
115
117
118- (JSContext*)context;
119- (JSValueConst)globalObject;
120
122
123/* Tear down context and global object and rebuild them from scratch. This
124 invalidates -globalObject and all prototypes.
125*/
126- (BOOL)reset;
127
128// Call a JS function. *outResult is owned by the caller. Exceptions are reported and cleared.
129- (BOOL)callJSFunction:(JSValueConst)function
130 forObject:(JSValueConst)jsThis
131 argc:(int)argc
132 argv:(JSValueConst*)argv
133 result:(JSValue*)outResult;
134
135- (void)garbageCollectionOpportunity:(BOOL)force;
136
138- (void)setShowErrorLocations:(BOOL)value;
139
140#ifdef OO_DEBUG_MONITOR_ENABLED
141- (BOOL)dumpStackForErrors;
142- (void)setDumpStackForErrors:(BOOL)value;
143
144- (BOOL)dumpStackForWarnings;
145- (void)setDumpStackForWarnings:(BOOL)value;
146
147// Install handler for JS "debugger" statment. (Not supported by QuickJS; does nothing.)
148- (void)enableDebuggerStatement;
149#endif
150
151/* Destroy the context and runtime. All native objects holding JSValues must
152 have released them first. Returns the number of JS objects still alive
153 after a final garbage collection; if it is non-zero, they are logged
154 and the runtime is abandoned rather than freed.
155*/
156- (NSUInteger)shutDown;
157
158@end
159
160#if OOJSENGINE_MONITOR_SUPPORT
161
162/* Protocol for debugging "monitor" object.
163 The monitor is an object -- in Oolite, or via Distributed Objects -- which
164 is provided with debugging information by the OOJavaScriptEngine.
165
166 QuickJS has no JSErrorReport, so problems are described by severity
167 (@"exception" or @"warning") and the innermost location on the stack, if
168 any (file is nil otherwise).
169*/
170@protocol OOJavaScriptEngineMonitor <NSObject>
171
172// Sent for JS errors or warnings.
173- (oneway void)jsEngine:(in byref OOJavaScriptEngine*)engine
174 context:(in JSContext*)context
175 problemOfSeverity:(in NSString*)severity
176 inFile:(in NSString*)file
177 line:(in unsigned)line
178 stackSkip:(in unsigned)stackSkip
179 showingLocation:(in BOOL)showLocation
180 withMessage:(in NSString*)message;
181
182// Sent for JS log messages. Note: messageClass will be nil if Log() is used rather than LogWithClass().
183- (oneway void)jsEngine:(in byref OOJavaScriptEngine*)engine
184 context:(in JSContext*)context
185 logMessage:(in NSString*)message
186 ofClass:(in NSString*)messageClass;
187
188@end
189
190@interface OOJavaScriptEngine (OOMonitorSupport)
191
192- (void)setMonitor:(id<OOJavaScriptEngineMonitor>)monitor;
193
194@end
195
196#endif
197
198// There is only one context, created on the main thread.
200{
201 extern JSContext* gOOJSMainThreadContext;
202 NSCAssert(gOOJSMainThreadContext != NULL, @"Attempt to use JavaScript context before JavaScript engine is initialized.");
204}
205
206OOINLINE void OOJSRelinquishContext(JSContext* context)
207{
208 (void)context;
209}
210
211// Notifications sent when JavaScript engine is reset.
212extern NSString* const kOOJavaScriptEngineWillResetNotification;
213extern NSString* const kOOJavaScriptEngineDidResetNotification;
214
215/* Engine-neutral names, also defined by the SpiderMonkey header, so code
216 outside src/Core/Scripting can be built against either engine.
217*/
218#define OOJSFreeValue(context, value) JS_FreeValue((context), (value))
219#define OOJSUndefinedValue() JS_UNDEFINED
220#define OOJSNullValue() JS_NULL
221OOINLINE BOOL OOJSValueIsUndefined(JSValueConst value)
222{
223 return JS_IsUndefined(value);
224}
225OOINLINE JSValue OOJSValueFromDouble(JSContext* context, double value)
226{
227 return JS_NewNumber(context, value);
228}
229// JavaScript truthiness (like JS_ValueToBoolean()); NO if conversion throws.
230BOOL OOJSValueToBOOL(JSContext* context, JSValueConst value);
231
232/* OOJSValueToInt32(): replacement for SpiderMonkey's JS_ValueToInt32(),
233 which converted to a number and rounded to nearest, failing with an error
234 if the result was NaN or out of range. (QuickJS's JS_ToInt32() is ECMA
235 ToInt32, which truncates and wraps silently, like JS_ValueToECMAInt32().)
236 On failure an exception is pending.
237*/
238BOOL OOJSValueToInt32(JSContext* context, JSValueConst value, int32_t* outValue);
239
240/* Script source wrapping.
241
242 SpiderMonkey ran each script with its script object at the head of the
243 scope chain, so a bare identifier resolved to a property of the script
244 object before the global object (many OXPs rely on this). QuickJS has no
245 API for that, but a sloppy-mode with statement provides the same scope
246 chain, and strict-mode code nested inside it remains legal. The wrapper
247 stays on the first line so line numbers are unchanged.
248
249 Top-level var declarations become local to the script instead of being
250 added to the global object (JSOPTION_VAROBJFIX). No known OXP depends
251 on that, and it prevents scripts clobbering each other's globals.
252
253 Anything prepended to a script (such as the debug-build "use strict"
254 directive) must be added before wrapping: a with statement is a syntax
255 error in strict code.
256*/
257NSString* OOJSWrapScriptSource(NSString* source);
258
259/* The compatibility script's const rewriter (see RewriteLegacyConst() in
260 OOJSScript.m), or JS_UNDEFINED if it failed to load. Kept here rather
261 than on the global object so that OXPs can't see or replace it. The
262 caller does not own the returned value.
263*/
264JSValueConst OOJSLegacyConstRewriter(void);
265
266// Report and clear a pending exception, as SpiderMonkey's error reporter did.
267void OOJSReportPendingException(JSContext* context);
268
269/* Error and warning reporters.
270
271 The error reporters throw an Error. The caller must return JS_EXCEPTION
272 (or NO from a BOOL helper whose caller returns JS_EXCEPTION).
273 Warnings are logged with the current script location and do not throw.
274*/
275void OOJSReportError(JSContext* context, NSString* format, ...);
276void OOJSReportErrorWithArguments(JSContext* context, NSString* format, va_list args);
277void OOJSReportErrorForCaller(JSContext* context, NSString* scriptClass, NSString* function, NSString* format, ...);
278
279void OOJSReportWarning(JSContext* context, NSString* format, ...);
280void OOJSReportWarningWithArguments(JSContext* context, NSString* format, va_list args);
281void OOJSReportWarningForCaller(JSContext* context, NSString* scriptClass, NSString* function, NSString* format, ...);
282
283// Name of the property with the given magic (tinyid) in a property table, for error messages.
284NSString* OOStringFromJSPropertyMagic(int magic, const JSCFunctionListEntry* list, size_t count);
285
286void OOJSReportBadPropertySelector(JSContext* context, JSValueConst thisObj, int magic, const JSCFunctionListEntry* list, size_t count);
287void OOJSReportBadPropertyValue(JSContext* context, JSValueConst thisObj, int magic, const JSCFunctionListEntry* list, size_t count, JSValueConst value);
288void OOJSReportBadArguments(JSContext* context, NSString* scriptClass, NSString* function, int argc, JSValueConst* argv, NSString* message, NSString* expectedArgsDescription);
289
290void OOJSReportWrappedException(JSContext* context, id exception);
291
292/* OOJSNativeFailure()
293
294 SpiderMonkey natives could return NO without reporting an error, which
295 silently stopped the running script. A QuickJS native must never return
296 JS_EXCEPTION without a pending exception: scripts would catch a bogus
297 "[uninitialized]" exception. Natives therefore fail with
298 return OOJSNativeFailure(context);
299 which returns the pending exception if there is one, and otherwise
300 throws an uncatchable error that is not logged, stopping the script as
301 before. (Directly after OOJSReportError(), return JS_EXCEPTION is fine.)
302*/
303JSValue OOJSNativeFailure(JSContext* context);
304
305/* OOJSSetWarningOrErrorStackSkip()
306
307 Indicate that the direct call site is not relevant for error handler.
308 Currently, if non-zero, no call site information is provided.
309*/
310void OOJSSetWarningOrErrorStackSkip(unsigned skip);
311
312/* Get a number from an argument list. NaN is treated as failure, as before.
313 The NoError variant leaves no pending exception.
314*/
315BOOL OOJSArgumentListGetNumber(JSContext* context, NSString* scriptClass, NSString* function, int argc, JSValueConst* argv, double* outNumber, int* outConsumed);
316BOOL OOJSArgumentListGetNumberNoError(JSContext* context, int argc, JSValueConst* argv, double* outNumber, int* outConsumed);
317
319{
320 return JS_NewBool(NULL, b != 0);
321}
322
323@interface NSObject (OOJavaScript)
324
325/* -oo_jsValueInContext:
326
327 Return the JavaScript value representation of an object, owned by the
328 caller. The default implementation returns JS_UNDEFINED.
329 If the receiver may be nil, use OOJSValueFromNativeObject() instead.
330*/
331- (JSValue)oo_jsValueInContext:(JSContext*)context;
332
333/* -oo_jsDescription
334 -oo_jsDescriptionWithClassName:
335 -oo_jsClassName
336
337 See comments for -descriptionComponents in OOFoundation.h.
338*/
339- (NSString*)oo_jsDescription;
340- (NSString*)oo_jsDescriptionWithClassName:(NSString*)className;
341- (NSString*)oo_jsClassName;
342
343/* oo_clearJSSelf:
344 This is called by OOJSObjectWrapperFinalize() when a JS object wrapper is
345 collected. The default implementation does nothing.
346*/
347- (void)oo_clearJSSelf:(JSValueConst)selfVal;
348
349@end
350
351// Return an owned JavaScript value for an object, or null if passed nil.
352OOINLINE JSValue OOJSValueFromNativeObject(JSContext* context, id object)
353{
354 if (object != nil)
355 return [object oo_jsValueInContext:context];
356 return JS_NULL;
357}
358
359// Like OOJSValueFromNativeObject(), but primitives are boxed. Returns an owned object or JS_EXCEPTION.
360JSValue OOJSObjectFromNativeObject(JSContext* context, id object);
361
362/* OOJSValue: an object whose purpose in life is to hold a JavaScript value.
363 This is somewhat useful for putting JavaScript objects in ObjC collections,
364 for instance to pass as properties to script loaders. The value is held
365 (with its own reference) until the OOJSValue is deallocated or the engine
366 is reset.
367*/
368@interface OOJSValue : NSObject {
369 JSValue _val;
370}
371
372+ (id)valueWithJSValue:(JSValueConst)value inContext:(JSContext*)context;
373- (id)initWithJSValue:(JSValueConst)value inContext:(JSContext*)context;
374
375@end
376
377/**** String utilities ****/
378
379/* OOJSSTR(const char * [literal])
380
381 An owned string value for a string literal. The string is interned the
382 first time the macro is hit.
383*/
384#define OOJSSTR(str) JS_AtomToString(OOJSAcquireContext(), OOJSID(str))
385
386/* Convert an arbitrary JS value to an NSString, calling its toString method
387 if needed. OOStringFromJSValue() returns nil if value is null or
388 undefined, OOStringFromJSValueEvenIfNull() returns "null" or "undefined".
389*/
390NSString* OOStringFromJSValue(JSContext* context, JSValueConst value);
391NSString* OOStringFromJSValueEvenIfNull(JSContext* context, JSValueConst value);
392
393/* Describe a value for debugging or error reporting. Strings are quoted,
394 escaped and limited in length. Functions are described as "function foo"
395 (or just "function" if they're anonymous). Up to four elements of arrays
396 are included, followed by total count of there are more than four.
397 If abbreviateObjects, the description "[object Object]" is replaced with
398 "{...}", which may or may not be clearer depending on context.
399*/
400NSString* OOJSDescribeValue(JSContext* context, JSValueConst value, BOOL abbreviateObjects);
401
402// Name of the value's JS class, e.g. "Vector3D", for error messages.
403NSString* OOJSClassNameOfValue(JSContext* context, JSValueConst value);
404
405// Convert a property ID to an NSString.
406NSString* OOStringFromJSID(JSAtom propID);
407
408// Convert an NSString to a property ID (interned for the life of the process; JS_ATOM_NULL for nil).
409JSAtom OOJSIDFromString(NSString* string);
410
411@interface NSString (OOJavaScriptExtensions)
412
413// For diagnostic messages; produces things like @"(42, true, "a string", an object description)".
414+ (NSString*)stringWithJavaScriptParameters:(JSValueConst*)params count:(int)count inContext:(JSContext*)context;
415
416// Concatenate sequence of arbitrary JS objects into string.
417+ (NSString*)concatenationOfStringsFromJavaScriptValues:(JSValueConst*)values count:(size_t)count separator:(NSString*)separator inContext:(JSContext*)context;
418
419// Add escape codes for string so that it's a valid JavaScript literal (if you put "" or '' around it).
421
422@end
423
424#if !OOJS_POC_HARNESS
425
426// OOEntityFilterPredicate wrapping a JavaScript function.
427typedef struct
428{
429 JSContext* context;
430 JSValueConst function; // Caller is responsible for ensuring this is a function object (using OOJSValueIsFunction()).
431 JSValueConst jsThis;
432 BOOL errorFlag; // Set if a JS exception occurs. The
433 // exception will have been reported.
434 // This also supresses further filtering.
436BOOL JSFunctionPredicate(Entity* entity, void* parameter);
437
438// YES for ships and (normal) planets. Parameter: ignored.
439BOOL JSEntityIsJavaScriptVisiblePredicate(Entity* entity, void* parameter);
440
441// YES for ships other than sub-entities and menu-display ships, and planets other than atmospheres and menu miniatures. Parameter: ignored.
442BOOL JSEntityIsJavaScriptSearchablePredicate(Entity* entity, void* parameter);
443
444// YES for menu-display ships. Parameter: ignored
445BOOL JSEntityIsDemoShipPredicate(Entity* entity, void* parameter);
446
447#endif
448
449// Class IDs of the standard classes, looked up when the engine starts.
451
452id OOJSNativeObjectFromJSValue(JSContext* context, JSValueConst value);
453id OOJSNativeObjectFromJSObject(JSContext* context, JSValueConst object);
454id OOJSNativeObjectOfClassFromJSValue(JSContext* context, JSValueConst value, Class requiredClass);
455id OOJSNativeObjectOfClassFromJSObject(JSContext* context, JSValueConst object, Class requiredClass);
456
457OOINLINE BOOL OOJSValueIsFunction(JSContext* context, JSValueConst value)
458{
459 return JS_IsFunction(context, value);
460}
461
462OOINLINE BOOL OOJSValueIsArray(JSContext* context, JSValueConst value)
463{
464 return JS_IsArray(value);
465}
466
467/* OOJSDictionaryFromJSValue(context, value)
468 OOJSDictionaryFromJSObject(context, object)
469
470 Converts a JavaScript value to a dictionary by calling
471 OOJSNativeObjectFromJSValue() on each of its values.
472
473 Only enumerable own (i.e., not inherited) properties are included.
474 Integer keys become NSNumbers, as before.
475*/
476NSDictionary* OOJSDictionaryFromJSValue(JSContext* context, JSValueConst value);
477NSDictionary* OOJSDictionaryFromJSObject(JSContext* context, JSValueConst object);
478
479/* OOJSDictionaryFromStringTable(context, value)
480
481 Treat an arbitrary JavaScript object as a dictionary mapping strings to
482 strings, and convert to a corresponding NSDictionary. The values are
483 converted to strings.
484
485 Only enumerable own (i.e., not inherited) properties with string keys are
486 included.
487*/
488NSDictionary* OOJSDictionaryFromStringTable(JSContext* context, JSValueConst value);
489
490/* Classes
491
492 OOJSRegisterClass() allocates a class ID (once per process; *ioClassID
493 must start as 0) and registers the class with the runtime. Prototypes
494 are created per context by each class's Init function.
495
496 Oolite reflects part of its class hierarchy as related JS classes whose
497 prototypes inherit each other. For instance, JS Entity methods work on JS
498 Ships. OOJSRegisterSubclass() records such a relationship, and
499 OOJSIsSubclass() tests whether putativeSubclass is equal to superclass
500 or a registered subclass of it, recursively.
501*/
502enum { kOOJSMaxClassID = 1 << 16 }; // QuickJS's limit.
503
504JSClassID OOJSRegisterClass(JSClassID* ioClassID, const JSClassDef* classDef);
505
506// Object.prototype for the current context (owned).
507JSValue OOJSObjectPrototype(JSContext* context);
508const char* OOJSClassName(JSClassID classID);
509
510void OOJSRegisterSubclass(JSClassID subclass, JSClassID superclass);
511BOOL OOJSIsSubclass(JSClassID putativeSubclass, JSClassID superclass);
512OOINLINE BOOL OOJSIsMemberOfSubclass(JSContext* context, JSValueConst object, JSClassID superclass)
513{
514 return JS_IsObject(object) && OOJSIsSubclass(JS_GetClassID(object), superclass);
515}
516
517/* Create the prototype for a class whose instances wrap native objects. As
518 with SpiderMonkey's JS_InitClass(), the prototype is itself an instance
519 of the class (with no native object), inheriting from parentPrototype
520 (Object.prototype if JS_UNDEFINED). If constructor is non-NULL, a global
521 constructor function named after the class is also defined.
522
523 The prototype is set as the class prototype for the context; the
524 return value is borrowed from there.
525
526 SpiderMonkey reported the properties of a JS_InitClass() prototype
527 (JSPROP_SHARED | JSPROP_PERMANENT) as own properties of every instance,
528 so Object.keys(), hasOwnProperty() and JSON.stringify() saw them; e.g.
529 JSON.stringify(new Vector3D(1, 2, 3)) is {"x":1,"y":2,"z":3}. Classes
530 registered with OOJSRegisterClass() and no exotic methods of their own
531 reproduce this for the getter/setter properties passed to OOJSInitClass().
532 As in SpiderMonkey, only the object's direct prototype counts: a ship's
533 Ship properties are own properties, its Entity properties are not.
534 Classes with their own exotic methods can call the functions below from
535 theirs to get the same behaviour.
536*/
537int OOJSGetSharedPermanentOwnProperty(JSContext* context, JSPropertyDescriptor* desc, JSValueConst object, JSAtom prop);
538int OOJSGetSharedPermanentOwnPropertyNames(JSContext* context, JSPropertyEnum** ptab, uint32_t* plen, JSValueConst object);
539
540JSValueConst OOJSInitClass(JSContext* context, JSValueConst global, JSClassID classID, JSValueConst parentPrototype,
541 JSCFunction* constructor, int constructorArgCount,
542 const JSCFunctionListEntry* properties, size_t propertyCount,
543 const JSCFunctionListEntry* methods, size_t methodCount,
544 const JSCFunctionListEntry* staticMethods, size_t staticMethodCount);
545
546/*
547 DEFINE_JS_OBJECT_GETTER()
548 Defines a helper to extract Objective-C objects from the private field of
549 JS objects, with runtime type checking. Weakrefs are automatically
550 unpacked.
551
552 Types which extend other types, such as entity subtypes, must register
553 their relationships with OOJSRegisterSubclass().
554
555 The signature of the generated function is:
556 BOOL <name>(JSContext *context, JSValueConst inObject, <class>** outObject)
557 If it returns NO, inObject is of the wrong class and an error has been
558 raised. Otherwise, outObject is either a native object of the specified
559 class (or a subclass) or nil (for prototypes and stale references).
560*/
561#define DEFINE_JS_OBJECT_GETTER(NAME, JSCLASSID, OBJCCLASSNAME) \
562 static BOOL NAME(JSContext* context, JSValueConst inObject, OBJCCLASSNAME** outObject) GCC_ATTR((unused)); \
563 static BOOL NAME(JSContext* context, JSValueConst inObject, OBJCCLASSNAME** outObject) \
564 { \
565 NSCParameterAssert(outObject != NULL); \
566 static Class cls = Nil; \
567 if (EXPECT_NOT(cls == Nil)) \
568 cls = [OBJCCLASSNAME class]; \
569 return OOJSObjectGetterImplPRIVATE(context, inObject, (JSCLASSID), cls, #NAME, (id*)outObject); \
570 }
571
572// For DEFINE_JS_OBJECT_GETTER()'s use.
573BOOL OOJSObjectGetterImplPRIVATE(JSContext* context, JSValueConst object, JSClassID requiredClassID, Class requiredObjCClass, const char* name, id* outObject);
574
575/* Support for OOJSNativeObjectFromJSValue() family
576
577 OOJSClassConverterCallback specifies the prototype for a callback function
578 which converts a JavaScript object to an Objective-C object.
579
580 OOJSBasicPrivateObjectConverter() is a OOJSClassConverterCallback which
581 returns the JS object's private storage value. It automatically unpacks
582 OOWeakReferences if relevant.
583
584 OOJSRegisterObjectConverter() registers a callback for a specific JS class.
585 It is not automatically propagated to subclasses.
586*/
587typedef id (*OOJSClassConverterCallback)(JSContext* context, JSValueConst object);
588id OOJSBasicPrivateObjectConverter(JSContext* context, JSValueConst object);
589
590void OOJSRegisterObjectConverter(JSClassID classID, OOJSClassConverterCallback converter);
591
592// Time limiter. Calls must be balanced, as before; nesting is supported.
593#define kOOJSLongTimeLimit (5.0)
595#define OOJSStartTimeLimiter() OOJSStartTimeLimiterWithTimeLimit(0.0)
596void OOJSStopTimeLimiter(void);
597void OOJSPauseTimeLimiter(void);
598void OOJSResumeTimeLimiter(void);
599
600#ifndef NDEBUG
601// Debug console support for the time limiter.
602void OOJSResetTimeLimiter(void);
605#endif
606
607/* OOJSDumpStack()
608 Write the current JavaScript stack to the log. QuickJS provides only
609 function names and locations, not local variables.
610*/
611#if OOLITE_DEBUG || defined(OO_DEBUG_MONITOR_ENABLED)
612void OOJSDumpStack(JSContext* context);
613#else
614#define OOJSDumpStack(cx) \
615 do { \
616 } while (0)
617#endif
618
619/***** Reusable JS callbacks ****/
620
621/* OOJSUnconstructableConstruct
622
623 Constructor callback for pseudo-classes which can't be constructed.
624*/
625JSValue OOJSUnconstructableConstruct(JSContext* context, JSValueConst this, int argc, JSValueConst* argv);
626
627/* OOJSObjectWrapperFinalize
628
629 Finalizer for JS classes whose private storage is a retained object
630 reference (generally an OOWeakReference, but doesn't have to be).
631*/
632void OOJSObjectWrapperFinalize(JSRuntime* runtime, JSValueConst this);
633
634/* OOJSObjectWrapperToString
635
636 Implementation of toString() for JS classes whose private storage is an
637 Objective-C object reference (generally an OOWeakReference).
638
639 Calls -oo_jsDescription and, if that fails, -description.
640*/
641JSValue OOJSObjectWrapperToString(JSContext* context, JSValueConst this, int argc, JSValueConst* argv);
642
643/* Native function and property callback conveniences.
644
645 Native functions are declared as
646 static JSValue Foo(OOJS_NATIVE_ARGS);
647 and use OOJS_THIS, OOJS_ARGV and argc as the SpiderMonkey versions did.
648 Property callbacks are declared as
649 static JSValue FooGetProperty(OOJS_GETTER_ARGS);
650 static JSValue FooSetProperty(OOJS_SETTER_ARGS);
651 and switch on magic (the old tinyid). A setter receives its value as
652 value and returns JS_UNDEFINED on success.
653*/
654#define OOJS_NATIVE_ARGS JSContext *context, JSValueConst oojsThis, int argc, JSValueConst *oojsArgv
655#define OOJS_GETTER_ARGS JSContext *context, JSValueConst this, int magic
656#define OOJS_SETTER_ARGS JSContext *context, JSValueConst this, JSValueConst value, int magic
657#define OOJS_THIS oojsThis
658#define OOJS_ARGV oojsArgv
659
660/* Replacement for SpiderMonkey's JS_IsConstructing(), valid only in
661 constructors created by OOJSInitClass() (JS_CFUNC_constructor_or_func):
662 QuickJS passes new.target as this when called with new, and undefined
663 when called as a function.
664*/
665#define OOJS_IS_CONSTRUCTING (!JS_IsUndefined(OOJS_THIS))
666
667#define OOJS_RETURN(v) \
668 do { \
669 return (v); \
670 } while (0)
671#define OOJS_RETURN_VOID OOJS_RETURN(JS_UNDEFINED)
672#define OOJS_RETURN_NULL OOJS_RETURN(JS_NULL)
673#define OOJS_RETURN_BOOL(v) OOJS_RETURN(OOJSValueFromBOOL(v))
674#define OOJS_RETURN_INT(v) OOJS_RETURN(JS_NewInt32(context, (v)))
675#define OOJS_RETURN_DOUBLE(v) OOJS_RETURN(JS_NewFloat64(context, (v)))
676#define OOJS_RETURN_OBJECT(o) OOJS_RETURN(OOJSValueFromNativeObject(context, (o)))
677
678#define OOJS_RETURN_WITH_HELPER(helper, value) \
679 do { \
680 JSValue oojsRVal; \
681 if (!helper(context, (value), &oojsRVal)) \
682 return OOJSNativeFailure(context); \
683 return oojsRVal; \
684 } while (0)
685
686#define OOJS_RETURN_VECTOR(value) OOJS_RETURN_WITH_HELPER(VectorToJSValue, value)
687#define OOJS_RETURN_HPVECTOR(value) OOJS_RETURN_WITH_HELPER(HPVectorToJSValue, value)
688#define OOJS_RETURN_QUATERNION(value) OOJS_RETURN_WITH_HELPER(QuaternionToJSValue, value)
689
690/* OOJS_NATIVE_ENTER()/OOJS_NATIVE_EXIT bracket natives that call into
691 Objective-C code which may throw; the exception is converted into a JS
692 error. OOJS_PROFILE_ENTER/EXIT bracket natives that cannot throw. When
693 OOJS_PROFILE is set, both also record the time spent in the native for
694 the profiler.
695*/
696#if OOJS_PROFILE
697
699
700/*
701 Profiler implementation details. This should be internal to
702 OOJSEngineTimeManagement.m, but needs to be declared on the stack by the
703 macros below when profiling is enabled.
704*/
705typedef struct OOJSProfileStackFrame OOJSProfileStackFrame;
706struct OOJSProfileStackFrame {
707 OOJSProfileStackFrame* back; // Stack link
708 const void* key; // Key to look up profile entries: the function name, or the bytecode of a JS function.
709 const char* function; // Name of function.
710 OOHighResTimeValue startTime; // Time frame was entered.
711 OOTimeDelta subTime; // Time spent in subroutine calls.
712 OOTimeDelta* total; // Pointer to accumulator for this type of frame.
713 void (*cleanup)(OOJSProfileStackFrame*); // Cleanup function if needed (used for JS frames).
714};
715
716void OOJSProfileEnter(OOJSProfileStackFrame* frame, const char* function);
717void OOJSProfileExit(OOJSProfileStackFrame* frame);
718
719#define OOJS_PROFILE_ENTER_NAMED(NAME) \
720 { \
721 OOJSProfileStackFrame oojsProfilerStackFrame; \
722 @try { \
723 OOJSProfileEnter(&oojsProfilerStackFrame, NAME);
724
725#define OOJS_PROFILE_EXIT \
726 } \
727 @finally \
728 { \
729 OOJSProfileExit(&oojsProfilerStackFrame); \
730 } \
731 }
732
733#define OOJS_NATIVE_ENTER(cx) \
734 { \
735 JSContext* oojsNativeContext = (cx); \
736 OOJSProfileStackFrame oojsProfilerStackFrame; \
737 @try { \
738 OOJSProfileEnter(&oojsProfilerStackFrame, __FUNCTION__);
739
740#define OOJS_NATIVE_EXIT \
741 } \
742 @catch (id exception) \
743 { \
744 OOJSReportWrappedException(oojsNativeContext, exception); \
745 return JS_EXCEPTION; \
746 } \
747 @finally \
748 { \
749 OOJSProfileExit(&oojsProfilerStackFrame); \
750 } \
751 }
752
753#else
754
755#define OOJS_PROFILE_ENTER_NAMED(NAME) {
756#define OOJS_PROFILE_EXIT }
757
758#define OOJS_NATIVE_ENTER(cx) \
759 { \
760 JSContext* oojsNativeContext = (cx); \
761 @try {
762
763#define OOJS_NATIVE_EXIT \
764 } \
765 @catch (id exception) \
766 { \
767 OOJSReportWrappedException(oojsNativeContext, exception); \
768 return JS_EXCEPTION; \
769 } \
770 }
771
772#endif // OOJS_PROFILE
773
774#define OOJS_PROFILE_ENTER OOJS_PROFILE_ENTER_NAMED(__FUNCTION__)
775#define OOJS_PROFILE_EXIT_VOID OOJS_PROFILE_EXIT
776
777#define OOJS_BEGIN_FULL_NATIVE(context) \
778 { \
779 (void)(context); \
780 OOJSPauseTimeLimiter(); \
781 @try {
782
783#define OOJS_END_FULL_NATIVE \
784 } \
785 @finally \
786 { \
787 OOJSResumeTimeLimiter(); \
788 } \
789 }
790
791/***** Property attributes, equivalent to the SpiderMonkey OOJS_PROP_* flags *****/
792
793// Callback-based (JS_CGETSET_MAGIC_DEF2). Read-only properties are defined without a setter.
794#define OOJS_PROP_READWRITE_CB JS_PROP_ENUMERABLE
795#define OOJS_PROP_READONLY_CB JS_PROP_ENUMERABLE
796#define OOJS_PROP_HIDDEN_READWRITE_CB 0
797#define OOJS_PROP_HIDDEN_READONLY_CB 0
798
799// Slot-based (JS_DefinePropertyValue*).
800#define OOJS_PROP_READWRITE (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE)
801#define OOJS_PROP_READONLY JS_PROP_ENUMERABLE
802#define OOJS_PROP_HIDDEN_READWRITE JS_PROP_WRITABLE
803#define OOJS_PROP_HIDDEN_READONLY 0
804#define OOJS_METHOD_READONLY OOJS_PROP_HIDDEN_READONLY
805
806// Property definition shorthands for the common cases.
807#define OOJS_PROPERTY_RW(name, getter, setter, magic) JS_CGETSET_MAGIC_DEF2(name, getter, setter, magic, OOJS_PROP_READWRITE_CB)
808#define OOJS_PROPERTY_RO(name, getter, magic) JS_CGETSET_MAGIC_DEF2(name, getter, NULL, magic, OOJS_PROP_READONLY_CB)
#define OOINLINE
#define OOJSProfileExit(frame)
#define OOJSProfileEnter(frame, function)
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiterWithTimeLimit(limit)
void OOJSResetTimeLimiter(void)
OOTimeDelta OOJSGetTimeLimiterLimit(void)
void OOJSSetTimeLimiterLimit(OOTimeDelta limit)
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,...)
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)
OOINLINE jsval OOJSValueFromDouble(JSContext *context, double value)
NSString *const kOOJavaScriptEngineWillResetNotification
void OOJSReportWarningWithArguments(JSContext *context, NSString *format, va_list args)
NSString *const kOOJavaScriptEngineDidResetNotification
NSString * OOStringFromJSID(jsid propID)
OOINLINE BOOL OOJSValueIsArray(JSContext *context, jsval value)
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)
OOINLINE BOOL OOJSValueToBOOL(JSContext *context, jsval value)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
#define OOJSDumpStack(cx)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
OOINLINE BOOL OOJSIsMemberOfSubclass(JSContext *context, JSObject *object, JSClass *superclass)
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,...)
OOINLINE BOOL OOJSValueToInt32(JSContext *context, jsval value, int32_t *outValue)
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)
OOINLINE void OOJSReportPendingException(JSContext *context)
void OOJSReportError(JSContext *context, NSString *format,...)
OOINLINE jsval OOJSValueFromBOOL(int b) INLINE_CONST_FUNC
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)
NSDictionary * OOJSDictionaryFromStringTable(JSContext *context, jsval value)
void OOJSReportErrorWithArguments(JSContext *context, NSString *format, va_list args)
OOINLINE BOOL OOJSValueIsUndefined(jsval value)
void OOJSResumeTimeLimiter(void)
BOOL JSEntityIsJavaScriptVisiblePredicate(Entity *entity, void *parameter)
BOOL OOJSIsSubclass(JSClass *putativeSubclass, JSClass *superclass)
id OOJSNativeObjectOfClassFromJSObject(JSContext *context, JSObject *object, Class requiredClass)
void OOJSReportWrappedException(JSContext *context, id exception)
JSContext * gOOJSMainThreadContext
unsigned count
return nil
uint64_t OOHighResTimeValue
double OOTimeDelta
Definition OOTypes.h:193
int OOJSGetSharedPermanentOwnPropertyNames(JSContext *context, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst object)
JSValueConst OOJSLegacyConstRewriter(void)
JSClassID gOOJSArrayClassID
JSValue OOJSObjectPrototype(JSContext *context)
Definition OOJSClasses.m:81
NSString * OOJSClassNameOfValue(JSContext *context, JSValueConst value)
@ kOOJSMaxClassID
JSClassID gOOJSNumberClassID
JSValue OOJSNativeFailure(JSContext *context)
JSClassID gOOJSBooleanClassID
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
Definition OOJSClasses.m:61
JSClassID gOOJSStringClassID
int OOJSGetSharedPermanentOwnProperty(JSContext *context, JSPropertyDescriptor *desc, JSValueConst object, JSAtom prop)
const char * OOJSClassName(JSClassID classID)
Definition OOJSClasses.m:89
NSString * OOStringFromJSPropertyMagic(int magic, const JSCFunctionListEntry *list, size_t count)
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)
JSClassID gOOJSObjectClassID
NSString * OOJSWrapScriptSource(NSString *source)
JSRuntime OOJSInterruptHandlerArg
OOJavaScriptEngine * sharedEngine()