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