The compiler turns the Rexx Parser's AST (the Tree API) into R-code.
This chapter covers the pipeline from source text to a loaded program,
the structure of the compiler, how names are resolved, how directives
and ::REQUIRES become R-code and are linked at run time,
INTERPRET (and the other run-time compilations) in both hosts, the
.rcode cache, and how the prelude is compiled. It assumes
the R-code format and instruction set of 04-rcode.md; the parser itself is documented with
the Rexx Parser (bin/parser/), and only what the compiler
relies on is described here.
Code: ../RVM.Compiler.cls
(RVM.Compiler, RVM.Unit, the
::rcompile methods), ../rvm.rex (the front end and the
compiler's command protocol), in ../RVM.Machine.cls the
loaders (LoadProgram, LoadPackage,
LoadExternal, FindExternal,
CachedRCode, SourceHash,
WriteCache, Interpret,
CompileSource, RVM.PreludeLoader,
RVM.SourceCompiler) and the start of a package (label
StartPackage in RVM.Machine~run); in JS ../js/compiler.mjs, ../js/host-node.mjs, ../js/host-browser.mjs,
../js/runner.mjs and
appendFragment / findExternal /
cachePath in ../js/rcode.mjs.
There is a single compiler, written in Rexx:
RVM.Compiler.cls plus the Rexx Parser. Every host uses it,
so every host gets the same R-code for the same source:
| Host | How it compiles |
|---|---|
ooRexx host (rvm, rvm.rex) |
In process: native ooRexx runs the parser and the compiler. |
JS host under Node (js/rvm, rvm.mjs) |
Spawns native ooRexx on rvm.rex with a request option
(-p FILE, -s OPTION, -f) per
compilation (NodeHost~loadExternal,
compileSource, compileFragment). ooRexx must
be installed. |
| JS host in a browser | The compiler runs on the JS RVM itself
(compiler.mjs): the R-code of rvm.rex and of
the packages it requires (the parser, the compiler) is given to the page
as a library; BrowserHost.enableCompiler turns it on.
Without it the page can only run R-code. |
The parser and the compiler are ordinary ooRexx programs; they run on either RVM as well as on native ooRexx, which is what makes the browser case possible.
ProgramSource::buildDescriptors): the text ends at the
first Ctrl-Z (1Ax), and a line ends with CR, LF or CR LF
(SourceLines in Rexx, sourceLines in JS). The
same lines serve the clause texts and SOURCELINE..Rexx.Parser~new(name, lines, options) builds the AST; its
~package is the root (prolog body and directives). The
parser raises translation errors itself (syntax, 99.913 GUARD WHEN,
99.917 EXTERNAL specifications, ...). Options used by the RVM: none for
a program, METHOD for a method source given at run time
(EXPOSE allowed in its body), INTERPRET (with the running
body's labels) for INTERPRET data. The parser's second pass
(bin/parser/SecondPass.cls) classifies every call against
the parser's BIF set .Parser.BIF, built with the signatures
.Parser.BIFInfo by LoadBIFInfo in
bin/parser/BIFs.cls (name
resolution). The parser's own documentation is at https://rexx.epbcn.com/rexx-parser/.RVM.Compiler~compile(package, lines, name) returns an
RVM.Unit.RVM.RCode~write(unit, hash)
produces the R-code text as an Array of lines, with the
SOURCE hash of the file text (- when there is
no file).RVM.RCode~read(lines)
(readRCode in JS) builds an RVM.Program and
runs the verifier. The ooRexx host always runs a program from the text
it has just written; nothing is passed from compiler to machine except
that text.A source that does not parse is reported as native ooRexx reports it,
with the clause the parser gives (ParseErrorLine); a source
loaded at run time (external routine, ::REQUIRES) raises
its error at the call or directive that loaded it, its own line first in
the report.
rvm.rex options: none (compile, or take the cache, and
run), -l (list the R-code on standard output),
-c (write CachePath(FILE)), -w
(run, and write the cache of every source compiled),
-e PROGRAM (a program in a string, named INSTORE), a
.rcode FILE (run it); and, for the JS host,
-p FILE, -s OPTION and -f (see the request protocol). The launchers
rvm and js/rvm are described in 01-overview.md.
The compiler is a visitor over the AST, built the
same way as the parser's other modules (and the identity compiler in
bin/modules/identity): each AST class it handles gets a
floating method "Class::rcompile", and
Load.Parser.Module.rex, called from the prolog of
RVM.Compiler.cls, defines each of them on its class.
LOOP reuses DO's method. The routine
Gen(node, unit) compiles any node: a node whose class has
no rcompile compiles to
ERR 93.900 "RVM: <class> is not supported yet",
raised only if that code runs. The classes of the AST that have none,
each with its reason, are listed in the smoke test's astcheck.rex, which
reports any other (16).
Conventions:
unit~clause(node[, kind]), which emits a LABEL
for each label of the clause, then CLAUSE c kind, and
returns the address of the first of them (the target of =
at an interactive pause). Most instructions end with the pause
instruction that matches them (PAUSE, BPAUSE,
CPAUSE, IPAUSE, TPAUSE).N (default), C (a command,
or ADDRESS env expr), X (an implicit EXIT), E
(EXPOSE), W and Q for the parts of blocks that
must not be traced as clauses of their own (04-rcode.md).Implicit.Exit.Instruction, compiled to
CLAUSE c X + EXIT — an EXIT, not a RETURN, as
ooRexx does; the method's ~source extent ends there.RVM.Unit holds the state of one compilation: the code
(an Array of instructions), the constant pool (const: each
value once), the names (slot: one numbering for the whole
program, a stem as "A."), the clause table
(clauseNo: each AST clause once, with its line and text
computed by RVM.BaseContext~clauseText), the labels of the
body being compiled, the descriptor count, the WITH table, and the
directive tables (classes, methods, routines, requires, annotations,
resources, options). Forward jumps use RVM.Ref objects
(newRef, place), replaced by addresses in
finish.
RVM.Compiler~compile proceeds in this order: the
::OPTIONS (CompileOptions), the
::ANNOTATE targets (CompileAnnotations), the
prolog body, its pending "redo" pieces (flushRedos, see
LEAVE/ITERATE below), every directive (CompileDirectives:
method and routine bodies are appended after the prolog, each with
labels of its own: startBody / endBody), the
annotation targets of methods (resolveAnnotations), and
finish. Translation-time errors that ooRexx raises while
translating but that the parser does not (33.1 for an
::OPTIONS DIGITS/FUZZ pair, 99.945 for an
::ANNOTATE without a target) are compiled as code at
address 1 that raises them at the directive's clause before the prolog
runs.
| AST | R-code |
|---|---|
| number | PUSHN k (the literal as written) |
| simple variable | LOADV s |
| constant symbol, string | PUSHC k (a lone . is the constant
".") |
| environment symbol | ENV k |
compound A.I.3 |
the tail pieces (TAILV per variable, PUSHQ
per constant run, joined at run time), then LOADC s n k
with the stem's slot and the name as written for the trace |
stem A. |
LOADS s |
>x, <x |
VREF s |
| operators | the operands, then one opcode per operator (CompileExpr
and the *.Expression::rcompile methods); comparisons carry
the operator as written, with the not signs AAx and
ACx mapped to \ (also in the trace and in the
message sent to an object, as ooRexx) |
(a, b, ...), x = a, b |
each item, TRARG, then MKARR n (an omitted
item is PUSHNONE) |
| function call | the arguments (CompileArgs: each one, or
PUSHNONE, then TRARG), then
FUNCI/FUNCB/FUNCX by its
resolution |
ns:name(...), ns:name |
FUNCNS, NSCLASS |
r~m(...), r~~m, r[...],
r~m:scope |
receiver, scope (+ SCOPE), arguments,
SEND/CASC (CompileMessage) |
Conditions (IF, WHEN) are compiled by CompileCondition:
the value, RES, BPAUSE,
JF a IF|WHEN; a list evaluates its items one by one,
stopping at the first 0 (JF fail LIST), and traces the
resulting 1/0 with TRES.
A loop is laid out as follows (from rvm -l of a program
whose second clause is do i = 1 to 3 while i < 5, with
body call sub i; addresses on the left, several
instructions per line where marked with /):
10 CLAUSE 2 N do i = 1 to 3 while i < 5
11 BASE 1 descriptor 1: the loop's level and state
12 PUSHN 3 / DOSTART 1 start
14 PUSHN 4 / DOTO 1 TO (start, TO, BY, FOR in the order written)
16 DOINIT 1 1 default BY, assign i
17 INDENT
18 JMP 25 first round: skip the step
19 SETIND 1 top: <- ITERATE
20 TCLAUSE 2 the DO clause, traced again each round
21 INDENT
22 CLAUSE 3 Q (errors in UNTIL and in the step are reported on END)
23 DOSTEP 1 1 i = i + BY
24 CLAUSE 2 Q
25 DOTEST 1 43 TO passed / FOR exhausted -> over
26 LOADV 1 / PUSHN 6 / LT 7 / KEYW 5 / JF 43 WHILE
31 DOPAUSE 10 1 interactive pause, first round only
32 JPAUSE R where a pending LEAVE/ITERATE "=" lands
33 DOBODY 1
34 ...body... CLAUSE 4 N / call sub i
39 CLAUSE 3 Q / SETIND 1 / TCLAUSE 3 / JMP 19 end
43 DOEXIT 1 over: the checks ended the loop
44 DOPAUSE 10 1 / JPAUSE E / JMP 49
47 SETIND 1 / JPAUSE E exit: <- LEAVE
49 done
UNTIL is tested at the top of each later round, before the step. DO
OVER adds DOOVER/DOOVERS and
DONEXT (before DOTEST), DO WITH adds
DOWITH, DONEXTW and WITHSET,
COUNTER adds DOCTR/TRCTR. A control variable
(or COUNTER, INDEX, ITEM target) that is a stem or a compound uses the
push forms (DOINITP, DOSTEPP,
DOSKIP/DOITEM, WITHGET) followed
by an ordinary store (LoopTarget, LoopStore,
LoopLoad). A simple DO ... END is
BASE, INDENT, BPAUSE, the body,
and its END.
LEAVE and ITERATE are resolved at compile time: the parser gives the
target block (instruction~iteration), and the compiler
jumps to that loop's exit or top
(CompileJump, JumpTarget). With no valid
target, it emits ERRJ 28.x with the indentation offset
ooRexx reports it at (failedJumpOffset). An ITERATE whose
target is a SELECT or a simple DO (the parser gives that block as
~iteration unless the ITERATE early check is
on) compiles to ERRJ 28.5, raised when it runs, as in
ooRexx; it is preceded by SETIND of the outermost block
inside the target, because ooRexx ends those blocks before it reports
the error. For interactive trace, a jump is preceded by
JMARK and two "redo" pieces, compiled out of line at the
end of the body (RVM.Unit~redo, redoHere,
flushRedos), which = runs to repeat the jump
from where it landed.
Constructs the compiler does not support compile to
ERR 93.900 with a message, so a program that never executes
them still runs: USE NAMED ARG; trailing blocks; invoked terms
(r(...) on a routine or method object); messages without a
name; compound assignment to a stem (a. += 1); USE ARG to
any target other than a simple variable, stem, compound, message term or
>reference; message instructions and message assignments
of other forms; AST classes with no rcompile
(Upper.Instruction). Some errors native ooRexx gives at run
time are also compiled as ERR: USE LOCAL outside a method
(98.993), PROCEDURE in INTERPRET data (17.1; elsewhere the machine
checks it, 05), a SELECT without
OTHERWISE reaching its END (7.3), GUARD WHEN with no exposed variable to
watch (99.913).
Names are bound as statically as ooRexx binds them.
Calls. The parser's second pass
(CheckCallTypes in bin/parser/SecondPass.cls)
sets the subCategory of every function or subroutine name,
against the labels of the body that contains the call:
| Name | subCategory |
Instruction |
|---|---|---|
| a symbol that is a label of the body | INTERNAL.FUNCTION.NAME /
INTERNAL.SUBROUTINE.NAME |
FUNCI / CALLI (label k, SIGL line) |
a built-in function name (the table in BIFs.cls) |
BUILTIN.* |
FUNCB / CALLB |
a ::ROUTINE of the package |
PACKAGE.* |
FUNCX / CALLX |
| anything else | EXTERNAL.* |
FUNCX / CALLX |
A string name is never a label, and is a built-in only if it is the
built-in's name exactly (upper case): 'LENGTH'(x) is the
BIF, 'length'(x) is an external call (43.1 when no such
file exists), and call 'SUB' skips the internal label
SUB. This is native behaviour: ooRexx resolves the label
target of a call when it translates the program
(RexxExpressionFunction::resolve in
ExpressionFunction.cpp,
RexxInstructionCall::resolve in
CallInstruction.cpp).
What is left to run time:
FUNCX/CALLX: a ::ROUTINE of
the running program first, then the public routines of required
packages, libraries and external programs (05-machine.md). Routines of a required package
are therefore not known to the compiler: they are linked when
called.CALL (expr) (CALLN): the label with
exactly that name, else a BIF, else as CALLX.SIGNAL label and SIGNAL VALUE: looked up
in the running body's labels (16.1 when missing).::CONSTANT name (expr) are in no
body: ooRexx resolves their calls with no labels (BIF,
::ROUTINE, external), and so does the parser
(package~constantCalls).ENV),
classes and messages are always
resolved at run time.CompileDirectives walks the directives in order:
| Directive | R-code |
|---|---|
::CLASS |
a CLASSES entry (ClassEntry); the class number becomes
the "active class" of the methods that follow |
::METHOD |
a METHODS entry: CODE with a body of its own,
ABSTRACT, DELEGATE, REXX f,
LIBRARY ...; with ATTRIBUTE, the getter and the setter |
::ATTRIBUTE |
GET/SET methods (flag A), or
ABSTRACT, DELEGATE, LIBRARY
(entries GETname/SETname), or a CODE body |
::CONSTANT |
two CONST methods (instance and class);
::CONSTANT name (expr) two CCONST methods,
plus a K method ::CONSTANT per class whose
code evaluates each expression, traces it, and stores it with
SETCONST (ConstantInitializer, ooRexx's
resolveConstants) |
::ROUTINE |
a ROUTINES entry: CODE with a body of its own, or
EXTERNAL |
::REQUIRES |
a REQUIRES entry (clause, name as written, LIBRARY,
NAMESPACE) |
::RESOURCE |
a RESOURCES entry (ResourceLines) |
::OPTIONS |
folded into the OPTIONS line (CompileOptions,
OptionsLine) |
::ANNOTATE |
ANNOTATIONS entries, targets found as ooRexx finds them while
translating (CompileAnnotations) |
A method before the first ::CLASS is floating (class 0).
Formats: 04-rcode.md.
The compiler only records the ::REQUIRES; linking
happens when the program starts (StartPackage in
RVM.Machine~run; machine.mjs does the
same):
CheckExternals), as ooRexx does when it translates the
package.LIBRARY: one of the RVM's libraries
(RVMLibrary) is loaded, or 98.903 (12-libraries.md)..cls first (FindExternal(name, caller, .True);
not found: 43.901), and loaded once per run (LoadProgram,
keyed by path; with a security manager, RequiresProgram
asks it first). A NAMESPACE is recorded on the requiring program. A
package already started is reused; one still LOADING is a
circular reference (98.952). A new one starts in its turn (its own
requires, its classes) and its prolog runs as a call with no arguments
(PARSE SOURCE says REQUIRES; the result is discarded; NOPROLOG
suppresses it).RVM.World~install), and
the program is READY.A program sees its own classes and routines and the public ones of
the packages it requires (transitively, as ooRexx); a method or routine
always runs in the program it was compiled in. An external routine
called by name is a new package at each call (LoadExternal
→ FreshProgram), its R-code loaded once. Details: 08-objects.md, 09-reflection.md.
INTERPRET expr compiles to the expression,
RES, IPAUSE a, INTERP c. At run
time the data string is compiled in the context of the running
body:
INTERPRET with the labels of
the body that is running (prolog, routine or method) as
RVM.LabelRef objects, so that CheckCallTypes
classifies calls in the data against the caller's labels (INTERPRET data
has no labels of its own). Parser options are global
(.environment), so Options.Interpret is reset
after parsing;RVM.Fragments with the line of the INTERPRET clause, so
that SIGL, trace lines and error lines in the data show that line;IEND returnTo clause (back after the
INTERP, with the INTERPRET clause current again). A line
typed at an interactive pause is compiled the same way and ends with
DEND.The compiled address is cached per INTERP instruction and
data string (icache), without limit: a loop that
interprets the same string compiles it once. Data that does not parse
raises its error at the INTERPRET, the line of the INTERPRET inserted
where the error text has a line, and the report showing the parser's
clause (or the data).
How each host compiles it:
| Host | Mechanism |
|---|---|
| ooRexx | Interpret → LoadData →
RVM.Compiler~extend(package, program, ...): the unit
shares the loaded program's code, constants, names,
clauses, labels and WITH table and appends to them
(RVM.Unit~share); new clauses and redirections are turned
into machine objects, and the verifier runs from the new code's start
and thunks. |
| JS, Node | host.compileFragment("I", line, name, labels, data) →
rexx rvm.rex -f → RVM.Compiler~fragment: a
stand-alone fragment numbered from 1, ending IEND 0 0,
which appendFragment relocates into the program and
verifies (04-rcode.md). |
| JS, browser with compiler | The same request, answered by compiler.mjs
(Compiler~fragment) on the JS RVM. |
| JS, browser without compiler | 93.900 "INTERPRET is not available in this RVM"; interactive trace pauses do nothing. |
Interactive trace (typed lines, kind D) uses the same
paths, so it works in the ooRexx host, in Node, and in a browser with
the compiler enabled (reading the page's standard input).
Method~new, Routine~new,
Package~new with source lines, DEFINE and SETMETHOD with a
source, .Package~loadPackage with lines: each compiles a
package of its own (RVM.SourceCompiler,
CompileSource in the ooRexx host;
host.compileSource(option, name, lines) in JS, i.e.
rvm.rex -s OPTION under Node or
Compiler~source in the browser). A method source uses the
parser option METHOD; the others none (so EXPOSE and USE
LOCAL there fail when they run: 98.992, 98.993). A run-time program sees
what its parent sees (09-reflection.md).
In JS, the main program given as text (rvm.mjs -e,
runSource in the browser) also goes through
compileSource.
rvm.rex answers three requests on standard input /
output, used by the Node host (one process each) and, through
compiler.mjs, by the browser:
| Request | Input | Output |
|---|---|---|
-f |
FRAGMENT kind line (kind I or
D), the program name, the labels (hex, blank-separated),
the data (hex) |
OK + the fragment's R-code, or
ERROR code column clause (clause in hex or -)
+ one line per insert (hex) |
-p FILE |
— (reads FILE; double quotes around it are dropped, as Windows passes them) | OK + the R-code (with its SOURCE hash), or
ERROR code line + the report line (hex) + the inserts
(hex); a FILE that is not there: rvm -p: no such file: FILE
on standard error, RC 1 |
-s OPTION |
the name (hex), the number of lines, the lines (hex) | as -p (SOURCE -) |
In the browser, Compiler (compiler.mjs)
runs rvm.rex's R-code with these arguments in a world of
its own that it keeps: the parser and compiler packages are loaded by
the first compilation only. It is not reentrant (a nested request is
93.900); a failure of the compiler itself is 93.900 "the compiler
failed".
A source file can have its R-code next to it:
CachePath / cachePath gives
x.rcode for x.rex (any case of
.rex) and name.rcode for any other name
(x.cls.rcode, prelude.orx.rcode).
When it is used. Whenever a source is loaded — the
main program (rvm FILE, js/rvm FILE), an
external routine, a ::REQUIRESd package, the prelude — the
cache is read instead of compiling when its first three lines are
exactly:
RCODE <the reader's RVM.RCode~VERSION>
COMPILER <RVM.Compiler~VERSION> <RVM.ISA~VERSION> <RVM.Compiler~frontier>
SOURCE <SourceHash of the current source text>
(CachedRCode in Rexx; the same test in
NodeHost~loadExternal, which reads
RVM.Compiler~VERSION from the source of
RVM.Compiler.cls and the frontier from its file.)
RVM.Compiler~frontier is the Rexx Parser's frontier
stamp: the first line of bin/resources/frontier,
an integer that the parser raises whenever something the compiler
consumes changes (the AST, .Parser.BIFInfo, the error
texts, the INTERPRET and METHOD options, what a parse error carries (a
Rexx.Parser.Error); see 20), or 0 when the file
does not exist. rvm -l and rvm -c always
compile.
When it is invalidated. When the source text changes (the hash covers every byte and the length), or any of the three versions or the parser's frontier stamp changes. File dates are not used. The cache does not record the versions of required packages: they have caches of their own.
Who writes it. rvm -c FILE (only that
file, no run); rvm -w FILE and js/rvm -w FILE
(run, and write the cache of every source compiled during the run: the
main program, external routines, required packages, and in the ooRexx
host the prelude). A file that cannot be written is skipped silently.
Without -w nothing is written: a stale cache only costs a
compilation.
R-code without source. The search for an external
routine or a ::REQUIRES looks for sources first in every
directory and extension, and only then for their .rcode
files (FindExternal, findExternal): a deployed
.rcode with no source runs. A file named
*.rcode is run as R-code, never compiled.
In the browser the library given by
BrowserHost.addLibrary maps each
x.rcode/x.cls.rcode file to the source name it
belongs to and is used as is (format and ISA versions are checked on
load, the compiler version and hash are not). Without the compiler, only
R-code (library files and page files ending in .rcode) can
be found or run; with it, sources are compiled on demand
(-p), with no cache.
The prelude (ooRexx's CoreClasses.orx cut by
makeprelude.rex, plus prelude-rvm.orx; and
prelude-streams.orx from StreamClasses.orx) is
an ordinary source compiled by the same compiler:
RVM.PreludeLoader~load
loads prelude.orx (next to RVM.Machine.cls)
through LoadProgram, so its cache
prelude.orx.rcode is used when up to date and the source is
compiled otherwise (and the cache written with -w). It is
loaded the first time a run needs it, renamed REXX, with no
source lines. prelude-streams.orx is loaded the same way
when present.genprelude.rex turns prelude.orx.rcode into
rvm-prelude.mjs (and prelude-streams.orx.rcode
into rvm-prelude-streams.mjs). They must be regenerated
whenever the prelude, the compiler output, the R-code format or the ISA
changes.Generation and contents: 10-prelude-and-classes.md.
::rcompile methods, not a dispatch
table. Each node knows how to compile itself, as in the
parser's other modules. Gotcha: floating
::METHOD "Class::name" directives must come before the
first ::CLASS of the file (otherwise they become methods of
that class), which is why RVM.Compiler and
RVM.Unit are at the end of
RVM.Compiler.cls.rvm.rex -f/-p/-s), so
the JS host contains no compiler code of its own; the browser answers
the same protocol with the compiler running on the JS RVM.-c, -w), so a run
never writes next to the user's sources unasked.