\input texinfo @iftex@afourpaper@headings double@end iftex @titlepage@afourpaper@sp 7@center @titlefont{QuickJS Javascript Engine}@sp 3@end titlepage @setfilename spec.info@settitle QuickJS Javascript Engine @contents @chapter Introduction QuickJS is a small and embeddable Javascript engine. It supports theES2020 specification@footnote{@url{https://tc39.es/ecma262/}}including modules, asynchronous generators, proxies and BigInt. It supports mathematical extensions such as big decimal float floatnumbers (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, 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 ES2020 support including modules, asynchronousgenerators and full Annex B support (legacy web compatibility). Manyfeatures 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 ES2020 features. @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: BigDecimal, BigFloat, operator overloading, bigint mode, math mode. @item Command line interpreter with contextual colorization and completion implemented in Javascript. @item Small built-in standard library with C library wrappers. @end itemize @chapter Usage @section Installation A Makefile is provided to compile the engine on Linux or MacOS/X. Apreliminary Windows support is available thru cross compilation on aLinux host with the MingGW tools. Edit the top of the @code{Makefile} if you wish to select specificoptions then run @code{make}. You can type @code{make install} as root if you wish to install the binaries and support files to@code{/usr/local} (this is not necessary to use QuickJS). @section Quick start @code{qjs} is the command line interpreter (Read-Eval-Print Loop). You can passJavascript files and/or expressions as arguments to execute them: @example./qjs examples/hello.js@end example @code{qjsc} is the command line compiler: @example./qjsc -o hello examples/hello.js./hello@end example generates a @code{hello} executable with no external dependency. @section Command line options @subsection @code{qjs} interpreter @verbatimusage: qjs [options] [file [args]]@end verbatim Options are:@table @code@item -h@item --helpList options. @item -e @code{EXPR}@item --eval @code{EXPR}Evaluate EXPR. @item -i@item --interactiveGo to interactive mode (it is not the default when files are provided on the command line). @item -m@item --moduleLoad as ES6 module (default=autodetect). A module is autodetected ifthe filename extension is @code{.mjs} or if the first keyword of thesource is @code{import}. @item --scriptLoad as ES6 script (default=autodetect). @item --bignumEnable the bignum extensions: BigDecimal object, BigFloat object andthe @code{"use math"} directive. @item -I file@item --include fileInclude an additional file. @end table Advanced options are: @table @code@item --stdMake the @code{std} and @code{os} modules available to the loadedscript even if it is not a module. @item -d@item --dumpDump the memory usage stats. @item -q@item --quitjust instantiate the interpreter and quit. @end table @subsection @code{qjsc} compiler @verbatimusage: qjsc [options] [files]@end verbatim Options are:@table @code@item -cOnly output bytecode in a C file. The default is to output an executable file.@item -e Output @code{main()} and bytecode in a C file. The default is to output anexecutable file.@item -o outputSet the output filename (default = @file{out.c} or @file{a.out}). @item -N cnameSet the C name of the generated data. @item -mCompile as Javascript module (default=autodetect). @item -D module_nameCompile a dynamically loaded module and its dependencies. This optionis needed when your code uses the @code{import} keyword or the@code{os.Worker} constructor because the compiler cannot staticallyfind 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. @item -xByte swapped output (only used for cross compilation). @item -fltoUse link time optimization. The compilation is slower but theexecutable is smaller and faster. This option is automatically setwhen the @code{-fno-x} options are used. @item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]Disable selected language features to produce a smaller executable file. @item -fbignumEnable the bignum extensions: BigDecimal object, BigFloat object andthe @code{"use math"} directive. @end table @section @code{qjscalc} application The @code{qjscalc} application is a superset of the @code{qjs}command line interpreter implementing a Javascript calculator witharbitrarily large integer and floating point numbers, fractions,complex numbers, polynomials and matrices. The source code is in@file{qjscalc.js}. More documentation and a web version are available at@url{http://numcalc.com}. @section Built-in tests Run @code{make test} to run the few built-in tests included in theQuickJS archive. @section Test262 (ECMAScript Test Suite) A test262 runner is included in the QuickJS archive. The test262 testscan be installed in the QuickJS source directory with: @examplegit clone https://github.com/tc39/test262.git test262cd test262patch -p1 < ../tests/test262.patchcd ..@end example The patch adds the implementation specific @code{harness} functionsand optimizes the inefficient RegExp character classes and Unicodeproperty escapes tests (the tests themselves are not modified, only aslow string initialization function is optimized). The tests can be run with@examplemake test2@end example The configuration files @code{test262.conf}(resp. @code{test262o.conf} for the old ES5.1 tests@footnote{The oldES5.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 excludedbased on features or filename. The file @code{test262_errors.txt} contains the current list oferrors. The runner displays a message when a new error appears or whenan existing error is corrected or modified. Use the @code{-u} optionto update the current list of errors (or @code{make test2-update}). The file @code{test262_report.txt} contains the logs of all thetests. It is useful to have a clearer analysis of a particularerror. In case of crash, the last line corresponds to the failingtest. Use the syntax @code{./run-test262 -c test262.conf -f filename.js} torun a single test. Use the syntax @code{./run-test262 -c test262.confN} to start testing at test number @code{N}. For more information, run @code{./run-test262} to see the command lineoptions of the test262 runner. @code{run-test262} accepts the @code{-N} option to be invoked from@code{test262-harness}@footnote{@url{https://github.com/bterlson/test262-harness}}thru @code{eshost}. Unless you want to compare QuickJS with otherengines under the same conditions, we do not recommend to run thetests this way as it is much slower (typically half an hour instead ofabout 100 seconds). @chapter Specifications @section Language support @subsection ES2020 support The ES2020 specification is almost fully supported including the AnnexB (legacy web compatibility) and the Unicode related features. The following features are not supported yet: @itemize @item Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.} @end itemize @subsection ECMA402 ECMA402 (Internationalization API) is not supported. @subsection Extensions @itemize @item The directive @code{"use strip"} indicates that the debug information (including the source code of the functions) should not be retained to save memory. As @code{"use strict"}, the directive can be global to a script or local to a function. @item The first line of a script beginning with @code{#!} is ignored. @end itemize @subsection Mathematical extensions The mathematical extensions are fully backward compatible withstandard Javascript. See @code{jsbignum.pdf} for more information. @itemize @item @code{BigDecimal} support: arbitrary large floating point numbers in base 10. @item @code{BigFloat} support: arbitrary large floating point numbers in base 2. @item Operator overloading. @item The directive @code{"use bigint"} enables the bigint mode where integers are @code{BigInt} by default. @item The directive @code{"use math"} enables the math mode where the division and power operators on integers produce fractions. Floating point literals are @code{BigFloat} by default and integers are @code{BigInt} by default. @end itemize @section Modules ES6 modules are fully supported. The default name resolution is thefollowing: @itemize @item Module names with a leading @code{.} or @code{..} are relativeto the current module path. @item Module names without a leading @code{.} or @code{..} are systemmodules, such as @code{std} or @code{os}. @item Module names ending with @code{.so} are native modules using theQuickJS C API. @end itemize @section Standard library The standard library is included by default in the command lineinterpreter. It contains the two modules @code{std} and @code{os} anda few global objects. @subsection Global objects @table @code@item scriptArgsProvides the command line arguments. The first argument is the script name.@item print(...args)Print the arguments separated by spaces and a trailing newline.@item console.log(...args)Same as print(). @end table @subsection @code{std} module The @code{std} module provides wrappers to the libc @file{stdlib.h}and @file{stdio.h} and a few other utilities. Available exports: @table @code @item exit(n)Exit the process. @item evalScript(str, options = undefined)Evaluate the string @code{str} as a script (globaleval). @code{options} is an optional object containing the followingoptional 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 loadFile(filename)Load the file @code{filename} and return it as a string assuming UTF-8encoding. Return @code{null} in case of I/O error. @item open(filename, flags, errorObj = undefined)Open a file (wrapper to the libc @code{fopen()}). Return the FILEobject or @code{null} in case of I/O error. If @code{errorObj} is notundefined, set its @code{errno} property to the error code or to 0 ifno error occured. @item popen(command, flags, errorObj = undefined)Open a process by creating a pipe (wrapper to the libc@code{popen()}). Return the FILEobject or @code{null} in case of I/O error. If @code{errorObj} is notundefined, set its @code{errno} property to the error code or to 0 ifno error occured. @item fdopen(fd, flags, errorObj = undefined)Open a file from a file handle (wrapper to the libc@code{fdopen()}). Return the FILEobject or @code{null} in case of I/O error. If @code{errorObj} is notundefined, set its @code{errno} property to the error code or to 0 ifno error occured. @item tmpfile(errorObj = undefined)Open a temporary file. Return the FILEobject or @code{null} in case of I/O error. If @code{errorObj} is notundefined, set its @code{errno} property to the error code or to 0 ifno error occured. @item puts(str)Equivalent to @code{std.out.puts(str)}. @item printf(fmt, ...args)Equivalent to @code{std.out.printf(fmt, ...args)}. @item sprintf(fmt, ...args)Equivalent to the libc sprintf(). @item in@item out@item errWrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}. @item SEEK_SET@item SEEK_CUR@item SEEK_ENDConstants 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 removalalgorithm is automatically started when needed, so this function isuseful in case of specific memory constraints or for testing. @item getenv(name)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 lineutility. @code{options} is an optional object containing the followingoptional properties: @table @code @item binary Boolean (default = false). If true, the response is an ArrayBuffer instead of a string. When a string is returned, the data is assumed 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). @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 numbersLines 1–500 of 1096. Load more
\input texinfo @iftex @afourpaper @headings double @end iftex @titlepage @afourpaper @sp 7 @center @titlefont{QuickJS Javascript Engine} @sp 3 @end titlepage @setfilename spec.info @settitle QuickJS Javascript Engine @contents @chapter Introduction QuickJS is a small and embeddable Javascript engine. It supports the ES2020 specification @footnote{@url{https://tc39.es/ecma262/}} including modules, asynchronous generators, proxies and BigInt. 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, 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 ES2020 support including modules, asynchronous generators and full Annex B support (legacy web compatibility). Many 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 ES2020 features. @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: BigDecimal, BigFloat, operator overloading, bigint mode, math mode. @item Command line interpreter with contextual colorization and completion implemented in Javascript. @item Small built-in standard library with C library wrappers. @end itemize @chapter Usage @section Installation A Makefile is provided to compile the engine on Linux or MacOS/X. A preliminary Windows support is available thru cross compilation on a Linux host with the MingGW tools. Edit the top of the @code{Makefile} if you wish to select specific options then run @code{make}. You can type @code{make install} as root if you wish to install the binaries and support files to @code{/usr/local} (this is not necessary to use QuickJS). @section Quick start @code{qjs} is the command line interpreter (Read-Eval-Print Loop). You can pass Javascript files and/or expressions as arguments to execute them: @example ./qjs examples/hello.js @end example @code{qjsc} is the command line compiler: @example ./qjsc -o hello examples/hello.js ./hello @end example generates a @code{hello} executable with no external dependency. @section Command line options @subsection @code{qjs} interpreter @verbatim usage: qjs [options] [file [args]] @end verbatim Options are: @table @code @item -h @item --help List options. @item -e @code{EXPR} @item --eval @code{EXPR} Evaluate EXPR. @item -i @item --interactive Go to interactive mode (it is not the default when files are provided on the command line). @item -m @item --module 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. @item -q @item --quit just instantiate the interpreter and quit. @end table @subsection @code{qjsc} compiler @verbatim usage: qjsc [options] [files] @end verbatim Options are: @table @code @item -c Only output bytecode in a C file. The default is to output an executable file. @item -e Output @code{main()} and bytecode in a C file. The default is to output an executable file. @item -o output Set the output filename (default = @file{out.c} or @file{a.out}). @item -N cname 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. @item -x Byte swapped output (only used for cross compilation). @item -flto 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|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{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 @file{qjscalc.js}. More documentation and a web version are available at @url{http://numcalc.com}. @section Built-in tests Run @code{make test} to run the few built-in tests included in the QuickJS archive. @section Test262 (ECMAScript Test Suite) 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 cd test262 patch -p1 < ../tests/test262.patch cd .. @end example The patch adds the implementation specific @code{harness} functions and optimizes the inefficient RegExp character classes and Unicode property escapes tests (the tests themselves are not modified, only a slow string initialization function is optimized). The tests can be run with @example make test2 @end example 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 an existing error is corrected or modified. Use the @code{-u} option to update the current list of errors (or @code{make test2-update}). The file @code{test262_report.txt} contains the logs of all the tests. It is useful to have a clearer analysis of a particular error. In case of crash, the last line corresponds to the failing test. Use the syntax @code{./run-test262 -c test262.conf -f filename.js} to run a single test. Use the syntax @code{./run-test262 -c test262.conf N} to start testing at test number @code{N}. For more information, run @code{./run-test262} to see the command line options of the test262 runner. @code{run-test262} accepts the @code{-N} option to be invoked from @code{test262-harness}@footnote{@url{https://github.com/bterlson/test262-harness}} thru @code{eshost}. Unless you want to compare QuickJS with other engines under the same conditions, we do not recommend to run the tests this way as it is much slower (typically half an hour instead of about 100 seconds). @chapter Specifications @section Language support @subsection ES2020 support 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 Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.} @end itemize @subsection ECMA402 ECMA402 (Internationalization API) is not supported. @subsection Extensions @itemize @item The directive @code{"use strip"} indicates that the debug information (including the source code of the functions) should not be retained to save memory. As @code{"use strict"}, the directive can be global to a script or local to a function. @item The first line of a script beginning with @code{#!} is ignored. @end itemize @subsection Mathematical extensions The mathematical extensions are fully backward compatible with standard Javascript. See @code{jsbignum.pdf} for more information. @itemize @item @code{BigDecimal} support: arbitrary large floating point numbers in base 10. @item @code{BigFloat} support: arbitrary large floating point numbers in base 2. @item Operator overloading. @item The directive @code{"use bigint"} enables the bigint mode where integers are @code{BigInt} by default. @item The directive @code{"use math"} enables the math mode where the division and power operators on integers produce fractions. Floating point literals are @code{BigFloat} by default and integers are @code{BigInt} by default. @end itemize @section Modules ES6 modules are fully supported. The default name resolution is the following: @itemize @item Module names with a leading @code{.} or @code{..} are relative to the current module path. @item Module names without a leading @code{.} or @code{..} are system modules, such as @code{std} or @code{os}. @item Module names ending with @code{.so} are native modules using the QuickJS C API. @end itemize @section Standard library The standard library is included by default in the command line interpreter. It contains the two modules @code{std} and @code{os} and a few global objects. @subsection Global objects @table @code @item scriptArgs Provides the command line arguments. The first argument is the script name. @item print(...args) Print the arguments separated by spaces and a trailing newline. @item console.log(...args) Same as print(). @end table @subsection @code{std} module The @code{std} module provides wrappers to the libc @file{stdlib.h} and @file{stdio.h} and a few other utilities. Available exports: @table @code @item exit(n) Exit the process. @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 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. @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. @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. @item fdopen(fd, flags, errorObj = undefined) Open a file from a file handle (wrapper to the libc @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(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)}. @item sprintf(fmt, ...args) Equivalent to the libc sprintf(). @item in @item out @item err Wrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}. @item SEEK_SET @item SEEK_CUR @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 useful in case of specific memory constraints or for testing. @item getenv(name) 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 utility. @code{options} is an optional object containing the following optional properties: @table @code @item binary Boolean (default = false). If true, the response is an ArrayBuffer instead of a string. When a string is returned, the data is assumed 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). @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