quickjs-tart

quickjs-based runtime for wallet-core logic
Log | Files | Refs | README | LICENSE

quickjs.texi (33321B)


      1 \input texinfo
      2 
      3 @iftex
      4 @afourpaper
      5 @headings double
      6 @end iftex
      7 
      8 @include version.texi
      9 
     10 @titlepage
     11 @afourpaper
     12 @sp 7
     13 @center @titlefont{QuickJS Javascript Engine}
     14 @sp 3
     15 @center Version: @value{VERSION}
     16 @end titlepage
     17 
     18 @setfilename spec.info
     19 @settitle QuickJS Javascript Engine
     20 
     21 @contents
     22 
     23 @chapter Introduction
     24 
     25 QuickJS (version @value{VERSION}) is a small and embeddable Javascript
     26 engine. It supports most of the ES2025 specification
     27 @footnote{@url{https://tc39.es/ecma262/2025 }}.
     28 
     29 @section Main Features
     30 
     31 @itemize
     32 
     33 @item Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple ``hello world'' program.
     34 
     35 @item Fast interpreter with very low startup time: runs the tests of the ECMAScript Test Suite@footnote{@url{https://github.com/tc39/test262}} in less than 2 minutes on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.
     36 
     37 @item Almost complete ES2025 support.
     38 
     39 @item Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2025 features.
     40 
     41 @item Compile Javascript sources to executables with no external dependency.
     42 
     43 @item Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.
     44 
     45 @item Command line interpreter with contextual colorization and completion implemented in Javascript.
     46 
     47 @item Small built-in standard library with C library wrappers.
     48 
     49 @end itemize
     50 
     51 @chapter Usage
     52 
     53 @section Installation
     54 
     55 A Makefile is provided to compile the engine on Linux or MacOS/X.  A
     56 preliminary Windows support is available thru cross compilation on a
     57 Linux host with the MingGW tools.
     58 
     59 Edit the top of the @code{Makefile} if you wish to select specific
     60 options then run @code{make}.
     61 
     62 You can type @code{make install} as root if you wish to install the binaries and support files to
     63 @code{/usr/local} (this is not necessary to use QuickJS).
     64 
     65 Note: On some OSes atomic operations are not available or need a
     66 specific library. If you get related errors, you should either add
     67 @code{-latomics} in the Makefile @code{LIBS} variable or disable
     68 @code{CONFIG_ATOMICS} in @file{quickjs.c}.
     69 
     70 @section Quick start
     71 
     72 @code{qjs} is the command line interpreter (Read-Eval-Print Loop). You can pass
     73 Javascript files and/or expressions as arguments to execute them:
     74 
     75 @example
     76 ./qjs examples/hello.js
     77 @end example
     78 
     79 @code{qjsc} is the command line compiler:
     80 
     81 @example
     82 ./qjsc -o hello examples/hello.js
     83 ./hello
     84 @end example
     85 
     86 generates a @code{hello} executable with no external dependency.
     87 
     88 @section Command line options
     89 
     90 @subsection @code{qjs} interpreter
     91 
     92 @verbatim
     93 usage: qjs [options] [file [args]]
     94 @end verbatim
     95 
     96 Options are:
     97 @table @code
     98 @item -h
     99 @item --help
    100 List options.
    101 
    102 @item -e @code{EXPR}
    103 @item --eval @code{EXPR}
    104 Evaluate EXPR.
    105 
    106 @item -i
    107 @item --interactive
    108 Go to interactive mode (it is not the default when files are provided on the command line).
    109 
    110 @item -m
    111 @item --module
    112 Load as ES6 module (default=autodetect). A module is autodetected if
    113 the filename extension is @code{.mjs} or if the first keyword of the
    114 source is @code{import}.
    115 
    116 @item --script
    117 Load as ES6 script (default=autodetect).
    118 
    119 @item -I file
    120 @item --include file
    121 Include an additional file.
    122 
    123 @end table
    124 
    125 Advanced options are:
    126 
    127 @table @code
    128 @item --std
    129 Make the @code{std} and @code{os} modules available to the loaded
    130 script even if it is not a module.
    131 
    132 @item -d
    133 @item --dump
    134 Dump the memory usage stats.
    135 
    136 @item -q
    137 @item --quit
    138 just instantiate the interpreter and quit.
    139 
    140 @end table
    141 
    142 @subsection @code{qjsc} compiler
    143 
    144 @verbatim
    145 usage: qjsc [options] [files]
    146 @end verbatim
    147 
    148 Options are:
    149 @table @code
    150 @item -c
    151 Only output bytecode in a C file. The default is to output an executable file.
    152 @item -e
    153 Output @code{main()} and bytecode in a C file. The default is to output an
    154 executable file.
    155 @item -o output
    156 Set the output filename (default = @file{out.c} or @file{a.out}).
    157 
    158 @item -N cname
    159 Set the C name of the generated data.
    160 
    161 @item -m
    162 Compile as Javascript module (default=autodetect).
    163 
    164 @item -D module_name
    165 Compile a dynamically loaded module and its dependencies. This option
    166 is needed when your code uses the @code{import} keyword or the
    167 @code{os.Worker} constructor because the compiler cannot statically
    168 find the name of the dynamically loaded modules.
    169 
    170 @item -M module_name[,cname]
    171 Add initialization code for an external C module. See the
    172 @code{c_module} example.
    173 
    174 @item -x
    175 Byte swapped output (only used for cross compilation).
    176 
    177 @item -flto
    178 Use link time optimization. The compilation is slower but the
    179 executable is smaller and faster. This option is automatically set
    180 when the @code{-fno-x} options are used.
    181 
    182 @item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]
    183 Disable selected language features to produce a smaller executable file.
    184 
    185 @end table
    186 
    187 @section Built-in tests
    188 
    189 Run @code{make test} to run the few built-in tests included in the
    190 QuickJS archive.
    191 
    192 @section Test262 (ECMAScript Test Suite)
    193 
    194 A test262 runner is included in the QuickJS archive. The test262 tests
    195 can be installed in the QuickJS source directory with:
    196 
    197 @example
    198 git clone https://github.com/tc39/test262.git test262
    199 cd test262
    200 patch -p1 < ../tests/test262.patch
    201 cd ..
    202 @end example
    203 
    204 The patch adds the implementation specific @code{harness} functions
    205 and optimizes the inefficient RegExp character classes and Unicode
    206 property escapes tests (the tests themselves are not modified, only a
    207 slow string initialization function is optimized).
    208 
    209 The tests can be run with
    210 @example
    211 make test2
    212 @end example
    213 
    214 The configuration files @code{test262.conf}
    215 (resp. @code{test262o.conf} for the old ES5.1 tests@footnote{The old
    216 ES5.1 tests can be extracted with @code{git clone --single-branch
    217 --branch es5-tests https://github.com/tc39/test262.git test262o}}))
    218 contain the options to run the various tests. Tests can be excluded
    219 based on features or filename.
    220 
    221 The file @code{test262_errors.txt} contains the current list of
    222 errors. The runner displays a message when a new error appears or when
    223 an existing error is corrected or modified. Use the @code{-u} option
    224 to update the current list of errors (or @code{make test2-update}).
    225 
    226 The file @code{test262_report.txt} contains the logs of all the
    227 tests. It is useful to have a clearer analysis of a particular
    228 error. In case of crash, the last line corresponds to the failing
    229 test.
    230 
    231 Use the syntax @code{./run-test262 -c test262.conf -f filename.js} to
    232 run a single test. Use the syntax @code{./run-test262 -c test262.conf
    233 N} to start testing at test number @code{N}.
    234 
    235 For more information, run @code{./run-test262} to see the command line
    236 options of the test262 runner.
    237 
    238 @code{run-test262} accepts the @code{-N} option to be invoked from
    239 @code{test262-harness}@footnote{@url{https://github.com/bterlson/test262-harness}}
    240 thru @code{eshost}. Unless you want to compare QuickJS with other
    241 engines under the same conditions, we do not recommend to run the
    242 tests this way as it is much slower (typically half an hour instead of
    243 about 100 seconds).
    244 
    245 @chapter Specifications
    246 
    247 @section Language support
    248 
    249 @subsection ES2025 support
    250 
    251 The ES2025 specification is almost fully supported including the Annex
    252 B (legacy web compatibility) and the Unicode related features.
    253 
    254 The following features are not supported yet:
    255 
    256 @itemize
    257 
    258 @item Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.}
    259 
    260 @item Atomics.waitAsync
    261 
    262 @end itemize
    263 
    264 @subsection ECMA402
    265 
    266 ECMA402 (Internationalization API) is not supported.
    267 
    268 @section Modules
    269 
    270 ES6 modules are fully supported. The default name resolution is the
    271 following:
    272 
    273 @itemize
    274 
    275 @item Module names with a leading @code{.} or @code{..} are relative
    276 to the current module path.
    277 
    278 @item Module names without a leading @code{.} or @code{..} are system
    279 modules, such as @code{std} or @code{os}.
    280 
    281 @item Module names ending with @code{.so} are native modules using the
    282 QuickJS C API.
    283 
    284 @end itemize
    285 
    286 @section Standard library
    287 
    288 The standard library is included by default in the command line
    289 interpreter. It contains the two modules @code{std} and @code{os} and
    290 a few global objects.
    291 
    292 @subsection Global objects
    293 
    294 @table @code
    295 @item scriptArgs
    296 Provides the command line arguments. The first argument is the script name.
    297 @item print(...args)
    298 Print the arguments separated by spaces and a trailing newline.
    299 @item console.log(...args)
    300 Same as print().
    301 
    302 @end table
    303 
    304 @subsection @code{std} module
    305 
    306 The @code{std} module provides wrappers to the libc @file{stdlib.h}
    307 and @file{stdio.h} and a few other utilities.
    308 
    309 Available exports:
    310 
    311 @table @code
    312 
    313 @item exit(n)
    314 Exit the process.
    315 
    316 @item evalScript(str, options = undefined)
    317 Evaluate the string @code{str} as a script (global
    318 eval). @code{options} is an optional object containing the following
    319 optional properties:
    320 
    321   @table @code
    322   @item backtrace_barrier
    323   Boolean (default = false). If true, error backtraces do not list the
    324   stack frames below the evalScript.
    325   @item async
    326   Boolean (default = false). If true, @code{await} is accepted in the
    327   script and a promise is returned. The promise is resolved with an
    328   object whose @code{value} property holds the value returned by the
    329   script.
    330   @end table
    331 
    332 @item loadScript(filename)
    333 Evaluate the file @code{filename} as a script (global eval).
    334 
    335 @item loadFile(filename)
    336 Load the file @code{filename} and return it as a string assuming UTF-8
    337 encoding. Return @code{null} in case of I/O error.
    338 
    339 @item open(filename, flags, errorObj = undefined)
    340 Open a file (wrapper to the libc @code{fopen()}). Return the FILE
    341 object or @code{null} in case of I/O error. If @code{errorObj} is not
    342 undefined, set its @code{errno} property to the error code or to 0 if
    343 no error occured.
    344 
    345 @item popen(command, flags, errorObj = undefined)
    346 Open a process by creating a pipe (wrapper to the libc
    347 @code{popen()}). Return the FILE
    348 object or @code{null} in case of I/O error. If @code{errorObj} is not
    349 undefined, set its @code{errno} property to the error code or to 0 if
    350 no error occured.
    351 
    352 @item fdopen(fd, flags, errorObj = undefined)
    353 Open a file from a file handle (wrapper to the libc
    354 @code{fdopen()}). Return the FILE
    355 object or @code{null} in case of I/O error. If @code{errorObj} is not
    356 undefined, set its @code{errno} property to the error code or to 0 if
    357 no error occured.
    358 
    359 @item tmpfile(errorObj = undefined)
    360 Open a temporary file. Return the FILE
    361 object or @code{null} in case of I/O error. If @code{errorObj} is not
    362 undefined, set its @code{errno} property to the error code or to 0 if
    363 no error occured.
    364 
    365 @item puts(str)
    366 Equivalent to @code{std.out.puts(str)}.
    367 
    368 @item printf(fmt, ...args)
    369 Equivalent to @code{std.out.printf(fmt, ...args)}.
    370 
    371 @item sprintf(fmt, ...args)
    372 Equivalent to the libc sprintf().
    373 
    374 @item in
    375 @item out
    376 @item err
    377 Wrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}.
    378 
    379 @item SEEK_SET
    380 @item SEEK_CUR
    381 @item SEEK_END
    382 Constants for seek().
    383 
    384 @item Error
    385 
    386 Enumeration object containing the integer value of common errors
    387 (additional error codes may be defined):
    388 
    389   @table @code
    390   @item EINVAL
    391   @item EIO
    392   @item EACCES
    393   @item EEXIST
    394   @item ENOSPC
    395   @item ENOSYS
    396   @item EBUSY
    397   @item ENOENT
    398   @item EPERM
    399   @item EPIPE
    400   @end table
    401 
    402 @item strerror(errno)
    403 Return a string that describes the error @code{errno}.
    404 
    405 @item gc()
    406 Manually invoke the cycle removal algorithm. The cycle removal
    407 algorithm is automatically started when needed, so this function is
    408 useful in case of specific memory constraints or for testing.
    409 
    410 @item getenv(name)
    411 Return the value of the environment variable @code{name} or
    412 @code{undefined} if it is not defined.
    413 
    414 @item setenv(name, value)
    415 Set the value of the environment variable @code{name} to the string
    416 @code{value}.
    417 
    418 @item unsetenv(name)
    419 Delete the environment variable @code{name}.
    420 
    421 @item getenviron()
    422 Return an object containing the environment variables as key-value pairs.
    423 
    424 @item urlGet(url, options = undefined)
    425 
    426 Download @code{url} using the @file{curl} command line
    427 utility. @code{options} is an optional object containing the following
    428 optional properties:
    429 
    430   @table @code
    431   @item binary
    432   Boolean (default = false). If true, the response is an ArrayBuffer
    433   instead of a string. When a string is returned, the data is assumed
    434   to be UTF-8 encoded.
    435 
    436   @item full
    437 
    438   Boolean (default = false). If true, return the an object contains
    439   the properties @code{response} (response content),
    440   @code{responseHeaders} (headers separated by CRLF), @code{status}
    441   (status code). @code{response} is @code{null} is case of protocol or
    442   network error. If @code{full} is false, only the response is
    443   returned if the status is between 200 and 299. Otherwise @code{null}
    444   is returned.
    445 
    446   @end table
    447 
    448 @item parseExtJSON(str)
    449 
    450   Parse @code{str} using a superset of @code{JSON.parse}. The superset
    451   is very close to the JSON5 specification. The following extensions
    452   are accepted:
    453 
    454   @itemize
    455   @item Single line and multiline comments
    456   @item unquoted properties (ASCII-only Javascript identifiers)
    457   @item trailing comma in array and object definitions
    458   @item single quoted strings
    459   @item @code{\v} escape and multi-line strings with trailing @code{\}
    460   @item @code{\f} and @code{\v} are accepted as space characters
    461   @item leading plus or decimal point in numbers
    462   @item hexadecimal (@code{0x} prefix), octal (@code{0o} prefix) and binary (@code{0b} prefix) integers
    463   @item @code{NaN} and @code{Infinity} are accepted as numbers
    464   @end itemize
    465 @end table
    466 
    467 FILE prototype:
    468 
    469 @table @code
    470 @item close()
    471 Close the file. Return 0 if OK or @code{-errno} in case of I/O error.
    472 @item puts(str)
    473 Outputs the string with the UTF-8 encoding.
    474 @item printf(fmt, ...args)
    475 Formatted printf.
    476 
    477 The same formats as the standard C library @code{printf} are
    478 supported. Integer format types (e.g. @code{%d}) truncate the Numbers
    479 or BigInts to 32 bits. Use the @code{l} modifier (e.g. @code{%ld}) to
    480 truncate to 64 bits.
    481 
    482 @item flush()
    483 Flush the buffered file.
    484 @item seek(offset, whence)
    485 Seek to a give file position (whence is
    486 @code{std.SEEK_*}). @code{offset} can be a number or a bigint. Return
    487 0 if OK or @code{-errno} in case of I/O error.
    488 @item tell()
    489 Return the current file position.
    490 @item tello()
    491 Return the current file position as a bigint.
    492 @item eof()
    493 Return true if end of file.
    494 @item fileno()
    495 Return the associated OS handle.
    496 @item error()
    497 Return true if there was an error.
    498 @item clearerr()
    499 Clear the error indication.
    500 
    501 @item read(buffer, position, length)
    502 Read @code{length} bytes from the file to the ArrayBuffer @code{buffer} at byte
    503 position @code{position} (wrapper to the libc @code{fread}).
    504 
    505 @item write(buffer, position, length)
    506 Write @code{length} bytes to the file from the ArrayBuffer @code{buffer} at byte
    507 position @code{position} (wrapper to the libc @code{fwrite}).
    508 
    509 @item getline()
    510 Return the next line from the file, assuming UTF-8 encoding, excluding
    511 the trailing line feed.
    512 
    513 @item readAsString(max_size = undefined)
    514 Read @code{max_size} bytes from the file and return them as a string
    515 assuming UTF-8 encoding. If @code{max_size} is not present, the file
    516 is read up its end.
    517 
    518 @item getByte()
    519 Return the next byte from the file. Return -1 if the end of file is reached.
    520 
    521 @item putByte(c)
    522 Write one byte to the file.
    523 @end table
    524 
    525 @subsection @code{os} module
    526 
    527 The @code{os} module provides Operating System specific functions:
    528 
    529 @itemize
    530 @item low level file access
    531 @item signals
    532 @item timers
    533 @item asynchronous I/O
    534 @item workers (threads)
    535 @end itemize
    536 
    537 The OS functions usually return 0 if OK or an OS specific negative
    538 error code.
    539 
    540 Available exports:
    541 
    542 @table @code
    543 @item open(filename, flags, mode = 0o666)
    544 Open a file. Return a handle or < 0 if error.
    545 
    546 @item O_RDONLY
    547 @item O_WRONLY
    548 @item O_RDWR
    549 @item O_APPEND
    550 @item O_CREAT
    551 @item O_EXCL
    552 @item O_TRUNC
    553 POSIX open flags.
    554 
    555 @item O_TEXT
    556 (Windows specific). Open the file in text mode. The default is binary mode.
    557 
    558 @item close(fd)
    559 Close the file handle @code{fd}.
    560 
    561 @item seek(fd, offset, whence)
    562 Seek in the file. Use @code{std.SEEK_*} for
    563 @code{whence}. @code{offset} is either a number or a bigint. If
    564 @code{offset} is a bigint, a bigint is returned too.
    565 
    566 @item read(fd, buffer, offset, length)
    567 Read @code{length} bytes from the file handle @code{fd} to the
    568 ArrayBuffer @code{buffer} at byte position @code{offset}.
    569 Return the number of read bytes or < 0 if error.
    570 
    571 @item write(fd, buffer, offset, length)
    572 Write @code{length} bytes to the file handle @code{fd} from the
    573 ArrayBuffer @code{buffer} at byte position @code{offset}.
    574 Return the number of written bytes or < 0 if error.
    575 
    576 @item isatty(fd)
    577 Return @code{true} is @code{fd} is a TTY (terminal) handle.
    578 
    579 @item ttyGetWinSize(fd)
    580 Return the TTY size as @code{[width, height]} or @code{null} if not available.
    581 
    582 @item ttySetRaw(fd)
    583 Set the TTY in raw mode.
    584 
    585 @item remove(filename)
    586 Remove a file. Return 0 if OK or @code{-errno}.
    587 
    588 @item rename(oldname, newname)
    589 Rename a file. Return 0 if OK or @code{-errno}.
    590 
    591 @item realpath(path)
    592 Return @code{[str, err]} where @code{str} is the canonicalized absolute
    593 pathname of @code{path} and @code{err} the error code.
    594 
    595 @item getcwd()
    596 Return @code{[str, err]} where @code{str} is the current working directory
    597 and @code{err} the error code.
    598 
    599 @item chdir(path)
    600 Change the current directory. Return 0 if OK or @code{-errno}.
    601 
    602 @item mkdir(path, mode = 0o777)
    603 Create a directory at @code{path}. Return 0 if OK or @code{-errno}.
    604 
    605 @item stat(path)
    606 @item lstat(path)
    607 
    608 Return @code{[obj, err]} where @code{obj} is an object containing the
    609 file status of @code{path}. @code{err} is the error code. The
    610 following fields are defined in @code{obj}: dev, ino, mode, nlink,
    611 uid, gid, rdev, size, blocks, atime, mtime, ctime. The times are
    612 specified in milliseconds since 1970. @code{lstat()} is the same as
    613 @code{stat()} excepts that it returns information about the link
    614 itself.
    615 
    616 @item S_IFMT
    617 @item S_IFIFO
    618 @item S_IFCHR
    619 @item S_IFDIR
    620 @item S_IFBLK
    621 @item S_IFREG
    622 @item S_IFSOCK
    623 @item S_IFLNK
    624 @item S_ISGID
    625 @item S_ISUID
    626 Constants to interpret the @code{mode} property returned by
    627 @code{stat()}. They have the same value as in the C system header
    628 @file{sys/stat.h}.
    629 
    630 @item utimes(path, atime, mtime)
    631 Change the access and modification times of the file @code{path}. The
    632 times are specified in milliseconds since 1970. Return 0 if OK or @code{-errno}.
    633 
    634 @item symlink(target, linkpath)
    635 Create a link at @code{linkpath} containing the string @code{target}. Return 0 if OK or @code{-errno}.
    636 
    637 @item readlink(path)
    638 Return @code{[str, err]} where @code{str} is the link target and @code{err}
    639 the error code.
    640 
    641 @item readdir(path)
    642 Return @code{[array, err]} where @code{array} is an array of strings
    643 containing the filenames of the directory @code{path}. @code{err} is
    644 the error code.
    645 
    646 @item setReadHandler(fd, func)
    647 Add a read handler to the file handle @code{fd}. @code{func} is called
    648 each time there is data pending for @code{fd}. A single read handler
    649 per file handle is supported. Use @code{func = null} to remove the
    650 handler.
    651 
    652 @item setWriteHandler(fd, func)
    653 Add a write handler to the file handle @code{fd}. @code{func} is
    654 called each time data can be written to @code{fd}. A single write
    655 handler per file handle is supported. Use @code{func = null} to remove
    656 the handler.
    657 
    658 @item signal(signal, func)
    659 Call the function @code{func} when the signal @code{signal}
    660 happens. Only a single handler per signal number is supported. Use
    661 @code{null} to set the default handler or @code{undefined} to ignore
    662 the signal. Signal handlers can only be defined in the main thread.
    663 
    664 @item SIGINT
    665 @item SIGABRT
    666 @item SIGFPE
    667 @item SIGILL
    668 @item SIGSEGV
    669 @item SIGTERM
    670 POSIX signal numbers.
    671 
    672 @item kill(pid, sig)
    673 Send the signal @code{sig} to the process @code{pid}.
    674 
    675 @item exec(args[, options])
    676 Execute a process with the arguments @code{args}. @code{options} is an
    677 object containing optional parameters:
    678 
    679   @table @code
    680   @item block
    681   Boolean (default = true). If true, wait until the process is
    682   terminated. In this case, @code{exec} return the exit code if positive
    683   or the negated signal number if the process was interrupted by a
    684   signal. If false, do not block and return the process id of the child.
    685 
    686   @item usePath
    687   Boolean (default = true). If true, the file is searched in the
    688   @code{PATH} environment variable.
    689 
    690   @item file
    691   String (default = @code{args[0]}). Set the file to be executed.
    692 
    693   @item cwd
    694   String. If present, set the working directory of the new process.
    695 
    696   @item stdin
    697   @item stdout
    698   @item stderr
    699   If present, set the handle in the child for stdin, stdout or stderr.
    700 
    701   @item env
    702   Object. If present, set the process environment from the object
    703   key-value pairs. Otherwise use the same environment as the current
    704   process.
    705 
    706   @item uid
    707   Integer. If present, the process uid with @code{setuid}.
    708 
    709   @item gid
    710   Integer. If present, the process gid with @code{setgid}.
    711 
    712   @end table
    713 
    714 @item getpid()
    715 Return the current process ID.
    716 
    717 @item waitpid(pid, options)
    718 @code{waitpid} Unix system call. Return the array @code{[ret,
    719 status]}. @code{ret} contains @code{-errno} in case of error.
    720 
    721 @item WNOHANG
    722 Constant for the @code{options} argument of @code{waitpid}.
    723 
    724 @item dup(fd)
    725 @code{dup} Unix system call.
    726 
    727 @item dup2(oldfd, newfd)
    728 @code{dup2} Unix system call.
    729 
    730 @item pipe()
    731 @code{pipe} Unix system call. Return two handles as @code{[read_fd,
    732 write_fd]} or null in case of error.
    733 
    734 @item sleep(delay_ms)
    735 Sleep during @code{delay_ms} milliseconds.
    736 
    737 @item sleepAsync(delay_ms)
    738 Asynchronouse sleep during @code{delay_ms} milliseconds. Returns a promise. Example:
    739 @example
    740 await os.sleepAsync(500);
    741 @end example
    742 
    743 @item now()
    744 Return a timestamp in milliseconds with more precision than
    745 @code{Date.now()}. The time origin is unspecified and is normally not
    746 impacted by system clock adjustments.
    747 
    748 @item setTimeout(func, delay)
    749 Call the function @code{func} after @code{delay} ms. Return a handle
    750 to the timer.
    751 
    752 @item clearTimeout(handle)
    753 Cancel a timer.
    754 
    755 @item platform
    756 Return a string representing the platform: @code{"linux"}, @code{"darwin"},
    757 @code{"win32"} or @code{"js"}.
    758 
    759 @item Worker(module_filename)
    760 Constructor to create a new thread (worker) with an API close to the
    761 @code{WebWorkers}. @code{module_filename} is a string specifying the
    762 module filename which is executed in the newly created thread. As for
    763 dynamically imported module, it is relative to the current script or
    764 module path. Threads normally don't share any data and communicate
    765 between each other with messages. Nested workers are not supported. An
    766 example is available in @file{tests/test_worker.js}.
    767 
    768 The worker class has the following static properties:
    769 
    770   @table @code
    771   @item parent
    772   In the created worker, @code{Worker.parent} represents the parent
    773   worker and is used to send or receive messages.
    774   @end table
    775 
    776 The worker instances have the following properties:
    777 
    778   @table @code
    779   @item postMessage(msg)
    780 
    781   Send a message to the corresponding worker. @code{msg} is cloned in
    782   the destination worker using an algorithm similar to the @code{HTML}
    783   structured clone algorithm. @code{SharedArrayBuffer} are shared
    784   between workers.
    785 
    786   Current limitations: @code{Map} and @code{Set} are not supported
    787   yet.
    788 
    789   @item onmessage
    790 
    791   Getter and setter. Set a function which is called each time a
    792   message is received. The function is called with a single
    793   argument. It is an object with a @code{data} property containing the
    794   received message. The thread is not terminated if there is at least
    795   one non @code{null} @code{onmessage} handler.
    796 
    797   @end table
    798 
    799 @end table
    800 
    801 @section QuickJS C API
    802 
    803 The C API was designed to be simple and efficient. The C API is
    804 defined in the header @code{quickjs.h}.
    805 
    806 @subsection Runtime and contexts
    807 
    808 @code{JSRuntime} represents a Javascript runtime corresponding to an
    809 object heap. Several runtimes can exist at the same time but they
    810 cannot exchange objects. Inside a given runtime, no multi-threading is
    811 supported.
    812 
    813 @code{JSContext} represents a Javascript context (or Realm). Each
    814 JSContext has its own global objects and system objects. There can be
    815 several JSContexts per JSRuntime and they can share objects, similar
    816 to frames of the same origin sharing Javascript objects in a
    817 web browser.
    818 
    819 @subsection JSValue
    820 
    821 @code{JSValue} represents a Javascript value which can be a primitive
    822 type or an object. Reference counting is used, so it is important to
    823 explicitly duplicate (@code{JS_DupValue()}, increment the reference
    824 count) or free (@code{JS_FreeValue()}, decrement the reference count)
    825 JSValues.
    826 
    827 @subsection C functions
    828 
    829 C functions can be created with
    830 @code{JS_NewCFunction()}. @code{JS_SetPropertyFunctionList()} is a
    831 shortcut to easily add functions, setters and getters properties to a
    832 given object.
    833 
    834 Unlike other embedded Javascript engines, there is no implicit stack,
    835 so C functions get their parameters as normal C parameters. As a
    836 general rule, C functions take constant @code{JSValue}s as parameters
    837 (so they don't need to free them) and return a newly allocated (=live)
    838 @code{JSValue}.
    839 
    840 @subsection Exceptions
    841 
    842 Exceptions: most C functions can return a Javascript exception. It
    843 must be explicitly tested and handled by the C code. The specific
    844 @code{JSValue} @code{JS_EXCEPTION} indicates that an exception
    845 occurred. The actual exception object is stored in the
    846 @code{JSContext} and can be retrieved with @code{JS_GetException()}.
    847 
    848 @subsection Script evaluation
    849 
    850 Use @code{JS_Eval()} to evaluate a script or module source.
    851 
    852 If the script or module was compiled to bytecode with @code{qjsc}, it
    853 can be evaluated by calling @code{js_std_eval_binary()}. The advantage
    854 is that no compilation is needed so it is faster and smaller because
    855 the compiler can be removed from the executable if no @code{eval} is
    856 required.
    857 
    858 Note: the bytecode format is linked to a given QuickJS
    859 version. Moreover, no security check is done before its
    860 execution. Hence the bytecode should not be loaded from untrusted
    861 sources. That's why there is no option to output the bytecode to a
    862 binary file in @code{qjsc}.
    863 
    864 @subsection JS Classes
    865 
    866 C opaque data can be attached to a Javascript object. The type of the
    867 C opaque data is determined with the class ID (@code{JSClassID}) of
    868 the object. Hence the first step is to register a new class ID and JS
    869 class (@code{JS_NewClassID()}, @code{JS_NewClass()}). Then you can
    870 create objects of this class with @code{JS_NewObjectClass()} and get or
    871 set the C opaque point with
    872 @code{JS_GetOpaque()}/@code{JS_SetOpaque()}.
    873 
    874 When defining a new JS class, it is possible to declare a finalizer
    875 which is called when the object is destroyed. The finalizer should be
    876 used to release C resources. It is invalid to execute JS code from
    877 it. A @code{gc_mark} method can be provided so that the cycle removal
    878 algorithm can find the other objects referenced by this object. Other
    879 methods are available to define exotic object behaviors.
    880 
    881 The Class ID are globally allocated (i.e. for all runtimes). The
    882 JSClass are allocated per @code{JSRuntime}. @code{JS_SetClassProto()}
    883 is used to define a prototype for a given class in a given
    884 JSContext. @code{JS_NewObjectClass()} sets this prototype in the
    885 created object.
    886 
    887 Examples are available in @file{quickjs-libc.c}.
    888 
    889 @subsection C Modules
    890 
    891 Native ES6 modules are supported and can be dynamically or statically
    892 linked. Look at the @file{test_bjson} and @file{bjson.so}
    893 examples. The standard library @file{quickjs-libc.c} is also a good example
    894 of a native module.
    895 
    896 @subsection Memory handling
    897 
    898 Use @code{JS_SetMemoryLimit()} to set a global memory allocation limit
    899 to a given JSRuntime.
    900 
    901 Custom memory allocation functions can be provided with
    902 @code{JS_NewRuntime2()}.
    903 
    904 The maximum system stack size can be set with @code{JS_SetMaxStackSize()}.
    905 
    906 @subsection Execution timeout and interrupts
    907 
    908 Use @code{JS_SetInterruptHandler()} to set a callback which is
    909 regularly called by the engine when it is executing code. This
    910 callback can be used to implement an execution timeout.
    911 
    912 It is used by the command line interpreter to implement a
    913 @code{Ctrl-C} handler.
    914 
    915 @chapter Internals
    916 
    917 @section Bytecode
    918 
    919 The compiler generates bytecode directly with no intermediate
    920 representation such as a parse tree, hence it is very fast. Several
    921 optimizations passes are done over the generated bytecode.
    922 
    923 A stack-based bytecode was chosen because it is simple and generates
    924 compact code.
    925 
    926 For each function, the maximum stack size is computed at compile time so that
    927 no runtime stack overflow tests are needed.
    928 
    929 A separate compressed line number table is maintained for the debug
    930 information.
    931 
    932 Access to closure variables is optimized and is almost as fast as local
    933 variables.
    934 
    935 Direct @code{eval} in strict mode is optimized.
    936 
    937 @section Executable generation
    938 
    939 @subsection @code{qjsc} compiler
    940 
    941 The @code{qjsc} compiler generates C sources from Javascript files. By
    942 default the C sources are compiled with the system compiler
    943 (@code{gcc} or @code{clang}).
    944 
    945 The generated C source contains the bytecode of the compiled functions
    946 or modules. If a full complete executable is needed, it also
    947 contains a @code{main()} function with the necessary C code to initialize the
    948 Javascript engine and to load and execute the compiled functions and
    949 modules.
    950 
    951 Javascript code can be mixed with C modules.
    952 
    953 In order to have smaller executables, specific Javascript features can
    954 be disabled, in particular @code{eval} or the regular expressions. The
    955 code removal relies on the Link Time Optimization of the system
    956 compiler.
    957 
    958 @subsection Binary JSON
    959 
    960 @code{qjsc} works by compiling scripts or modules and then serializing
    961 them to a binary format. A subset of this format (without functions or
    962 modules) can be used as binary JSON. The example @file{test_bjson.js}
    963 shows how to use it.
    964 
    965 Warning: the binary JSON format may change without notice, so it
    966 should not be used to store persistent data. The @file{test_bjson.js}
    967 example is only used to test the binary object format functions.
    968 
    969 @section Runtime
    970 
    971 @subsection Strings
    972 
    973 Strings are stored either as an 8 bit or a 16 bit array of
    974 characters. Hence random access to characters is always fast.
    975 
    976 The C API provides functions to convert Javascript Strings to C UTF-8 encoded
    977 strings. The most common case where the Javascript string contains
    978 only ASCII characters involves no copying.
    979 
    980 @subsection Objects
    981 
    982 The object shapes (object prototype, property names and flags) are shared
    983 between objects to save memory.
    984 
    985 Arrays with no holes (except at the end of the array) are optimized.
    986 
    987 TypedArray accesses are optimized.
    988 
    989 @subsection Atoms
    990 
    991 Object property names and some strings are stored as Atoms (unique
    992 strings) to save memory and allow fast comparison. Atoms are
    993 represented as a 32 bit integer. Half of the atom range is reserved for
    994 immediate integer literals from @math{0} to @math{2^{31}-1}.
    995 
    996 @subsection Numbers
    997 
    998 Numbers are represented either as 32-bit signed integers or 64-bit IEEE-754
    999 floating point values. Most operations have fast paths for the 32-bit
   1000 integer case.
   1001 
   1002 @subsection Garbage collection
   1003 
   1004 Reference counting is used to free objects automatically and
   1005 deterministically. A separate cycle removal pass is done when the allocated
   1006 memory becomes too large. The cycle removal algorithm only uses the
   1007 reference counts and the object content, so no explicit garbage
   1008 collection roots need to be manipulated in the C code.
   1009 
   1010 @subsection JSValue
   1011 
   1012 It is a Javascript value which can be a primitive type (such as
   1013 Number, String, ...) or an Object. NaN boxing is used in the 32-bit version
   1014 to store 64-bit floating point numbers. The representation is
   1015 optimized so that 32-bit integers and reference counted values can be
   1016 efficiently tested.
   1017 
   1018 In 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The
   1019 rationale is that in 64-bit code memory usage is less critical.
   1020 
   1021 In both cases (32 or 64 bits), JSValue exactly fits two CPU registers,
   1022 so it can be efficiently returned by C functions.
   1023 
   1024 @subsection Function call
   1025 
   1026 The engine is optimized so that function calls are fast. The system
   1027 stack holds the Javascript parameters and local variables.
   1028 
   1029 @section RegExp
   1030 
   1031 A specific regular expression engine was developed. It is both small
   1032 and efficient and supports all the ES2025 features including the
   1033 Unicode properties. As the Javascript compiler, it directly generates
   1034 bytecode without a parse tree.
   1035 
   1036 Backtracking with an explicit stack is used so that there is no
   1037 recursion on the system stack. Simple quantifiers are specifically
   1038 optimized to avoid recursions.
   1039 
   1040 The full regexp library weights about 15 KiB (x86 code), excluding the
   1041 Unicode library.
   1042 
   1043 @section Unicode
   1044 
   1045 A specific Unicode library was developed so that there is no
   1046 dependency on an external large Unicode library such as ICU. All the
   1047 Unicode tables are compressed while keeping a reasonable access
   1048 speed.
   1049 
   1050 The library supports case conversion, Unicode normalization, Unicode
   1051 script queries, Unicode general category queries and all Unicode
   1052 binary properties.
   1053 
   1054 The full Unicode library weights about 45 KiB (x86 code).
   1055 
   1056 @section BigInt
   1057 
   1058 BigInts are represented using binary two's complement notation. An
   1059 additional short bigint value is used to optimize the performance on
   1060 small BigInt values.
   1061 
   1062 @chapter License
   1063 
   1064 QuickJS is released under the MIT license.
   1065 
   1066 Unless otherwise specified, the QuickJS sources are copyright Fabrice
   1067 Bellard and Charlie Gordon.
   1068 
   1069 @bye