14. The JavaScript host


14. The JavaScript host

This chapter describes the second implementation of the RVM, in JavaScript (../js/): how its modules are organised, how it runs under Node.js and in a web browser, the generated modules and how to regenerate them, and how it represents what the ooRexx host gets from native ooRexx. It assumes the overview of chapter 1; the machine, the object model and the runtime are described once, for both hosts, in chapters 2 to 13, and the file-by-file map is chapter 15.

The JS host is a port of the ooRexx host, method by method: machine.mjs is RVM.Machine.cls, objects.mjs is RVM.Objects.cls, and so on (15-source-map.md). It runs the same R-code text (chapter 4), carries the same instruction table and verifier, and is checked against native ooRexx and against the ooRexx host on the same R-code (16-testing.md). It contains no compiler of its own: R-code is made by RVM.Compiler, run either by native ooRexx or by the JS RVM itself (compiling).

Module graph

Every file is an ES module (.mjs). The core (machine, objects, runtime, libraries) imports nothing from Node; the system is reached only through a host object passed to the machine and a file layer that the host installs. Only four modules import node: built-ins: rvm.mjs, host-node.mjs, hostfile-node.mjs and sockets-node.mjs (plus the worker sockets-worker.mjs). So the same core is bundled for the browser with a different host.

 Node front end                          Browser front end
 js/rvm (sh) ──▶ rvm.mjs                  rvm-browser.mjs (bundle entry)
                  │                          │
      host-node.mjs ─┬─ hostfile-node.mjs   host-browser.mjs ── compiler.mjs
                     └─ sockets-node.mjs       │ (in-memory files)   │
                          └▶ sockets-worker    │                     │
                  │                          │                     │
                  └────────────▶ runner.mjs ◀┘ ◀───────────────────┘
                                   │  (runProgram, runSource...)
                                   ▼
                               machine.mjs ──▶ rvm-prelude.mjs, rvm-prelude-streams.mjs
                    ┌──────────┬───┴──────┬───────────┬──────────┬───────────┐
               objects.mjs  context.mjs  rcode.mjs   bifs.mjs   streams.mjs  hostemu.mjs
                    │                                 │
                    │        bifcore.mjs ◀── bifs-number, bifs-system, bifs-stream
                    ▼
               libraries.mjs ──▶ rexxutil.mjs, rxmath.mjs, rxregexp.mjs, rxsock.mjs
 leaves:  number.mjs, errors.mjs ──▶ rvm-data.mjs (also used by bifcore, rexxutil)
          files.mjs (filled by the host: installFiles)

Points worth knowing when editing:

  • bifs.mjs imports bifs-number.mjs, bifs-system.mjs and bifs-stream.mjs for their side effect: each registers its functions in the BIFS table of bifcore.mjs (register). isBIF/callBIF are in bifs.mjs.
  • host-node.mjs imports hostfile-node.mjs for its side effect: it calls installFiles with the Node FileSystem, HostFile and FileOps. host-browser.mjs installs its in-memory equivalents the same way. Code that needs files imports files from files.mjs and never a host module.
  • There are import cycles (machine.mjs ↔︎ rexxutil.mjs, objects.mjs ↔︎ bifs.mjs, ...). They are harmless because every cross-module use happens at call time, not at module evaluation.
  • Module-level state is per process (Node) or per page (browser): the external data queues (Queues in context.mjs), the REXXUTIL macrospace (SharedMacros), and in the browser the in-memory file store, the library and the compiler. This matches native ooRexx, whose queues and macrospace are per process when there is no rxapi (13-io-and-commands.md).

The host interface

The machine and the runtime call only these members of the host (both NodeHost and BrowserHost implement them; the optional ones are tested with typeof and their absence disables a feature):

