Merge branches/quickjs to trunk. This is the way.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3621 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
2021-01-02 18:10:00 +00:00
parent d293637741
commit 79022e1e1f
703 changed files with 419987 additions and 30640 deletions

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -10,12 +10,12 @@
@sp 7
@center @titlefont{Javascript Bignum Extensions}
@sp 3
@center Version 2018-06-16
@center Version 2020-01-11
@sp 3
@center Author: Fabrice Bellard
@end titlepage
@setfilename spec.info
@setfilename jsbignum.info
@settitle Javascript Bignum Extensions
@contents
@ -27,347 +27,51 @@ language while being 100% backward compatible:
@itemize
@item Overloading of the standard operators
to support new types such as complex numbers, fractions or matrixes.
@item Bigint mode where arbitrarily large integers are available by default (no @code{n} suffix is necessary as in the TC39 BigInt proposal@footnote{@url{https://tc39.github.io/proposal-bigint/}}).
@item Operator overloading with a dispatch logic inspired from the proposal available at @url{https://github.com/tc39/proposal-operator-overloading/}.
@item Arbitrarily large floating point numbers (@code{BigFloat}) in base 2 using the IEEE 754 semantics.
@item Optional @code{math} mode which modifies the semantics of the division, modulo and power operator. The division and power operator return a fraction with integer operands and the modulo operator is defined as the Euclidian remainder.
@item Arbitrarily large floating point numbers (@code{BigDecimal}) in base 10 based on the proposal available at
@url{https://github.com/littledan/proposal-bigdecimal}.
@item @code{math} mode: arbitrarily large integers and floating point numbers are available by default. The integer division and power can be overloaded for example to return a fraction. The modulo operator (@code{%}) is defined as the Euclidian
remainder. @code{^} is an alias to the power operator
(@code{**}). @code{^^} is used as the exclusive or operator.
@end itemize
The extensions are independent from each other except the @code{math}
mode which relies on the bigint mode and the operator overloading.
mode which relies on BigFloat and operator overloading.
@chapter Operator overloading
@section Introduction
Operator overloading is inspired from the proposal available at
@url{https://github.com/tc39/proposal-operator-overloading/}. It
implements the same dispatch logic but finds the operator sets by
looking at the @code{Symbol.operatorSet} property in the objects. The
changes were done in order to simplify the implementation.
If the operands of an operator have at least one object type, a custom
operator method is searched before doing the legacy Javascript
@code{ToNumber} conversion.
For unary operators, the custom function is looked up in the object
and has the following name:
@table @code
@item unary +
@code{Symbol.operatorPlus}
@item unary -
@code{Symbol.operatorNeg}
@item ++
@code{Symbol.operatorInc}
@item --
@code{Symbol.operatorDec}
@item ~
@code{Symbol.operatorNot}
@end table
For binary operators:
More precisely, the following modifications were made:
@itemize
@item
If both operands have the same constructor function, then the operator
is looked up in the constructor.
@item @code{with operators from} is not supported. Operator overloading is always enabled.
@item
Otherwise, the property @code{Symbol.operatorOrder} is looked up in both
constructors and converted to @code{Int32}. The operator is then
looked in the constructor with the larger @code{Symbol.operatorOrder}
value. A @code{TypeError} is raised if both constructors have the same
@code{Symbol.operatorOrder} value.
@item The dispatch is not based on a static @code{[[OperatorSet]]} field in all instances. Instead, a dynamic lookup of the @code{Symbol.operatorSet} property is done. This property is typically added in the prototype of each object.
@item @code{Operators.create(...dictionaries)} is used to create a new OperatorSet object. The @code{Operators} function is supported as an helper to be closer to the TC39 proposal.
@item @code{[]} cannot be overloaded.
@item In math mode, the BigInt division and power operators can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.
@end itemize
The operator is looked up with the following name:
@chapter BigInt extensions
A few properties are added to the BigInt object:
@table @code
@item +
@code{Symbol.operatorAdd}
@item -
@code{Symbol.operatorSub}
@item *
@code{Symbol.operatorMul}
@item /
@code{Symbol.operatorDiv}
@item %
@code{Symbol.operatorMod}
@item % (math mode)
@code{Symbol.operatorMathMod}
@item **
@code{Symbol.operatorPow}
@item |
@code{Symbol.operatorOr}
@item ^
@code{Symbol.operatorXor}
@item &
@code{Symbol.operatorAnd}
@item <<
@code{Symbol.operatorShl}
@item >>
@code{Symbol.operatorShr}
@item <
@code{Symbol.operatorCmpLT}
@item >
@code{Symbol.operatorCmpLT}, operands swapped
@item <=
@code{Symbol.operatorCmpLE}
@item >=
@code{Symbol.operatorCmpLE}, operands swapped
@item ==, !=
@code{Symbol.operatorCmpEQ}
@end table
The return value of @code{Symbol.operatorCmpLT}, @code{Symbol.operatorCmpLE} and
@code{Symbol.operatorCmpEQ} is converted to @code{Boolean}.
@section Builtin Object changes
@subsection @code{Symbol} constructor
The following global symbols are added for the operator overloading:
@table @code
@item operatorOrder
@item operatorAdd
@item operatorSub
@item operatorMul
@item operatorDiv
@item operatorMod
@item operatorPow
@item operatorShl
@item operatorShr
@item operatorAnd
@item operatorOr
@item operatorXor
@item operatorCmpLT
@item operatorCmpLE
@item operatorCmpEQ
@item operatorPlus
@item operatorNeg
@item operatorNot
@item operatorInc
@item operatorDec
@end table
@chapter The BigInt Mode
@section Introduction
The bigint mode is enabled with the @code{"use bigint"} directive. It
propagates the same way as the strict mode. In bigint mode, all
integers are considered as @code{bigint} (arbitrarily large integer,
similar to the TC39 BigInt
proposal@footnote{@url{https://tc39.github.io/proposal-bigint/}})
instead of @code{number} (floating point number). In order to be able
to exchange data between standard and bigint modes, numbers are
internally represented as 3 different types:
@itemize
@item Small integer (SmallInt): 32 bit integer@footnote{Could be extended to 53 bits without changing the principle.}.
@item Big integer (BigInt): arbitrarily large integer.
@item Floating point number (Float).
@end itemize
In standard mode, the semantics of each operation is modified so that
when it returns a @code{number}, it is either of SmallInt or
Float. But the difference between SmallInt and Float is not observable
in standard mode.
In bigint mode, each operation behaves differently whether its
operands are integer or float. The difference between SmallInt and
BigInt is not observable (i.e. they are both integers).
The following table summarizes the observable types:
@multitable @columnfractions .3 .3 .3
@headitem Internal type @tab Observable type@* (standard mode) @tab Observable type@* (bigint mode)
@item SmallInt @tab number @tab bigint
@item BigInt @tab bigint @tab bigint
@item Float @tab number @tab number
@end multitable
@section Changes that introduce incompatibilities with Javascript
@subsection Standard mode
There is no incompatibility with Javascript.
@subsection Bigint mode
The following changes are visible:
@itemize
@item Integer and Float are different types. Constants are typed. For example: @code{typeof 1.0 === "number"} and @code{typeof 1 === "bigint"}. Another consequence is that @code{1.0 === 1} is false.
@item The range of integers is unlimited. In standard mode: @code{2**53 + 1 === 2**53}. This is no longer true with the bignum extensions.
@item Binary bitwise operators do not truncate to 32 bits i.e. @code{0x800000000 | 1 === 0x800000001} while it gives @code{1} in standard mode.
@item Bitwise shift operators do not truncate to 32 bits and do not mask the shift count with @code{0x1f} i.e. @code{1 << 32 === 4294967296} while it gives @code{1} in standard mode. However, the @code{>>>} operator (unsigned right shift) which is useless with bignums keeps its standard mode behavior@footnote{The unsigned right right operator could be removed in bigint mode.}.
@item Operators with integer operands never return the minus zero floating point value as result. Hence @code{Object.is(0, -0) === true}. Use @code{-0.0} to create a minus zero floating point value.
@item The @code{ToPrimitive} abstract operation is called with the @code{"integer"} preferred type when an integer is required (e.g. for bitwise binary or shift operations).
@item The prototype of integers is no longer @code{Number.prototype}. Instead@* @code{Object.getPrototypeOf(1) === BigInt.prototype}. The prototype of floats remains Number.prototype.
@item If the TC39 BigInt proposal is supported, there is no observable difference between integers and @code{bigint}s.
@end itemize
@section Operators
@subsection Arithmetic operators
The operands are converted to number values as in normal
Javascript. Then the general case is that an Integer is returned if
both operands are Integer. Otherwise, a float is returned.
The @code{+} operator also accepts strings as input and behaves like
standard Javascript in this case.
The binary operator @code{%} returns the truncated remainder of the
division. When the result is an Integer type, a dividend of zero yields a
RangeError exception.
The binary operator @code{%} in math mode returns the Euclidian
remainder of the division i.e. it is always positive.
The binary operator @code{/} returns a float.
The binary operator @code{/} in math mode returns a float if one of
the operands is float. Otherwise, @code{BigInt[Symbol.operatorDiv]} is
invoked.
The returned type of @code{a ** b} is Float if @math{a} or @math{b}
are Float. If @math{a} and @math{b} are integers:
@itemize
@item @math{b < 0} returns a Float in bigint mode. In math mode, @code{BigInt[Symbol.operatorPow]} is invoked.
@item @math{b >= 0} returns an integer.
@end itemize
The unary @code{-} and unary @code{+} return the same type as their
operand. They performs no floating point rounding when the result is a
float.
The unary operators @code{++} and @code{--} return the same type as
their operand.
In standard mode:
If the operator returns an Integer and that the result fits a
SmallInt, it is converted to SmallInt. Otherwise, the Integer is
converted to a Float.
In bigint mode:
If the operator returns an Integer and that the result fits a
SmallInt, it is converted to SmallInt. Otherwise it is a BigInt.
@subsection Logical operators
In standard mode:
The operands have their standard behavior. If the result fits a
SmallInt it is converted to a SmallInt. Otherwise it is a Float.
In bigint mode:
The operands are converted to integer values. The floating point
values are converted to integer by rounding them to zero.
The logical operators are defined assuming the integers are
represented in two complement notation.
For @code{<<} and @code{<<}, the shift can be positive or negative. So
@code{a << b} is defined as @math{\lfloor a/2^{-b} \rfloor} and
@code{a >> b} is defined as @math{\lfloor a/2^{b} \rfloor}.
The operator @code{>>>} is supported for backward compatibility and
behaves the same way as Javascript i.e. implicit conversion to @code{Uint32}.
If the result fits a SmallInt it is converted to a SmallInt. Otherwise
it is a BigInt.
@subsection Relational operators
The relational operators <, <=, >, >=, ==, != work as expected with
integers and floating point numbers (e.g. @code{1.0 == 1} is true).
The strict equality operators === and !== have the usual Javascript
semantics. In particular, different types never equal, so @code{1.0
=== 1} is false.
@section Number literals
Number literals in bigint mode have a slightly different behavior than
in standard Javascript:
@enumerate
@item
A number literal without a decimal point or an exponent is considered
as an Integer. Otherwise it is a Float.
@item
Hexadecimal, octal or binary floating point literals are accepted with
a decimal point or an exponent. The exponent is specified with the
@code{p} letter assuming a base 2. The same convention is used by
C99. Example: @code{0x1p3} is the same as @code{8.0}.
@end enumerate
@section Builtin Object changes
@subsection @code{BigInt} function
The @code{BigInt} function cannot be invoked as a constructor. When
invoked as a function, it converts its first parameter to an
integer. When a floating point number is given as parameter, it is
truncated to an integer with infinite precision.
@code{BigInt} properties:
@table @code
@item asIntN(bits, a)
Set @math{b=a \pmod{2^{bits}}}. Return @math{b} if @math{b < 2^{bits-1}}
otherwise @math{b-2^{bits}}.
@item asUintN(bits, a)
Return @math{a \pmod{2^{bits}}}.
@item tdiv(a, b)
Return @math{trunc(a/b)}. @code{b = 0} raises a RangeError
@ -410,63 +114,12 @@ Return the number of trailing zeros in the two's complement binary representatio
@end table
@subsection @code{BigInt.prototype}
It is a normal object.
@subsection @code{Number} constructor
The number constructor returns its argument rounded to a Float using
the global floating point environement. In bigint mode, the Number
constructor returns a Float. In standard mode, it returns a SmallInt
if the value fits it, otherwise a Float.
@subsection @code{Number.prototype}
The following properties are modified:
@table @code
@item toString(radix)
In bigint mode, integers are converted to the specified radix with
infinite precision.
@item toPrecision(p)
@item toFixed(p)
@item toExponential(p)
In bigint mode, integers are accepted and converted to string with
infinite precision.
@item parseInt(string, radix)
In bigint mode, an integer is returned and the conversion is done with
infinite precision.
@end table
@subsection @code{Math} object
The following properties are modified:
@table @code
@item abs(x)
Absolute value. Return an integer if @code{x} is an Integer. Otherwise
return a Float. No rounding is performed.
@item min(a, b)
@item max(a, b)
No rounding is performed. The returned type is the same one as the
minimum (resp. maximum) value.
@end table
@chapter Arbitrarily large floating point numbers
@chapter BigFloat
@section Introduction
This extension adds the @code{BigFloat} primitive type. The
@code{BigFloat} type represents floating point numbers are in base 2
@code{BigFloat} type represents floating point numbers in base 2
with the IEEE 754 semantics. A floating
point number is represented as a sign, mantissa and exponent. The
special values @code{NaN}, @code{+/-Infinity}, @code{+0} and @code{-0}
@ -490,14 +143,13 @@ explicit.}. The status flags of the global environment cannot be
read@footnote{The rationale is to avoid side effects for the built-in
operators.}. The precision of the global environment is
@code{BigFloatEnv.prec}. The number of exponent bits of the global
environment is @code{BigFloatEnv.expBits}. If @code{BigFloatEnv.expBits} is
strictly smaller than the maximum allowed number of exponent bits
(@code{BigFloatEnv.expBitsMax}), then the global environment subnormal
flag is set to @code{true}. Otherwise it is set to @code{false};
environment is @code{BigFloatEnv.expBits}. The global environment
subnormal flag is set to @code{true}.
For example, @code{prec = 53} and @code{ expBits = 11} give exactly
the same precision as the IEEE 754 64 bit floating point type. It is
the default floating point precision.
For example, @code{prec = 53} and @code{ expBits = 11} exactly give
the same precision as the IEEE 754 64 bit floating point format. The
default precision is @code{prec = 113} and @code{ expBits = 15} (IEEE
754 128 bit floating point format).
The global floating point environment can only be modified temporarily
when calling a function (see @code{BigFloatEnv.setPrec}). Hence a
@ -568,6 +220,12 @@ means radix 10 unless there is a hexadecimal or binary prefix. The
result is rounded according to the floating point environment @code{e}
or the global environment if @code{e} is undefined.
@item isFinite(a)
Return true if @code{a} is a finite bigfloat.
@item isNaN(a)
Return true if @code{a} is a NaN bigfloat.
@item add(a, b[, e])
@item sub(a, b[, e])
@item mul(a, b[, e])
@ -577,12 +235,14 @@ point number @code{a} according to the floating point environment
@code{e} or the global environment if @code{e} is undefined. If
@code{e} is specified, the floating point status flags are updated.
@item floor(x[, e])
@item ceil(x[, e])
@item round(x[, e])
@item trunc(x[, e])
Round to integer. A rounded @code{BigFloat} is returned. @code{e} is an
optional floating point environment.
@item floor(x)
@item ceil(x)
@item round(x)
@item trunc(x)
Round to an integer. No additional rounding is performed.
@item abs(x)
Return the absolute value of x. No additional rounding is performed.
@item fmod(x, y[, e])
@item remainder(x, y[, e])
@ -614,6 +274,9 @@ number. @code{e} is an optional floating point environment.
The following properties are modified:
@table @code
@item valueOf()
Return the bigfloat primitive value corresponding to @code{this}.
@item toString(radix)
For floating point numbers:
@ -630,13 +293,16 @@ the global precision and round to nearest gives the same number.
@end itemize
@item toPrecision(p[, rnd_mode])
@item toFixed(p[, rnd_mode])
@item toExponential(p[, rnd_mode])
The exponent letter is @code{e} for base 10, @code{p} for bases 2, 8,
16 with a binary exponent and @code{@@} for the other bases.
@item toPrecision(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)
@item toFixed(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)
@item toExponential(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)
Same semantics as the corresponding @code{Number} functions with
BigFloats. There is no limit on the accepted precision @code{p}. The
rounding mode can be optionally specified. It is set by default to
@code{BigFloatEnv.RNDNA}.
rounding mode and radix can be optionally specified. The radix must be
between 2 and 36.
@end table
@ -673,13 +339,12 @@ subnormal flags is set to @code{false}. If @code{rndMode} is
@item prec
Getter. Return the precision in bits of the global floating point
environment. The initial value is @code{53}.
environment. The initial value is @code{113}.
@item expBits
Getter. Return the exponent size in bits of the global floating point
environment assuming an IEEE 754 representation. If @code{expBits <
expBitsMax}, then subnormal numbers are supported. The initial value
is @code{11}.
environment assuming an IEEE 754 representation. The initial value is
@code{15}.
@item setPrec(f, p[, e])
Set the precision of the global floating point environment to @code{p}
@ -687,15 +352,13 @@ and the exponent size to @code{e} then call the function
@code{f}. Then the Float precision and exponent size are reset to
their precious value and the return value of @code{f} is returned (or
an exception is raised if @code{f} raised an exception). If @code{e}
is @code{undefined} it is set to @code{BigFloatEnv.expBitsMax}. @code{p}
must be >= 53 and @code{e} must be >= 11 so that the global precision
is at least equivalent to the IEEE 754 64 bit doubles.
is @code{undefined} it is set to @code{BigFloatEnv.expBitsMax}.
@item precMin
Read-only integer. Return the minimum allowed precision. Must be at least 2.
@item precMax
Read-only integer. Return the maximum allowed precision. Must be at least 53.
Read-only integer. Return the maximum allowed precision. Must be at least 113.
@item expBitsMin
Read-only integer. Return the minimum allowed exponent size in
@ -703,7 +366,7 @@ bits. Must be at least 3.
@item expBitsMax
Read-only integer. Return the maximum allowed exponent size in
bits. Must be at least 11.
bits. Must be at least 15.
@item RNDN
Read-only integer. Round to nearest, with ties to even rounding mode.
@ -720,12 +383,12 @@ Read-only integer. Round to +Infinity rounding mode.
@item RNDNA
Read-only integer. Round to nearest, with ties away from zero rounding mode.
@item RNDNU
Read-only integer. Round to nearest, with ties to +Infinity rounding mode.
@item RNDA
Read-only integer. Round away from zero rounding mode.
@item RNDF@footnote{Could be removed in case a deterministic behvior for floating point operations is required.}
@item RNDF@footnote{Could be removed in case a deterministic behavior for floating point operations is required.}
Read-only integer. Faithful rounding mode. The result is
non-deterministicly rounded to -Infinity or +Infinity. This rounding
non-deterministically rounded to -Infinity or +Infinity. This rounding
mode usually gives a faster and deterministic running time for the
floating point operations.
@ -761,69 +424,166 @@ Getter and setter (Boolean). Status flags.
@end table
@subsection @code{Math} object
@chapter BigDecimal
The following properties are modified:
This extension adds the @code{BigDecimal} primitive type. The
@code{BigDecimal} type represents floating point numbers in base
10. It is inspired from the proposal available at
@url{https://github.com/littledan/proposal-bigdecimal}.
The @code{BigDecimal} floating point numbers are always normalized and
finite. There is no concept of @code{-0}, @code{Infinity} or
@code{NaN}. By default, all the computations are done with infinite
precision.
@section Operators
The following builtin operators support BigDecimal:
@table @code
@item abs(x)
Absolute value. If @code{x} is a BigFloat, its absolute value is
returned as a BigFloat. No rounding is performed.
@item min(a, b)
@item max(a, b)
The returned type is the same one as the minimum (resp. maximum)
value, so @code{BigFloat} values are accepted. When a @code{BigFloat}
is returned, no rounding is performed.
@item +
@item -
@item *
Both operands must be BigDecimal. The result is computed with infinite
precision.
@item %
Both operands must be BigDecimal. The result is computed with infinite
precision. A range error is throws in case of division by zero.
@item /
Both operands must be BigDecimal. A range error is throws in case of
division by zero or if the result cannot be represented with infinite
precision (use @code{BigDecimal.div} to specify the rounding).
@item **
Both operands must be BigDecimal. The exponent must be a positive
integer. The result is computed with infinite precision.
@item ===
When one of the operand is a BigDecimal, return true if both operands
are a BigDecimal and if they are equal.
@item ==
@item !=
@item <=
@item >=
@item <
@item >
Numerical comparison. When one of the operand is not a BigDecimal, it is
converted to BigDecimal by using ToString(). Hence comparisons between
Number and BigDecimal do not use the exact mathematical value of the
Number value.
@end table
@section BigDecimal literals
BigDecimal literals are decimal floating point numbers with a trailing
@code{m} suffix.
@section Builtin Object changes
@subsection The @code{BigDecimal} function.
It returns @code{0m} if no parameter is provided. Otherwise the first
parameter is converted to a bigdecimal by using ToString(). Hence
Number values are not converted to their exact numerical value as
BigDecimal.
@subsection Properties of the @code{BigDecimal} object
@table @code
@item add(a, b[, e])
@item sub(a, b[, e])
@item mul(a, b[, e])
@item div(a, b[, e])
@item mod(a, b[, e])
@item sqrt(a, e)
@item round(a, e)
Perform the specified floating point operation and round the floating
point result according to the rounding object @code{e}. If the
rounding object is not present, the operation is executed with
infinite precision.
For @code{div}, a @code{RangeError} exception is thrown in case of
division by zero or if the result cannot be represented with infinite
precision if no rounding object is present.
For @code{sqrt}, a range error is thrown if @code{a} is less than
zero.
The rounding object must contain the following properties:
@code{roundingMode} is a string specifying the rounding mode
(@code{"floor"}, @code{"ceiling"}, @code{"down"}, @code{"up"},
@code{"half-even"}, @code{"half-up"}). Either
@code{maximumSignificantDigits} or @code{maximumFractionDigits} must
be present to specify respectively the number of significant digits
(must be >= 1) or the number of digits after the decimal point (must
be >= 0).
@end table
@subsection Properties of the @code{BigDecimal.prototype} object
@table @code
@item valueOf()
Return the bigdecimal primitive value corresponding to @code{this}.
@item toString()
Convert @code{this} to a string with infinite precision in base 10.
@item toPrecision(p, rnd_mode = "half-up")
@item toFixed(p, rnd_mode = "half-up")
@item toExponential(p, rnd_mode = "half-up")
Convert the BigDecimal @code{this} to string with the specified
precision @code{p}. There is no limit on the accepted precision
@code{p}. The rounding mode can be optionally
specified. @code{toPrecision} outputs either in decimal fixed notation
or in decimal exponential notation with a @code{p} digits of
precision. @code{toExponential} outputs in decimal exponential
notation with @code{p} digits after the decimal point. @code{toFixed}
outputs in decimal notation with @code{p} digits after the decimal
point.
@end table
@chapter Math mode
@section Introduction
A new @emph{math mode} is enabled with the @code{"use math"}
directive. @code{"use bigint"} is implied in math mode. With this
mode, writing mathematical expressions is more intuitive, exact
results (e.g. fractions) can be computed for all operators and floating
point literals have the @code{BigFloat} type by default.
directive. It propagates the same way as the @emph{strict mode}. It is
designed so that arbitrarily large integers and floating point numbers
are available by default. In order to minimize the number of changes
in the Javascript semantics, integers are represented either as Number
or BigInt depending on their magnitude. Floating point numbers are
always represented as BigFloat.
It propagates the same way as the @emph{strict mode}. In
this mode:
The following changes are made to the Javascript semantics:
@itemize
@item The @code{^} operator is a similar to the power operator (@code{**}).
@item Floating point literals (i.e. number with a decimal point or an exponent) are @code{BigFloat} by default (i.e. a @code{l} suffix is implied). Hence @code{typeof 1.0 === "bigfloat"}.
@item Integer literals (i.e. numbers without a decimal point or an exponent) with or without the @code{n} suffix are @code{BigInt} if their value cannot be represented as a safe integer. A safe integer is defined as a integer whose absolute value is smaller or equal to @code{2**53-1}. Hence @code{typeof 1 === "number "}, @code{typeof 1n === "number"} but @code{typeof 9007199254740992 === "bigint" }.
@item All the bigint builtin operators and functions are modified so that their result is returned as a Number if it is a safe integer. Otherwise the result stays a BigInt.
@item The builtin operators are modified so that they return an exact result (which can be a BigInt) if their operands are safe integers. Operands between Number and BigInt are accepted provided the Number operand is a safe integer. The integer power with a negative exponent returns a BigFloat as result. The integer division returns a BigFloat as result.
@item The @code{^} operator is an alias to the power operator (@code{**}).
@item The power operator (both @code{^} and @code{**}) grammar is modified so that @code{-2^2} is allowed and yields @code{-4}.
@item The logical xor operator is still available with the @code{^^} operator.
@item The division operator invokes @code{BigInt[Symbol.operatorDiv]} in case both operands are integers.
@item The modulo operator (@code{%}) returns the Euclidian remainder (always positive) instead of the truncated remainder.
@item The power operator invokes @code{BigInt[Symbol.operatorPow]} in case both operands are integers and the exponent is strictly negative.
@item The integer division operator can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.
@item The modulo operator returns the Euclidian remainder (always positive) instead of the truncated remainder.
@item Floating point literals are @code{BigFloat} by default (i.e. a @code{l} suffix is implied).
@item The integer power operator with a non zero negative exponent can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.
@end itemize
@section Builtin Object changes
@subsection @code{Symbol} constructor
The following global symbol is added for the operator overloading:
@table @code
@item operatorMathMod
@end table
@section Remaining issues
@enumerate
@item A new floating point literal suffix could be added for @code{Number} literals.
@end enumerate
@bye

View File

@ -1,8 +1,7 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by GNU Texinfo 6.5, http://www.gnu.org/software/texinfo/ -->
<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>QuickJS Javascript Engine</title>
<meta name="description" content="QuickJS Javascript Engine">
@ -10,6 +9,7 @@
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="#SEC_Contents" rel="contents" title="Table of Contents">
<style type="text/css">
<!--
@ -72,11 +72,10 @@ ul.no-bullet {list-style: none}
<ul class="no-bullet">
<li><a name="toc-Language-support" href="#Language-support">3.1 Language support</a>
<ul class="no-bullet">
<li><a name="toc-ES2019-support" href="#ES2019-support">3.1.1 ES2019 support</a></li>
<li><a name="toc-JSON" href="#JSON">3.1.2 JSON</a></li>
<li><a name="toc-ECMA402" href="#ECMA402">3.1.3 ECMA402</a></li>
<li><a name="toc-Extensions" href="#Extensions">3.1.4 Extensions</a></li>
<li><a name="toc-Mathematical-extensions" href="#Mathematical-extensions">3.1.5 Mathematical extensions</a></li>
<li><a name="toc-ES2020-support" href="#ES2020-support">3.1.1 ES2020 support</a></li>
<li><a name="toc-ECMA402" href="#ECMA402">3.1.2 ECMA402</a></li>
<li><a name="toc-Extensions" href="#Extensions">3.1.3 Extensions</a></li>
<li><a name="toc-Mathematical-extensions" href="#Mathematical-extensions">3.1.4 Mathematical extensions</a></li>
</ul></li>
<li><a name="toc-Modules" href="#Modules">3.2 Modules</a></li>
<li><a name="toc-Standard-library" href="#Standard-library">3.3 Standard library</a>
@ -118,7 +117,7 @@ ul.no-bullet {list-style: none}
</ul></li>
<li><a name="toc-RegExp" href="#RegExp">4.4 RegExp</a></li>
<li><a name="toc-Unicode" href="#Unicode">4.5 Unicode</a></li>
<li><a name="toc-BigInt-and-BigFloat" href="#BigInt-and-BigFloat">4.6 BigInt and BigFloat</a></li>
<li><a name="toc-BigInt_002c-BigFloat_002c-BigDecimal" href="#BigInt_002c-BigFloat_002c-BigDecimal">4.6 BigInt, BigFloat, BigDecimal</a></li>
</ul></li>
<li><a name="toc-License" href="#License">5 License</a></li>
@ -130,34 +129,34 @@ ul.no-bullet {list-style: none}
<h2 class="chapter">1 Introduction</h2>
<p>QuickJS is a small and embeddable Javascript engine. It supports the
ES2019 specification
ES2020 specification
<a name="DOCF1" href="#FOOT1"><sup>1</sup></a>
including modules, asynchronous generators and proxies.
including modules, asynchronous generators, proxies and BigInt.
</p>
<p>It optionally supports mathematical extensions such as big integers
(BigInt), big floating point numbers (BigFloat) and operator
overloading.
<p>It supports mathematical extensions such as big decimal float float
numbers (BigDecimal), big binary floating point numbers (BigFloat),
and operator overloading.
</p>
<a name="Main-Features"></a>
<h3 class="section">1.1 Main Features</h3>
<ul>
<li> Small and easily embeddable: just a few C files, no external dependency, 180 KiB of x86 code for a simple &ldquo;hello world&rdquo; program.
<li> Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple &ldquo;hello world&rdquo; program.
</li><li> Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite<a name="DOCF2" href="#FOOT2"><sup>2</sup></a> in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.
</li><li> Almost complete ES2019 support including modules, asynchronous
</li><li> Almost complete ES2020 support including modules, asynchronous
generators and full Annex B support (legacy web compatibility). Many
features from the upcoming ES2020 specification
features from the upcoming ES2021 specification
<a name="DOCF3" href="#FOOT3"><sup>3</sup></a> are also supported.
</li><li> Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2019 features.
</li><li> Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.
</li><li> Can compile Javascript sources to executables with no external dependency.
</li><li> Compile Javascript sources to executables with no external dependency.
</li><li> Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.
</li><li> Mathematical extensions: BigInt, BigFloat, operator overloading, bigint mode, math mode.
</li><li> Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.
</li><li> Command line interpreter with contextual colorization and completion implemented in Javascript.
@ -200,29 +199,13 @@ Javascript files and/or expressions as arguments to execute them:
<p>generates a <code>hello</code> executable with no external dependency.
</p>
<p><code>qjsbn</code> and <code>qjscbn</code> are the corresponding interpreter and
compiler with the mathematical extensions:
</p>
<div class="example">
<pre class="example">./qjsbn examples/pi.js 1000
</pre></div>
<p>displays 1000 digits of PI.
</p>
<div class="example">
<pre class="example">./qjsbnc -o pi examples/pi.js
./pi 1000
</pre></div>
<p>compiles and executes the PI program.
</p>
<a name="Command-line-options"></a>
<h3 class="section">2.3 Command line options</h3>
<a name="qjs-interpreter"></a>
<h4 class="subsection">2.3.1 <code>qjs</code> interpreter</h4>
<pre class="verbatim">usage: qjs [options] [files]
<pre class="verbatim">usage: qjs [options] [file [args]]
</pre>
<p>Options are:
</p><dl compact="compact">
@ -243,18 +226,35 @@ compiler with the mathematical extensions:
</dd>
<dt><code>-m</code></dt>
<dt><code>--module</code></dt>
<dd><p>Load as ES6 module (default=autodetect).
<dd><p>Load as ES6 module (default=autodetect). A module is autodetected if
the filename extension is <code>.mjs</code> or if the first keyword of the
source is <code>import</code>.
</p>
</dd>
<dt><code>--script</code></dt>
<dd><p>Load as ES6 script (default=autodetect).
</p>
</dd>
<dt><code>--bignum</code></dt>
<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and
the <code>&quot;use math&quot;</code> directive.
</p>
</dd>
<dt><code>-I file</code></dt>
<dt><code>--include file</code></dt>
<dd><p>Include an additional file.
</p>
</dd>
</dl>
<p>Advanced options are:
</p>
<dl compact="compact">
<dt><code>--std</code></dt>
<dd><p>Make the <code>std</code> and <code>os</code> modules available to the loaded
script even if it is not a module.
</p>
</dd>
<dt><code>-d</code></dt>
<dt><code>--dump</code></dt>
<dd><p>Dump the memory usage stats.
@ -293,6 +293,13 @@ executable file.
<dd><p>Compile as Javascript module (default=autodetect).
</p>
</dd>
<dt><code>-D module_name</code></dt>
<dd><p>Compile a dynamically loaded module and its dependencies. This option
is needed when your code uses the <code>import</code> keyword or the
<code>os.Worker</code> constructor because the compiler cannot statically
find the name of the dynamically loaded modules.
</p>
</dd>
<dt><code>-M module_name[,cname]</code></dt>
<dd><p>Add initialization code for an external C module. See the
<code>c_module</code> example.
@ -308,16 +315,21 @@ executable is smaller and faster. This option is automatically set
when the <code>-fno-x</code> options are used.
</p>
</dd>
<dt><code>-fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise]</code></dt>
<dt><code>-fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]</code></dt>
<dd><p>Disable selected language features to produce a smaller executable file.
</p>
</dd>
<dt><code>-fbignum</code></dt>
<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and
the <code>&quot;use math&quot;</code> directive.
</p>
</dd>
</dl>
<a name="qjscalc-application"></a>
<h3 class="section">2.4 <code>qjscalc</code> application</h3>
<p>The <code>qjscalc</code> application is a superset of the <code>qjsbn</code>
<p>The <code>qjscalc</code> application is a superset of the <code>qjs</code>
command line interpreter implementing a Javascript calculator with
arbitrarily large integer and floating point numbers, fractions,
complex numbers, polynomials and matrices. The source code is in
@ -333,13 +345,8 @@ QuickJS archive.
<a name="Test262-_0028ECMAScript-Test-Suite_0029"></a>
<h3 class="section">2.6 Test262 (ECMAScript Test Suite)</h3>
<p>A test262 runner is included in the QuickJS archive.
</p>
<p>For reference, the full test262 tests are provided in the archive
<samp>qjs-tests-yyyy-mm-dd.tar.xz</samp>. You just need to untar it into the
QuickJS source code directory.
</p>
<p>Alternatively, the test262 tests can be installed with:
<p>A test262 runner is included in the QuickJS archive. The test262 tests
can be installed in the QuickJS source directory with:
</p>
<div class="example">
<pre class="example">git clone https://github.com/tc39/test262.git test262
@ -358,11 +365,10 @@ slow string initialization function is optimized).
<pre class="example">make test2
</pre></div>
<p>The configuration files <code>test262.conf</code> (resp
<code>test262bn.conf</code> for the bignum version, <code>test262o.conf</code> for
the old ES5.1 tests<a name="DOCF4" href="#FOOT4"><sup>4</sup></a>)) contain the options
to run the various tests. Tests can be excluded based on features or
filename.
<p>The configuration files <code>test262.conf</code>
(resp. <code>test262o.conf</code> for the old ES5.1 tests<a name="DOCF4" href="#FOOT4"><sup>4</sup></a>))
contain the options to run the various tests. Tests can be excluded
based on features or filename.
</p>
<p>The file <code>test262_errors.txt</code> contains the current list of
errors. The runner displays a message when a new error appears or when
@ -394,33 +400,26 @@ about 100 seconds).
<a name="Language-support"></a>
<h3 class="section">3.1 Language support</h3>
<a name="ES2019-support"></a>
<h4 class="subsection">3.1.1 ES2019 support</h4>
<a name="ES2020-support"></a>
<h4 class="subsection">3.1.1 ES2020 support</h4>
<p>The ES2019 specification is almost fully supported including the Annex
<p>The ES2020 specification is almost fully supported including the Annex
B (legacy web compatibility) and the Unicode related features.
</p>
<p>The following features are not supported yet:
</p>
<ul>
<li> Realms (althougth the C API supports different runtimes and contexts)
</li><li> Tail calls<a name="DOCF6" href="#FOOT6"><sup>6</sup></a>
<li> Tail calls<a name="DOCF6" href="#FOOT6"><sup>6</sup></a>
</li></ul>
<a name="JSON"></a>
<h4 class="subsection">3.1.2 JSON</h4>
<p>The JSON parser is currently more tolerant than the specification.
</p>
<a name="ECMA402"></a>
<h4 class="subsection">3.1.3 ECMA402</h4>
<h4 class="subsection">3.1.2 ECMA402</h4>
<p>ECMA402 (Internationalization API) is not supported.
</p>
<a name="Extensions"></a>
<h4 class="subsection">3.1.4 Extensions</h4>
<h4 class="subsection">3.1.3 Extensions</h4>
<ul>
<li> The directive <code>&quot;use strip&quot;</code> indicates that the debug information (including the source code of the functions) should not be retained to save memory. As <code>&quot;use strict&quot;</code>, the directive can be global to a script or local to a function.
@ -430,14 +429,13 @@ B (legacy web compatibility) and the Unicode related features.
</li></ul>
<a name="Mathematical-extensions"></a>
<h4 class="subsection">3.1.5 Mathematical extensions</h4>
<h4 class="subsection">3.1.4 Mathematical extensions</h4>
<p>The mathematical extensions are available in the <code>qjsbn</code> version and are fully
backward compatible with standard Javascript. See <code>jsbignum.pdf</code>
for more information.
<p>The mathematical extensions are fully backward compatible with
standard Javascript. See <code>jsbignum.pdf</code> for more information.
</p>
<ul>
<li> The <code>BigInt</code> (big integers) TC39 proposal is supported.
<li> <code>BigDecimal</code> support: arbitrary large floating point numbers in base 10.
</li><li> <code>BigFloat</code> support: arbitrary large floating point numbers in base 2.
@ -503,58 +501,56 @@ and <samp>stdio.h</samp> and a few other utilities.
<dd><p>Exit the process.
</p>
</dd>
<dt><code>evalScript(str)</code></dt>
<dd><p>Evaluate the string <code>str</code> as a script (global eval).
<dt><code>evalScript(str, options = undefined)</code></dt>
<dd><p>Evaluate the string <code>str</code> as a script (global
eval). <code>options</code> is an optional object containing the following
optional properties:
</p>
<dl compact="compact">
<dt><code>backtrace_barrier</code></dt>
<dd><p>Boolean (default = false). If true, error backtraces do not list the
stack frames below the evalScript.
</p></dd>
</dl>
</dd>
<dt><code>loadScript(filename)</code></dt>
<dd><p>Evaluate the file <code>filename</code> as a script (global eval).
</p>
</dd>
<dt><code>Error(errno)</code></dt>
<dd>
<p><code>std.Error</code> constructor. Error instances contain the field
<code>errno</code> (error code) and <code>message</code> (result of
<code>std.Error.strerror(errno)</code>).
</p>
<p>The constructor contains the following fields:
</p>
<dl compact="compact">
<dt><code>EINVAL</code></dt>
<dt><code>EIO</code></dt>
<dt><code>EACCES</code></dt>
<dt><code>EEXIST</code></dt>
<dt><code>ENOSPC</code></dt>
<dt><code>ENOSYS</code></dt>
<dt><code>EBUSY</code></dt>
<dt><code>ENOENT</code></dt>
<dt><code>EPERM</code></dt>
<dt><code>EPIPE</code></dt>
<dd><p>Integer value of common errors (additional error codes may be defined).
</p></dd>
<dt><code>strerror(errno)</code></dt>
<dd><p>Return a string that describes the error <code>errno</code>.
</p></dd>
</dl>
</dd>
<dt><code>open(filename, flags)</code></dt>
<dd><p>Open a file (wrapper to the libc <code>fopen()</code>). Throws
<code>std.Error</code> in case of I/O error.
<dt><code>loadFile(filename)</code></dt>
<dd><p>Load the file <code>filename</code> and return it as a string assuming UTF-8
encoding. Return <code>null</code> in case of I/O error.
</p>
</dd>
<dt><code>popen(command, flags)</code></dt>
<dd><p>Open a process by creating a pipe (wrapper to the libc <code>popen()</code>). Throws
<code>std.Error</code> in case of I/O error.
<dt><code>open(filename, flags, errorObj = undefined)</code></dt>
<dd><p>Open a file (wrapper to the libc <code>fopen()</code>). Return the FILE
object or <code>null</code> in case of I/O error. If <code>errorObj</code> is not
undefined, set its <code>errno</code> property to the error code or to 0 if
no error occured.
</p>
</dd>
<dt><code>fdopen(fd, flags)</code></dt>
<dt><code>popen(command, flags, errorObj = undefined)</code></dt>
<dd><p>Open a process by creating a pipe (wrapper to the libc
<code>popen()</code>). Return the FILE
object or <code>null</code> in case of I/O error. If <code>errorObj</code> is not
undefined, set its <code>errno</code> property to the error code or to 0 if
no error occured.
</p>
</dd>
<dt><code>fdopen(fd, flags, errorObj = undefined)</code></dt>
<dd><p>Open a file from a file handle (wrapper to the libc
<code>fdopen()</code>). Throws <code>std.Error</code> in case of I/O error.
<code>fdopen()</code>). Return the FILE
object or <code>null</code> in case of I/O error. If <code>errorObj</code> is not
undefined, set its <code>errno</code> property to the error code or to 0 if
no error occured.
</p>
</dd>
<dt><code>tmpfile()</code></dt>
<dd><p>Open a temporary file. Throws <code>std.Error</code> in case of I/O error.
<dt><code>tmpfile(errorObj = undefined)</code></dt>
<dd><p>Open a temporary file. Return the FILE
object or <code>null</code> in case of I/O error. If <code>errorObj</code> is not
undefined, set its <code>errno</code> property to the error code or to 0 if
no error occured.
</p>
</dd>
<dt><code>puts(str)</code></dt>
@ -562,7 +558,7 @@ and <samp>stdio.h</samp> and a few other utilities.
</p>
</dd>
<dt><code>printf(fmt, ...args)</code></dt>
<dd><p>Equivalent to <code>std.out.printf(fmt, ...args)</code>
<dd><p>Equivalent to <code>std.out.printf(fmt, ...args)</code>.
</p>
</dd>
<dt><code>sprintf(fmt, ...args)</code></dt>
@ -581,6 +577,29 @@ and <samp>stdio.h</samp> and a few other utilities.
<dd><p>Constants for seek().
</p>
</dd>
<dt><code>Error</code></dt>
<dd>
<p>Enumeration object containing the integer value of common errors
(additional error codes may be defined):
</p>
<dl compact="compact">
<dt><code>EINVAL</code></dt>
<dt><code>EIO</code></dt>
<dt><code>EACCES</code></dt>
<dt><code>EEXIST</code></dt>
<dt><code>ENOSPC</code></dt>
<dt><code>ENOSYS</code></dt>
<dt><code>EBUSY</code></dt>
<dt><code>ENOENT</code></dt>
<dt><code>EPERM</code></dt>
<dt><code>EPIPE</code></dt>
</dl>
</dd>
<dt><code>strerror(errno)</code></dt>
<dd><p>Return a string that describes the error <code>errno</code>.
</p>
</dd>
<dt><code>gc()</code></dt>
<dd><p>Manually invoke the cycle removal algorithm. The cycle removal
algorithm is automatically started when needed, so this function is
@ -592,6 +611,19 @@ useful in case of specific memory constraints or for testing.
<code>undefined</code> if it is not defined.
</p>
</dd>
<dt><code>setenv(name, value)</code></dt>
<dd><p>Set the value of the environment variable <code>name</code> to the string
<code>value</code>.
</p>
</dd>
<dt><code>unsetenv(name)</code></dt>
<dd><p>Delete the environment variable <code>name</code>.
</p>
</dd>
<dt><code>getenviron()</code></dt>
<dd><p>Return an object containing the environment variables as key-value pairs.
</p>
</dd>
<dt><code>urlGet(url, options = undefined)</code></dt>
<dd>
<p>Download <code>url</code> using the <samp>curl</samp> command line
@ -606,16 +638,33 @@ optional properties:
</p>
</dd>
<dt><code>full</code></dt>
<dd><p>Boolean (default = false). If true, return the an object contains
<dd>
<p>Boolean (default = false). If true, return the an object contains
the properties <code>response</code> (response content),
<code>responseHeaders</code> (headers separated by CRLF), <code>status</code>
(status code). If <code>full</code> is false, only the response is
returned if the status is between 200 and 299. Otherwise an
<code>std.Error</code> exception is raised.
(status code). <code>response</code> is <code>null</code> is case of protocol or
network error. If <code>full</code> is false, only the response is
returned if the status is between 200 and 299. Otherwise <code>null</code>
is returned.
</p>
</dd>
</dl>
</dd>
<dt><code>parseExtJSON(str)</code></dt>
<dd>
<p>Parse <code>str</code> using a superset of <code>JSON.parse</code>. The
following extensions are accepted:
</p>
<ul>
<li> Single line and multiline comments
</li><li> unquoted properties (ASCII-only Javascript identifiers)
</li><li> trailing comma in array and object definitions
</li><li> single quoted strings
</li><li> <code>\f</code> and <code>\v</code> are accepted as space characters
</li><li> leading plus in numbers
</li><li> octal (<code>0o</code> prefix) and hexadecimal (<code>0x</code> prefix) numbers
</li></ul>
</dd>
</dl>
@ -623,29 +672,45 @@ optional properties:
</p>
<dl compact="compact">
<dt><code>close()</code></dt>
<dd><p>Close the file.
<dd><p>Close the file. Return 0 if OK or <code>-errno</code> in case of I/O error.
</p></dd>
<dt><code>puts(str)</code></dt>
<dd><p>Outputs the string with the UTF-8 encoding.
</p></dd>
<dt><code>printf(fmt, ...args)</code></dt>
<dd><p>Formatted printf, same formats as the libc printf.
</p></dd>
<dd><p>Formatted printf.
</p>
<p>The same formats as the standard C library <code>printf</code> are
supported. Integer format types (e.g. <code>%d</code>) truncate the Numbers
or BigInts to 32 bits. Use the <code>l</code> modifier (e.g. <code>%ld</code>) to
truncate to 64 bits.
</p>
</dd>
<dt><code>flush()</code></dt>
<dd><p>Flush the buffered file.
</p></dd>
<dt><code>seek(offset, whence)</code></dt>
<dd><p>Seek to a give file position (whence is <code>std.SEEK_*</code>). Throws a
<code>std.Error</code> in case of I/O error.
<dd><p>Seek to a give file position (whence is
<code>std.SEEK_*</code>). <code>offset</code> can be a number or a bigint. Return
0 if OK or <code>-errno</code> in case of I/O error.
</p></dd>
<dt><code>tell()</code></dt>
<dd><p>Return the current file position.
</p></dd>
<dt><code>tello()</code></dt>
<dd><p>Return the current file position as a bigint.
</p></dd>
<dt><code>eof()</code></dt>
<dd><p>Return true if end of file.
</p></dd>
<dt><code>fileno()</code></dt>
<dd><p>Return the associated OS handle.
</p></dd>
<dt><code>error()</code></dt>
<dd><p>Return true if there was an error.
</p></dd>
<dt><code>clearerr()</code></dt>
<dd><p>Clear the error indication.
</p>
</dd>
<dt><code>read(buffer, position, length)</code></dt>
@ -655,7 +720,7 @@ position <code>position</code> (wrapper to the libc <code>fread</code>).
</dd>
<dt><code>write(buffer, position, length)</code></dt>
<dd><p>Write <code>length</code> bytes to the file from the ArrayBuffer <code>buffer</code> at byte
position <code>position</code> (wrapper to the libc <code>fread</code>).
position <code>position</code> (wrapper to the libc <code>fwrite</code>).
</p>
</dd>
<dt><code>getline()</code></dt>
@ -663,8 +728,14 @@ position <code>position</code> (wrapper to the libc <code>fread</code>).
the trailing line feed.
</p>
</dd>
<dt><code>readAsString(max_size = undefined)</code></dt>
<dd><p>Read <code>max_size</code> bytes from the file and return them as a string
assuming UTF-8 encoding. If <code>max_size</code> is not present, the file
is read up its end.
</p>
</dd>
<dt><code>getByte()</code></dt>
<dd><p>Return the next byte from the file.
<dd><p>Return the next byte from the file. Return -1 if the end of file is reached.
</p>
</dd>
<dt><code>putByte(c)</code></dt>
@ -682,6 +753,7 @@ the trailing line feed.
</li><li> signals
</li><li> timers
</li><li> asynchronous I/O
</li><li> workers (threads)
</li></ul>
<p>The OS functions usually return 0 if OK or an OS specific negative
@ -713,7 +785,9 @@ error code.
</p>
</dd>
<dt><code>seek(fd, offset, whence)</code></dt>
<dd><p>Seek in the file. Use <code>std.SEEK_*</code> for <code>whence</code>.
<dd><p>Seek in the file. Use <code>std.SEEK_*</code> for
<code>whence</code>. <code>offset</code> is either a number or a bigint. If
<code>offset</code> is a bigint, a bigint is returned too.
</p>
</dd>
<dt><code>read(fd, buffer, offset, length)</code></dt>
@ -741,11 +815,11 @@ Return the number of written bytes or &lt; 0 if error.
</p>
</dd>
<dt><code>remove(filename)</code></dt>
<dd><p>Remove a file. Return 0 if OK or &lt; 0 if error.
<dd><p>Remove a file. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>rename(oldname, newname)</code></dt>
<dd><p>Rename a file. Return 0 if OK or &lt; 0 if error.
<dd><p>Rename a file. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>realpath(path)</code></dt>
@ -758,8 +832,12 @@ pathname of <code>path</code> and <code>err</code> the error code.
and <code>err</code> the error code.
</p>
</dd>
<dt><code>chdir(path)</code></dt>
<dd><p>Change the current directory. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>mkdir(path, mode = 0o777)</code></dt>
<dd><p>Create a directory at <code>path</code>. Return the error code.
<dd><p>Create a directory at <code>path</code>. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>stat(path)</code></dt>
@ -791,11 +869,11 @@ itself.
</dd>
<dt><code>utimes(path, atime, mtime)</code></dt>
<dd><p>Change the access and modification times of the file <code>path</code>. The
times are specified in milliseconds since 1970.
times are specified in milliseconds since 1970. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>symlink(target, linkpath)</code></dt>
<dd><p>Create a link at <code>linkpath</code> containing the string <code>target</code>.
<dd><p>Create a link at <code>linkpath</code> containing the string <code>target</code>. Return 0 if OK or <code>-errno</code>.
</p>
</dd>
<dt><code>readlink(path)</code></dt>
@ -813,21 +891,21 @@ the error code.
<dd><p>Add a read handler to the file handle <code>fd</code>. <code>func</code> is called
each time there is data pending for <code>fd</code>. A single read handler
per file handle is supported. Use <code>func = null</code> to remove the
hander.
handler.
</p>
</dd>
<dt><code>setWriteHandler(fd, func)</code></dt>
<dd><p>Add a write handler to the file handle <code>fd</code>. <code>func</code> is
called each time data can be written to <code>fd</code>. A single write
handler per file handle is supported. Use <code>func = null</code> to remove
the hander.
the handler.
</p>
</dd>
<dt><code>signal(signal, func)</code></dt>
<dd><p>Call the function <code>func</code> when the signal <code>signal</code>
happens. Only a single handler per signal number is supported. Use
<code>null</code> to set the default handler or <code>undefined</code> to ignore
the signal.
the signal. Signal handlers can only be defined in the main thread.
</p>
</dd>
<dt><code>SIGINT</code></dt>
@ -850,7 +928,7 @@ object containing optional parameters:
<dl compact="compact">
<dt><code>block</code></dt>
<dd><p>Boolean (default = true). If true, wait until the process is
termined. In this case, <code>exec</code> return the exit code if positive
terminated. In this case, <code>exec</code> return the exit code if positive
or the negated signal number if the process was interrupted by a
signal. If false, do not block and return the process id of the child.
</p>
@ -872,13 +950,28 @@ object containing optional parameters:
<dt><code>stdout</code></dt>
<dt><code>stderr</code></dt>
<dd><p>If present, set the handle in the child for stdin, stdout or stderr.
</p>
</p>
</dd>
<dt><code>env</code></dt>
<dd><p>Object. If present, set the process environment from the object
key-value pairs. Otherwise use the same environment as the current
process.
</p>
</dd>
<dt><code>uid</code></dt>
<dd><p>Integer. If present, the process uid with <code>setuid</code>.
</p>
</dd>
<dt><code>gid</code></dt>
<dd><p>Integer. If present, the process gid with <code>setgid</code>.
</p>
</dd>
</dl>
</dd>
<dt><code>waitpid(pid, options)</code></dt>
<dd><p><code>waitpid</code> Unix system call. Return the array <code>[ret, status]</code>.
<dd><p><code>waitpid</code> Unix system call. Return the array <code>[ret,
status]</code>. <code>ret</code> contains <code>-errno</code> in case of error.
</p>
</dd>
<dt><code>WNOHANG</code></dt>
@ -915,6 +1008,50 @@ to the timer.
<dd><p>Return a string representing the platform: <code>&quot;linux&quot;</code>, <code>&quot;darwin&quot;</code>,
<code>&quot;win32&quot;</code> or <code>&quot;js&quot;</code>.
</p>
</dd>
<dt><code>Worker(module_filename)</code></dt>
<dd><p>Constructor to create a new thread (worker) with an API close to the
<code>WebWorkers</code>. <code>module_filename</code> is a string specifying the
module filename which is executed in the newly created thread. As for
dynamically imported module, it is relative to the current script or
module path. Threads normally don&rsquo;t share any data and communicate
between each other with messages. Nested workers are not supported. An
example is available in <samp>tests/test_worker.js</samp>.
</p>
<p>The worker class has the following static properties:
</p>
<dl compact="compact">
<dt><code>parent</code></dt>
<dd><p>In the created worker, <code>Worker.parent</code> represents the parent
worker and is used to send or receive messages.
</p></dd>
</dl>
<p>The worker instances have the following properties:
</p>
<dl compact="compact">
<dt><code>postMessage(msg)</code></dt>
<dd>
<p>Send a message to the corresponding worker. <code>msg</code> is cloned in
the destination worker using an algorithm similar to the <code>HTML</code>
structured clone algorithm. <code>SharedArrayBuffer</code> are shared
between workers.
</p>
<p>Current limitations: <code>Map</code> and <code>Set</code> are not supported
yet.
</p>
</dd>
<dt><code>onmessage</code></dt>
<dd>
<p>Getter and setter. Set a function which is called each time a
message is received. The function is called with a single
argument. It is an object with a <code>data</code> property containing the
received message. The thread is not terminated if there is at least
one non <code>null</code> <code>onmessage</code> handler.
</p>
</dd>
</dl>
</dd>
</dl>
@ -934,7 +1071,7 @@ supported.
</p>
<p><code>JSContext</code> represents a Javascript context (or Realm). Each
JSContext has its own global objects and system objects. There can be
several JSContexts per JSRuntime and they can share objects, similary
several JSContexts per JSRuntime and they can share objects, similar
to frames of the same origin sharing Javascript objects in a
web browser.
</p>
@ -943,7 +1080,7 @@ web browser.
<p><code>JSValue</code> represents a Javascript value which can be a primitive
type or an object. Reference counting is used, so it is important to
explicitely duplicate (<code>JS_DupValue()</code>, increment the reference
explicitly duplicate (<code>JS_DupValue()</code>, increment the reference
count) or free (<code>JS_FreeValue()</code>, decrement the reference count)
JSValues.
</p>
@ -965,9 +1102,9 @@ general rule, C functions take constant <code>JSValue</code>s as parameters
<h4 class="subsection">3.4.4 Exceptions</h4>
<p>Exceptions: most C functions can return a Javascript exception. It
must be explicitely tested and handled by the C code. The specific
must be explicitly tested and handled by the C code. The specific
<code>JSValue</code> <code>JS_EXCEPTION</code> indicates that an exception
occured. The actual exception object is stored in the
occurred. The actual exception object is stored in the
<code>JSContext</code> and can be retrieved with <code>JS_GetException()</code>.
</p>
<a name="Script-evaluation"></a>
@ -1171,16 +1308,16 @@ stack holds the Javascript parameters and local variables.
<a name="RegExp"></a>
<h3 class="section">4.4 RegExp</h3>
<p>A specific regular expression engine was developped. It is both small
<p>A specific regular expression engine was developed. It is both small
and efficient and supports all the ES2020 features including the
Unicode properties. As the Javascript compiler, it directly generates
bytecode without a parse tree.
</p>
<p>Backtracking with an explicit stack is used so that there is no
recursion on the system stack. Simple quantizers are specifically
recursion on the system stack. Simple quantifiers are specifically
optimized to avoid recursions.
</p>
<p>Infinite recursions coming from quantizers with empty terms are
<p>Infinite recursions coming from quantifiers with empty terms are
avoided.
</p>
<p>The full regexp library weights about 15 KiB (x86 code), excluding the
@ -1189,9 +1326,9 @@ Unicode library.
<a name="Unicode"></a>
<h3 class="section">4.5 Unicode</h3>
<p>A specific Unicode library was developped so that there is no
<p>A specific Unicode library was developed so that there is no
dependency on an external large Unicode library such as ICU. All the
Unicode tables are compressed while keeping a reasonnable access
Unicode tables are compressed while keeping a reasonable access
speed.
</p>
<p>The library supports case conversion, Unicode normalization, Unicode
@ -1200,11 +1337,11 @@ binary properties.
</p>
<p>The full Unicode library weights about 45 KiB (x86 code).
</p>
<a name="BigInt-and-BigFloat"></a>
<h3 class="section">4.6 BigInt and BigFloat</h3>
<a name="BigInt_002c-BigFloat_002c-BigDecimal"></a>
<h3 class="section">4.6 BigInt, BigFloat, BigDecimal</h3>
<p>BigInt and BigFloat are implemented with the <code>libbf</code>
library<a name="DOCF7" href="#FOOT7"><sup>7</sup></a>. It weights about 60
<p>BigInt, BigFloat and BigDecimal are implemented with the <code>libbf</code>
library<a name="DOCF7" href="#FOOT7"><sup>7</sup></a>. It weights about 90
KiB (x86 code) and provides arbitrary precision IEEE 754 floating
point operations and transcendental functions with exact rounding.
</p>
@ -1221,15 +1358,15 @@ Bellard and Charlie Gordon.
<h4 class="footnotes-heading">Footnotes</h4>
<h3><a name="FOOT1" href="#DOCF1">(1)</a></h3>
<p><a href="https://www.ecma-international.org/ecma-262/10.0">https://www.ecma-international.org/ecma-262/10.0</a></p>
<p><a href="https://tc39.es/ecma262/">https://tc39.es/ecma262/</a></p>
<h3><a name="FOOT2" href="#DOCF2">(2)</a></h3>
<p><a href="https://github.com/tc39/test262">https://github.com/tc39/test262</a></p>
<h3><a name="FOOT3" href="#DOCF3">(3)</a></h3>
<p><a href="https://tc39.github.io/ecma262/">https://tc39.github.io/ecma262/</a></p>
<h3><a name="FOOT4" href="#DOCF4">(4)</a></h3>
<p>The old ES5.1 tests can be extracted with
<code>git clone --single-branch --branch es5-tests
https://github.com/tc39/test262.git test262o</code></p>
<p>The old
ES5.1 tests can be extracted with <code>git clone --single-branch
--branch es5-tests https://github.com/tc39/test262.git test262o</code></p>
<h3><a name="FOOT5" href="#DOCF5">(5)</a></h3>
<p><a href="https://github.com/bterlson/test262-harness">https://github.com/bterlson/test262-harness</a></p>
<h3><a name="FOOT6" href="#DOCF6">(6)</a></h3>

Binary file not shown.

View File

@ -20,34 +20,34 @@
@chapter Introduction
QuickJS is a small and embeddable Javascript engine. It supports the
ES2019 specification
@footnote{@url{https://www.ecma-international.org/ecma-262/10.0}}
including modules, asynchronous generators and proxies.
ES2020 specification
@footnote{@url{https://tc39.es/ecma262/}}
including modules, asynchronous generators, proxies and BigInt.
It optionally supports mathematical extensions such as big integers
(BigInt), big floating point numbers (BigFloat) and operator
overloading.
It supports mathematical extensions such as big decimal float float
numbers (BigDecimal), big binary floating point numbers (BigFloat),
and operator overloading.
@section Main Features
@itemize
@item Small and easily embeddable: just a few C files, no external dependency, 180 KiB of x86 code for a simple ``hello world'' program.
@item Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple ``hello world'' program.
@item Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite@footnote{@url{https://github.com/tc39/test262}} in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.
@item Almost complete ES2019 support including modules, asynchronous
@item Almost complete ES2020 support including modules, asynchronous
generators and full Annex B support (legacy web compatibility). Many
features from the upcoming ES2020 specification
features from the upcoming ES2021 specification
@footnote{@url{https://tc39.github.io/ecma262/}} are also supported.
@item Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2019 features.
@item Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.
@item Can compile Javascript sources to executables with no external dependency.
@item Compile Javascript sources to executables with no external dependency.
@item Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.
@item Mathematical extensions: BigInt, BigFloat, operator overloading, bigint mode, math mode.
@item Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.
@item Command line interpreter with contextual colorization and completion implemented in Javascript.
@ -87,28 +87,12 @@ Javascript files and/or expressions as arguments to execute them:
generates a @code{hello} executable with no external dependency.
@code{qjsbn} and @code{qjscbn} are the corresponding interpreter and
compiler with the mathematical extensions:
@example
./qjsbn examples/pi.js 1000
@end example
displays 1000 digits of PI.
@example
./qjsbnc -o pi examples/pi.js
./pi 1000
@end example
compiles and executes the PI program.
@section Command line options
@subsection @code{qjs} interpreter
@verbatim
usage: qjs [options] [files]
usage: qjs [options] [file [args]]
@end verbatim
Options are:
@ -127,16 +111,30 @@ Go to interactive mode (it is not the default when files are provided on the com
@item -m
@item --module
Load as ES6 module (default=autodetect).
Load as ES6 module (default=autodetect). A module is autodetected if
the filename extension is @code{.mjs} or if the first keyword of the
source is @code{import}.
@item --script
Load as ES6 script (default=autodetect).
@item --bignum
Enable the bignum extensions: BigDecimal object, BigFloat object and
the @code{"use math"} directive.
@item -I file
@item --include file
Include an additional file.
@end table
Advanced options are:
@table @code
@item --std
Make the @code{std} and @code{os} modules available to the loaded
script even if it is not a module.
@item -d
@item --dump
Dump the memory usage stats.
@ -169,6 +167,12 @@ Set the C name of the generated data.
@item -m
Compile as Javascript module (default=autodetect).
@item -D module_name
Compile a dynamically loaded module and its dependencies. This option
is needed when your code uses the @code{import} keyword or the
@code{os.Worker} constructor because the compiler cannot statically
find the name of the dynamically loaded modules.
@item -M module_name[,cname]
Add initialization code for an external C module. See the
@code{c_module} example.
@ -181,14 +185,18 @@ Use link time optimization. The compilation is slower but the
executable is smaller and faster. This option is automatically set
when the @code{-fno-x} options are used.
@item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise]
@item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]
Disable selected language features to produce a smaller executable file.
@item -fbignum
Enable the bignum extensions: BigDecimal object, BigFloat object and
the @code{"use math"} directive.
@end table
@section @code{qjscalc} application
The @code{qjscalc} application is a superset of the @code{qjsbn}
The @code{qjscalc} application is a superset of the @code{qjs}
command line interpreter implementing a Javascript calculator with
arbitrarily large integer and floating point numbers, fractions,
complex numbers, polynomials and matrices. The source code is in
@ -202,13 +210,8 @@ QuickJS archive.
@section Test262 (ECMAScript Test Suite)
A test262 runner is included in the QuickJS archive.
For reference, the full test262 tests are provided in the archive
@file{qjs-tests-yyyy-mm-dd.tar.xz}. You just need to untar it into the
QuickJS source code directory.
Alternatively, the test262 tests can be installed with:
A test262 runner is included in the QuickJS archive. The test262 tests
can be installed in the QuickJS source directory with:
@example
git clone https://github.com/tc39/test262.git test262
@ -227,13 +230,12 @@ The tests can be run with
make test2
@end example
The configuration files @code{test262.conf} (resp
@code{test262bn.conf} for the bignum version, @code{test262o.conf} for
the old ES5.1 tests@footnote{The old ES5.1 tests can be extracted with
@code{git clone --single-branch --branch es5-tests
https://github.com/tc39/test262.git test262o}})) contain the options
to run the various tests. Tests can be excluded based on features or
filename.
The configuration files @code{test262.conf}
(resp. @code{test262o.conf} for the old ES5.1 tests@footnote{The old
ES5.1 tests can be extracted with @code{git clone --single-branch
--branch es5-tests https://github.com/tc39/test262.git test262o}}))
contain the options to run the various tests. Tests can be excluded
based on features or filename.
The file @code{test262_errors.txt} contains the current list of
errors. The runner displays a message when a new error appears or when
@ -263,25 +265,19 @@ about 100 seconds).
@section Language support
@subsection ES2019 support
@subsection ES2020 support
The ES2019 specification is almost fully supported including the Annex
The ES2020 specification is almost fully supported including the Annex
B (legacy web compatibility) and the Unicode related features.
The following features are not supported yet:
@itemize
@item Realms (althougth the C API supports different runtimes and contexts)
@item Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.}
@end itemize
@subsection JSON
The JSON parser is currently more tolerant than the specification.
@subsection ECMA402
ECMA402 (Internationalization API) is not supported.
@ -298,13 +294,12 @@ ECMA402 (Internationalization API) is not supported.
@subsection Mathematical extensions
The mathematical extensions are available in the @code{qjsbn} version and are fully
backward compatible with standard Javascript. See @code{jsbignum.pdf}
for more information.
The mathematical extensions are fully backward compatible with
standard Javascript. See @code{jsbignum.pdf} for more information.
@itemize
@item The @code{BigInt} (big integers) TC39 proposal is supported.
@item @code{BigDecimal} support: arbitrary large floating point numbers in base 10.
@item @code{BigFloat} support: arbitrary large floating point numbers in base 2.
@ -364,56 +359,55 @@ Available exports:
@item exit(n)
Exit the process.
@item evalScript(str)
Evaluate the string @code{str} as a script (global eval).
@item evalScript(str, options = undefined)
Evaluate the string @code{str} as a script (global
eval). @code{options} is an optional object containing the following
optional properties:
@table @code
@item backtrace_barrier
Boolean (default = false). If true, error backtraces do not list the
stack frames below the evalScript.
@end table
@item loadScript(filename)
Evaluate the file @code{filename} as a script (global eval).
@item Error(errno)
@item loadFile(filename)
Load the file @code{filename} and return it as a string assuming UTF-8
encoding. Return @code{null} in case of I/O error.
@code{std.Error} constructor. Error instances contain the field
@code{errno} (error code) and @code{message} (result of
@code{std.Error.strerror(errno)}).
@item open(filename, flags, errorObj = undefined)
Open a file (wrapper to the libc @code{fopen()}). Return the FILE
object or @code{null} in case of I/O error. If @code{errorObj} is not
undefined, set its @code{errno} property to the error code or to 0 if
no error occured.
The constructor contains the following fields:
@item popen(command, flags, errorObj = undefined)
Open a process by creating a pipe (wrapper to the libc
@code{popen()}). Return the FILE
object or @code{null} in case of I/O error. If @code{errorObj} is not
undefined, set its @code{errno} property to the error code or to 0 if
no error occured.
@table @code
@item EINVAL
@item EIO
@item EACCES
@item EEXIST
@item ENOSPC
@item ENOSYS
@item EBUSY
@item ENOENT
@item EPERM
@item EPIPE
Integer value of common errors (additional error codes may be defined).
@item strerror(errno)
Return a string that describes the error @code{errno}.
@end table
@item open(filename, flags)
Open a file (wrapper to the libc @code{fopen()}). Throws
@code{std.Error} in case of I/O error.
@item popen(command, flags)
Open a process by creating a pipe (wrapper to the libc @code{popen()}). Throws
@code{std.Error} in case of I/O error.
@item fdopen(fd, flags)
@item fdopen(fd, flags, errorObj = undefined)
Open a file from a file handle (wrapper to the libc
@code{fdopen()}). Throws @code{std.Error} in case of I/O error.
@code{fdopen()}). Return the FILE
object or @code{null} in case of I/O error. If @code{errorObj} is not
undefined, set its @code{errno} property to the error code or to 0 if
no error occured.
@item tmpfile()
Open a temporary file. Throws @code{std.Error} in case of I/O error.
@item tmpfile(errorObj = undefined)
Open a temporary file. Return the FILE
object or @code{null} in case of I/O error. If @code{errorObj} is not
undefined, set its @code{errno} property to the error code or to 0 if
no error occured.
@item puts(str)
Equivalent to @code{std.out.puts(str)}.
@item printf(fmt, ...args)
Equivalent to @code{std.out.printf(fmt, ...args)}
Equivalent to @code{std.out.printf(fmt, ...args)}.
@item sprintf(fmt, ...args)
Equivalent to the libc sprintf().
@ -428,6 +422,27 @@ Wrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}.
@item SEEK_END
Constants for seek().
@item Error
Enumeration object containing the integer value of common errors
(additional error codes may be defined):
@table @code
@item EINVAL
@item EIO
@item EACCES
@item EEXIST
@item ENOSPC
@item ENOSYS
@item EBUSY
@item ENOENT
@item EPERM
@item EPIPE
@end table
@item strerror(errno)
Return a string that describes the error @code{errno}.
@item gc()
Manually invoke the cycle removal algorithm. The cycle removal
algorithm is automatically started when needed, so this function is
@ -437,6 +452,16 @@ useful in case of specific memory constraints or for testing.
Return the value of the environment variable @code{name} or
@code{undefined} if it is not defined.
@item setenv(name, value)
Set the value of the environment variable @code{name} to the string
@code{value}.
@item unsetenv(name)
Delete the environment variable @code{name}.
@item getenviron()
Return an object containing the environment variables as key-value pairs.
@item urlGet(url, options = undefined)
Download @code{url} using the @file{curl} command line
@ -450,37 +475,66 @@ optional properties:
to be UTF-8 encoded.
@item full
Boolean (default = false). If true, return the an object contains
the properties @code{response} (response content),
@code{responseHeaders} (headers separated by CRLF), @code{status}
(status code). If @code{full} is false, only the response is
returned if the status is between 200 and 299. Otherwise an
@code{std.Error} exception is raised.
(status code). @code{response} is @code{null} is case of protocol or
network error. If @code{full} is false, only the response is
returned if the status is between 200 and 299. Otherwise @code{null}
is returned.
@end table
@item parseExtJSON(str)
Parse @code{str} using a superset of @code{JSON.parse}. The
following extensions are accepted:
@itemize
@item Single line and multiline comments
@item unquoted properties (ASCII-only Javascript identifiers)
@item trailing comma in array and object definitions
@item single quoted strings
@item @code{\f} and @code{\v} are accepted as space characters
@item leading plus in numbers
@item octal (@code{0o} prefix) and hexadecimal (@code{0x} prefix) numbers
@end itemize
@end table
FILE prototype:
@table @code
@item close()
Close the file.
Close the file. Return 0 if OK or @code{-errno} in case of I/O error.
@item puts(str)
Outputs the string with the UTF-8 encoding.
@item printf(fmt, ...args)
Formatted printf, same formats as the libc printf.
Formatted printf.
The same formats as the standard C library @code{printf} are
supported. Integer format types (e.g. @code{%d}) truncate the Numbers
or BigInts to 32 bits. Use the @code{l} modifier (e.g. @code{%ld}) to
truncate to 64 bits.
@item flush()
Flush the buffered file.
@item seek(offset, whence)
Seek to a give file position (whence is @code{std.SEEK_*}). Throws a
@code{std.Error} in case of I/O error.
Seek to a give file position (whence is
@code{std.SEEK_*}). @code{offset} can be a number or a bigint. Return
0 if OK or @code{-errno} in case of I/O error.
@item tell()
Return the current file position.
@item tello()
Return the current file position as a bigint.
@item eof()
Return true if end of file.
@item fileno()
Return the associated OS handle.
@item error()
Return true if there was an error.
@item clearerr()
Clear the error indication.
@item read(buffer, position, length)
Read @code{length} bytes from the file to the ArrayBuffer @code{buffer} at byte
@ -488,14 +542,19 @@ position @code{position} (wrapper to the libc @code{fread}).
@item write(buffer, position, length)
Write @code{length} bytes to the file from the ArrayBuffer @code{buffer} at byte
position @code{position} (wrapper to the libc @code{fread}).
position @code{position} (wrapper to the libc @code{fwrite}).
@item getline()
Return the next line from the file, assuming UTF-8 encoding, excluding
the trailing line feed.
@item readAsString(max_size = undefined)
Read @code{max_size} bytes from the file and return them as a string
assuming UTF-8 encoding. If @code{max_size} is not present, the file
is read up its end.
@item getByte()
Return the next byte from the file.
Return the next byte from the file. Return -1 if the end of file is reached.
@item putByte(c)
Write one byte to the file.
@ -510,6 +569,7 @@ The @code{os} module provides Operating System specific functions:
@item signals
@item timers
@item asynchronous I/O
@item workers (threads)
@end itemize
The OS functions usually return 0 if OK or an OS specific negative
@ -537,7 +597,9 @@ POSIX open flags.
Close the file handle @code{fd}.
@item seek(fd, offset, whence)
Seek in the file. Use @code{std.SEEK_*} for @code{whence}.
Seek in the file. Use @code{std.SEEK_*} for
@code{whence}. @code{offset} is either a number or a bigint. If
@code{offset} is a bigint, a bigint is returned too.
@item read(fd, buffer, offset, length)
Read @code{length} bytes from the file handle @code{fd} to the
@ -559,10 +621,10 @@ Return the TTY size as @code{[width, height]} or @code{null} if not available.
Set the TTY in raw mode.
@item remove(filename)
Remove a file. Return 0 if OK or < 0 if error.
Remove a file. Return 0 if OK or @code{-errno}.
@item rename(oldname, newname)
Rename a file. Return 0 if OK or < 0 if error.
Rename a file. Return 0 if OK or @code{-errno}.
@item realpath(path)
Return @code{[str, err]} where @code{str} is the canonicalized absolute
@ -572,8 +634,11 @@ pathname of @code{path} and @code{err} the error code.
Return @code{[str, err]} where @code{str} is the current working directory
and @code{err} the error code.
@item chdir(path)
Change the current directory. Return 0 if OK or @code{-errno}.
@item mkdir(path, mode = 0o777)
Create a directory at @code{path}. Return the error code.
Create a directory at @code{path}. Return 0 if OK or @code{-errno}.
@item stat(path)
@item lstat(path)
@ -602,10 +667,10 @@ Constants to interpret the @code{mode} property returned by
@item utimes(path, atime, mtime)
Change the access and modification times of the file @code{path}. The
times are specified in milliseconds since 1970.
times are specified in milliseconds since 1970. Return 0 if OK or @code{-errno}.
@item symlink(target, linkpath)
Create a link at @code{linkpath} containing the string @code{target}.
Create a link at @code{linkpath} containing the string @code{target}. Return 0 if OK or @code{-errno}.
@item readlink(path)
Return @code{[str, err]} where @code{str} is the link target and @code{err}
@ -620,19 +685,19 @@ the error code.
Add a read handler to the file handle @code{fd}. @code{func} is called
each time there is data pending for @code{fd}. A single read handler
per file handle is supported. Use @code{func = null} to remove the
hander.
handler.
@item setWriteHandler(fd, func)
Add a write handler to the file handle @code{fd}. @code{func} is
called each time data can be written to @code{fd}. A single write
handler per file handle is supported. Use @code{func = null} to remove
the hander.
the handler.
@item signal(signal, func)
Call the function @code{func} when the signal @code{signal}
happens. Only a single handler per signal number is supported. Use
@code{null} to set the default handler or @code{undefined} to ignore
the signal.
the signal. Signal handlers can only be defined in the main thread.
@item SIGINT
@item SIGABRT
@ -652,7 +717,7 @@ object containing optional parameters:
@table @code
@item block
Boolean (default = true). If true, wait until the process is
termined. In this case, @code{exec} return the exit code if positive
terminated. In this case, @code{exec} return the exit code if positive
or the negated signal number if the process was interrupted by a
signal. If false, do not block and return the process id of the child.
@ -670,11 +735,23 @@ object containing optional parameters:
@item stdout
@item stderr
If present, set the handle in the child for stdin, stdout or stderr.
@item env
Object. If present, set the process environment from the object
key-value pairs. Otherwise use the same environment as the current
process.
@item uid
Integer. If present, the process uid with @code{setuid}.
@item gid
Integer. If present, the process gid with @code{setgid}.
@end table
@item waitpid(pid, options)
@code{waitpid} Unix system call. Return the array @code{[ret, status]}.
@code{waitpid} Unix system call. Return the array @code{[ret,
status]}. @code{ret} contains @code{-errno} in case of error.
@item WNOHANG
Constant for the @code{options} argument of @code{waitpid}.
@ -703,6 +780,46 @@ Cancel a timer.
Return a string representing the platform: @code{"linux"}, @code{"darwin"},
@code{"win32"} or @code{"js"}.
@item Worker(module_filename)
Constructor to create a new thread (worker) with an API close to the
@code{WebWorkers}. @code{module_filename} is a string specifying the
module filename which is executed in the newly created thread. As for
dynamically imported module, it is relative to the current script or
module path. Threads normally don't share any data and communicate
between each other with messages. Nested workers are not supported. An
example is available in @file{tests/test_worker.js}.
The worker class has the following static properties:
@table @code
@item parent
In the created worker, @code{Worker.parent} represents the parent
worker and is used to send or receive messages.
@end table
The worker instances have the following properties:
@table @code
@item postMessage(msg)
Send a message to the corresponding worker. @code{msg} is cloned in
the destination worker using an algorithm similar to the @code{HTML}
structured clone algorithm. @code{SharedArrayBuffer} are shared
between workers.
Current limitations: @code{Map} and @code{Set} are not supported
yet.
@item onmessage
Getter and setter. Set a function which is called each time a
message is received. The function is called with a single
argument. It is an object with a @code{data} property containing the
received message. The thread is not terminated if there is at least
one non @code{null} @code{onmessage} handler.
@end table
@end table
@section QuickJS C API
@ -719,7 +836,7 @@ supported.
@code{JSContext} represents a Javascript context (or Realm). Each
JSContext has its own global objects and system objects. There can be
several JSContexts per JSRuntime and they can share objects, similary
several JSContexts per JSRuntime and they can share objects, similar
to frames of the same origin sharing Javascript objects in a
web browser.
@ -727,7 +844,7 @@ web browser.
@code{JSValue} represents a Javascript value which can be a primitive
type or an object. Reference counting is used, so it is important to
explicitely duplicate (@code{JS_DupValue()}, increment the reference
explicitly duplicate (@code{JS_DupValue()}, increment the reference
count) or free (@code{JS_FreeValue()}, decrement the reference count)
JSValues.
@ -747,9 +864,9 @@ general rule, C functions take constant @code{JSValue}s as parameters
@subsection Exceptions
Exceptions: most C functions can return a Javascript exception. It
must be explicitely tested and handled by the C code. The specific
must be explicitly tested and handled by the C code. The specific
@code{JSValue} @code{JS_EXCEPTION} indicates that an exception
occured. The actual exception object is stored in the
occurred. The actual exception object is stored in the
@code{JSContext} and can be retrieved with @code{JS_GetException()}.
@subsection Script evaluation
@ -934,16 +1051,16 @@ stack holds the Javascript parameters and local variables.
@section RegExp
A specific regular expression engine was developped. It is both small
A specific regular expression engine was developed. It is both small
and efficient and supports all the ES2020 features including the
Unicode properties. As the Javascript compiler, it directly generates
bytecode without a parse tree.
Backtracking with an explicit stack is used so that there is no
recursion on the system stack. Simple quantizers are specifically
recursion on the system stack. Simple quantifiers are specifically
optimized to avoid recursions.
Infinite recursions coming from quantizers with empty terms are
Infinite recursions coming from quantifiers with empty terms are
avoided.
The full regexp library weights about 15 KiB (x86 code), excluding the
@ -951,9 +1068,9 @@ Unicode library.
@section Unicode
A specific Unicode library was developped so that there is no
A specific Unicode library was developed so that there is no
dependency on an external large Unicode library such as ICU. All the
Unicode tables are compressed while keeping a reasonnable access
Unicode tables are compressed while keeping a reasonable access
speed.
The library supports case conversion, Unicode normalization, Unicode
@ -962,10 +1079,10 @@ binary properties.
The full Unicode library weights about 45 KiB (x86 code).
@section BigInt and BigFloat
@section BigInt, BigFloat, BigDecimal
BigInt and BigFloat are implemented with the @code{libbf}
library@footnote{@url{https://bellard.org/libbf}}. It weights about 60
BigInt, BigFloat and BigDecimal are implemented with the @code{libbf}
library@footnote{@url{https://bellard.org/libbf}}. It weights about 90
KiB (x86 code) and provides arbitrary precision IEEE 754 floating
point operations and transcendental functions with exact rounding.