Oolite
Loading...
Searching...
No Matches
QuickJS Directory Reference
Directory dependency graph for QuickJS:

Directories

 
poc

Files

 
EntityOOJavaScriptExtensions.h
 
EntityOOJavaScriptExtensions.m
 
OOConstToJSString.h
 
OOConstToJSString.m
 
OOJavaScriptEngine.h
 
OOJavaScriptEngine.m
 
OOJSCall.h
 
OOJSCall.m
 
OOJSClasses.m
 
OOJSClock.h
 
OOJSClock.m
 
OOJSDock.h
 
OOJSDock.m
 
OOJSEngineDebuggerHelpers.m
 
OOJSEngineNativeWrappers.h
 
OOJSEngineTimeManagement.h
 
OOJSEngineTimeManagement.m
 
OOJSEntity.h
 
OOJSEntity.m
 
OOJSEquipmentInfo.h
 
OOJSEquipmentInfo.m
 
OOJSExhaustPlume.h
 
OOJSExhaustPlume.m
 
OOJSFlasher.h
 
OOJSFlasher.m
 
OOJSFont.h
 
OOJSFont.m
 
OOJSFrameCallbacks.h
 
OOJSFrameCallbacks.m
 
OOJSFunction.h
 
OOJSFunction.m
 
OOJSGlobal.h
 
OOJSGlobal.m
 
OOJSGuiScreenKeyDefinition.h
 
OOJSGuiScreenKeyDefinition.m
 
OOJSInterfaceDefinition.h
 
OOJSInterfaceDefinition.m
 
OOJSManifest.h
 
OOJSManifest.m
 
OOJSMission.h
 
OOJSMission.m
 
OOJSMissionVariables.h
 
OOJSMissionVariables.m
 
OOJSOolite.h
 
OOJSOolite.m
 
OOJSPlanet.h
 
OOJSPlanet.m
 
OOJSPlayer.h
 
OOJSPlayer.m
 
OOJSPlayerShip.h
 
OOJSPlayerShip.m
 
OOJSPopulatorDefinition.h
 
OOJSPopulatorDefinition.m
 
OOJSPropID.h
 
OOJSQuaternion.h
 
OOJSQuaternion.m
 
OOJSScript.h
 
OOJSScript.m
 
OOJSShip.h
 
OOJSShip.m
 
OOJSShipGroup.h
 
OOJSShipGroup.m
 
OOJSSound.h
 
OOJSSound.m
 
OOJSSoundSource.h
 
OOJSSoundSource.m
 
OOJSSpecialFunctions.h
 
OOJSSpecialFunctions.m
 
OOJSStation.h
 
OOJSStation.m
 
OOJSSun.h
 
OOJSSun.m
 
OOJSSystem.h
 
OOJSSystem.m
 
OOJSSystemInfo.h
 
OOJSSystemInfo.m
 
OOJSTimer.h
 
OOJSTimer.m
 
OOJSVector.h
 
OOJSVector.m
 
OOJSVisualEffect.h
 
OOJSVisualEffect.m
 
OOJSWaypoint.h
 
OOJSWaypoint.m
 
OOJSWorldScripts.h
 
OOJSWorldScripts.m
 
OOJSWormhole.h
 
OOJSWormhole.m

Detailed Description

QuickJS-ng scripting engine

This directory is a port of Oolite's JavaScript layer (src/Core/Scripting) from SpiderMonkey 1.8.5 to QuickJS-ng v0.17.0. See issue #580.

Building

meson setup build/qjs --native-file clang.ini -Djs_engine=quickjs
meson compile -C build/qjs

js_engine defaults to spidermonkey, which builds exactly as before. With quickjs, the files here replace the SpiderMonkey files of the same name in the parent directory (this directory comes first on the include path), and QuickJS-ng is built from source as a meson subproject (subprojects/quickjs-ng.wrap) unless a system quickjs-ng is found. No SpiderMonkey headers or libraries are needed.