Group Members Notes
Output say, writeOut, writeErr, traceLine, flush Node buffers standard output and flushes it before anything goes to standard error or to a command.
Input readStdinLine, fillStdin, stdinBuffer, stdinEOF stdinBuffer is shared by PULL/LINEIN and the STDIN HostFile.
Compiler (optional) compileFragment, compileSource Without compileFragment: no INTERPRET (93.900) and no interactive trace. Without compileSource: no Method~new/Routine~new from source, no runSource.
Programs findExternal, loadExternal External routines and ::REQUIRES (03-compiler.md).
System systemName, sysVersion, rexxInfo (optional), now, userid, beep, gc, qualifyName now() returns [local µs since 0001-01-01, UTC offset µs] as BigInts.
Environment getEnv, setEnv, currentDirectory, changeDirectory, hasLocalEnvironments, pushLocal, popLocal, endProgram SETLOCAL/ENDLOCAL snapshots; endProgram restores the outermost one.
Commands initialAddress, lineEnd, strategyFor, run, start, ended, finish (a command its activity waits for: 07; a host without start runs every command waited for), runInternally, readFile, openOutputFile, UNKNOWN_COMMAND, NOT_REGISTERED A port of RVM.CommandHost (13-io-and-commands.md).
Sockets (optional) sockets (call, wait) Absent: rxsock is 98.903.

This table is the authoritative list for the JS host (the ooRexx host's classes are in 13). rexxInfo() also supplies executable and libraryPath for .RexxInfo. Members a host has beyond these (envExists; on Node writeCache and shareQueues, set and called by the launcher rvm.mjs) are not part of the contract. The file layer is installed apart, with installFiles (../js/files.mjs). Node's file layer also uses the Node host's standard streams as files (StdFile: stdinFile, outFile, errFile; tellOut, tellErr, seekOut, seekErr, takeStdin, seekStdin; said, the lines SAY wrote), for standard streams redirected to files (13); the browser's standard streams are always transient.

Running under Node.js

Requirements: Node.js 22 or later and, to compile anything, native ooRexx 5 (rexx) on the PATH.

The launcher and rvm.mjs

../js/rvm is a shell script that sets RVM_EXECUTABLE to the path it was called by (links not resolved), puts the package's bin first in REXX_PATH and runs node rvm.mjs "$@" from its own (resolved) directory; ../js/rvm.cmd does the same on Windows. Because .RexxInfo~executable is the launcher, a program that starts another Rexx program through it (ooTest's execRexxPrg, samples) keeps running on the JS RVM. Without the launcher, .RexxInfo~executable is Node's executable.

js/rvm program.rex [arguments]        # a source, compiled as an external routine is
js/rvm program.rcode [arguments]      # R-code (first line "RCODE n")
js/rvm -e "say 'hello'" [arguments]   # a program in a string, named INSTORE
node js/rvm.mjs [-s SOURCE] [-w] FILE [arguments]

../js/rvm.mjs (the command line):

  • FILE is used as given; if it is not a file, it is searched as an external routine is (NodeHost~findExternal with no caller: current directory, REXX_PATH, PATH; see 03-compiler.md).
  • If its text starts with RCODE, it is run as R-code. -s SOURCE names the source it was compiled from: PARSE SOURCE and error reports use that name and SOURCELINE sees its lines.
  • Otherwise it is a source, loaded by NodeHost~loadExternal: its .rcode cache when present and valid (same text hash, same RVM.Compiler~VERSION, same ISA and R-code versions), else compiled by rexx rvm.rex -p FILE. -w writes the cache of every source compiled this way (the main program and its external routines and packages).
  • -e PROGRAM compiles the string with rvm.rex -s - and runs it as INSTORE with no .SYSCARGS, as rexx -e does. The program text is taken as UTF-8 from the command line and turned into bytes.
  • The exit status is the program's exit code modulo 256; an untrapped error gives minus the error number (error 6 exits with 250, as native).
  • Before running, NodeHost~shareQueues picks up the queues and macrospace of a parent RVM (RVM_QUEUES, RVM_MACROSPACE: 13-io-and-commands.md).

The worker

