This chapter describes what a Rexx value is inside the RVM, in both hosts: strings (always byte strings), numbers (an immutable decimal object that travels between operations without being turned into text), and the objects of the object model. It then gives the decimal arithmetic in detail (the "operate in a window, then round" model of native ooRexx), NUMERIC DIGITS/FUZZ/FORM, LOSTDIGITS, whole-number conversions and the comparison rules. It assumes the reader knows Rexx arithmetic as the ooRexx reference describes it; the machine that calls these routines is in 05-machine.md, the object model in 08-objects.md.
Code: ../RVM.Number.cls
and ../js/number.mjs (the
value model, both CPL: derived from ooRexx's
NumberStringMath.cpp, NumberStringMath2.cpp,
NumberStringClass.cpp, IntegerClass.cpp); the
operators in the machine loop (../RVM.Machine.cls, ../js/machine.mjs);
CompareNormal/Boolean in ../RVM.Objects.cls /
compareNormal/boolean in ../js/objects.mjs;
NumberValue/WholeValue in ../RVM.BIFs.cls / ../js/bifcore.mjs.
A value on the machine's stack, in a variable or in a collection is one of three kinds. Strings and numbers are never boxed: they are the host's own values, and they have the behaviour of the String class "by type" (08-objects.md).
| Kind | ooRexx host | JS host |
|---|---|---|
| String | a host .String |
a JS string primitive, one character per byte |
| Number | RVM.Number, or its subclass
RVM.Integer |
RexxNumber, or its subclass
RexxInteger |
| Object | RVM.Obj (behaviour, pools, native value) |
Obj |
.nil is an object of the RVM
(context~world~nil), not the host's .nil.
num() and
str()The two representations meet in exactly two routines (exported from the value-model module in both hosts):
num(v, ctx) — a Number passes through; an RVM object is
replaced by its string value; a string is parsed
(fromString), recording the current NUMERIC settings. A
string that is not a number raises 41.1 with the value as it is (blanks
kept); for an empty value the whole message is supplied explicitly
(Nonnumeric value ("") used in arithmetic operation.),
since an empty insert would not be substituted.str(v) — a string passes through; a Number is
serialised (lazily, see Layout); an RVM object
gives its string value (which may run its STRING
method).Uses num (numeric view) |
Uses str (text view) |
|---|---|
operands of + - * / % // ** |
strict comparisons
== \== << >> <<= >>= |
prefix + and - |
logical operators & \| && \ |
| normal comparisons, when both sides are numbers | concatenation (\|\|, abuttal, blank) |
NUMERIC DIGITS/FUZZ values, DO counts, PARSE positions (through
wholeNumber) |
SAY, compound tails, BIF string arguments, INTERPRET, VALUE, commands |
Assignment stores whatever value it gets: a variable may hold a
Number. There is no write-back: a string variable used in arithmetic is
parsed again each time (num on the stack value), and the
parsed Number is not stored into the variable.
isNum(v) (is it a number? — a Number always is, a string
if parseNumber accepts it) replaces
DATATYPE(v, 'N') inside the RVM.
The compiler emits a numeric constant symbol as PUSHN
and a quoted string as PUSHC (04-rcode.md). PUSHN evaluates the
literal with lit(source, ctx) and caches the result per
instruction address (numCache, kept on the program object
in both hosts) keyed on the current DIGITS and FORM; Numbers are
immutable, so the cached object is shared.
lit decides the class by the text of
the literal, as ooRexx does:
WholeDigits (18
on a 64-bit host, below) significant digits
→ born Integer, carrying its literal text
(007);1.5,
1e3) → a plain Number, even if its value is whole (so
1e3*1.5 keeps the exponent structure);0.1E-999999999) → a string, the symbol's name in
upper case.A literal keeps its own text as its string value, canonicalised as
ooRexx's string representation is (canonLiteral): strip
blanks, drop a leading +, upper-case e.
Everything else is verbatim:
x = 007; say x x||5 x+0 (x == 7) (x = 7) -- 007 0075 7 0 1
say 1e3 6e0 1.50 -- 1E3 6E0 1.50
A Rexx string is a sequence of bytes, never of Unicode characters, in both hosts.
latin1, so every byte goes through unchanged:
source files, .rcode files, stream I/O, standard
input/output/error, queue and macrospace files (../js/host-node.mjs). Two
boundaries are text by nature and convert UTF-8: environment variables
are read as UTF-8 bytes
(Buffer.from(v, "utf8").toString("latin1")) and written
back the other way, and a command line is decoded from its bytes as
UTF-8 before it is given to /bin/sh. The browser host (../js/host-browser.mjs)
keeps the same convention for its in-memory files.Consequences: LENGTH, SUBSTR,
C2X and every BIF count bytes (length("é") is
2 and c2x("é") is C3A9 for a UTF-8 source, on
all three of native, the ooRexx RVM and the JS RVM); JS string
comparison (<, ===) on binary strings is
byte comparison, which is what Rexx strict comparison needs.
A string or array JS cannot build (a JS RangeError, e.g.
a string beyond the engine's maximum length) is turned into Rexx error 5
by the machine loop, as native ooRexx reports running out of memory. The
ooRexx host has no such limit below the memory of the process.
A Number is immutable after construction and holds:
| Field | Meaning |
|---|---|
sign |
-1, 0 or 1 (0 iff the value is exactly zero) |
digits |
the significant digits as a string, no leading zeros,
trailing zeros kept (they carry scale);
"0" for zero |
exp |
the power of ten of the last digit |
createdDigits |
NUMERIC DIGITS in force when the value was made |
form |
NUMERIC FORM in force when the value was made |
| string cache | the text, computed lazily (or the literal's text) |
So the value is sign * digits * 10**exp:
1.5 is (1, 15, -1), 2.50 is (1,
250, -2), 100 written as 100 is
(1, 100, 0), zero is (0, 0, 0).
This mirrors native ooRexx's NumberString (sign, digit
bytes, exponent, digitsCount, createdDigits,
form, cached string). createdDigits is observable: the
layout of a value depends on the DIGITS it was born under, not on the
current one.
numeric digits 12; c = 123456789012*1
numeric digits 5; say c c+0 -- 123456789012 1.2346E+11
b = 1/3 -- at DIGITS 9
numeric digits 5; say b (+b) -- 0.333333333 0.33333
Integer (RVM.Integer /
RexxInteger) is a subclass that also keeps the value as a
native whole number (whole: a whole-number string computed
at host DIGITS 40 in the ooRexx host, a BigInt in JS) and
an optional literal text. Its base fields are materialised at
construction (digits is the whole written out,
exp 0, trailing zeros kept), so every inherited Number
method works unchanged on it. An Integer and a Number of the
same whole value are indistinguishable from outside: the
subclass exists only for speed (see Fast
paths).
parseNumber, fromString)parseNumber is a handwritten recogniser (not
DATATYPE), the same in both hosts: optional blanks (blank
and horizontal tab), optional sign, optional blanks, a mantissa with at
least one digit and at most one point, optional
E/e with an optionally signed exponent of
digits; blanks after. It returns (sign, digits without leading zeros,
exp) or "not a number".
Exponent limits (ooRexx's NumberStringBuilder::finish):
the written exponent must have at most 9 significant digits, and both
the exponent of the last digit and that of the number in exponential
form (exp + length - 1) must lie within ±999999999. So
10E999999999 and 0.1E-999999999 are not
numbers (41.1 in arithmetic; DATATYPE gives
CHAR; as a constant symbol, a string), while
1E999999999 is.
fromString keeps the canonicalised original text as the
string cache, so str(num(s)) gives back s up
to canonLiteral (' 1.50' →
1.50).
adjustPrecision
and the string layoutProducing a result and laying out its text are separate steps:
adjustPrecision(n) rounds the number
in place (round half up, with carry), strips leading zeros, normalises
zero, records n as createdDigits, clears the
cache, and checks the result's exponent like
NumberString::checkOverflow: 42.901 when
exp + length - 1 > 999999999, 42.902 when
exp < -999999999. Every computed result goes through it
(fromPartsSigned).string lays out the text, with no
rounding, from createdDigits and form, and
caches it.Division results go through fromPartsStripped: after
rounding, trailing zeros are stripped to lowest terms
(stripTrailingZeros), and then, if the value lays out plain
and is integer-valued, the integer zeros are put back so its structure
is that of its plain string (4630/1 is (1,
4630, 0), and (4630/1)*345.435 keeps the
scale: 1599364.05). Power strips without re-expanding
(stripAllZeros, ooRexx's StripResultZeros):
(2e1)**5 stays (1, 32, 5).
With adjustedExp = exp + length(digits) - 1, a value
lays out in exponential form when
adjustedExp >= createdDigits or
exp < -2 * createdDigits (so 1/3000000000
is plain, 1/30000000000 is 3.33333333E-11).
SCIENTIFIC puts one digit before the point; ENGINEERING puts 1–3 digits
and makes the exponent a multiple of 3. A zero exponent is not written
at all (ooRexx's formatExponent leaves the buffer empty):
at DIGITS 2, ENGINEERING, 344.7+0 is 340, not
340E+0 (ExpSuffix /
expSuffix).
Native ooRexx does not compute an exact result and
then round. Each operator prepares its operands in a window of DIGITS+1
positions, operates there, and rounds the result to DIGITS. The RVM
reproduces the mechanics of NumberStringMath.cpp step by
step (addSub, truncToMax,
subWindowed, longDivide and their JS twins),
because the observable results differ from "exact then round":
checkNumber).
Every operator truncates (does not round) each operand to DIGITS+1
digits (truncToMax): at DIGITS 3,
9525.461245-(-9) is 9.53E+3.adjA + lenA > lenB + DIGITS),
the larger is returned untouched, rounded only if wider than DIGITS:
1E20+1 is 1E+20 (one digit kept). A zero
operand returns a rounded copy of the other.NumberString::subtractNumbers): the difference is built
MSD-first with its full position count, leading zeros included, and only
then rounded: 1E9-1 is 0999999999 (10
positions) → 1.00000000E+9.| Operator | Mechanics |
|---|---|
+ - |
addSub as above; same signs add magnitudes keeping
scale (999999999+2 keeps zeros); - is
+ of the negated right operand |
* |
exact product of the truncated operands, rounded; scale kept
(2.0*3.0 is 6.00) |
/ |
long division to DIGITS+1 significant digits, rounded, trailing
zeros stripped (0.5/999999999 at DIGITS 5 is
0.0000000005: stripped before choosing the layout) |
% |
integer quotient, truncated toward zero; 26.11 if it has more than DIGITS digits |
// |
remainder read from the same long division
(intQuotient), sign of the dividend; when |a|<|b| the
result is a with its own scale (7.5//2 is
1.5); a quotient wider than DIGITS is 26.12 |
** |
see below |
prefix - |
always a copy rounded to DIGITS (negate) |
prefix + |
returns the value itself only when it has no cached text,
createdDigits equals DIGITS and form equals
FORM (NumberString::plus); otherwise a rounded copy, so
+007 is 7 |
% and // first decide from the exponents
alone: |a| < |b| gives quotient 0 (and remainder a); an
adjusted-exponent difference larger than DIGITS is 26.11/26.12 at once.
This avoids building a digit string as long as the exponent difference
(1e999999999 % 0.1 is 26.11 immediately).
Division by zero (for / % //) is 42.3.
Power. The exponent must be a whole number at the
current DIGITS (wholeNumber(other, DIGITS), anything else
including a non-number is 26.8). The base is truncated to DIGITS+1. A
zero base gives 1 for 0**0, 0 for 0**n, 42.903
for 0**-n. Overflow is detected before any work: if
|adjustedExp(base)| * n > 999999999 it is 42.1.
Otherwise exponentiation by squaring runs at working precision
DIGITS + length(n) + 1 exactly (not +2:
299**37 at DIGITS 5 is 3.9795E+91); a negative
exponent takes the reciprocal at one more digit (so the result is
rounded once, not twice: 35**-3 at DIGITS 12); the result
is rounded to DIGITS and stripped of trailing zeros
(9.99**5 is 99500.999, 123000**2
is 1.5129E+10 while 123000*123000 is
1.51290000E+10). ** is left-associative
(2**3**2 is 64).
The text of a number loses information the arithmetic depends on.
Positive exponents below the layout trigger are not recoverable from the
text, and +0 is not a normalisation but a clone:
say (1e3+0)*1.5 -- 1500 (not 1500.0)
say (2.9191e6+0)*9.99 -- 29161809
2.9191e6 has 5 significant digits and
2919100 has 7; both lay out the same, but they multiply
differently. Carrying the Number (with its digits, exponent and
createdDigits) between operations, and making text only at
the str boundary, is what makes these results come out as
in ooRexx.
An operand with more significant digits than DIGITS is reported by
checkLost(ctx) to the NUMERIC context
(ctx~lostDigits(n)):
+ - * / % //, the base of **
(not the exponent), prefix + and -, normal
comparison (also again inside the subtraction at DIGITS-FUZZ, so under
FUZZ a shorter operand can raise it);* checks before its zero shortcut;
/ % // after the zero checks (so 0/12345 at
DIGITS 3 does not raise it);FLOOR, CEILING, ROUND (String
methods) and TRUNC never raise it: they work in a
NumCtx without reporter, as ooRexx's
prepareNumber with ROUND.The interpreter's context (lostDigits in ../RVM.BaseContext.cls /
../js/context.mjs) raises
the condition, described by the operand's value; only
SIGNAL ON LOSTDIGITS can trap it, and untrapped it does
nothing (the operand is simply truncated). Under
::OPTIONS LOSTDIGITS SYNTAX it is error 98.972. See 06-conditions-and-errors.md.
signal on lostdigits
numeric digits 3; say 1234 + 1
lostdigits: say condition('D') -- 1234
Two fast paths compute some results with the host's own arithmetic. Both give exactly the result of the general path; they only skip work.
Integer (both hosts; ooRexx's
RexxInteger, IntegerClass.cpp). When both
operands are Integers whose wholes "fit" —
|v| <= 10**min(DIGITS, WholeDigits) - 1
(Numerics::isValid), tested per operation against the
current DIGITS — and the result fits too,
+ - * % //, exact /, ** and
prefix - are done on the native whole and give an Integer.
Otherwise the method forwards to the Number method
(self~op:super / super.op). Integers come from
integer literals, fast-path results and fromWhole; a Number
never becomes an Integer again. Deliberate forwardings, as in
ooRexx:
n**2 is never fast-pathed (** strips
trailing zeros, * does not);/ only when the division is exact;500+600 fails the "result fits" test and
goes the general way: 1.10E+3.Exact plus/minus/compare (ooRexx host only). In
RVM.Number~plus, ~minus and
~compare: when both operands are non-zero (for plus/minus)
and, aligned at the smaller exponent, each has at most DIGITS digits
(DIGITS-FUZZ for compare), addSub would truncate nothing,
take neither magnitude-gap exit, and produce the exact sum at the
smaller exponent. The routine ExactAddSub computes that sum
with host arithmetic at DIGITS+2 (exact for two numbers of DIGITS
digits) and rounds it with fromPartsSigned;
compare returns the sign of the exact difference. No
LOSTDIGITS check is needed (neither operand is longer than DIGITS). This
covers decimals and numbers parsed from strings, which the Integer path
does not. The JS host has no such path: its digit operations
(addDigits, mulDigits...) already use JS
numbers for short strings and BigInt otherwise, so
plus, minus and compare always
run the general code.
The settings live in the execution context (digits,
fuzz, form on RVM.BaseContext /
the JS context; defaults 9, 0, SCIENTIFIC). Every Number
operation receives a context ctx as argument and reads only
ctx~digits, ctx~fuzz, ctx~form
and ctx~lostDigits(n). Internal working precisions (power,
comparison under FUZZ, FLOOR/CEILING/ROUND, BIF argument conversion) use
RVM.NumCtx / NumCtx, a lightweight context
with the same interface; its lostDigits does nothing unless
it was given a reporter (the comparison under FUZZ reports
to the program's context).
Setting them (Numeric / numeric,
NumericForm / numericForm in the machine):
| Instruction | Rule |
|---|---|
NUMERIC DIGITS v |
unsignedWholeNumber(v, DIGITS); not whole or < 1 →
26.5 (NUMERIC DIGITS '' too); <= FUZZ →
33.1 |
NUMERIC FUZZ v |
unsignedWholeNumber(v, DIGITS); not whole → 26.6;
>= DIGITS → 33.1 |
NUMERIC FORM SCIENTIFIC \| ENGINEERING |
set |
NUMERIC FORM VALUE v |
must be exactly SCIENTIFIC or ENGINEERING,
else 25.11 |
| no value | the package default (its ::OPTIONS), else 9 / 0 /
SCIENTIFIC |
How the settings are saved across CALL, start fresh in an external
routine, or are inherited (::OPTIONS NUMERIC INHERIT) is in
05-machine.md.
Interpreted DIGITS versus host DIGITS (ooRexx host).
The program's DIGITS is data in the context; the RVM.Number
code never executes Numeric Digits context~digits. The
package runs under ::Options Digits 20 for its own
bookkeeping (exponents reach 999999999 and sums like
exp + length go past it; at host DIGITS 9 they would round,
and 10**999999999 would print with a mangled exponent), and
raises it locally (Numeric Digits 40) where a whole number
or an exponent check needs more. The JS host uses JS numbers for
exponents and BigInt for wholes, so it has no such
concern.
Several places need "the whole number a value stands for". There are two conversions, matching two different native routines.
numberValue /
unsignedNumberValuePort of NumberString::numberValue,
checkIntegerDigits and createUnsignedValue
(convertWhole in both hosts). At precision d:
round the value to d significant digits; every remaining
fractional digit must be zero (or, when the rounding carries into them,
nine); the magnitude must be at most
10**min(d, WholeDigits) - 1. The unsigned variant rejects
negatives. So at DIGITS 9, 1.0000000005 is 1 and
1.9999999999 is 2, but 2.5 and
1000000000 are not whole.
A native quirk is kept on purpose: a value that is entirely
fractional and rounds up to one gives 1 whatever its sign
(e = '-0.9999'; numeric digits 3; say 2 ** e is
2, in native and both RVMs).
wholeNumber(v, d) and
unsignedWholeNumber(v, d) apply these to any value: a
string that is not a number is simply not whole (.Nil /
null), and the caller raises its own error (26.8 for
**, 26.2/26.3 for DO/FOR, 26.4 for PARSE positions,
26.5/26.6 for NUMERIC...), never 41.
WholeDigits is the widest whole a conversion can
produce: in the ooRexx host .RexxInfo~internalDigits (18 on
a 64-bit build, 9 on 32-bit); in JS the constant
WHOLE_DIGITS = 18.
| Use | Precision |
|---|---|
** exponent |
current DIGITS (26.8) |
| DO count, FOR | an Integer is taken as is at DIGITS >= 9; otherwise
isNum (26.2/26.3), prefix +,
numberValue(DIGITS) (LoopCount) |
| NUMERIC DIGITS / FUZZ | unsigned at current DIGITS |
| PARSE absolute/relative positions and lengths | unsigned at current DIGITS (26.4) |
stem.0 counts (ADDRESS WITH, commands) |
unsigned at WholeDigits (26.904) |
| class methods with counts/indexes (Array, MutableBuffer, String...) | mostly unsigned at 18 |
WholeValue
(built-in function arguments, DATATYPE W)BIF arguments of type WHOLE (and DATATYPE(v, 'W'),
TRACE n) use WholeValue(s, digits): the value,
rounded to the precision, must lay out without an exponent and its
rounded value must have no fractional part. BIF WHOLE
arguments use WholeDigits (40.12, then 40.13/40.14 for the
sign requirements); D2C/D2X use the caller's DIGITS. This follows
ooRexx, which looks at the value, not at the text as the ANSI standard
does: 123E-2 is not whole and 1.5E1 is; at 3
digits 475.7 rounds to 476 and is whole. The argument types
are described in 11-builtins.md.
wholeNumber, unsignedWholeNumber and
isNum, like num, take an object's string
value. A Stem object in a whole-number context (DO x.,
NUMERIC DIGITS x., BIF lengths and positions) is replaced
by its default value without a string conversion (StemValue
/ stemValue), as ooRexx's
StemClass::numberValue does, so no NOSTRING condition is
raised there; arithmetic, ABS, SAY and similar still
convert (and can raise NOSTRING).
Normal comparison
(= \= <> >< < > <= >= \< \>;
CompareNormal / compareNormal): if both
operands are numbers, compare gives the sign of
a - b computed at DIGITS-FUZZ (at least 1); otherwise both
are compared as strings: leading and trailing blanks (blank and tab)
removed, the shorter padded on the right with blanks, then byte
comparison.
say (' 1 ' = '1') ('1.0' = '1') ('ab' = 'ab ') ('a' = 'a'||'00'x) -- 1 1 1 0
Strict comparison
(== \== << >> <<= >>=) never looks
at numbers: it compares str of both sides byte by byte with
no stripping or padding ('1.0' == '1' is 0,
'a' << 'a ' is 1).
.nil. A string or a number compared
with .nil is never equal and never in order: every
comparison operator gives 0 except \=,
<>, >< and \==, which
give 1 (native String, NumberString and Integer). If the left operand is
an object, the operator is a message to it (08-objects.md).
Logical operators (&,
|, &&, prefix \;
Boolean / boolean) require exactly the strings
0 or 1; anything else is 34.901, with no
numeric normalisation (1.0 & 1 is an error). The left
operand is checked first. Conditions of IF/WHEN/UNTIL/WHILE, GUARD WHEN
and CASE use the same test with their own minor codes (34.902,
34.905...).
Concatenation (||, abuttal, blank) uses
the value as it is (str), never normalising a number:
007||5 is 0075.
| Aspect | ooRexx host | JS host |
|---|---|---|
| Strings | host strings (bytes) | binary JS strings, latin1 at I/O |
| Digit arithmetic | Rexx string loops on digit strings | JS numbers for short operands, BigInt otherwise;
%/// and long division on
BigInt |
Integer whole |
whole-number string (host DIGITS 40) | BigInt |
| Exact plus/minus/compare path | yes (ExactAddSub) |
no |
WholeDigits |
.RexxInfo~internalDigits (18 or 9) |
18 |
| Strings too long for the host | memory-bound | RangeError → error 5 |
Results are identical: both are checked against native ooRexx (16-testing.md).
a + b with its
own +, but then half the semantics would stay implicit in
the host and the JS host would have nothing to port. The decimal
mechanics are written explicitly, as a port of
NumberStringMath.cpp/NumberStringMath2.cpp,
and native ooRexx is the oracle for them. (This is why these files are
under the CPL: see 19-licensing.md.) The
exact fast path is the only place where host arithmetic computes a Rexx
result, and only where it is provably the same as the windowed
algorithm.str boundary; otherwise results like
(1e3+0)*1.5 cannot be reproduced. Strings stay unwrapped
because a wrapper costs an allocation per value and buys nothing.adjustPrecision versus string): rounding
happens once, when a result is made; layout happens when text is needed,
from createdDigits, which is why a value made at DIGITS 12
still prints all its digits at DIGITS 5.IntegerClass.cpp's fast paths
and forwards exactly where ooRexx forwards; an Integer and a Number of
the same value are indistinguishable.BigInt for the heavy
operations are simple and fast enough. The digit helpers
(addDigits, subDigits, mulDigits,
compareDigits) keep the representation private, so it can
be changed (e.g. to limbs) without touching the operators.C2X, BITAND,
hashing and comparison are all per byte, and a file read and written
back must be byte-identical. JS strings are UTF-16; using one code unit
per byte (0–255) and latin1 at every boundary gives byte semantics with
native string operations, and comparing two binary strings with
< is byte order.parseNumber follows ooRexx's
numberStringScan/parseNumber, including the
exponent limits, instead of calling DATATYPE: the JS host
needs the same code, and the exact boundary (blanks, tabs, exponent
width) matters.NumberStringClass.cpp, NumberStringMath.cpp,
NumberStringMath2.cpp, IntegerClass.cpp,
Numerics.cpp): literals keep their text; a RexxInteger is
born only from digits-only literals and integer results; a NumberString
never goes back to RexxInteger; createdDigits drives the
layout; +x returns the same object only under the
conditions above; ARGUMENT_DIGITS is 18 on 64-bit.MIN/MAX with
integer arguments follow the NumberString path (rounding to DIGITS,
honouring FUZZ), not native's RexxInteger shortcut (at DIGITS 3 native
min(12345) is 12345, the RVM gives
1.23E+4). See 17-divergences.md.