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