rvm.mjs runs the program in a worker thread (node:worker_threads), and the main thread only waits for it. The reason is Ctrl-C: Node runs a signal handler only when its event loop is free, and the machine runs synchronously to the end (07). The main thread (launch):

  • starts the worker on rvm.mjs itself, with the arguments, the environment shared (SHARE_ENV: VALUE(..., 'ENVIRONMENT') and the commands see the same one), a SharedArrayBuffer of three cells and one of 64 KiB for standard input;
  • takes SIGINT, SIGTERM and SIGHUP: cell 0 is set (the machine takes it: interrupt.mjs) and its waiters are woken (Scheduler.sleep waits on it); a signal while cell 0 is still set ends the process with 128 + the signal number;
  • changes the directory for the worker, which cannot (process.chdir is not supported in a worker): NodeHost~chdir posts the directory and waits on cell 1 (1: done, 2: failed); process.cwd() in the worker sees the change;
  • reads standard input for an activity that waits for it (07): NodeHost~stdinFetch posts a request, and the main thread runs a reader, dd bs=65536 count=1, that inherits standard input; when it ends, its bytes go into the 64 KiB buffer and cell 2 becomes their count + 1 (1: the end; -1: nothing, the reader was killed, as Ctrl-C at a terminal does), and its waiters are woken (stdinCollect takes them, stdinWait waits on the cell). A process, because a read of the main thread could not be stopped: Node would not exit while a thread of its pool read;
  • exits with the worker's exit code, killing a reader still reading; an exception that escapes the worker is written to standard error (exit code 1).

The worker runs what rvm.mjs always ran (run). Its I/O is unchanged: the host writes and reads file descriptors synchronously (fs.writeSync, fs.readSync), never process.stdout, which in a worker is an asynchronous pipe to the main thread; whether standard output is a terminal is tty.isatty(1). Starting the worker costs about 75 ms (a second V8 isolate). RVM_WORKER=0 runs the program in the main thread, as before: a signal then ends the process.

js/rvm puts bin/ first on REXX_PATH, as ../rvm does, so a program run by the JS host can ::REQUIRES "parser.cls"; host-node.mjs also prepends bin/ for the rexx processes it spawns to compile.

runner.mjs: what every front end does

../js/runner.mjs is shared by the Node CLI, the browser and the browser's compiler:

