Debian Codegraph @

quickjs/doc/quickjs.texi

raw
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.
383 @end table
384
385 @item loadScript(filename)
386 Evaluate the file @code{filename} as a script (global eval).
387
388 @item loadFile(filename)
389 Load the file @code{filename} and return it as a string assuming UTF-8
390 encoding. Return @code{null} in case of I/O error.
391
392 @item open(filename, flags, errorObj = undefined)
393 Open a file (wrapper to the libc @code{fopen()}). Return the FILE
394 object or @code{null} in case of I/O error. If @code{errorObj} is not
395 undefined, set its @code{errno} property to the error code or to 0 if
396 no error occured.
397
398 @item popen(command, flags, errorObj = undefined)
399 Open a process by creating a pipe (wrapper to the libc
400 @code{popen()}). Return the FILE
401 object or @code{null} in case of I/O error. If @code{errorObj} is not
402 undefined, set its @code{errno} property to the error code or to 0 if
403 no error occured.
404
405 @item fdopen(fd, flags, errorObj = undefined)
406 Open a file from a file handle (wrapper to the libc
407 @code{fdopen()}). Return the FILE
408 object or @code{null} in case of I/O error. If @code{errorObj} is not
409 undefined, set its @code{errno} property to the error code or to 0 if
410 no error occured.
411
412 @item tmpfile(errorObj = undefined)
413 Open a temporary file. Return the FILE
414 object or @code{null} in case of I/O error. If @code{errorObj} is not
415 undefined, set its @code{errno} property to the error code or to 0 if
416 no error occured.
417
418 @item puts(str)
419 Equivalent to @code{std.out.puts(str)}.
420
421 @item printf(fmt, ...args)
422 Equivalent to @code{std.out.printf(fmt, ...args)}.
423
424 @item sprintf(fmt, ...args)
425 Equivalent to the libc sprintf().
426
427 @item in
428 @item out
429 @item err
430 Wrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}.
431
432 @item SEEK_SET
433 @item SEEK_CUR
434 @item SEEK_END
435 Constants for seek().
436
437 @item Error
438
439 Enumeration object containing the integer value of common errors
440 (additional error codes may be defined):
441
442 @table @code
443 @item EINVAL
444 @item EIO
445 @item EACCES
446 @item EEXIST
447 @item ENOSPC
448 @item ENOSYS
449 @item EBUSY
450 @item ENOENT
451 @item EPERM
452 @item EPIPE
453 @end table
454
455 @item strerror(errno)
456 Return a string that describes the error @code{errno}.
457
458 @item gc()
459 Manually invoke the cycle removal algorithm. The cycle removal
460 algorithm is automatically started when needed, so this function is
461 useful in case of specific memory constraints or for testing.
462
463 @item getenv(name)
464 Return the value of the environment variable @code{name} or
465 @code{undefined} if it is not defined.
466
467 @item setenv(name, value)
468 Set the value of the environment variable @code{name} to the string
469 @code{value}.
470
471 @item unsetenv(name)
472 Delete the environment variable @code{name}.
473
474 @item getenviron()
475 Return an object containing the environment variables as key-value pairs.
476
477 @item urlGet(url, options = undefined)
478
479 Download @code{url} using the @file{curl} command line
480 utility. @code{options} is an optional object containing the following
481 optional properties:
482
483 @table @code
484 @item binary
485 Boolean (default = false). If true, the response is an ArrayBuffer
486 instead of a string. When a string is returned, the data is assumed
487 to be UTF-8 encoded.
488
489 @item full
490
491 Boolean (default = false). If true, return the an object contains
492 the properties @code{response} (response content),
493 @code{responseHeaders} (headers separated by CRLF), @code{status}
494 (status code). @code{response} is @code{null} is case of protocol or
495 network error. If @code{full} is false, only the response is
496 returned if the status is between 200 and 299. Otherwise @code{null}
497 is returned.
498
499 @end table
500
501 @item parseExtJSON(str)
502
503 Parse @code{str} using a superset of @code{JSON.parse}. The
504 following extensions are accepted:
505
506 @itemize
507 @item Single line and multiline comments
508 @item unquoted properties (ASCII-only Javascript identifiers)
509 @item trailing comma in array and object definitions
510 @item single quoted strings
511 @item @code{\f} and @code{\v} are accepted as space characters
512 @item leading plus in numbers
513 @item octal (@code{0o} prefix) and hexadecimal (@code{0x} prefix) numbers
514 @end itemize
515 @end table
516
517 FILE prototype:
518
519 @table @code
520 @item close()
521 Close the file. Return 0 if OK or @code{-errno} in case of I/O error.
522 @item puts(str)
523 Outputs the string with the UTF-8 encoding.
524 @item printf(fmt, ...args)
525 Formatted printf.
526
527 The same formats as the standard C library @code{printf} are
528 supported. Integer format types (e.g. @code{%d}) truncate the Numbers
529 or BigInts to 32 bits. Use the @code{l} modifier (e.g. @code{%ld}) to
530 truncate to 64 bits.
531
532 @item flush()
533 Flush the buffered file.
534 @item seek(offset, whence)
535 Seek to a give file position (whence is
536 @code{std.SEEK_*}). @code{offset} can be a number or a bigint. Return
537 0 if OK or @code{-errno} in case of I/O error.
538 @item tell()
539 Return the current file position.
540 @item tello()
541 Return the current file position as a bigint.
542 @item eof()
543 Return true if end of file.
544 @item fileno()
545 Return the associated OS handle.
546 @item error()
547 Return true if there was an error.
548 @item clearerr()
549 Clear the error indication.
550
551 @item read(buffer, position, length)
552 Read @code{length} bytes from the file to the ArrayBuffer @code{buffer} at byte
553 position @code{position} (wrapper to the libc @code{fread}).
554
555 @item write(buffer, position, length)
556 Write @code{length} bytes to the file from the ArrayBuffer @code{buffer} at byte
557 position @code{position} (wrapper to the libc @code{fwrite}).
558
559 @item getline()
560 Return the next line from the file, assuming UTF-8 encoding, excluding
561 the trailing line feed.
562
563 @item readAsString(max_size = undefined)
564 Read @code{max_size} bytes from the file and return them as a string
565 assuming UTF-8 encoding. If @code{max_size} is not present, the file
566 is read up its end.
567
568 @item getByte()
569 Return the next byte from the file. Return -1 if the end of file is reached.
570
571 @item putByte(c)
572 Write one byte to the file.
573 @end table
574
575 @subsection @code{os} module
576
577 The @code{os} module provides Operating System specific functions:
578
579 @itemize
580 @item low level file access
581 @item signals
582 @item timers
583 @item asynchronous I/O
584 @item workers (threads)
585 @end itemize
586
587 The OS functions usually return 0 if OK or an OS specific negative
588 error code.
589
590 Available exports:
591
592 @table @code
593 @item open(filename, flags, mode = 0o666)
594 Open a file. Return a handle or < 0 if error.
595
596 @item O_RDONLY
597 @item O_WRONLY
598 @item O_RDWR
599 @item O_APPEND
600 @item O_CREAT
601 @item O_EXCL
602 @item O_TRUNC
603 POSIX open flags.
604
605 @item O_TEXT
606 (Windows specific). Open the file in text mode. The default is binary mode.
607
608 @item close(fd)
609 Close the file handle @code{fd}.
610
611 @item seek(fd, offset, whence)
612 Seek in the file. Use @code{std.SEEK_*} for
613 @code{whence}. @code{offset} is either a number or a bigint. If
614 @code{offset} is a bigint, a bigint is returned too.
615
616 @item read(fd, buffer, offset, length)
617 Read @code{length} bytes from the file handle @code{fd} to the
618 ArrayBuffer @code{buffer} at byte position @code{offset}.
619 Return the number of read bytes or < 0 if error.
620
621 @item write(fd, buffer, offset, length)
622 Write @code{length} bytes to the file handle @code{fd} from the
623 ArrayBuffer @code{buffer} at byte position @code{offset}.
624 Return the number of written bytes or < 0 if error.
625
626 @item isatty(fd)
627 Return @code{true} is @code{fd} is a TTY (terminal) handle.
628
629 @item ttyGetWinSize(fd)
630 Return the TTY size as @code{[width, height]} or @code{null} if not available.
631
632 @item ttySetRaw(fd)
633 Set the TTY in raw mode.
634
635 @item remove(filename)
636 Remove a file. Return 0 if OK or @code{-errno}.
637
638 @item rename(oldname, newname)
639 Rename a file. Return 0 if OK or @code{-errno}.
640
641 @item realpath(path)
642 Return @code{[str, err]} where @code{str} is the canonicalized absolute
643 pathname of @code{path} and @code{err} the error code.
644
645 @item getcwd()
646 Return @code{[str, err]} where @code{str} is the current working directory
647 and @code{err} the error code.
648
649 @item chdir(path)
650 Change the current directory. Return 0 if OK or @code{-errno}.
651
652 @item mkdir(path, mode = 0o777)
653 Create a directory at @code{path}. Return 0 if OK or @code{-errno}.
654
655 @item stat(path)
656 @item lstat(path)
657
658 Return @code{[obj, err]} where @code{obj} is an object containing the
659 file status of @code{path}. @code{err} is the error code. The
660 following fields are defined in @code{obj}: dev, ino, mode, nlink,
661 uid, gid, rdev, size, blocks, atime, mtime, ctime. The times are
662 specified in milliseconds since 1970. @code{lstat()} is the same as
663 @code{stat()} excepts that it returns information about the link
664 itself.
665
666 @item S_IFMT
667 @item S_IFIFO
668 @item S_IFCHR
669 @item S_IFDIR
670 @item S_IFBLK
671 @item S_IFREG
672 @item S_IFSOCK
673 @item S_IFLNK
674 @item S_ISGID
675 @item S_ISUID
676 Constants to interpret the @code{mode} property returned by
677 @code{stat()}. They have the same value as in the C system header
678 @file{sys/stat.h}.
679
680 @item utimes(path, atime, mtime)
681 Change the access and modification times of the file @code{path}. The
682 times are specified in milliseconds since 1970. Return 0 if OK or @code{-errno}.
683
684 @item symlink(target, linkpath)
685 Create a link at @code{linkpath} containing the string @code{target}. Return 0 if OK or @code{-errno}.
686
687 @item readlink(path)
688 Return @code{[str, err]} where @code{str} is the link target and @code{err}
689 the error code.
690
691 @item readdir(path)
692 Return @code{[array, err]} where @code{array} is an array of strings
693 containing the filenames of the directory @code{path}. @code{err} is
694 the error code.
695
696 @item setReadHandler(fd, func)
697 Add a read handler to the file handle @code{fd}. @code{func} is called
698 each time there is data pending for @code{fd}. A single read handler
699 per file handle is supported. Use @code{func = null} to remove the
700 handler.
701
702 @item setWriteHandler(fd, func)
703 Add a write handler to the file handle @code{fd}. @code{func} is
704 called each time data can be written to @code{fd}. A single write
705 handler per file handle is supported. Use @code{func = null} to remove
706 the handler.
707
708 @item signal(signal, func)
709 Call the function @code{func} when the signal @code{signal}
710 happens. Only a single handler per signal number is supported. Use
711 @code{null} to set the default handler or @code{undefined} to ignore
712 the signal. Signal handlers can only be defined in the main thread.
713
714 @item SIGINT
715 @item SIGABRT
716 @item SIGFPE
717 @item SIGILL
718 @item SIGSEGV
719 @item SIGTERM
720 POSIX signal numbers.
721
722 @item kill(pid, sig)
723 Send the signal @code{sig} to the process @code{pid}.
724
725 @item exec(args[, options])
726 Execute a process with the arguments @code{args}. @code{options} is an
727 object containing optional parameters:
728
729 @table @code
730 @item block
731 Boolean (default = true). If true, wait until the process is
732 terminated. In this case, @code{exec} return the exit code if positive
733 or the negated signal number if the process was interrupted by a
734 signal. If false, do not block and return the process id of the child.
735
736 @item usePath
737 Boolean (default = true). If true, the file is searched in the
738 @code{PATH} environment variable.
739
740 @item file
741 String (default = @code{args[0]}). Set the file to be executed.
742
743 @item cwd
744 String. If present, set the working directory of the new process.
745
746 @item stdin
747 @item stdout
748 @item stderr
749 If present, set the handle in the child for stdin, stdout or stderr.
750
751 @item env
752 Object. If present, set the process environment from the object
753 key-value pairs. Otherwise use the same environment as the current
754 process.
755
756 @item uid
757 Integer. If present, the process uid with @code{setuid}.
758
759 @item gid
760 Integer. If present, the process gid with @code{setgid}.
761
762 @end table
763
764 @item getpid()
765 Return the current process ID.
766
767 @item waitpid(pid, options)
768 @code{waitpid} Unix system call. Return the array @code{[ret,
769 status]}. @code{ret} contains @code{-errno} in case of error.
770
771 @item WNOHANG
772 Constant for the @code{options} argument of @code{waitpid}.
773
774 @item dup(fd)
775 @code{dup} Unix system call.
776
777 @item dup2(oldfd, newfd)
778 @code{dup2} Unix system call.
779
780 @item pipe()
781 @code{pipe} Unix system call. Return two handles as @code{[read_fd,
782 write_fd]} or null in case of error.
783
784 @item sleep(delay_ms)
785 Sleep during @code{delay_ms} milliseconds.
786
787 @item sleepAsync(delay_ms)
788 Asynchronouse sleep during @code{delay_ms} milliseconds. Returns a promise. Example:
789 @example
790 await os.sleepAsync(500);
791 @end example
792
793 @item now()
794 Return a timestamp in milliseconds with more precision than
795 @code{Date.now()}. The time origin is unspecified and is normally not
796 impacted by system clock adjustments.
797
798 @item setTimeout(func, delay)
799 Call the function @code{func} after @code{delay} ms. Return a handle
800 to the timer.
801
802 @item clearTimeout(handle)
803 Cancel a timer.
804
805 @item platform
806 Return a string representing the platform: @code{"linux"}, @code{"darwin"},
807 @code{"win32"} or @code{"js"}.
808
809 @item Worker(module_filename)
810 Constructor to create a new thread (worker) with an API close to the
811 @code{WebWorkers}. @code{module_filename} is a string specifying the
812 module filename which is executed in the newly created thread. As for
813 dynamically imported module, it is relative to the current script or
814 module path. Threads normally don't share any data and communicate
815 between each other with messages. Nested workers are not supported. An
816 example is available in @file{tests/test_worker.js}.
817
818 The worker class has the following static properties:
819
820 @table @code
821 @item parent
822 In the created worker, @code{Worker.parent} represents the parent
823 worker and is used to send or receive messages.
824 @end table
825
826 The worker instances have the following properties:
827
828 @table @code
829 @item postMessage(msg)
830
831 Send a message to the corresponding worker. @code{msg} is cloned in
832 the destination worker using an algorithm similar to the @code{HTML}
833 structured clone algorithm. @code{SharedArrayBuffer} are shared
834 between workers.
835
836 Current limitations: @code{Map} and @code{Set} are not supported
837 yet.
838
839 @item onmessage
840
841 Getter and setter. Set a function which is called each time a
842 message is received. The function is called with a single
843 argument. It is an object with a @code{data} property containing the
844 received message. The thread is not terminated if there is at least
845 one non @code{null} @code{onmessage} handler.
846
847 @end table
848
849 @end table
850
851 @section QuickJS C API
852
853 The C API was designed to be simple and efficient. The C API is
854 defined in the header @code{quickjs.h}.
855
856 @subsection Runtime and contexts
857
858 @code{JSRuntime} represents a Javascript runtime corresponding to an
859 object heap. Several runtimes can exist at the same time but they
860 cannot exchange objects. Inside a given runtime, no multi-threading is
861 supported.
862
863 @code{JSContext} represents a Javascript context (or Realm). Each
864 JSContext has its own global objects and system objects. There can be
865 several JSContexts per JSRuntime and they can share objects, similar
866 to frames of the same origin sharing Javascript objects in a
867 web browser.
868
869 @subsection JSValue
870
871 @code{JSValue} represents a Javascript value which can be a primitive
872 type or an object. Reference counting is used, so it is important to
873 explicitly duplicate (@code{JS_DupValue()}, increment the reference
874 count) or free (@code{JS_FreeValue()}, decrement the reference count)
875 JSValues.
876
877 @subsection C functions
878
879 C functions can be created with
880 @code{JS_NewCFunction()}. @code{JS_SetPropertyFunctionList()} is a
881 shortcut to easily add functions, setters and getters properties to a
882 given object.
883
884 Unlike other embedded Javascript engines, there is no implicit stack,
885 so C functions get their parameters as normal C parameters. As a
886 general rule, C functions take constant @code{JSValue}s as parameters
887 (so they don't need to free them) and return a newly allocated (=live)
888 @code{JSValue}.
889
890 @subsection Exceptions
891
892 Exceptions: most C functions can return a Javascript exception. It
893 must be explicitly tested and handled by the C code. The specific
894 @code{JSValue} @code{JS_EXCEPTION} indicates that an exception
895 occurred. The actual exception object is stored in the
896 @code{JSContext} and can be retrieved with @code{JS_GetException()}.
897
898 @subsection Script evaluation
899
900 Use @code{JS_Eval()} to evaluate a script or module source.
901
902 If the script or module was compiled to bytecode with @code{qjsc}, it
903 can be evaluated by calling @code{js_std_eval_binary()}. The advantage
904 is that no compilation is needed so it is faster and smaller because
905 the compiler can be removed from the executable if no @code{eval} is
906 required.
907
908 Note: the bytecode format is linked to a given QuickJS
909 version. Moreover, no security check is done before its
910 execution. Hence the bytecode should not be loaded from untrusted
911 sources. That's why there is no option to output the bytecode to a
912 binary file in @code{qjsc}.
913
914 @subsection JS Classes
915
916 C opaque data can be attached to a Javascript object. The type of the
917 C opaque data is determined with the class ID (@code{JSClassID}) of
918 the object. Hence the first step is to register a new class ID and JS
919 class (@code{JS_NewClassID()}, @code{JS_NewClass()}). Then you can
920 create objects of this class with @code{JS_NewObjectClass()} and get or
921 set the C opaque point with
922 @code{JS_GetOpaque()}/@code{JS_SetOpaque()}.
923
924 When defining a new JS class, it is possible to declare a finalizer
925 which is called when the object is destroyed. The finalizer should be
926 used to release C resources. It is invalid to execute JS code from
927 it. A @code{gc_mark} method can be provided so that the cycle removal
928 algorithm can find the other objects referenced by this object. Other
929 methods are available to define exotic object behaviors.
930
931 The Class ID are globally allocated (i.e. for all runtimes). The
932 JSClass are allocated per @code{JSRuntime}. @code{JS_SetClassProto()}
933 is used to define a prototype for a given class in a given
934 JSContext. @code{JS_NewObjectClass()} sets this prototype in the
935 created object.
936
937 Examples are available in @file{quickjs-libc.c}.
938
939 @subsection C Modules
940
941 Native ES6 modules are supported and can be dynamically or statically
942 linked. Look at the @file{test_bjson} and @file{bjson.so}
943 examples. The standard library @file{quickjs-libc.c} is also a good example
944 of a native module.
945
946 @subsection Memory handling
947
948 Use @code{JS_SetMemoryLimit()} to set a global memory allocation limit
949 to a given JSRuntime.
950
951 Custom memory allocation functions can be provided with
952 @code{JS_NewRuntime2()}.
953
954 The maximum system stack size can be set with @code{JS_SetMaxStackSize()}.
955
956 @subsection Execution timeout and interrupts
957
958 Use @code{JS_SetInterruptHandler()} to set a callback which is
959 regularly called by the engine when it is executing code. This
960 callback can be used to implement an execution timeout.
961
962 It is used by the command line interpreter to implement a
963 @code{Ctrl-C} handler.
964
965 @chapter Internals
966
967 @section Bytecode
968
969 The compiler generates bytecode directly with no intermediate
970 representation such as a parse tree, hence it is very fast. Several
971 optimizations passes are done over the generated bytecode.
972
973 A stack-based bytecode was chosen because it is simple and generates
974 compact code.
975
976 For each function, the maximum stack size is computed at compile time so that
977 no runtime stack overflow tests are needed.
978
979 A separate compressed line number table is maintained for the debug
980 information.
981
982 Access to closure variables is optimized and is almost as fast as local
983 variables.
984
985 Direct @code{eval} in strict mode is optimized.
986
987 @section Executable generation
988
989 @subsection @code{qjsc} compiler
990
991 The @code{qjsc} compiler generates C sources from Javascript files. By
992 default the C sources are compiled with the system compiler
993 (@code{gcc} or @code{clang}).
994
995 The generated C source contains the bytecode of the compiled functions
996 or modules. If a full complete executable is needed, it also
997 contains a @code{main()} function with the necessary C code to initialize the
998 Javascript engine and to load and execute the compiled functions and
999 modules.
1000
1001 Javascript code can be mixed with C modules.
1002
1003 In order to have smaller executables, specific Javascript features can
1004 be disabled, in particular @code{eval} or the regular expressions. The
1005 code removal relies on the Link Time Optimization of the system
1006 compiler.
1007
1008 @subsection Binary JSON
1009
1010 @code{qjsc} works by compiling scripts or modules and then serializing
1011 them to a binary format. A subset of this format (without functions or
1012 modules) can be used as binary JSON. The example @file{test_bjson.js}
1013 shows how to use it.
1014
1015 Warning: the binary JSON format may change without notice, so it
1016 should not be used to store persistent data. The @file{test_bjson.js}
1017 example is only used to test the binary object format functions.
1018
1019 @section Runtime
1020
1021 @subsection Strings
1022
1023 Strings are stored either as an 8 bit or a 16 bit array of
1024 characters. Hence random access to characters is always fast.
1025
1026 The C API provides functions to convert Javascript Strings to C UTF-8 encoded
1027 strings. The most common case where the Javascript string contains
1028 only ASCII characters involves no copying.
1029
1030 @subsection Objects
1031
1032 The object shapes (object prototype, property names and flags) are shared
1033 between objects to save memory.
1034
1035 Arrays with no holes (except at the end of the array) are optimized.
1036
1037 TypedArray accesses are optimized.
1038
1039 @subsection Atoms
1040
1041 Object property names and some strings are stored as Atoms (unique
1042 strings) to save memory and allow fast comparison. Atoms are
1043 represented as a 32 bit integer. Half of the atom range is reserved for
1044 immediate integer literals from @math{0} to @math{2^{31}-1}.
1045
1046 @subsection Numbers
1047
1048 Numbers are represented either as 32-bit signed integers or 64-bit IEEE-754
1049 floating point values. Most operations have fast paths for the 32-bit
1050 integer case.
1051
1052 @subsection Garbage collection
1053
1054 Reference counting is used to free objects automatically and
1055 deterministically. A separate cycle removal pass is done when the allocated
1056 memory becomes too large. The cycle removal algorithm only uses the
1057 reference counts and the object content, so no explicit garbage
1058 collection roots need to be manipulated in the C code.
1059
1060 @subsection JSValue
1061
1062 It is a Javascript value which can be a primitive type (such as
1063 Number, String, ...) or an Object. NaN boxing is used in the 32-bit version
1064 to store 64-bit floating point numbers. The representation is
1065 optimized so that 32-bit integers and reference counted values can be
1066 efficiently tested.
1067
1068 In 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The
1069 rationale is that in 64-bit code memory usage is less critical.
1070
1071 In both cases (32 or 64 bits), JSValue exactly fits two CPU registers,
1072 so it can be efficiently returned by C functions.
1073
1074 @subsection Function call
1075
1076 The engine is optimized so that function calls are fast. The system
1077 stack holds the Javascript parameters and local variables.
1078
1079 @section RegExp
1080
1081 A specific regular expression engine was developed. It is both small
1082 and efficient and supports all the ES2023 features including the
1083 Unicode properties. As the Javascript compiler, it directly generates
1084 bytecode without a parse tree.
1085
1086 Backtracking with an explicit stack is used so that there is no
1087 recursion on the system stack. Simple quantifiers are specifically
1088 optimized to avoid recursions.
1089
1090 The full regexp library weights about 15 KiB (x86 code), excluding the
1091 Unicode library.
1092
1093 @section Unicode
1094
1095 A specific Unicode library was developed so that there is no
1096 dependency on an external large Unicode library such as ICU. All the
1097 Unicode tables are compressed while keeping a reasonable access
1098 speed.
1099
1100 The library supports case conversion, Unicode normalization, Unicode
1101 script queries, Unicode general category queries and all Unicode
1102 binary properties.
1103
1104 The full Unicode library weights about 45 KiB (x86 code).
1105
1106 @section BigInt, BigFloat, BigDecimal
1107
1108 BigInt, BigFloat and BigDecimal are implemented with the @code{libbf}
1109 library@footnote{@url{https://bellard.org/libbf}}. It weights about 90
1110 KiB (x86 code) and provides arbitrary precision IEEE 754 floating
1111 point operations and transcendental functions with exact rounding.
1112
1113 @chapter License
1114
1115 QuickJS is released under the MIT license.
1116
1117 Unless otherwise specified, the QuickJS sources are copyright Fabrice
1118 Bellard and Charlie Gordon.
1119
1120 @bye