5. The machine


5. The machine

This chapter describes how R-code runs: the dispatch loop and its registers, activations, variables and stems, the call/return/signal/exit family, PARSE, NUMERIC and TRACE (including interactive trace), synchronous execution for natives (runSync, sendSync), and program startup and shutdown. It assumes the instruction set of chapter 4 and the value model of chapter 2. Conditions and the error report are in chapter 6; activities, scheduling, locks and GUARD are in chapter 7; message sends and methods in chapter 8.

Both hosts implement the same machine; names below are given as ooRexx host / JS host.

Piece ooRexx host JS host
Machine (loop, registers) RVM.Machine (run, execute) in ../RVM.Machine.cls Machine in ../js/machine.mjs
Execution state of an activity RVM.Context (subclass of RVM.BaseContext, ../RVM.BaseContext.cls) Context in ../js/context.mjs
Machine frame (return information) RVM.Frame MFrame
Saved caller state RVM.Activation Activation (context.mjs)
Activation as seen by .CONTEXT/StackFrame RVM.Level (../RVM.Objects.cls) Level (context.mjs)
Variable RVM.Var cell { v }
Variable frame RVM.Vars (a Directory: name → RVM.Var) Frame (cells[slot])
Stem / compound RVM.Stem, RVM.TailNode Stem, TailNode
Block descriptor RVM.Block Block
PARSE state RVM.Parse, RVM.ParseTarget ParseState, ParseTarget
Driver ../rvm.rex ../js/runner.mjs (runProgram)

Program startup and shutdown

