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