Export Does
runProgram(text, host, programName, argument = "", sourceLines = null, syscargs = null) Reads and verifies the R-code text (readRCode), makes a Context, runs Machine.run, calls host.endProgram(), reports an untrapped error as ooRexx does (report, on the host's standard error). Returns the exit code.
compileSource(text, host, programName) Compiles a source with the host's compileSource("-", ...): { rcode, source } or { error: { code, text, line, report } }. Without a compiling host: error 93.900 "RVM: compiling a source is not available in this RVM".
reportError(host, programName, error) Reports a compilation error as native reports a translation error; returns minus the error number.
runSource(text, host, programName, argument = "", syscargs = null) compileSource, then runProgram.

runProgram is synchronous: it returns when the program and all its activities have ended (07-concurrency.md).

Compiling under Node

The Node host has native ooRexx compile, in a process of its own per request, through rvm.rex's text protocol (03-compiler.md):

Need Request NodeHost method
A source file (main program, external routine, ::REQUIRES package) rexx rvm.rex -p FILE loadExternal
A source given at run time (Method~new, Routine~new, -e, runSource) rexx rvm.rex -s OPTION, source on stdin (hex) compileSource
INTERPRET data, a line typed at an interactive-trace pause rexx rvm.rex -f, FRAGMENT kind line on stdin compileFragment

The spawned process gets REXX_PATH with bin/ first. The answer is OK plus R-code lines, or ERROR ... plus hex-encoded inserts, which the host turns into the error the program sees; any other answer (ooRexx missing, a crash of the compiler) is 93.900 "RVM: the compiler failed: ...". The compiler version used to validate .rcode caches is read from the source of RVM.Compiler.cls (::Constant VERSION), and the parser's frontier stamp from bin/resources/frontier, so a cache made by another compiler or against another parser is never used.

Cost: each request starts native ooRexx and loads the parser, about a quarter of a second. INTERPRET caches the compiled fragment per instruction and string (03-compiler.md), so a loop that interprets the same string pays once; one that interprets a different string each time pays every time.

Commands, queues, sockets under Node

NodeHost is a port of the Unix RVM.CommandHost/RVM.SystemHost: commands go through /bin/sh -c (or the named shell, or no shell for the PATH environment) with spawnSync; redirections use temporary files in TMPDIR; cd, set, export, unset without redirection run in process. Every command gets RVM_QUEUES and RVM_MACROSPACE (snapshot files) and js/rxqueue/ first in its PATH, so ... | rxqueue reaches the RVM's queues (13-io-and-commands.md). systemName() is LINUX. On Windows it follows ooRexx for Windows: systemName() is WindowsNT, sysVersion() Windows <release> (and REXXUTIL has SysWinVer instead of SysLinVer), CMD is the initial environment, commands go through cmd.exe, SETLOCAL is 0, and files have Windows's names and sharing (13).

The sockets worker

rxsock (12-libraries.md) needs BSD sockets with non-blocking calls and a select; Node only has asynchronous streams (net), datagrams (dgram) and name lookup (dns), and the RVM's machine is synchronous. The two are joined by a worker thread:

  • ../js/sockets-worker.mjs keeps a table of descriptors (lowest free from 3), each with the state a kernel keeps (bound, listening, connecting, connected, received data, pending connections, pending error, options), and implements rxsock's C side (rxsock.cpp, rxsockfn.cpp: addresses from stems, options as Linux gives them, errno names). No call blocks: one that would gives EWOULDBLOCK (EINPROGRESS for a connect). WAIT waits until one of some descriptors is ready, or a timeout.
  • ../js/sockets-node.mjs (NodeSockets, host.sockets, created on first use) posts each request on a MessageChannel and blocks the machine's thread with Atomics.wait on a shared flag until the worker has answered (receiveMessageOnPort). The worker is unrefed: it does not keep the process alive.
  • ../js/rxsock.mjs turns EWOULDBLOCK on a socket the program has not made non-blocking into an I/O wait of the scheduler (SockWait); when no activity is ready the scheduler polls through host.sockets.wait (07-concurrency.md).

Differences from a kernel, by construction: a bound stream socket is already listening (Node binds and listens at once); sent data is buffered without limit (a send never waits); servers always have SO_REUSEADDR.

Running in a browser

The bundle

../js/rvm-browser.mjs is the entry point. It exports BrowserHost, runProgram, runSource, compileSource, reportError, readRCode and sourceLines. Any ES-module bundler works; with esbuild:

esbuild rvm-browser.mjs --bundle --format=iife --global-name=RVM --minify --outfile=rvm.js

gives one script that defines the global RVM. Its graph contains no node: import. Size: about 1.5 MB unminified, 0.9 MB minified, 0.24 MB gzipped; the two embedded preludes (rvm-prelude*.mjs) are a bit over half of it. The bundle is not in the repository; it is built when needed.

Running R-code

const host = new RVM.BrowserHost({ onOut, onErr, stdin: "" });
const exitCode = RVM.runProgram(rcodeText, host, "/home/rexx/prog.rex");

onOut(text) and onErr(text) receive what the program writes (SAY and STDOUT to onOut; trace, error reports and STDERR to onErr), with line ends. stdin is the whole standard input, given before the run: the machine is synchronous and cannot wait for a user to type.

What BrowserHost provides (../js/host-browser.mjs):

  • Files in memory, shared by every host of the page: a Map from qualified name to { data, mtime } (BrowserHost.files), with the directories /, /home, /home/rexx (home and initial directory) and /tmp. They implement the same FileSystem/HostFile/FileOps interface as hostfile-node.mjs (names normalised as ooRexx's SysFileSystem::normalizePathName; errno texts for the usual errors), so streams, .File and the REXXUTIL file functions work on them. BrowserHost.reset() clears the page's files and directories (not the library).
  • Environment variables are a table per host: HOME, USER (rexx), PATH, and REXX_PATH = the library roots. A page can set RVM_CLOCK, RVM_SLICE, RVM_LOCAL there before a run (host.env).
  • systemName() and sysVersion() are BROWSER (PARSE SOURCE says BROWSER COMMAND ...).

The library and the compiler

BrowserHost.addLibrary(files, root) adds read-only files for every run: files is { relativeName: text }. A name ending in .rcode is the R-code of the package whose source has that name without .rcode (x.cls.rcode → x.cls; x.rcode → x and x.rex), and is found by that source name, as a .rcode cache is. root goes into the REXX_PATH of every host made afterwards, so programs find the library's packages.

BrowserHost.enableCompiler(driver, path) turns the compiler on: driver is the library name of rvm.rex (its R-code must be in the library), path the REXX_PATH from which its ::REQUIRES are found. It creates a Compiler that runs rvm.rex on the JS RVM, in a world of its own (its own BrowserHost, whose output is collected), answering the same -f, -s OPTION, -p FILE requests as native ooRexx does under Node. The world is kept between requests: the parser and compiler packages load once (about 2 s on the first compilation), and later compilations only parse and compile (tens of milliseconds for a short program). Every BrowserHost created after enableCompiler gets compileFragment and compileSource; loadExternal compiles sources with Compiler~file. A request while the compiler is running is 93.900.

RVM.BrowserHost.addLibrary(lib, "/rvm/bin");
RVM.BrowserHost.enableCompiler("/rvm/bin/modules/rvm/rvm.rex", "/rvm/bin");
const host = new RVM.BrowserHost({ onOut, onErr, stdin });
const code = RVM.runSource(sourceText, host, "/home/rexx/prog.rex");

With the compiler, a page has INTERPRET, Method~new/Routine~new from source, interactive trace (typed lines are read from stdin), external routines and packages from their source, and ::REQUIRES of the parser's own packages.

Building the library. The library is the R-code of rvm.rex and of every package it requires (the Rexx Parser and the RVM compiler), as written by the R-code caches. A recipe, working on a copy of bin/ so that no cache is written into the repository:

cp -r PROJ/bin LIB                      # a scratch copy
export PATH=LIB:$PATH                   # so the JS host finds the packages
rexx LIB/modules/rvm/rvm.rex -c LIB/modules/rvm/rvm.rex      # -> rvm.rcode
printf 'FRAGMENT I 1\nx\n\n4E4F50\n' |
  node LIB/modules/rvm/js/rvm.mjs -w -s LIB/modules/rvm/rvm.rex \
       LIB/modules/rvm/rvm.rcode -f > /dev/null               # x.cls.rcode caches

The second step runs the compiler on the JS RVM once (compiling the fragment NOP), which loads every package through rvm.rex -p and, with -w, writes each one's .rcode next to it. Then collect every *.rcode under LIB except prelude* into one JSON object keyed by the path relative to LIB, and add the two Unicode data files the parser only checks for, as empty strings (parser/resources/UnicodeData-15.0.0.txt, parser/resources/NameAliases-15.0.0.txt). The result is about 35 files, 5.8 MB of JSON; building it takes a few minutes. The page then calls addLibrary(json, "/rvm/bin") as above.

What is not available in a browser, and why

Feature In a browser Reason
Commands (ADDRESS, command instructions) Every environment is unknown: RC 30, FAILURE (13-io-and-commands.md) A page cannot start processes (strategyFor returns null, run starts nothing).
INTERPRET, run-time sources, interactive trace, external routines from source Only with the compiler; otherwise 93.900 "RVM: INTERPRET is not available in this RVM" / "compiling a source is not available", pauses do nothing, externals must be .rcode Compiling needs the parser and compiler, which the page must provide.
rxsock 98.903 (library not loaded) No sockets in a page; there is no host.sockets.
Queues and macrospace shared with other processes Not applicable No commands, no RVM_QUEUES/RVM_MACROSPACE.
Interactive standard input stdin is fixed before the run The run is synchronous.
.RexxInfo~executable, ~libraryPath .nil BrowserHost has no rexxInfo; the other .RexxInfo values take Unix defaults.
Real files In-memory only —
RVM_TBCHECK Ignored Read from process.env only.

rxmath, rxregexp, hostemu and REXXUTIL work (REXXUTIL's file functions on the in-memory files; SysVersion is BROWSER). Waits (SysSleep, Alarm, TIME-based timers) use Atomics.wait where a thread may block; on a page's main thread, where it may not, they busy-wait, and the page does not respond until the run ends.

Generated modules

Three modules are generated from ooRexx-side data and must never be edited by hand. All three carry a CPL header written by their generator (CPLHeader), because their content comes from ooRexx (19-licensing.md).

Module Generator Content Regenerate when
../js/rvm-data.mjs ../js/gendata.rex ERROR_TEXT (ERRORTEXT 0–99), SECONDARY (the host's ErrorText(major.minor) of every code 0.1–99.999 that has one), BIF_INFO (.Parser.BIFInfo: min, max, argument types per BIF), MESSAGES (the interpreter's numbered messages for REXXUTIL's SysGetMessage) ooRexx's error texts (a new revision with new messages) or the Rexx Parser's BIF table (BIFs.cls) change.
../js/rvm-prelude.mjs ../js/genprelude.rex PRELUDE_RCODE: the text of ../prelude.orx.rcode prelude.orx changes, or anything that changes the R-code the compiler makes for it (compiler, ISA, R-code format).
../js/rvm-prelude-streams.mjs genprelude.rex PRELUDE_STREAMS_RCODE: the text of ../prelude-streams.orx.rcode The same, for prelude-streams.orx.

The prelude chain and the role of the preludes are described in 10-prelude-and-classes.md; the JS machine loads PRELUDE_RCODE (and then PRELUDE_STREAMS_RCODE) when a run first needs the prelude, exactly as the ooRexx host loads the .rcode files. genprelude.rex replaces the PROGRAM line by PROGRAM "REXX" (the name of the package) and writes each line as a JS string literal (bytes outside " ".."~" as \u00XX).

Exact commands

From bin/modules/rvm/. The R-code of the preludes is made with the ooRexx host (./rvm sets REXX_PATH; rexx rvm.rex needs bin/ on REXX_PATH). CoreClasses.orx and StreamClasses.orx are ooRexx's (interpreter/RexxClasses/ in the ooRexx source tree), not in this repository: 10 says how to export them, and how to rebuild prelude.orx without them when only prelude-rvm.orx changes.

# the prelude
rexx makeprelude.rex .../RexxClasses/CoreClasses.orx > prelude.orx
./rvm -l prelude.orx > prelude.orx.rcode                 # about 10 s
(cd js && rexx genprelude.rex ../prelude.orx.rcode > rvm-prelude.mjs)

# the streams program
rexx makeprelude.rex .../RexxClasses/StreamClasses.orx streams > prelude-streams.orx
./rvm -l prelude-streams.orx > prelude-streams.orx.rcode
(cd js && rexx genprelude.rex ../prelude-streams.orx.rcode PRELUDE_STREAMS_RCODE \
          > rvm-prelude-streams.mjs)

# the tables (needs bin/ on REXX_PATH for parser/BIFs.cls)
(cd js && REXX_PATH=$(cd ../../.. && pwd) rexx gendata.rex > rvm-data.mjs)

gendata.rex fills MESSAGES from the running ooRexx's own SysGetMessage (Unix message catalog); on an ooRexx without it the table is empty. On an unchanged tree all three commands reproduce the files byte for byte, which is a quick check that the toolchain is right.

Any change that alters a .orx or the compiler's output requires the .rcode and the .mjs to be regenerated in the same change; otherwise the two hosts run different preludes (20-maintaining.md).

How the JS host represents what ooRexx provides

The ooRexx host is a Rexx program and leans on native ooRexx for strings, collections, files and some libraries; the JS host has to write each of these itself. Value semantics are identical (02-values-and-arithmetic.md).

Concept ooRexx host JS host
Byte string the host's .String a JS string with one character per byte (0–255); latin1 at every I/O boundary; UTF-8 for environment variables and command lines
Number RVM.Number / RVM.Integer (digit strings, host arithmetic on whole numbers at DIGITS 40) RexxNumber / RexxInteger (digit strings; BigInt for long digit operations and wholes)
A string too long for the host memory-bound JS RangeError → Rexx error 5
RVM object, class, method RVM.Obj, RVM.ClassData, RVM.Method Obj, ClassData, Method
.nil an RVM.Obj of the world an Obj of the world
Variable frame RVM.Vars (a Directory: name → RVM.Var) Frame (array of cells indexed by slot)
Array contents the host's .Array (V.HOST natives) RArray, a port of ArrayClass.cpp (multidimensional included)
List, Queue the host's .List/.Queue (HostCollection) RList (port of ListContents), RQueue
Set, Bag, Relation, Directory, Table... the host's collections RHash (port of HashContents); RexxMap/HashShadow reproduce ooRexx's iteration order; stringHash is getStringHash
MutableBuffer RVM.MBuffer MBuffer
Rexx error inside the RVM a host SYNTAX condition (Raise Syntax) a JS exception, RexxError (../js/errors.mjs)
Files RVM.HostFile over a host .Stream HostFile over fs (hostfile-node.mjs, with ooRexx's 4096-byte write buffering), or in memory
Commands RVM.CommandHost (host ADDRESS SYSTEM) NodeHost.run (spawnSync of /bin/sh)
Clock host TIME/DATE performance.timeOrigin + performance.now(), µs since 0001-01-01 as BigInt
Sleeping host SysSleep Atomics.wait (busy-wait where a thread may not block)
rxmath the host's rxmath library, after the RVM's argument checks computed in JS (rxmath.mjs), emulating the x87 long double of its angle conversions
rxregexp the host's RegularExpression methods (RVM.RxRegExpHost) a port of rxregexp.cpp, automaton.cpp, dblqueue.cpp (Automaton)
rxsock the host's rxsock (sockets always non-blocking) the sockets worker
Compiler in process (RVM.Compiler) rexx rvm.rex subprocess, or compiler.mjs
Error texts, BIF signatures the host's ErrorText and the parser's .Parser.BIFInfo, live rvm-data.mjs, generated from them
Prelude prelude*.orx.rcode files rvm-prelude*.mjs, embedded

Design notes

  • A faithful port, not a re-design. Each JS module mirrors one ooRexx file and keeps its method names (camel-cased), so a change is made in both hosts at the same place and a divergence between them is a bug. The second host is what proves the R-code is self-contained: anything the ooRexx host got implicitly from native ooRexx had to be made explicit to be ported.
  • The core never touches the system. Everything goes through the host object and the installed file layer, so one core serves Node and the browser, and a third host (another runtime, a test double) needs only the members listed in the host interface.
  • Everything is synchronous. The machine loop, like the ooRexx host's, calls the host and expects an answer; making the host asynchronous would turn every function on the call path into an async one and break the method-by-method correspondence. Rexx concurrency is the RVM's own scheduler (07-concurrency.md), not the JS event loop. Consequences: Node uses readSync, spawnSync and, for sockets, a worker answered through Atomics.wait; a page gives standard input up front and is busy while a program runs.
  • Strings are binary JS strings, not Uint8Arrays: JS string operations are fast and give byte semantics for free (comparison is code-unit comparison), and latin1 maps bytes 0–255 one to one.
  • No compiler in JS. The compiler is a Rexx program over the Rexx Parser's AST. Under Node, native ooRexx runs it (the oracle compiles); in the browser, the JS RVM runs the same R-code of the same compiler. There is one compiler and every host gets identical R-code for the same source.
  • Tables and preludes are generated, not read at run time. The JS host cannot load .cls packages or rexxmsg.xml; generating rvm-data.mjs and embedding the prelude R-code keeps the browser free of file access at startup and keeps Node and the browser identical.
  • Collections are ported, not mapped to JS Map/Array. Iteration order of hashed collections, index rules and error behaviour must match ooRexx's; RexxMap/HashShadow reproduce ooRexx's hash-table order on top of JS maps.

Known gaps

  • Under Node, every compilation (a source, INTERPRET of a new string, a run-time source, a typed trace line) spawns native ooRexx: ooRexx must be installed, and each one costs about a quarter of a second.
  • A Ctrl-C while the machine is blocked (a read of a pipe with nothing else to run, a command waited for, a long native operation) is a HALT only when it unblocks; a second one ends the process (17). A read of a terminal, or one that lets other activities run, waits for the reader and is cut short (07).
  • NodeHost knows Unix (as LINUX) and Windows; on Windows, commands do not share the RVM's queues and macrospace.
  • In a browser: no commands, no rxsock, no interactive standard input, .RexxInfo~executable/libraryPath are .nil, waits busy-wait on the main thread, and sources compiled by the browser's compiler are not cached. Without the compiler, no INTERPRET, run-time sources or interactive trace.
  • RVM_TBCHECK works only under Node.
  • Sockets emulated by the worker differ from a kernel's: a bound stream socket already listens, sends are buffered without limit, servers always have SO_REUSEADDR.
  • The browser host has been exercised under Node and in Chromium-based browsers only.