Drivers. rvm.rex (ooRexx host) compiles the source with the parser and RVM.Compiler (or takes an up-to-date .rcode cache, see chapter 3), writes the R-code text with RVM.RCode~write, reads it back with RVM.RCode~read into an RVM.Program, makes an RVM.Context (program name, source lines for SOURCELINE, the argument string, .SYSCARGS) and calls .RVM.Machine~run(program, context). runProgram in runner.mjs does the same from R-code text in JS (runSource compiles first through the host's compileSource). A program always runs from its R-code text, never from compiler objects.

run (both hosts, class/static method):

  1. Makes the scheduler (RVM.Scheduler / Scheduler), reads RVM_SLICE and RVM_CLOCK (chapter 7), applies the main program's ::OPTIONS to the context (applyOptions), and creates the main activity. RVM_LOCAL=eager builds .LOCAL at once (as ooRexx); otherwise it is built on first use.
  2. Loops: run the current activity (launch → execute / execute) until it waits (WAITING) or ends (ENDED, FAILED); an ended activity goes through EndActivity / endActivity, which reports its error, if any; then the next ready activity runs.
  3. When no activity is ready, objects due an UNINIT get it in an activity of their own (uninitActivity / uninitNext); when there is none, the run is over. Activities still waiting are abandoned (native ooRexx would wait forever).

Package start. The first time a program's code runs (state NEW or LOADING), StartPackage / startPackage checks its EXTERNAL routines and methods, then loads each ::REQUIRES in order: a library (RVMLibrary) is registered; a Rexx package is loaded once (LoadPackage), started recursively and its prolog run in an activation of kind REQ (PARSE SOURCE REQUIRES, no arguments, result discarded). A package found in state LOADING is a circular require: 98.952. Then the classes are made (World~install, by messages) and the program becomes READY. With ::OPTIONS NOPROLOG, a required package returns as soon as its classes are made. Details of loading and visibility are in chapter 3 and chapter 9.

The prelude (the REXX package, chapter 10) is loaded lazily, the first time the world needs an object feature (RVM.World~ensurePrelude): a program that uses no objects never pays for it. Its prolog runs with runSync (see below).

Shutdown and exit code. RETURN or EXIT in the main program sets context~exitCode to the string of its value (QuietString: converting it never raises NOSTRING) or ""; Finished pops any open activations and the activity ends. The driver exits with that value when it is a whole number (JS: wholeExit, truncated to 32 bits), else 0. An untrapped error is reported (ErrorReport / report, chapter 6) and the exit code is minus the major error number. The main program's error is raised out of run to the driver only when no other activity is alive and no UNINIT is due; otherwise it is reported when the activity ends and the run goes on (as native ooRexx). SystemHost~endProgram / host.endProgram flushes and closes host resources.

The execution loop

Registers

The machine's state for one activity:

Register Meaning
code, consts, names, clauses, labels, withs tables of the program running (SwitchProgram reloads them)
pc next instruction (1-based in both hosts)
stack, sp operand stack: values (strings, numbers, objects) and "none" (.Nil / null, an omitted argument)
frames machine frames of the open activations (also context~frames, read by tracebacks)
descs block descriptors of the current activation
parse PARSE state of the current activation
labels labels of the body running (a program's prolog, a ::ROUTINE, a method)
curMethod, curFrame, curSender the method running, its variable frame, its receiver (private-method checks)
entryAllowed, entryDone, entryClause, entryText entry/exit trace of a routine or method (>I>, <I<)
exitVal, again, pendingFlow, fromLabel, atStart EXIT value, resume address after CALL ON traps, a flow change waiting for traps, label trace after SIGNAL/CALL, "clause started traced"
pauses, jumpMark, iheld, iflow, traceIgnored, cmdTraced interactive trace
insPc, insSp, convPc, convSaved the instruction running and its stack depth; string conversions (see NeedString)
sliceLeft, act, resumeAt time slice, the activity, where to resume after a wait

In the ooRexx host the registers are local variables of RVM.Machine~execute (one method holding the whole loop). In the JS host they are fields of the Machine; loop() caches pc and sp in locals and writes them back (sync()) before anything that can leave the loop, reading them again afterwards (load()).

Dispatch

Each iteration fetches code[pc], records insPc/insSp, increments pc and dispatches on the opcode (Select Case / switch). An unknown opcode is 93.900. The compiler keeps the stack balanced per clause: between clauses it is normally empty; a value that lives across an interactive-trace pause point (e.g. an IF condition) is recorded by the pause, so that = can drop it.

CLAUSE n k starts every clause and is the single hook for: counting the time slice (yield when it reaches zero and another activity is ready); running pending CALL ON traps (and a pending HALT) of the previous clause (then the CLAUSE itself runs again); setting the current clause (its line is SIGL, the error line and the clause time stamp); the entry trace rule; and clause tracing according to k (N, W, E traced under TRACE A; C under TRACE C). LABEL and BOUND are the other boundaries where pending CALL ON traps run; they also run before RETURN, EXIT and SIGNAL (see chapter 6).

Blocks. There is no runtime block stack. BASE d creates descriptor d (RVM.Block/Block: trace indentation base, control value, TO, BY, FOR, first, CASE value, OVER items, COUNTER, DO WITH supplier state); LEAVE, ITERATE and SIGNAL are plain jumps. A CALL saves descs in the machine frame and the callee starts with none.

Leaving the loop. Instructions that change activation or program, or wait, are handled outside the instruction switch:

Situation ooRexx host (labels in execute, reached by Signal) JS host
return, delivery DoReturn, Deliver doReturn, deliver
EXIT unwinding ExitUnwind exitUnwind
CALL ON handlers RunTraps, CallTrap, TrapRoutine, TrapDone runTraps, callTrap, trapRoutine, trapDone
routines, programs CallRoutine, EnterProgram, StartPackage, LeaveProgram same names, camelCase
messages DoSend, SendLoop, EnterMethod, NeedString doSend, sendLoop, enterMethod; NeedString exception
errors Failed, FailedUnwind (Rexx Syntax condition) failed, unwind (RexxError exception)
wait Suspend (saves .context~variables in act~regs, returns WAITING; resumed by Signal Value act~resumeAt) suspend (stores a resume closure, throws WAITING)
end Finished finished (FINISHED symbol)
program switch SwitchProgram (registers reloaded in place) SWITCH symbol: executeBody re-enters loop() with the other program's tables

The ooRexx handlers return to the loop with Signal Resume, which also re-arms Signal On Syntax Name Failed.

NeedString: re-executing an instruction

When an instruction must convert an object whose STRING (or MAKESTRING for a REQUEST) method is written in Rexx, the conversion raises RVM.NeedString (a SYNTAX condition with that description / a NeedString exception). The machine abandons the instruction (sp = insSp, pc = insPc), sends the message, caches the result in RVM.Obj~conversions/requests (JS CONVERSIONS, REQUESTS, keyed by object), and runs the instruction again; this time the conversion finds the cached string. The cache lasts for one instruction (convPc). While the STRING method runs, the interrupted instruction's conversions are pushed on convSaved and restored on delivery, so an instruction can convert several objects in turn. This requires every instruction to check all its operands before any side effect. An operator whose left operand is an object is a message to it (SendOperator / sendOperator), whose result lands where the operation's would.

Activations and frames

An activation exists in three parallel stacks, pushed and popped together:

  1. Machine frame (RVM.Frame / MFrame, in frames): where to return (returnTo), the caller's descs, parse, sp, iheld, atStart, and, for an activation in another program, the caller's program, name, source, invocation, labels, method, entry-trace state. Its kind is:

    kind made by
    SUB, FUNC CALL / function call (internal; also external, with program set)
    TRAP a CALL ON handler (trap, rest: the traps still to run)
    REQ a ::REQUIRES prolog
    RCALL Routine~call, or a package prolog run because a native loaded it (override, addTo)
    METHOD a method written in Rexx
  2. Saved caller state (RVM.Activation, in callStack, pushed by pushActivation): the caller's variable frame, arguments, NUMERIC DIGITS/FUZZ/FORM, ADDRESS (current, alternate, WITH configurations), trap table and its ownership, condition, pending CALL ON traps, current clause, clock (clause time stamp, elapsed timer), TRACE setting and indentation, active INTERPRETs, interactive debug state, ::OPTIONS ... SYNTAX conditions, security manager, stream scope. popActivation restores all of it. What is not saved is shared by the whole activity or run: output, data queue, command host, streams, RANDOM seed, clause texts.

  3. Level (RVM.Level / Level, in context~levels): what .CONTEXT, StackFrames, TRACEBACK and locks see (type PROGRAM, ROUTINE, METHOD, INTERNALCALL, INTERPRET; name, executable, arguments, .RS, pool, lock, HALT and FORWARD state). pushActivation makes an INTERNALCALL level (inheriting .RS); EnterLevel retypes it as ROUTINE or METHOD; popActivation closes it, its INTERPRET levels and releases its lock.

Internal call (CALLI, FUNCI, CALLN): new machine frame, pushActivation(args), SIGL set to the line of the call, pc = label. The callee shares the caller's variable frame until it runs PROCEDURE; it inherits the caller's settings, which RETURN restores.

Program-level activation (external routine, ::ROUTINE, ::REQUIRES prolog, Routine object): EnterProgram also calls startProgram, which gives a fresh variable frame and program-level settings (NUMERIC 9/0/ SCIENTIFIC, TRACE N, empty trap table, no condition, indentation 0, fresh elapsed clock) and then applies the target package's ::OPTIONS (applyOptions; ::OPTIONS NUMERIC INHERIT takes the caller's NUMERIC). A ::ROUTINE, a Routine object, a required prolog and a method start with the default ADDRESS; an external program file keeps the caller's ADDRESS (native callExternalRexx passes currentAddress). The program registers are switched (SwitchProgram) and restored on return (LeaveProgram). A method activation (EnterMethod) is similar, with its own variable frame bound to the object's pool and SELF/SUPER (chapter 8).

AtMain / atMain() is true when the current activation is the main one of its program: the bottom one, an external routine's or a method's.

Depth limit. More than RVM.Machine~maxDepth / MAX_DEPTH (10000) machine frames in one activity raises 11.1. Native ooRexx reaches 11.1 at about 22000 nested calls, when its C stack is nearly full.

Variables and stems

Cells

A variable is an object holding a value, as ooRexx's RexxVariable: RVM.Var (value, .Nil = no value) / a JS cell { v } (undefined = no value). A variable frame maps names to cells: RVM.Vars is a Directory keyed by the uppercased name; the JS Frame is an array of cells indexed by slot. Slots are a per-program numbering of variable names made by the compiler (the names table of R-code); a name first seen at run time (VALUE(), INTERPRET data, an EXPOSE list) gets a new slot (Program.slot). The ooRexx host keys by the slot's name (names[ins[2]]); the JS host indexes by slot.

Every frame that holds a cell shares it: EXPOSE, PROCEDURE EXPOSE and VariableReferences (>x) all work by putting the same cell in another frame. Nothing is copied back on return.

Context methods: setVar, getVar (unset → the uppercased name), lookupVar (unset → .Nil/null, the caller raises NOVALUE), dropVar, isSet, variable (cell, created valueless: for >x). JS adds slot-based versions used by the machine (lookupSlot, setSlot, dropSlot, stemAt, ...). An unset simple variable read by LOADV raises NOVALUE (NoValue / noValue; with ::OPTIONS NOVALUE SYNTAX, 98.986) and yields its name.

Stems

A stem variable lives under its key with the dot (A.), separate from the simple A. Its cell holds a stem object (RVM.Stem / Stem), created on first reference. The stem has a name, a default value (dropped when none) and its tails, kept in a port of ooRexx's CompoundVariableTable: a balanced tree of TailNodes (findEntry, balance, moveNode; tails compare by length, then bytes) plus an index by tail; traversal (nodes) is the native's post-order, so DO OVER, ALLINDEXES, MAKEARRAY give tails in native order. A node's value is RVM.Dropped/DROPPED when it has none.

Operation Effect
read a.t (LOADC) node value; else the default; else NOVALUE and the derived name A.t
a.t = v (STOREC) setTail on the node's real variable
drop a.t node value = dropped (reads as its name even with a default)
a. = v (STORES) v a Stem object: the cell now holds that same stem (a. = b. aliases); otherwise a new stem with default v
drop a. a new empty stem without default
read a. (LOADS) the Stem object; never NOVALUE

Tails are passed already derived (each component resolved), so a.007 and a.7 are different tails. The compiler pushes the tail pieces; LOADC, STOREC, DROPC, EXPC, PWORDC concatenate them.

EXPOSE and PROCEDURE

PROCEDURE (PROC) is valid only as the first instruction of an internal call, as native: the machine sets procValid on the new activation when the call (CALLI, FUNCI, CALLN, or a CALL ON trap) lands on LABELs, CLAUSE, PROC (ProcedureFirst / procedureFirst, native's look-ahead in RexxActivation::run), and PROC raises 17.1 when it is not set (a PROCEDURE after another instruction, a second one, one in the main program or in an external routine) and clears it. The flag is saved and restored with the activation, so a CALL ON trap that runs at the boundary before the PROCEDURE does not clear it. Then PROC remembers the caller's frame (callerFrame), installs a fresh frame (freshFrame) and is followed by the exposures:

Opcode Effect
EXPV v fresh frame gets the caller's cell (created valueless if absent)
EXPS a. the same for a stem (creating the stem if needed)
TAILC v push the value of a tail variable in the caller's frame
EXPC a. n expose one compound: ExposeCompound gets the caller stem's node (exposeTail: an absent node takes the stem's default) and makes the callee stem's node point to it (shareTail: TailNode~real)
EXPI x EXPOSE (x): x is exposed first (by a preceding EXPV); its value is split into names, all validated before any is exposed (31.3, 31.2, 20.928: ExposeNames), then each is exposed in order (ExposeWord)

Order follows native ooRexx, not the text: the compiler emits lists first (last list first) then simple names (ExposeOrder, chapter 3). A tail is resolved with the variables visible at that moment (expose i a.i uses the exposed i). An exposed compound shares the node: DROP, assignment and a. = x in the callee act on the caller's variable. If an unset x in EXPOSE (x) raises a NOVALUE that a SIGNAL ON trap catches, the fresh frame is emptied first (as native: nothing stays exposed).

In a method, EXPOSE (EXPO, EXPOS, EXPOC, EXPOI) shares cells of the object's variable pool for the method's scope (RVM.MethodFrame~share / poolCell); outside a method it is 98.992. USE LOCAL (USEL) declares the listed names (plus RC, RESULT, SIGL, SELF, SUPER) local; every other name becomes the object's variable on its first reference (RVM.MethodFrame~resolve / Frame.auto), whatever the access (read, assignment, DROP, VALUE(), PARSE and USE ARG targets, tails, loop control variables). Outside a method: 98.993. See chapter 8.

VariableReference. VREF (>x, >a., <x) pushes a reference to the cell (made valueless if absent). USE ARG >v / >s. (USEREF, UseRef / useRef) checks the argument (88.931 omitted, 88.928 not a reference, 88.929/88.930 stem/simple mismatch) and that the local can be aliased (local, no value; a stem must be empty with its own name as default: else 98.995), then puts the referenced cell in the frame (alias; the original name is kept for .context~variables). See chapter 9.

Calls, returns, SIGNAL and EXIT

Which call opcode is decided by the compiler (chapter 3): CALLI/FUNCI for a label of the body, CALLB/FUNCB for a built-in function, CALLNS/FUNCNS for ns:name, CALLX/FUNCX for anything else, CALLN for CALL (expr) (label, then BIF, then routine search; label and BIF names are matched exactly).

Routine search for CALLX (CallRoutine / callRoutine): a ::ROUTINE of the program or a public routine of a package it requires (RVM.World~findRoutine, case-insensitive); otherwise the activation's security manager (CALL); a macrospace macro with "before" order; a REXXUTIL routine; a routine of a loaded library; an external program file (LoadExternal / loadExternal, searched by FindExternal / the host's findExternal; then the parents of a program compiled at run time); a macro with "after" order; else 43.1. FindExternal is extension-major: for each extension in turn (none other when the name already has one; otherwise .cls first for a ::REQUIRES, then the caller's, .REX, .rex, none) it tries the name as given and then in lower case, in each directory in turn (the caller's directory, the current directory, REXX_PATH, PATH, split at :, on Windows at ;; a name starting with /, ~, ./ or ../, and on Windows one with a drive or starting with \, .\ or ..\, only there; on Windows the caller's directory ends at its last / or \). A name found that is not a file ends that name's search. Sources are searched first, then their .rcode caches. Native routines (REXXUTIL, libraries) run at once with a "Compiled routine" line in the traceback and may make the activity wait (chapter 12).

External program semantics. The external program runs as a SUBROUTINE or FUNCTION activation with fresh variables and program-level settings, the caller's ADDRESS, the shared queue and streams; SIGL is not set; EXIT returns to the caller; a function returning nothing is 44.1. Each call gets a fresh package (FreshProgram → RVM.Program~fresh / Program.fresh): a clone of the program read and verified once, with its own classes, clauses, labels and caches. As native reads and translates the file at each call, the RVM reads it again at each call and compiles it again only when its text is not the one it was loaded from (LoadProgram with reread / loadProgramFile with host.externalText; a .rcode file is compared the same way), so a file rewritten between two calls runs its new text, and an unchanged one costs a read. A ::REQUIRES package is loaded once per run, as native. On successful return its public classes and routines are merged into the caller's package (World~mergePackage, first wins), as native mergeRequired.

RESULT and return values (DoReturn / doReturn). A SUB return sets RESULT to the value (an object stays an object; a string value as string) or drops RESULT; a FUNC return pushes it, or raises 44.1 when there is none. REQ discards it; RCALL and METHOD deliver it as the message result; a TRAP frame ignores it, re-enables the trap (ON) and runs the next pending handler or resumes at again (the instruction that ran the traps runs again). A pending RAISE ... RETURN condition is raised in the caller after the pop (chapter 6). RETURN in the main program ends it as EXIT does. After REPLY, a RETURN with a value is 98.936 and an EXIT with a value 98.937 (chapter 7).

EXIT (ExitUnwind / exitUnwind). The value can be any object. In an internal routine, activations are popped (pending CALL ON traps of intermediate levels are lost, as native) until AtMain; there the pending traps run, and then: at the bottom, the program ends with the value as exit code; in an external program or a method, the value is returned to its caller as by RETURN. EXIT and RETURN end interactive debug of their activation.

SIGNAL (SIGNAL, SIGNALV): runs pending CALL ON traps first; looks the label up in the body's labels (16.1 if absent); sets SIGL; resets the trace indentation to 0 unless inside INTERPRET data; leaves all active INTERPRETs of the activation; jumps. It does not leave the activation. SIGNAL ON traps are in chapter 6.

INTERPRET (INTERP, IEND). The data string is parsed with the labels of the running body and compiled as a fragment appended to the running program (Interpret/LoadData; JS: the host's compileFragment and appendFragment), ending with an IEND that jumps back; the address is cached per INTERP site and data string (icache). The fragment shares everything with the activation; its clauses report the INTERPRET's line; an INTERPRET has its own level (a StackFrame) while it runs. Translation restrictions are the parser's (chapter 3). In JS, INTERPRET needs a host that can compile: under Node compileFragment runs rexx rvm.rex -f in a child process; in the browser it uses the in-browser compiler (../js/compiler.mjs) when loaded. Without one, INTERPRET raises 93.900.

PARSE

PSRC variant flags (or PSRCV for VAR/VALUE with the value on the stack) starts a PARSE: a new RVM.Parse/ParseState with the UPPER/LOWER/CASELESS flags and the source strings: ARG (one per argument; omitted → ""), VAR / VALUE (traced >K>), PULL (queue head, or a line of standard input when the queue is empty, NOTREADY at its end), LINEIN, SOURCE (<system> <invocation> <program name>: invocation is COMMAND, SUBROUTINE, FUNCTION, METHOD or REQUIRES), VERSION. PTPL k selects template k's source (case-converted, traced >>>) into a ParseTarget, a port of ooRexx's RexxTarget. Patterns: PSRCH (string search, caseless if asked), PABS/PFWD/PBWD/PFLEN/PBLEN (positional; the value must be a non-negative whole number, else 26.4). Targets: PWORD/PREST (simple), PWORDC/PRESTC (compound: tail resolved at assignment time, so parse value '2 u' with i a.i sets A.2), PWORDS/PRESTS (whole stem: sets a new stem's default), PWORDM/PRESTM+PTRM (message term), PDOTW/PDOTR (placeholder ., traced >.> under TRACE I).

PARSE VERSION gives RVM.Context~VERSION / VERSION in context.mjs, of the form REXX-RVM-<target>-<version> <language level> <date> with target ooRexx or JavaScript; .RexxInfo~name returns the same string.

NUMERIC per activation

DIGITS, FUZZ and FORM are context attributes saved by pushActivation and restored by popActivation: an internal routine starts with the caller's settings and its changes are undone on return. A program-level activation starts with 9/0/SCIENTIFIC overridden by its package's ::OPTIONS (or the caller's, with NUMERIC INHERIT). NUMDIG/NUMFUZZ (Numeric routine): non-negative whole number (26.5 / 26.6), DIGITS ≥ 1, FUZZ < DIGITS (33.1); without an expression the package default. NUMFORM (NumericForm): SCIENTIFIC, ENGINEERING, or VALUE that must be exactly one of them (25.11); no value → package default. PUSHN caches the parsed numeric literal per address keyed by (DIGITS, FORM). Arithmetic itself is in chapter 2.

TRACE

Settings

The setting is per activation (saved/restored like NUMERIC; program-level activations start with their package's ::OPTIONS TRACE, default N). setTrace ports ooRexx's parseTraceSetting: each leading ? toggles the debug request; the first letter must be one of ACEFILNOR (24.1); "" is N; ? alone toggles debug (not with O); O turns debug off. setTraceFlags derives the flags:

flag settings traces
traceA A R I every clause
traceR R I results (>>>, >=>, >K>...)
traceI I intermediate values (>V>, >L>, >O>, >C>, >F>...)
traceL A R I L labels; routine/method entry and exit
traceC A R I C commands
traceE / traceF E / E F N failing commands
pausing / pauseL ? with A R I / with A R I L interactive pauses

TRACE n (numeric) is valid only at an interactive pause (24.901): it skips the next n pauses, and with n < 0 also suppresses tracing meanwhile (DebugSkip).

Output

Trace lines go through traceOut (silent while a typed debug line runs or under negative skip) to traceRaw, which turns characters below blank (except tab, LF, CR) into ? and writes to .TRACEOUTPUT as a TraceObject when that is observable, else straight to standard error (fast path; see chapter 13). Formats (clauseTraceLine, traceValue, traceTagged):

     3 *-* y = x + 1                      -- Right(line,6) "*-*" + 1+2*min(indent,20) blanks + clause text
       >V>   X => "1"                     -- 7 blanks, prefix, 3+2*indent blanks, tag, value
       >>>   "2"

The indentation (traceIndent) is one more per call and follows the blocks through the compiler's INDENT, UNINDENT, UNIND2, BASE, SETIND, DOBODY, DOEXIT instructions. The clause text is the source from its first token to its end (clauseText); an INTERPRET fragment's clauses carry the INTERPRET's line. An assignment's result is traced only if its clause started traced (RESA, atStart). When a program-level activation starts tracing labels in its first instruction (or its package traces), its entry is shown as >I> Routine "f" in package "f". (methods: >I> Method ...) and its exit as <I<; an EXPOSE before the first instruction does not count (CLAUSE c E).

Interactive trace

The compiler emits pause instructions where native ooRexx pauses (after most instructions; IF/WHEN after the condition; SELECT on entry; DO on its first execution; never on THEN/ELSE/OTHERWISE/END); the machine pauses only when pausing holds:

Opcode Pause
PAUSE a after an instruction; = goes to a
BPAUSE a d b in a block; = drops d stack values and restores block b's indentation
DOPAUSE a d DO, first execution only
IPAUSE a before INTERPRET (a flow change typed there waits for the data)
TPAUSE a a TRACE instruction in debug changes nothing and pauses
CPAUSE a after a traced command
JMARK/JPAUSE LEAVE/ITERATE pause where they land
LABEL labels traced under ?A ?R ?I ?L pause

PauseStart (DebugStart: skips if a typed line is running, after a bypass, or under TRACE n; prints the +++ Interactive trace. prompt once) records the pause and reads a line (DebugLineIn: from .DEBUGINPUT when it is not the original monitor, else standard input; JS host.readStdinLine). An empty line continues; = re-executes from the pause address; any other line is compiled like INTERPRET data ending in DEND (DebugCompile), runs untraced with debugPause set (pending CALL ON traps of the paused clause are held aside), and the machine reads again. A SIGNAL, RETURN or EXIT typed at a pause goes through DebugFlow/DoFlow (held until the data ends at an IPAUSE; a SIGNAL to the label that comes next anyway keeps the pause, as native); an error in a typed line is shown (+++ Interactive trace. Error ...) and the pause continues. A command typed at a pause raises no ERROR/FAILURE condition and does not change .RS. Pauses nest across calls made from a typed line. The JS host pauses only when its host can compile (this.interactive: Node, or the browser with its compiler loaded); input in the browser is the supplied standard-input text.

Synchronous execution: runSync, sendSync, thunks

The machine itself is never re-entered (see Design notes). Three cases run code to completion on the host stack, each in a separate machine instance:

  • RVM.Machine~runSync(program, context) / Machine.runSync runs a program's main code to its end as a main program in a context of its own (activityContext), inside the running activity (so with its locks). It mirrors native Setup.cpp runProgram; the RVM uses it for the prelude's prolog (RVM.PreludeLoader~runProlog).
  • sendSync(receiver, name, args, program, context) runs one message to completion (execute jumps to DoSend in mode SYNC; Deliver SYNC returns the value). RVM.PreludeLoader~sendSync / loader.sendSync wraps it for natives that need a result now, mirroring native C++ sendMessage: HASHCODE and == of user objects in hashed collections, REQUEST ARRAY for DO OVER and RAISE ADDITIONAL, security-manager calls, TraceObjects to .TRACEOUTPUT, LINEIN from .DEBUGINPUT, WITH targets that are objects. sendSyncWatch also collects conditions raised to the sender (RAISE ... RETURN in the method).
  • Thunks (run(..., nested = .True) / nested): an ADDRESS ... WITH redirection target given as an expression is compiled as a small piece of caller code that ends in YIELD; it runs in the caller's context, as part of the activation running the ADDRESS (native evaluates the expression there). It goes on with that machine's frames (context~frames), from base (their count when it starts): what it calls is on the stack (the natives' lines, the programs of external routines, TRACEBACK and STACKFRAMES), and its own Failed takes errors and traps above base (a routine's SIGNAL ON, NOTREADY, an object whose STRING is Rexx). What gets down to base goes on in the machine below: a condition with its throw (NestedHandoff: the same condition raised again, with context~nestedHandoff set, so that the machine below takes it as a trap and keeps the lines collected; JS: the same error, nestedHandoff), and an EXIT with its value (context~nestedExit and a condition RVM.Exit; JS: NestedExit), which goes on unwinding there (ExitUnwind / exitUnwind).

A wait in one of these machines (sync or nested) does not leave it: the activity they run in (the context carries it, so the natives that wait see it) is marked WAITING and Suspend/suspend calls pump (RVM.Machine~pump / Machine.pump), which runs the other activities as the run loop does (next, launch, EndActivity) until this one is ready again. Then the machine goes on at resumeAt (JS: executeBody again, which runs this.resume) with its registers as they were: they never left the host stack. Meanwhile the activity is trapped (sched~trapped, innermost on top): next gives neither it nor any other trapped one, since their frames are below the pump's. A wait that nothing can end is 93.900 ("an activity waits for something that cannot come"), and so is one that needs an activity trapped below it ("nested waits cross", see 17). A REPLY there gives the native its value and moves the rest of the method to a new activity whose machine is not nested (07). There is no slice yield in a nested machine and no UNINIT activity in a pump.

An error that ends such a machine goes on in the machine below, as native's exception goes up through the native: the same condition (its POSITION and PROGRAM are where it was raised inside), with the report lines collected there, then the natives' and the caller's (errors). The stack of a sendSync context (syncRoot: its first activation only sends the message and is no frame) goes on with the context below (outerContext: the previous one in the activity's syncs, or its context), so TRACEBACK and STACKFRAMES taken inside see the whole stack. That first activation runs as the caller's (level~runs of the caller's level): the message it sends is checked with the caller's sender and package (08), and a condition raised there (a NOMETHOD) is the caller's (RVM.Context~raiseCondition / raiseCondition hands it to outerContext): a SIGNAL ON trap of the caller sets that context's throw, and its RVM.Trap goes up through this machine untouched (Failed / failed: no throw here, the caller's set) to be taken below as a trap. Both save and restore the conversion caches (conversions/requests), since the native may have been called in the middle of an instruction that is converting objects, and the NOSTRING reporter (RVM.Obj~reporter / REPORTER).

Environment variables read by the machine

Variable Effect Hosts
RVM_SLICE clauses per time slice (0 or negative: never yield; default 10000) both
RVM_CLOCK=virtual virtual timer clock (chapter 7) both
RVM_LOCAL=eager build .LOCAL at start both
RVM_TBCHECK compare each untrapped error's report with its TRACEBACK (chapter 16) ooRexx; JS under Node
RVM_ACTTRACE print ACT id outcome resumeAt (JS: ACT id outcome, its machines go on through closures) on the error stream at each activity switch both

Others (RVM_QUEUES, RVM_MACROSPACE, ...) are described in chapter 1.

Design notes

  • The machine never nests. One activity is one loop with explicit registers. When something needs a Rexx method's result in the middle of an instruction (an operator on an object, a conversion to string), the instruction is abandoned, the message is sent as an ordinary send in the same loop, and the instruction re-executes with the cached result (NeedString). The reason is suspension: an activity that waits must be resumable from its registers alone (ooRexx host: .context~variables and Signal Value resumeAt; JS: a closure and a thrown WAITING). Host-stack frames of a nested machine could not be saved. Precondition: every instruction checks all its operands before any side effect.
  • Natives never call user code; they delegate. A native that must send a message ends by returning an RVM.Delegate ("send this; the result is ..."): NEW sends INIT, SEND sends its message, SUBCLASS chains several via then. Algorithms that call back into user code (sorting with COMPARETO, SORTWITH) are written in Rexx in the prelude rather than as natives. The remaining places where a native needs a value at once use sendSync or runSync in a separate machine. When that code waits, the other activities run in place (pump); the price of keeping the main machine flat is that such waits nest on the host stack, so two of them cannot cross (07).
  • Variables as cells. A variable is an object (RVM.Var / {v}), as native RexxVariable. EXPOSE and PROCEDURE EXPOSE share the cell, so there is no copy-in/copy-out, DROP and stem reassignment propagate naturally, and VariableReference is just a cell. RVM.Var has no INIT method: an INIT would cost a method run per variable. Only cells watched by GUARD WHEN pay for change notification (RVM.Var~watchBy installs its own VALUE=; JS defines an accessor).
  • Single per-program variable numbering. The compiler numbers names once per program; frames are cell arrays (JS) or name directories (ooRexx). Names unknown at compile time go by name and get a slot when first seen.
  • Stems are a port of CompoundVariableTable, tree and balancing included, so that every traversal yields tails in native order.
  • CLAUSE is the single per-clause hook: slice counting, pending CALL ON traps and HALT, SIGL/error line, clause time stamp, trace and the entry trace rule all hang on it.
  • No runtime block stack. Loops and SELECT use per-activation descriptors created by BASE; LEAVE, ITERATE and SIGNAL are jumps.
  • Three parallel stacks (machine frames, saved activations, levels) all go through pushActivation/popActivation, so no exit path (RETURN, EXIT, SIGNAL ON unwinding, Failed) needs to know about levels or locks.
  • Fresh package per external call, cloned not re-read. Native ooRexx re-reads and re-translates the file on each CALL. The RVM reads and verifies it once and clones the program per call, which preserves the observable "new package" semantics (fresh classes, merge on return) at a fraction of the cost. Consequence: edits to the file during the run are not seen.
  • R-code always from text. The machine only ever runs what the compiler wrote, so any host that reads R-code runs the same program.
  • Prelude on demand. Building the object world is deferred until the first object feature is used.
  • Depth limit 10000 rather than native's C-stack-dependent ~22000: deep recursion exhausted Node's memory before reaching the native limit.

Known gaps

  • JS host: INTERPRET and interactive trace require a compiling host (Node spawns rexx rvm.rex -f, so ooRexx must be installed; the browser needs its compiler loaded). Otherwise INTERPRET is 93.900 and pauses are skipped.
  • In code run by runSync/sendSync (or a thunk), nested waits that cross are 93.900; native lets them go on.
  • In Node without its worker (RVM_WORKER=0) and in the browser, a read of standard input blocks all activities while it waits (chapter 7).