Files that don't use a JavaScript engine API (OOScript.m, OOPListScript.m, OOScriptTimer.m, OOLegacyScriptWhitelist.m) are shared by both engines. Game code outside src/Core/Scripting builds with either engine, using the engine-neutral names OOJSVal, OOJSPropID, OOJSFreeValue() etc. and #if OOJS_QUICKJS for engine-specific declarations.

Status

The game builds, boots, loads saved games, launches and flies with QuickJS. The parity probe (below) gives the same results as SpiderMonkey apart from the differences listed below, and in debug builds no JavaScript objects are left alive when the engine resets or shuts down.

Not yet done:

  • Stack dumps with local variables: QuickJS has no frame inspection API. Stack dumps (dumpStackForErrors and friends) list the call stack with function names, files and lines, but not this or local variables.

Linux (amd64) and macOS (arm64) builds pass the parity probe, and CI builds and runs the launch test with QuickJS on Ubuntu, Windows and macOS.

Conventions

The comment at the top of OOJavaScriptEngine.h is the reference. In short:

  • QuickJS values are reference counted. JSValueConst parameters are borrowed; every JSValue you are given is owned and must be freed or handed on. -oo_jsValueInContext:, OOJSValueFromNativeObject() and OOJSSTR() return owned values.
  • Natives are static JSValue F(OOJS_NATIVE_ARGS) and fail with return OOJSNativeFailure(context);, which keeps SpiderMonkey's behaviour of silently stopping the script when no error was reported.
  • Property callbacks switch on magic (the old tinyid).
  • JS_ValueToInt32() becomes OOJSValueToInt32() (it rounds and rejects NaN, unlike QuickJS's JS_ToInt32()).
  • There is one runtime per process; -reset replaces the context. Anything holding a JSValue releases it on kOOJavaScriptEngineWillResetNotification.

Behaviour that needed emulating, all in the engine core:

  • Scope chain. SpiderMonkey put each script's object at the head of its scope chain, so bare names resolve to script properties. Scripts are wrapped in with(this){(function(){ ... }).call(this)} (OOJSWrapScriptSource()); strict mode and line numbers are unaffected. Top-level vars are local to the script rather than global.
  • Own properties. SpiderMonkey reported a prototype's accessor properties as own properties of instances, so JSON.stringify(vector) and Object.keys(ship) see them (OOJSClasses.m).
  • toSource() / uneval() are provided by Resources/Scripts/oolite-quickjs-compat.js.
  • const. In SpiderMonkey 1.8.5, const was function-scoped and usable before its declaration, and a few OXPs rely on that. Before compiling, every script's const keywords are replaced with var (same length, so positions are unchanged) by a rewriter in the compatibility script, which the engine keeps out of OXPs' reach (OOJSLegacyConstRewriter()); only the read-only check is lost. The rewriter was checked against acorn's tokenizer on 488 OXP scripts: it changed exactly the const keywords.
  • Global object. QuickJS-ng defines ES2015 and later globals (Map, Symbol, Promise, globalThis and so on) that SpiderMonkey 1.8.5 didn't have. They are removed when the context is created (RemoveNonSpiderMonkeyGlobals()), so the global object has the same names under both engines and OXPs can't come to depend on QuickJS-only built-ins. Some couldn't work anyway: nothing runs QuickJS's job queue, so Promise reactions and queueMicrotask() callbacks would never be called. Newer syntax and methods on the remaining built-ins are not affected.
  • Properties on primitives. SpiderMonkey 1.8.5 silently ignored "str".foo = 1 even in strict code (Route Planner relies on this); QuickJS throws. QuickJS-ng is patched to match (subprojects/packagefiles/quickjs-ng/), and a warning (script.javaScript.init.unpatchedEngine) is logged if Oolite is linked against an unpatched system QuickJS-ng. An upstream option to replace the patch has been requested (quickjs-ng/quickjs#1837).
  • new on native functions. SpiderMonkey 1.8.5 let any native function be called with new, and OXPs do it by mistake (new Vector3D.random()); QuickJS throws "not a constructor". QuickJS-ng is patched to do what SpiderMonkey did: the function is called with a new plain object as this, and that object is the result unless the function returns an object. The unpatchedEngine check tests for this too.
  • Profiling. In debug builds OOJS_PROFILE is on, as with SpiderMonkey: natives bracketed by OOJS_NATIVE_ENTER/OOJS_PROFILE_ENTER are timed, and the debug console's profile(), getProfile() and trace() work. JavaScript functions are timed too, through a function call hook that Oolite's QuickJS-ng patch adds (the counterpart of SpiderMonkey's MOZ_TRACE_JSCALLS, which oo_javascript_trace turns on by default). The hook is only installed while profiling, so it costs nothing otherwise.
  • The time limiter uses QuickJS's interrupt handler; error locations come from the exception's stack.

Opting out of the emulation

A script whose directive prologue includes "use oolite modern" runs without the scope chain and const emulation above. It is compiled as a plain function called with the script object as this. tools/oxp-upgrade rewrites OXP scripts so that they don't need the emulation, and adds the directive; its README explains what changes and why. Marked scripts are logged under script.javaScript.load.modern (off by default). The other compatibility measures (own properties, toSource()/uneval() and the QuickJS-ng patches) apply to every script.

The emulation is intended to stay until OXPs have had time to upgrade; the proposed timeline is in the tool's README.

Compiled-script cache

As with SpiderMonkey's XDR cache, compiled scripts are kept in the data cache (OOCacheManager), keyed by path, in a separate cache named "compiled QuickJS scripts". Entries hold JS_WriteObject() bytecode, plus a hash of the exact text that was compiled (after the const rewrite and wrapping), the QuickJS version and a format number (kCompiledScriptFormat in OOJSScript.m). An entry is only used if all three match, so editing a script recompiles it even when the data cache is otherwise up to date. As before, the whole data cache is cleared when the Oolite version or the search paths change.

Within a session, each compiled script is also kept in memory by path, so a script loaded again (every ship's script and AI) isn't read, hashed or deserialised again; like SpiderMonkey, it doesn't notice a script edited during the session. Each load still runs a new closure of the bytecode, so scripts don't share state. The kept scripts are freed before the context is destroyed.

Because JS_EvalFunction() runs compiled code with the global object as this, the wrapped script is compiled as a function expression and then called with the script object as this. The prefix is on the first line, so line numbers don't change. Cache activity is logged under script.javaScript.cache (off by default).

Testing

  • tools/js-parity: runs the game headless (Xvfb) with a probe OXP and compares what scripts see with a SpiderMonkey baseline. See run_probe.sh. Accepted differences are listed in tools/js-parity/expected-differences.txt.
  • poc/: a standalone harness for the engine core, Vector3D, Quaternion and script wrapping (-Dquickjs_poc=true).
  • Debug QuickJS builds log script.javaScript.reset.liveObjects after every context teardown; anything other than zero is a reference counting bug.

Known behaviour differences

  • Debug console (src/Core/Debug/QuickJS/OOJSConsole.m): pedanticMode is remembered but has no effect, dumpNamedRoots() is gone, dumpHeap() writes QuickJS's memory usage summary, and console error reports have no "Error" or "strict mode" variants (QuickJS reports every error as an exception). Locations in code typed into the console are reported like any other location, not as <console input>.
  • Debug builds: a debugger; statement no longer logs a stack dump (QuickJS has no debugger hook), and the OO_DEBUG vector and quaternion conversion counters (reportJSVectorStatistics and friends) are gone.
  • Assigning to a read-only property in strict code throws TypeError: no setter for property (SpiderMonkey quoted the expression).
  • for..in lists integer-like keys first, in ascending order, as the current ECMAScript specification requires.
  • Function.prototype.toString()/toSource() return the original source text, not SpiderMonkey's decompiled text.
  • oolite.jsVersion is still 185, but oolite.jsVersionString names QuickJS-ng.
  • Exception log message classes are named after the error type (script.javaScript.exception.ReferenceError) rather than SpiderMonkey's error numbers.
  • SoundFromJSValue() now resumes the script time limiter on every path; the SpiderMonkey version left it paused in one case, so a script could run without a time limit after it.
  • Property reads on stale Station and Dock references stop the script silently (as in SpiderMonkey, where this was an unintended consequence of the code), whereas stale Ship references return undefined.