├── VERSION ├── test262o_errors.txt ├── .gitignore ├── examples ├── hello.js ├── hello_module.js ├── test_fib.js ├── fib_module.js ├── test_point.js ├── pi_bigfloat.js ├── pi_bigdecimal.js ├── fib.c ├── pi_bigint.js └── point.c ├── doc ├── jsbignum.pdf └── quickjs.pdf ├── src ├── compiler │ └── CMakeLists.txt ├── interpreter │ └── CMakeLists.txt ├── utils │ ├── libregexp-opcode.h │ ├── libregexp.h │ ├── list.h │ ├── libunicode.h │ ├── unicode_gen_def.h │ └── cutils.h ├── libc │ └── quickjs-libc.h ├── quickjs-parser-atom.h ├── runtime │ └── quickjs-js-math.h ├── quickjs-generator.h ├── quickjs-private.h └── quickjs-opcode.h ├── unicode_download.sh ├── README.md ├── CMakeLists.txt ├── tests ├── test262.patch ├── test_worker.js ├── bjson.c ├── test_closure.js ├── test_op_overloading.js ├── test_bjson.js ├── test_qjscalc.js ├── test_std.js ├── test_loop.js ├── test_language.js └── test_bignum.js ├── release.sh ├── Changelog ├── TODO ├── test262_errors.txt ├── test262.conf └── Makefile /VERSION: -------------------------------------------------------------------------------- 1 | 2020-07-05 2 | -------------------------------------------------------------------------------- /test262o_errors.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | cmake-build-debug -------------------------------------------------------------------------------- /examples/hello.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World"); 2 | -------------------------------------------------------------------------------- /doc/jsbignum.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LemonHX/AcidJS/HEAD/doc/jsbignum.pdf -------------------------------------------------------------------------------- /doc/quickjs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LemonHX/AcidJS/HEAD/doc/quickjs.pdf -------------------------------------------------------------------------------- /examples/hello_module.js: -------------------------------------------------------------------------------- 1 | /* example of JS module */ 2 | 3 | import { fib } from "./fib_module.js"; 4 | 5 | console.log("Hello World"); 6 | console.log("fib(10)=", fib(10)); 7 | -------------------------------------------------------------------------------- /examples/test_fib.js: -------------------------------------------------------------------------------- 1 | /* example of JS module importing a C module */ 2 | 3 | import { fib } from "./fib.so"; 4 | 5 | console.log("Hello World"); 6 | console.log("fib(10)=", fib(10)); 7 | -------------------------------------------------------------------------------- /examples/fib_module.js: -------------------------------------------------------------------------------- 1 | /* fib module */ 2 | export function fib(n) 3 | { 4 | if (n <= 0) 5 | return 0; 6 | else if (n == 1) 7 | return 1; 8 | else 9 | return fib(n - 1) + fib(n - 2); 10 | } 11 | -------------------------------------------------------------------------------- /src/compiler/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.1) 2 | project(quickjs_compiler) 3 | set(quickjs_version 2020-07-05) 4 | 5 | add_executable(${PROJECT_NAME} qjsc.c) 6 | target_link_libraries(quickjs_compiler quickjs) 7 | target_compile_definitions(${PROJECT_NAME} 8 | PRIVATE 9 | CONFIG_VERSION="${quickjs_version}" 10 | ) -------------------------------------------------------------------------------- /src/interpreter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.1) 2 | project(quickjs_interpreter) 3 | set(quickjs_version 2020-07-05) 4 | 5 | add_executable(${PROJECT_NAME} qjs.c) 6 | target_link_libraries(quickjs_interpreter quickjs) 7 | target_compile_definitions(${PROJECT_NAME} 8 | PRIVATE 9 | CONFIG_VERSION="${quickjs_version}" 10 | ) -------------------------------------------------------------------------------- /unicode_download.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | url="ftp://ftp.unicode.org/Public/13.0.0/ucd" 5 | emoji_url="${url}/emoji/emoji-data.txt" 6 | 7 | files="CaseFolding.txt DerivedNormalizationProps.txt PropList.txt \ 8 | SpecialCasing.txt CompositionExclusions.txt ScriptExtensions.txt \ 9 | UnicodeData.txt DerivedCoreProperties.txt NormalizationTest.txt Scripts.txt \ 10 | PropertyValueAliases.txt" 11 | 12 | mkdir -p unicode 13 | 14 | #for f in $files; do 15 | # g="${url}/${f}" 16 | # wget $g -O unicode/$f 17 | #done 18 | 19 | wget $emoji_url -O unicode/emoji-data.txt 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AcidJS 2 | This is a fork of QuickJS that compatible with MSVC and using CMAKE to compile. 3 | *All the modifications should only affect behaviors on Windows.* 4 | 5 | ## Build 6 | ``` 7 | cmake 8 | ``` 9 | and do what ever depending on the tool chain which you are using. 10 | 11 | the compiler and the interpreter I've put it under "subdirectory" due to my poor level of writing cmake files. 12 | 13 | ## TODO 14 | - [ ] support ATOMIC 15 | - [ ] format define _MSC_VER which are flying around. 16 | 17 | ## License of QuickJS 18 | QuickJS sources are copyright Fabrice Bellard and Charlie Gordon. 19 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.1) 2 | project(quickjs) 3 | 4 | set(quickjs_version 2020-07-05) 5 | set(quickjs_sources 6 | src/quickjs.c 7 | src/utils/libregexp.c 8 | src/utils/libunicode.c 9 | src/utils/libbf.c 10 | src/utils/cutils.c 11 | src/libc/quickjs-libc.c 12 | ) 13 | 14 | add_library(${PROJECT_NAME} 15 | ${quickjs_sources} 16 | ) 17 | 18 | target_compile_definitions(${PROJECT_NAME} 19 | PRIVATE 20 | CONFIG_VERSION="${quickjs_version}" 21 | ) 22 | 23 | add_subdirectory(src/compiler) 24 | add_subdirectory(src/interpreter) -------------------------------------------------------------------------------- /examples/test_point.js: -------------------------------------------------------------------------------- 1 | /* example of JS module importing a C module */ 2 | import { Point } from "./point.so"; 3 | 4 | function assert(b, str) 5 | { 6 | if (b) { 7 | return; 8 | } else { 9 | throw Error("assertion failed: " + str); 10 | } 11 | } 12 | 13 | class ColorPoint extends Point { 14 | constructor(x, y, color) { 15 | super(x, y); 16 | this.color = color; 17 | } 18 | get_color() { 19 | return this.color; 20 | } 21 | }; 22 | 23 | function main() 24 | { 25 | var pt, pt2; 26 | 27 | pt = new Point(2, 3); 28 | assert(pt.x === 2); 29 | assert(pt.y === 3); 30 | pt.x = 4; 31 | assert(pt.x === 4); 32 | assert(pt.norm() == 5); 33 | 34 | pt2 = new ColorPoint(2, 3, 0xffffff); 35 | assert(pt2.x === 2); 36 | assert(pt2.color === 0xffffff); 37 | assert(pt2.get_color() === 0xffffff); 38 | } 39 | 40 | main(); 41 | -------------------------------------------------------------------------------- /examples/pi_bigfloat.js: -------------------------------------------------------------------------------- 1 | /* 2 | * PI computation in Javascript using the QuickJS bigfloat type 3 | * (binary floating point) 4 | */ 5 | "use strict"; 6 | 7 | /* compute PI with a precision of 'prec' bits */ 8 | function calc_pi() { 9 | const CHUD_A = 13591409n; 10 | const CHUD_B = 545140134n; 11 | const CHUD_C = 640320n; 12 | const CHUD_C3 = 10939058860032000n; /* C^3/24 */ 13 | const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */ 14 | 15 | /* return [P, Q, G] */ 16 | function chud_bs(a, b, need_G) { 17 | var c, P, Q, G, P1, Q1, G1, P2, Q2, G2; 18 | if (a == (b - 1n)) { 19 | G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n); 20 | P = BigFloat(G * (CHUD_B * b + CHUD_A)); 21 | if (b & 1n) 22 | P = -P; 23 | G = BigFloat(G); 24 | Q = BigFloat(b * b * b * CHUD_C3); 25 | } else { 26 | c = (a + b) >> 1n; 27 | [P1, Q1, G1] = chud_bs(a, c, true); 28 | [P2, Q2, G2] = chud_bs(c, b, need_G); 29 | P = P1 * Q2 + P2 * G1; 30 | Q = Q1 * Q2; 31 | if (need_G) 32 | G = G1 * G2; 33 | else 34 | G = 0l; 35 | } 36 | return [P, Q, G]; 37 | } 38 | 39 | var n, P, Q, G; 40 | /* number of serie terms */ 41 | n = BigInt(Math.ceil(BigFloatEnv.prec / CHUD_BITS_PER_TERM)) + 10n; 42 | [P, Q, G] = chud_bs(0n, n, false); 43 | Q = Q / (P + Q * BigFloat(CHUD_A)); 44 | G = BigFloat((CHUD_C / 12n)) * BigFloat.sqrt(BigFloat(CHUD_C)); 45 | return Q * G; 46 | } 47 | 48 | (function() { 49 | var r, n_digits, n_bits; 50 | if (typeof scriptArgs != "undefined") { 51 | if (scriptArgs.length < 2) { 52 | print("usage: pi n_digits"); 53 | return; 54 | } 55 | n_digits = scriptArgs[1]; 56 | } else { 57 | n_digits = 1000; 58 | } 59 | n_bits = Math.ceil(n_digits * Math.log2(10)); 60 | /* we add more bits to reduce the probability of bad rounding for 61 | the last digits */ 62 | BigFloatEnv.setPrec( () => { 63 | r = calc_pi(); 64 | print(r.toFixed(n_digits, BigFloatEnv.RNDZ)); 65 | }, n_bits + 32); 66 | })(); 67 | -------------------------------------------------------------------------------- /examples/pi_bigdecimal.js: -------------------------------------------------------------------------------- 1 | /* 2 | * PI computation in Javascript using the QuickJS bigdecimal type 3 | * (decimal floating point) 4 | */ 5 | "use strict"; 6 | 7 | /* compute PI with a precision of 'prec' digits */ 8 | function calc_pi(prec) { 9 | const CHUD_A = 13591409m; 10 | const CHUD_B = 545140134m; 11 | const CHUD_C = 640320m; 12 | const CHUD_C3 = 10939058860032000m; /* C^3/24 */ 13 | const CHUD_DIGITS_PER_TERM = 14.18164746272548; /* log10(C/12)*3 */ 14 | 15 | /* return [P, Q, G] */ 16 | function chud_bs(a, b, need_G) { 17 | var c, P, Q, G, P1, Q1, G1, P2, Q2, G2, b1; 18 | if (a == (b - 1n)) { 19 | b1 = BigDecimal(b); 20 | G = (2m * b1 - 1m) * (6m * b1 - 1m) * (6m * b1 - 5m); 21 | P = G * (CHUD_B * b1 + CHUD_A); 22 | if (b & 1n) 23 | P = -P; 24 | G = G; 25 | Q = b1 * b1 * b1 * CHUD_C3; 26 | } else { 27 | c = (a + b) >> 1n; 28 | [P1, Q1, G1] = chud_bs(a, c, true); 29 | [P2, Q2, G2] = chud_bs(c, b, need_G); 30 | P = P1 * Q2 + P2 * G1; 31 | Q = Q1 * Q2; 32 | if (need_G) 33 | G = G1 * G2; 34 | else 35 | G = 0m; 36 | } 37 | return [P, Q, G]; 38 | } 39 | 40 | var n, P, Q, G; 41 | /* number of serie terms */ 42 | n = BigInt(Math.ceil(prec / CHUD_DIGITS_PER_TERM)) + 10n; 43 | [P, Q, G] = chud_bs(0n, n, false); 44 | Q = BigDecimal.div(Q, (P + Q * CHUD_A), 45 | { roundingMode: "half-even", 46 | maximumSignificantDigits: prec }); 47 | G = (CHUD_C / 12m) * BigDecimal.sqrt(CHUD_C, 48 | { roundingMode: "half-even", 49 | maximumSignificantDigits: prec }); 50 | return Q * G; 51 | } 52 | 53 | (function() { 54 | var r, n_digits, n_bits; 55 | if (typeof scriptArgs != "undefined") { 56 | if (scriptArgs.length < 2) { 57 | print("usage: pi n_digits"); 58 | return; 59 | } 60 | n_digits = scriptArgs[1] | 0; 61 | } else { 62 | n_digits = 1000; 63 | } 64 | /* we add more digits to reduce the probability of bad rounding for 65 | the last digits */ 66 | r = calc_pi(n_digits + 20); 67 | print(r.toFixed(n_digits, "down")); 68 | })(); 69 | -------------------------------------------------------------------------------- /src/utils/libregexp-opcode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Regular Expression Engine 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #ifdef DEF 26 | 27 | DEF(invalid, 1) /* never used */ 28 | DEF(char, 3) 29 | DEF(char32, 5) 30 | DEF(dot, 1) 31 | DEF(any, 1) /* same as dot but match any character including line terminator */ 32 | DEF(line_start, 1) 33 | DEF(line_end, 1) 34 | DEF(goto, 5) 35 | DEF(split_goto_first, 5) 36 | DEF(split_next_first, 5) 37 | DEF(match, 1) 38 | DEF(save_start, 2) /* save start position */ 39 | DEF(save_end, 2) /* save end position, must come after saved_start */ 40 | DEF(save_reset, 3) /* reset save positions */ 41 | DEF(loop, 5) /* decrement the top the stack and goto if != 0 */ 42 | DEF(push_i32, 5) /* push integer on the stack */ 43 | DEF(drop, 1) 44 | DEF(word_boundary, 1) 45 | DEF(not_word_boundary, 1) 46 | DEF(back_reference, 2) 47 | DEF(backward_back_reference, 2) /* must come after back_reference */ 48 | DEF(range, 3) /* variable length */ 49 | DEF(range32, 3) /* variable length */ 50 | DEF(lookahead, 5) 51 | DEF(negative_lookahead, 5) 52 | DEF(push_char_pos, 1) /* push the character position on the stack */ 53 | DEF(bne_char_pos, 5) /* pop one stack element and jump if equal to the character 54 | position */ 55 | DEF(prev, 1) /* go to the previous char */ 56 | DEF(simple_greedy_quant, 17) 57 | 58 | #endif /* DEF */ 59 | -------------------------------------------------------------------------------- /tests/test262.patch: -------------------------------------------------------------------------------- 1 | diff --git a/harness/atomicsHelper.js b/harness/atomicsHelper.js 2 | index 9c1217351e..3c24755558 100644 3 | --- a/harness/atomicsHelper.js 4 | +++ b/harness/atomicsHelper.js 5 | @@ -227,10 +227,14 @@ $262.agent.waitUntil = function(typedArray, index, expected) { 6 | * } 7 | */ 8 | $262.agent.timeouts = { 9 | - yield: 100, 10 | - small: 200, 11 | - long: 1000, 12 | - huge: 10000, 13 | +// yield: 100, 14 | +// small: 200, 15 | +// long: 1000, 16 | +// huge: 10000, 17 | + yield: 20, 18 | + small: 20, 19 | + long: 100, 20 | + huge: 1000, 21 | }; 22 | 23 | /** 24 | diff --git a/harness/regExpUtils.js b/harness/regExpUtils.js 25 | index be7039fda0..7b38abf8df 100644 26 | --- a/harness/regExpUtils.js 27 | +++ b/harness/regExpUtils.js 28 | @@ -6,24 +6,27 @@ description: | 29 | defines: [buildString, testPropertyEscapes, matchValidator] 30 | ---*/ 31 | 32 | +if ($262 && typeof $262.codePointRange === "function") { 33 | + /* use C function to build the codePointRange (much faster with 34 | + slow JS engines) */ 35 | + codePointRange = $262.codePointRange; 36 | +} else { 37 | + codePointRange = function codePointRange(start, end) { 38 | + const codePoints = []; 39 | + let length = 0; 40 | + for (codePoint = start; codePoint < end; codePoint++) { 41 | + codePoints[length++] = codePoint; 42 | + } 43 | + return String.fromCodePoint.apply(null, codePoints); 44 | + } 45 | +} 46 | + 47 | function buildString({ loneCodePoints, ranges }) { 48 | - const CHUNK_SIZE = 10000; 49 | - let result = Reflect.apply(String.fromCodePoint, null, loneCodePoints); 50 | - for (let i = 0; i < ranges.length; i++) { 51 | - const range = ranges[i]; 52 | - const start = range[0]; 53 | - const end = range[1]; 54 | - const codePoints = []; 55 | - for (let length = 0, codePoint = start; codePoint <= end; codePoint++) { 56 | - codePoints[length++] = codePoint; 57 | - if (length === CHUNK_SIZE) { 58 | - result += Reflect.apply(String.fromCodePoint, null, codePoints); 59 | - codePoints.length = length = 0; 60 | - } 61 | + let result = String.fromCodePoint.apply(null, loneCodePoints); 62 | + for (const [start, end] of ranges) { 63 | + result += codePointRange(start, end + 1); 64 | } 65 | - result += Reflect.apply(String.fromCodePoint, null, codePoints); 66 | - } 67 | - return result; 68 | + return result; 69 | } 70 | 71 | function testPropertyEscapes(regex, string, expression) { 72 | -------------------------------------------------------------------------------- /examples/fib.c: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS: Example of C module 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #include "../src/quickjs.h" 25 | 26 | #define countof(x) (sizeof(x) / sizeof((x)[0])) 27 | 28 | static int fib(int n) 29 | { 30 | if (n <= 0) 31 | return 0; 32 | else if (n == 1) 33 | return 1; 34 | else 35 | return fib(n - 1) + fib(n - 2); 36 | } 37 | 38 | static JSValue js_fib(JSContext *ctx, JSValueConst this_val, 39 | int argc, JSValueConst *argv) 40 | { 41 | int n, res; 42 | if (JS_ToInt32(ctx, &n, argv[0])) 43 | return JS_EXCEPTION; 44 | res = fib(n); 45 | return JS_NewInt32(ctx, res); 46 | } 47 | 48 | static const JSCFunctionListEntry js_fib_funcs[] = { 49 | JS_CFUNC_DEF("fib", 1, js_fib ), 50 | }; 51 | 52 | static int js_fib_init(JSContext *ctx, JSModuleDef *m) 53 | { 54 | return JS_SetModuleExportList(ctx, m, js_fib_funcs, 55 | countof(js_fib_funcs)); 56 | } 57 | 58 | #ifdef JS_SHARED_LIBRARY 59 | #define JS_INIT_MODULE js_init_module 60 | #else 61 | #define JS_INIT_MODULE js_init_module_fib 62 | #endif 63 | 64 | JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) 65 | { 66 | JSModuleDef *m; 67 | m = JS_NewCModule(ctx, module_name, js_fib_init); 68 | if (!m) 69 | return NULL; 70 | JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs)); 71 | return m; 72 | } 73 | -------------------------------------------------------------------------------- /src/libc/quickjs-libc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS C library 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #ifndef QUICKJS_LIBC_H 25 | #define QUICKJS_LIBC_H 26 | 27 | #include 28 | #include 29 | 30 | #include "../quickjs.h" 31 | 32 | #ifdef __cplusplus 33 | extern "C" { 34 | #endif 35 | 36 | JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name); 37 | JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name); 38 | void js_std_add_helpers(JSContext *ctx, int argc, char **argv); 39 | void js_std_loop(JSContext *ctx); 40 | void js_std_init_handlers(JSRuntime *rt); 41 | void js_std_free_handlers(JSRuntime *rt); 42 | void js_std_dump_error(JSContext *ctx); 43 | uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename); 44 | int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, 45 | JS_BOOL use_realpath, JS_BOOL is_main); 46 | JSModuleDef *js_module_loader(JSContext *ctx, 47 | const char *module_name, void *opaque); 48 | void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len, 49 | int flags); 50 | void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, 51 | JSValueConst reason, 52 | JS_BOOL is_handled, void *opaque); 53 | 54 | #ifdef __cplusplus 55 | } /* extern "C" { */ 56 | #endif 57 | 58 | #endif /* QUICKJS_LIBC_H */ 59 | -------------------------------------------------------------------------------- /tests/test_worker.js: -------------------------------------------------------------------------------- 1 | /* os.Worker API test */ 2 | import * as std from "std"; 3 | import * as os from "os"; 4 | 5 | function assert(actual, expected, message) { 6 | if (arguments.length == 1) 7 | expected = true; 8 | 9 | if (actual === expected) 10 | return; 11 | 12 | if (actual !== null && expected !== null 13 | && typeof actual == 'object' && typeof expected == 'object' 14 | && actual.toString() === expected.toString()) 15 | return; 16 | 17 | throw Error("assertion failed: got |" + actual + "|" + 18 | ", expected |" + expected + "|" + 19 | (message ? " (" + message + ")" : "")); 20 | } 21 | 22 | var worker; 23 | 24 | function test_worker() 25 | { 26 | var counter; 27 | 28 | /* Note: can use std.loadFile() to read from a file */ 29 | worker = new os.Worker(` 30 | import * as std from "std"; 31 | import * as os from "os"; 32 | 33 | var parent = os.Worker.parent; 34 | 35 | function handle_msg(e) { 36 | var ev = e.data; 37 | // print("child_recv", JSON.stringify(ev)); 38 | switch(ev.type) { 39 | case "abort": 40 | parent.postMessage({ type: "done" }); 41 | break; 42 | case "sab": 43 | /* modify the SharedArrayBuffer */ 44 | ev.buf[2] = 10; 45 | parent.postMessage({ type: "sab_done", buf: ev.buf }); 46 | break; 47 | } 48 | } 49 | 50 | function worker_main() { 51 | var i; 52 | 53 | parent.onmessage = handle_msg; 54 | for(i = 0; i < 10; i++) { 55 | parent.postMessage({ type: "num", num: i }); 56 | } 57 | } 58 | worker_main(); 59 | `); 60 | 61 | counter = 0; 62 | worker.onmessage = function (e) { 63 | var ev = e.data; 64 | // print("recv", JSON.stringify(ev)); 65 | switch(ev.type) { 66 | case "num": 67 | assert(ev.num, counter); 68 | counter++; 69 | if (counter == 10) { 70 | /* test SharedArrayBuffer modification */ 71 | let sab = new SharedArrayBuffer(10); 72 | let buf = new Uint8Array(sab); 73 | worker.postMessage({ type: "sab", buf: buf }); 74 | } 75 | break; 76 | case "sab_done": 77 | { 78 | let buf = ev.buf; 79 | /* check that the SharedArrayBuffer was modified */ 80 | assert(buf[2], 10); 81 | worker.postMessage({ type: "abort" }); 82 | } 83 | break; 84 | case "done": 85 | /* terminate */ 86 | worker.onmessage = null; 87 | break; 88 | } 89 | }; 90 | } 91 | 92 | 93 | test_worker(); 94 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Release the QuickJS source code 3 | 4 | set -e 5 | 6 | version=`cat VERSION` 7 | 8 | if [ "$1" = "-h" ] ; then 9 | echo "release.sh [all]" 10 | echo "" 11 | echo "all: build all the archives. Otherwise only build the quickjs source archive." 12 | exit 1 13 | fi 14 | 15 | extras="no" 16 | binary="no" 17 | quickjs="no" 18 | 19 | if [ "$1" = "all" ] ; then 20 | extras="yes" 21 | binary="yes" 22 | quickjs="yes" 23 | elif [ "$1" = "binary" ] ; then 24 | binary="yes" 25 | else 26 | quickjs="yes" 27 | fi 28 | 29 | #################################################" 30 | # extras 31 | 32 | if [ "$extras" = "yes" ] ; then 33 | 34 | d="quickjs-${version}" 35 | name="quickjs-extras-${version}" 36 | outdir="/tmp/${d}" 37 | 38 | rm -rf $outdir 39 | mkdir -p $outdir $outdir/unicode $outdir/tests 40 | 41 | cp unicode/* $outdir/unicode 42 | cp -a tests/bench-v8 $outdir/tests 43 | 44 | ( cd /tmp && tar Jcvf /tmp/${name}.tar.xz ${d} ) 45 | 46 | fi 47 | 48 | #################################################" 49 | # binary release 50 | 51 | if [ "$binary" = "yes" ] ; then 52 | 53 | make -j4 qjs run-test262 54 | make -j4 CONFIG_M32=y qjs32 run-test262-32 55 | strip qjs run-test262 qjs32 run-test262-32 56 | 57 | d="quickjs-linux-x86_64-${version}" 58 | outdir="/tmp/${d}" 59 | 60 | rm -rf $outdir 61 | mkdir -p $outdir 62 | 63 | cp qjs run-test262 $outdir 64 | 65 | ( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . ) 66 | 67 | d="quickjs-linux-i686-${version}" 68 | outdir="/tmp/${d}" 69 | 70 | rm -rf $outdir 71 | mkdir -p $outdir 72 | 73 | cp qjs32 $outdir/qjs 74 | cp run-test262-32 $outdir/run-test262 75 | 76 | ( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . ) 77 | 78 | fi 79 | 80 | #################################################" 81 | # quickjs 82 | 83 | if [ "$quickjs" = "yes" ] ; then 84 | 85 | make build_doc 86 | 87 | d="quickjs-${version}" 88 | outdir="/tmp/${d}" 89 | 90 | rm -rf $outdir 91 | mkdir -p $outdir $outdir/doc $outdir/tests $outdir/examples 92 | 93 | cp Makefile VERSION TODO Changelog readme.txt release.sh unicode_download.sh \ 94 | qjs.c qjsc.c qjscalc.js repl.js \ 95 | quickjs.c quickjs.h quickjs-atom.h \ 96 | quickjs-libc.c quickjs-libc.h quickjs-opcode.h \ 97 | cutils.c cutils.h list.h \ 98 | libregexp.c libregexp.h libregexp-opcode.h \ 99 | libunicode.c libunicode.h libunicode-table.h \ 100 | libbf.c libbf.h \ 101 | jscompress.c unicode_gen.c unicode_gen_def.h \ 102 | run-test262.c test262o.conf test262.conf \ 103 | test262o_errors.txt test262_errors.txt \ 104 | $outdir 105 | 106 | cp tests/*.js tests/*.patch tests/bjson.c $outdir/tests 107 | 108 | cp examples/*.js examples/*.c $outdir/examples 109 | 110 | cp doc/quickjs.texi doc/quickjs.pdf doc/quickjs.html \ 111 | doc/jsbignum.texi doc/jsbignum.html doc/jsbignum.pdf \ 112 | $outdir/doc 113 | 114 | ( cd /tmp && tar Jcvf /tmp/${d}.tar.xz ${d} ) 115 | 116 | fi 117 | -------------------------------------------------------------------------------- /examples/pi_bigint.js: -------------------------------------------------------------------------------- 1 | /* 2 | * PI computation in Javascript using the BigInt type 3 | */ 4 | "use strict"; 5 | 6 | /* return floor(log2(a)) for a > 0 and 0 for a = 0 */ 7 | function floor_log2(a) 8 | { 9 | var k_max, a1, k, i; 10 | k_max = 0n; 11 | while ((a >> (2n ** k_max)) != 0n) { 12 | k_max++; 13 | } 14 | k = 0n; 15 | a1 = a; 16 | for(i = k_max - 1n; i >= 0n; i--) { 17 | a1 = a >> (2n ** i); 18 | if (a1 != 0n) { 19 | a = a1; 20 | k |= (1n << i); 21 | } 22 | } 23 | return k; 24 | } 25 | 26 | /* return ceil(log2(a)) for a > 0 */ 27 | function ceil_log2(a) 28 | { 29 | return floor_log2(a - 1n) + 1n; 30 | } 31 | 32 | /* return floor(sqrt(a)) (not efficient but simple) */ 33 | function int_sqrt(a) 34 | { 35 | var l, u, s; 36 | if (a == 0n) 37 | return a; 38 | l = ceil_log2(a); 39 | u = 1n << ((l + 1n) / 2n); 40 | /* u >= floor(sqrt(a)) */ 41 | for(;;) { 42 | s = u; 43 | u = ((a / s) + s) / 2n; 44 | if (u >= s) 45 | break; 46 | } 47 | return s; 48 | } 49 | 50 | /* return pi * 2**prec */ 51 | function calc_pi(prec) { 52 | const CHUD_A = 13591409n; 53 | const CHUD_B = 545140134n; 54 | const CHUD_C = 640320n; 55 | const CHUD_C3 = 10939058860032000n; /* C^3/24 */ 56 | const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */ 57 | 58 | /* return [P, Q, G] */ 59 | function chud_bs(a, b, need_G) { 60 | var c, P, Q, G, P1, Q1, G1, P2, Q2, G2; 61 | if (a == (b - 1n)) { 62 | G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n); 63 | P = G * (CHUD_B * b + CHUD_A); 64 | if (b & 1n) 65 | P = -P; 66 | Q = b * b * b * CHUD_C3; 67 | } else { 68 | c = (a + b) >> 1n; 69 | [P1, Q1, G1] = chud_bs(a, c, true); 70 | [P2, Q2, G2] = chud_bs(c, b, need_G); 71 | P = P1 * Q2 + P2 * G1; 72 | Q = Q1 * Q2; 73 | if (need_G) 74 | G = G1 * G2; 75 | else 76 | G = 0n; 77 | } 78 | return [P, Q, G]; 79 | } 80 | 81 | var n, P, Q, G; 82 | /* number of serie terms */ 83 | n = BigInt(Math.ceil(Number(prec) / CHUD_BITS_PER_TERM)) + 10n; 84 | [P, Q, G] = chud_bs(0n, n, false); 85 | Q = (CHUD_C / 12n) * (Q << prec) / (P + Q * CHUD_A); 86 | G = int_sqrt(CHUD_C << (2n * prec)); 87 | return (Q * G) >> prec; 88 | } 89 | 90 | function main(args) { 91 | var r, n_digits, n_bits, out; 92 | if (args.length < 1) { 93 | print("usage: pi n_digits"); 94 | return; 95 | } 96 | n_digits = args[0] | 0; 97 | 98 | /* we add more bits to reduce the probability of bad rounding for 99 | the last digits */ 100 | n_bits = BigInt(Math.ceil(n_digits * Math.log2(10))) + 32n; 101 | r = calc_pi(n_bits); 102 | r = ((10n ** BigInt(n_digits)) * r) >> n_bits; 103 | out = r.toString(); 104 | print(out[0] + "." + out.slice(1)); 105 | } 106 | 107 | var args; 108 | if (typeof scriptArgs != "undefined") { 109 | args = scriptArgs; 110 | args.shift(); 111 | } else if (typeof arguments != "undefined") { 112 | args = arguments; 113 | } else { 114 | /* default: 1000 digits */ 115 | args=[1000]; 116 | } 117 | 118 | main(args); 119 | -------------------------------------------------------------------------------- /src/utils/libregexp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Regular Expression Engine 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #ifndef LIBREGEXP_H 25 | #define LIBREGEXP_H 26 | 27 | #include 28 | 29 | #include "libunicode.h" 30 | 31 | #define LRE_BOOL int /* for documentation purposes */ 32 | 33 | #define LRE_FLAG_GLOBAL (1 << 0) 34 | #define LRE_FLAG_IGNORECASE (1 << 1) 35 | #define LRE_FLAG_MULTILINE (1 << 2) 36 | #define LRE_FLAG_DOTALL (1 << 3) 37 | #define LRE_FLAG_UTF16 (1 << 4) 38 | #define LRE_FLAG_STICKY (1 << 5) 39 | 40 | #define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */ 41 | 42 | uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size, 43 | const char *buf, size_t buf_len, int re_flags, 44 | void *opaque); 45 | int lre_get_capture_count(const uint8_t *bc_buf); 46 | int lre_get_flags(const uint8_t *bc_buf); 47 | int lre_exec(uint8_t **capture, 48 | const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen, 49 | int cbuf_type, void *opaque); 50 | 51 | int lre_parse_escape(const uint8_t **pp, int allow_utf16); 52 | LRE_BOOL lre_is_space(int c); 53 | 54 | /* must be provided by the user */ 55 | LRE_BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size); 56 | void *lre_realloc(void *opaque, void *ptr, size_t size); 57 | 58 | /* JS identifier test */ 59 | extern uint32_t const lre_id_start_table_ascii[4]; 60 | extern uint32_t const lre_id_continue_table_ascii[4]; 61 | 62 | static inline int lre_js_is_ident_first(int c) 63 | { 64 | if ((uint32_t)c < 128) { 65 | return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1; 66 | } else { 67 | #ifdef CONFIG_ALL_UNICODE 68 | return lre_is_id_start(c); 69 | #else 70 | return !lre_is_space(c); 71 | #endif 72 | } 73 | } 74 | 75 | static inline int lre_js_is_ident_next(int c) 76 | { 77 | if ((uint32_t)c < 128) { 78 | return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1; 79 | } else { 80 | /* ZWNJ and ZWJ are accepted in identifiers */ 81 | #ifdef CONFIG_ALL_UNICODE 82 | return lre_is_id_continue(c) || c == 0x200C || c == 0x200D; 83 | #else 84 | return !lre_is_space(c) || c == 0x200C || c == 0x200D; 85 | #endif 86 | } 87 | } 88 | 89 | #undef LRE_BOOL 90 | 91 | #endif /* LIBREGEXP_H */ 92 | -------------------------------------------------------------------------------- /tests/bjson.c: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS: binary JSON module (test only) 3 | * 4 | * Copyright (c) 2017-2019 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #include "../src/libc/quickjs-libc.h" 25 | #include "../src/utils/cutils.h" 26 | 27 | static JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val, 28 | int argc, JSValueConst *argv) 29 | { 30 | uint8_t *buf; 31 | uint64_t pos, len; 32 | JSValue obj; 33 | size_t size; 34 | int flags; 35 | 36 | if (JS_ToIndex(ctx, &pos, argv[1])) 37 | return JS_EXCEPTION; 38 | if (JS_ToIndex(ctx, &len, argv[2])) 39 | return JS_EXCEPTION; 40 | buf = JS_GetArrayBuffer(ctx, &size, argv[0]); 41 | if (!buf) 42 | return JS_EXCEPTION; 43 | if (pos + len > size) 44 | return JS_ThrowRangeError(ctx, "array buffer overflow"); 45 | flags = 0; 46 | if (JS_ToBool(ctx, argv[3])) 47 | flags |= JS_READ_OBJ_REFERENCE; 48 | obj = JS_ReadObject(ctx, buf + pos, len, flags); 49 | return obj; 50 | } 51 | 52 | static JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val, 53 | int argc, JSValueConst *argv) 54 | { 55 | size_t len; 56 | uint8_t *buf; 57 | JSValue array; 58 | int flags; 59 | 60 | flags = 0; 61 | if (JS_ToBool(ctx, argv[1])) 62 | flags |= JS_WRITE_OBJ_REFERENCE; 63 | buf = JS_WriteObject(ctx, &len, argv[0], flags); 64 | if (!buf) 65 | return JS_EXCEPTION; 66 | array = JS_NewArrayBufferCopy(ctx, buf, len); 67 | js_free(ctx, buf); 68 | return array; 69 | } 70 | 71 | static const JSCFunctionListEntry js_bjson_funcs[] = { 72 | JS_CFUNC_DEF("read", 4, js_bjson_read ), 73 | JS_CFUNC_DEF("write", 2, js_bjson_write ), 74 | }; 75 | 76 | static int js_bjson_init(JSContext *ctx, JSModuleDef *m) 77 | { 78 | return JS_SetModuleExportList(ctx, m, js_bjson_funcs, 79 | countof(js_bjson_funcs)); 80 | } 81 | 82 | #ifdef JS_SHARED_LIBRARY 83 | #define JS_INIT_MODULE js_init_module 84 | #else 85 | #define JS_INIT_MODULE js_init_module_bjson 86 | #endif 87 | 88 | JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) 89 | { 90 | JSModuleDef *m; 91 | m = JS_NewCModule(ctx, module_name, js_bjson_init); 92 | if (!m) 93 | return NULL; 94 | JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs)); 95 | return m; 96 | } 97 | -------------------------------------------------------------------------------- /src/utils/list.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Linux klist like system 3 | * 4 | * Copyright (c) 2016-2017 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #ifndef LIST_H 25 | #define LIST_H 26 | 27 | #ifndef NULL 28 | #include 29 | #endif 30 | 31 | struct list_head { 32 | struct list_head *prev; 33 | struct list_head *next; 34 | }; 35 | 36 | #define LIST_HEAD_INIT(el) { &(el), &(el) } 37 | 38 | /* return the pointer of type 'type *' containing 'el' as field 'member' */ 39 | #define list_entry(el, type, member) \ 40 | ((type *)((uint8_t *)(el) - offsetof(type, member))) 41 | 42 | static inline void init_list_head(struct list_head *head) 43 | { 44 | head->prev = head; 45 | head->next = head; 46 | } 47 | 48 | /* insert 'el' between 'prev' and 'next' */ 49 | static inline void __list_add(struct list_head *el, 50 | struct list_head *prev, struct list_head *next) 51 | { 52 | prev->next = el; 53 | el->prev = prev; 54 | el->next = next; 55 | next->prev = el; 56 | } 57 | 58 | /* add 'el' at the head of the list 'head' (= after element head) */ 59 | static inline void list_add(struct list_head *el, struct list_head *head) 60 | { 61 | __list_add(el, head, head->next); 62 | } 63 | 64 | /* add 'el' at the end of the list 'head' (= before element head) */ 65 | static inline void list_add_tail(struct list_head *el, struct list_head *head) 66 | { 67 | __list_add(el, head->prev, head); 68 | } 69 | 70 | static inline void list_del(struct list_head *el) 71 | { 72 | struct list_head *prev, *next; 73 | prev = el->prev; 74 | next = el->next; 75 | prev->next = next; 76 | next->prev = prev; 77 | el->prev = NULL; /* fail safe */ 78 | el->next = NULL; /* fail safe */ 79 | } 80 | 81 | static inline int list_empty(struct list_head *el) 82 | { 83 | return el->next == el; 84 | } 85 | 86 | #define list_for_each(el, head) \ 87 | for(el = (head)->next; el != (head); el = el->next) 88 | 89 | #define list_for_each_safe(el, el1, head) \ 90 | for(el = (head)->next, el1 = el->next; el != (head); \ 91 | el = el1, el1 = el->next) 92 | 93 | #define list_for_each_prev(el, head) \ 94 | for(el = (head)->prev; el != (head); el = el->prev) 95 | 96 | #define list_for_each_prev_safe(el, el1, head) \ 97 | for(el = (head)->prev, el1 = el->prev; el != (head); \ 98 | el = el1, el1 = el->prev) 99 | 100 | #endif /* LIST_H */ 101 | -------------------------------------------------------------------------------- /Changelog: -------------------------------------------------------------------------------- 1 | 2020-07-05: 2 | 3 | - modified JS_GetPrototype() to return a live value 4 | - REPL: support unicode characters larger than 16 bits 5 | - added os.Worker 6 | - improved object serialization 7 | - added std.parseExtJSON 8 | - misc bug fixes 9 | 10 | 2020-04-12: 11 | 12 | - added cross realm support 13 | - added AggregateError and Promise.any 14 | - added env, uid and gid options in os.exec() 15 | - misc bug fixes 16 | 17 | 2020-03-16: 18 | 19 | - reworked error handling in std and os libraries: suppressed I/O 20 | exceptions in std FILE functions and return a positive errno value 21 | when it is explicit 22 | - output exception messages to stderr 23 | - added std.loadFile(), std.strerror(), std.FILE.prototype.tello() 24 | - added JS_GetRuntimeOpaque(), JS_SetRuntimeOpaque(), JS_NewUint32() 25 | - updated to Unicode 13.0.0 26 | - misc bug fixes 27 | 28 | 2020-01-19: 29 | 30 | - keep CONFIG_BIGNUM in the makefile 31 | - added os.chdir() 32 | - qjs: added -I option 33 | - more memory checks in the bignum operations 34 | - modified operator overloading semantics to be closer to the TC39 35 | proposal 36 | - suppressed "use bigint" mode. Simplified "use math" mode 37 | - BigDecimal: changed suffix from 'd' to 'm' 38 | - misc bug fixes 39 | 40 | 2020-01-05: 41 | 42 | - always compile the bignum code. Added '--bignum' option to qjs. 43 | - added BigDecimal 44 | - added String.prototype.replaceAll 45 | - misc bug fixes 46 | 47 | 2019-12-21: 48 | 49 | - added nullish coalescing operator (ES2020) 50 | - added optional chaining (ES2020) 51 | - removed recursions in garbage collector 52 | - test stack overflow in the parser 53 | - improved backtrace logic 54 | - added JS_SetHostPromiseRejectionTracker() 55 | - allow exotic constructors 56 | - improved c++ compatibility 57 | - misc bug fixes 58 | 59 | 2019-10-27: 60 | 61 | - added example of C class in a module (examples/test_point.js) 62 | - added JS_GetTypedArrayBuffer() 63 | - misc bug fixes 64 | 65 | 2019-09-18: 66 | 67 | - added os.exec and other system calls 68 | - exported JS_ValueToAtom() 69 | - qjsc: added 'qjsc_' prefix to the generated C identifiers 70 | - added cross-compilation support 71 | - misc bug fixes 72 | 73 | 2019-09-01: 74 | 75 | - added globalThis 76 | - documented JS_EVAL_FLAG_COMPILE_ONLY 77 | - added import.meta.url and import.meta.main 78 | - added 'debugger' statement 79 | - misc bug fixes 80 | 81 | 2019-08-18: 82 | 83 | - added os.realpath, os.getcwd, os.mkdir, os.stat, os.lstat, 84 | os.readlink, os.readdir, os.utimes, std.popen 85 | - module autodetection 86 | - added import.meta 87 | - misc bug fixes 88 | 89 | 2019-08-10: 90 | 91 | - added public class fields and private class fields, methods and 92 | accessors (TC39 proposal) 93 | - changed JS_ToCStringLen() prototype 94 | - qjsc: handle '-' in module names and modules with the same filename 95 | - added std.urlGet 96 | - exported JS_GetOwnPropertyNames() and JS_GetOwnProperty() 97 | - exported some bigint C functions 98 | - added support for eshost in run-test262 99 | - misc bug fixes 100 | 101 | 2019-07-28: 102 | 103 | - added dynamic import 104 | - added Promise.allSettled 105 | - added String.prototype.matchAll 106 | - added Object.fromEntries 107 | - reduced number of ticks in await 108 | - added BigInt support in Atomics 109 | - exported JS_NewPromiseCapability() 110 | - misc async function and async generator fixes 111 | - enabled hashbang support by default 112 | 113 | 2019-07-21: 114 | 115 | - updated test262 tests 116 | - updated to Unicode version 12.1.0 117 | - fixed missing Date object in qjsc 118 | - fixed multi-context creation 119 | - misc ES2020 related fixes 120 | - simplified power and division operators in bignum extension 121 | - fixed several crash conditions 122 | 123 | 2019-07-09: 124 | 125 | - first public release 126 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Misc: 2 | - use realpath in module name normalizer and put it in quickjs-libc 3 | - use custom printf to avoid C library compatibility issues 4 | - rename CONFIG_ALL_UNICODE, CONFIG_BIGNUM, CONFIG_ATOMICS, CONFIG_CHECK_JSVALUE ? 5 | - unify coding style and naming conventions 6 | - use names from the ECMA spec in library implementation 7 | - modules: if no ".", use a well known module loading path ? 8 | - use JSHoistedDef only for global variables (JSHoistedDef.var_name != JS_ATOM_NULL) 9 | - add index in JSVarDef and is_arg flag to merge args and vars in JSFunctionDef 10 | - replace most JSVarDef flags with var_type enumeration 11 | - use byte code emitters with typed arguments (for clarity) 12 | - use 2 bytecode DynBufs in JSFunctionDef, one for reading, one for writing 13 | and use the same wrappers in all phases 14 | - use more generic method for line numbers in resolve_variables and resolve_labels 15 | - use custom timezone support to avoid C library compatibility issues 16 | 17 | Memory: 18 | - test border cases for max number of atoms, object properties, string length 19 | - add emergency malloc mode for out of memory exceptions. 20 | - test all DynBuf memory errors 21 | - test all js_realloc memory errors 22 | - bignum: handle memory errors 23 | - use memory pools for objects, etc? 24 | - improve JS_ComputeMemoryUsage() with more info 25 | 26 | Optimizations: 27 | - 64-bit atoms in 64-bit mode ? 28 | - use auto-init properties for more global objects 29 | - reuse stack slots for disjoint scopes, if strip 30 | - optimize `for of` iterator for built-in array objects 31 | - add heuristic to avoid some cycles in closures 32 | - small String (0-2 charcodes) with immediate storage 33 | - perform static string concatenation at compile time 34 | - optimize string concatenation with ropes or miniropes? 35 | - add implicit numeric strings for Uint32 numbers? 36 | - optimize `s += a + b`, `s += a.b` and similar simple expressions 37 | - ensure string canonical representation and optimise comparisons and hashes? 38 | - remove JSObject.first_weak_ref, use bit+context based hashed array for weak references 39 | - optimize function storage with length and name accessors? 40 | - property access optimization on the global object, functions, 41 | prototypes and special non extensible objects. 42 | - create object literals with the correct length by backpatching length argument 43 | - remove redundant set_loc_uninitialized/check_uninitialized opcodes 44 | - peephole optim: push_atom_value, to_propkey -> push_atom_value 45 | - peephole optim: put_loc x, get_loc_check x -> set_loc x 46 | - comparative performance benchmark 47 | - use variable name when throwing uninitialized exception if available 48 | - convert slow array to fast array when all properties != length are numeric 49 | - optimize destructuring assignments for global and local variables 50 | - implement some form of tail-call-optimization 51 | - optimize OP_apply 52 | - optimize f(...b) 53 | 54 | Extensions: 55 | - support more features in [features] section 56 | - add built-in preprocessor in compiler, get rid of jscompress 57 | handle #if, #ifdef, #line, limited support for #define 58 | - get rid of __loadScript, use more common name 59 | - BSD sockets 60 | 61 | REPL: 62 | - debugger 63 | - readline: support MS Windows terminal 64 | - readline: handle dynamic terminal resizing 65 | - readline: handle double width unicode characters 66 | - multiline editing 67 | - runtime object and function inspectors 68 | - interactive object browser 69 | - use more generic approach to display evaluation results 70 | - improve directive handling: dispatch, colorize, completion... 71 | - save history 72 | - close all predefined methods in repl.js and jscalc.js 73 | 74 | Test262o: 0/11262 errors, 463 excluded 75 | Test262o commit: 7da91bceb9ce7613f87db47ddd1292a2dda58b42 (es5-tests branch) 76 | 77 | Test262: 30/71095 errors, 870 excluded, 549 skipped 78 | Test262 commit: 281eb10b2844929a7c0ac04527f5b42ce56509fd 79 | -------------------------------------------------------------------------------- /src/utils/libunicode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Unicode utilities 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #ifndef LIBUNICODE_H 25 | #define LIBUNICODE_H 26 | 27 | #include 28 | 29 | #define LRE_BOOL int /* for documentation purposes */ 30 | 31 | /* define it to include all the unicode tables (40KB larger) */ 32 | #define CONFIG_ALL_UNICODE 33 | 34 | #define LRE_CC_RES_LEN_MAX 3 35 | 36 | typedef enum { 37 | UNICODE_NFC, 38 | UNICODE_NFD, 39 | UNICODE_NFKC, 40 | UNICODE_NFKD, 41 | } UnicodeNormalizationEnum; 42 | 43 | int lre_case_conv(uint32_t *res, uint32_t c, int conv_type); 44 | LRE_BOOL lre_is_cased(uint32_t c); 45 | LRE_BOOL lre_is_case_ignorable(uint32_t c); 46 | 47 | /* char ranges */ 48 | 49 | typedef struct { 50 | int len; /* in points, always even */ 51 | int size; 52 | uint32_t *points; /* points sorted by increasing value */ 53 | void *mem_opaque; 54 | void *(*realloc_func)(void *opaque, void *ptr, size_t size); 55 | } CharRange; 56 | 57 | typedef enum { 58 | CR_OP_UNION, 59 | CR_OP_INTER, 60 | CR_OP_XOR, 61 | } CharRangeOpEnum; 62 | 63 | void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); 64 | void cr_free(CharRange *cr); 65 | int cr_realloc(CharRange *cr, int size); 66 | int cr_copy(CharRange *cr, const CharRange *cr1); 67 | 68 | static inline int cr_add_point(CharRange *cr, uint32_t v) 69 | { 70 | if (cr->len >= cr->size) { 71 | if (cr_realloc(cr, cr->len + 1)) 72 | return -1; 73 | } 74 | cr->points[cr->len++] = v; 75 | return 0; 76 | } 77 | 78 | static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2) 79 | { 80 | if ((cr->len + 2) > cr->size) { 81 | if (cr_realloc(cr, cr->len + 2)) 82 | return -1; 83 | } 84 | cr->points[cr->len++] = c1; 85 | cr->points[cr->len++] = c2; 86 | return 0; 87 | } 88 | 89 | int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len); 90 | 91 | static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2) 92 | { 93 | uint32_t b_pt[2]; 94 | b_pt[0] = c1; 95 | b_pt[1] = c2 + 1; 96 | return cr_union1(cr, b_pt, 2); 97 | } 98 | 99 | int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, 100 | const uint32_t *b_pt, int b_len, int op); 101 | 102 | int cr_invert(CharRange *cr); 103 | 104 | #ifdef CONFIG_ALL_UNICODE 105 | 106 | LRE_BOOL lre_is_id_start(uint32_t c); 107 | LRE_BOOL lre_is_id_continue(uint32_t c); 108 | 109 | int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, 110 | UnicodeNormalizationEnum n_type, 111 | void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); 112 | 113 | /* Unicode character range functions */ 114 | 115 | int unicode_script(CharRange *cr, 116 | const char *script_name, LRE_BOOL is_ext); 117 | int unicode_general_category(CharRange *cr, const char *gc_name); 118 | int unicode_prop(CharRange *cr, const char *prop_name); 119 | 120 | #endif /* CONFIG_ALL_UNICODE */ 121 | 122 | #undef LRE_BOOL 123 | 124 | #endif /* LIBUNICODE_H */ 125 | -------------------------------------------------------------------------------- /test262_errors.txt: -------------------------------------------------------------------------------- 1 | test262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: Test262Error: Expected a ReferenceError but got a ReferenceError 2 | test262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: strict mode: Test262Error: Expected a ReferenceError but got a ReferenceError 3 | test262/test/built-ins/Proxy/ownKeys/trap-is-undefined-target-is-proxy.js:29: Test262Error: Expected [0, length, foo, Symbol()] and [Symbol(), length, foo, 0] to have the same contents. 4 | test262/test/built-ins/Proxy/ownKeys/trap-is-undefined-target-is-proxy.js:29: strict mode: Test262Error: Expected [0, length, foo, Symbol()] and [Symbol(), length, foo, 0] to have the same contents. 5 | test262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: SyntaxError: invalid group name 6 | test262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: strict mode: SyntaxError: invalid group name 7 | test262/test/language/expressions/arrow-function/eval-var-scope-syntax-err.js:47: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 8 | test262/test/language/expressions/async-arrow-function/eval-var-scope-syntax-err.js:49: TypeError: $DONE() not called 9 | test262/test/language/expressions/async-function/named-eval-var-scope-syntax-err.js:33: TypeError: $DONE() not called 10 | test262/test/language/expressions/async-function/nameless-eval-var-scope-syntax-err.js:33: TypeError: $DONE() not called 11 | test262/test/language/expressions/async-generator/eval-var-scope-syntax-err.js:28: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 12 | test262/test/language/expressions/async-generator/named-eval-var-scope-syntax-err.js:28: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 13 | test262/test/language/expressions/class/elements/grammar-private-field-optional-chaining.js:26: SyntaxError: expecting field name 14 | test262/test/language/expressions/class/elements/grammar-private-field-optional-chaining.js:26: strict mode: SyntaxError: expecting field name 15 | test262/test/language/expressions/dynamic-import/usage-from-eval.js:26: TypeError: $DONE() not called 16 | test262/test/language/expressions/dynamic-import/usage-from-eval.js:26: strict mode: TypeError: $DONE() not called 17 | test262/test/language/expressions/function/eval-var-scope-syntax-err.js:48: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 18 | test262/test/language/expressions/generators/eval-var-scope-syntax-err.js:49: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 19 | test262/test/language/expressions/object/method-definition/async-gen-meth-eval-var-scope-syntax-err.js:32: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 20 | test262/test/language/expressions/object/method-definition/async-meth-eval-var-scope-syntax-err.js:36: TypeError: $DONE() not called 21 | test262/test/language/expressions/object/method-definition/gen-meth-eval-var-scope-syntax-err.js:54: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 22 | test262/test/language/expressions/object/method-definition/meth-eval-var-scope-syntax-err.js:50: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 23 | test262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:21: TypeError: cannot read property 'c' of undefined 24 | test262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:15: strict mode: TypeError: cannot read property '_b' of undefined 25 | test262/test/language/statements/async-function/eval-var-scope-syntax-err.js:33: TypeError: $DONE() not called 26 | test262/test/language/statements/async-generator/eval-var-scope-syntax-err.js:28: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 27 | test262/test/language/statements/class/elements/grammar-private-field-optional-chaining.js:26: SyntaxError: expecting field name 28 | test262/test/language/statements/class/elements/grammar-private-field-optional-chaining.js:26: strict mode: SyntaxError: expecting field name 29 | test262/test/language/statements/function/eval-var-scope-syntax-err.js:49: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 30 | test262/test/language/statements/generators/eval-var-scope-syntax-err.js:49: Test262Error: Expected a SyntaxError to be thrown but no exception was thrown at all 31 | -------------------------------------------------------------------------------- /test262.conf: -------------------------------------------------------------------------------- 1 | [config] 2 | # general settings for test262 ES6 version 3 | 4 | # framework style: old, new 5 | style=new 6 | 7 | # handle tests tagged as [noStrict]: yes, no, skip 8 | nostrict=yes 9 | 10 | # handle tests tagged as [strictOnly]: yes, no, skip 11 | strict=yes 12 | 13 | # test mode: default, default-nostrict, default-strict, strict, nostrict, both, all 14 | mode=default 15 | 16 | # handle tests flagged as [async]: yes, no, skip 17 | # for these, load 'harness/doneprintHandle.js' prior to test 18 | # and expect `print('Test262:AsyncTestComplete')` to be called for 19 | # successful termination 20 | async=yes 21 | 22 | # handle tests flagged as [module]: yes, no, skip 23 | module=yes 24 | 25 | # output error messages: yes, no 26 | verbose=yes 27 | 28 | # load harness files from this directory 29 | harnessdir=test262/harness 30 | 31 | # names of harness include files to skip 32 | #harnessexclude= 33 | 34 | # name of the error file for known errors 35 | errorfile=test262_errors.txt 36 | 37 | # exclude tests enumerated in this file (see also [exclude] section) 38 | #excludefile=test262_exclude.txt 39 | 40 | # report test results to this file 41 | reportfile=test262_report.txt 42 | 43 | # enumerate tests from this directory 44 | testdir=test262/test 45 | 46 | [features] 47 | # Standard language features and proposed extensions 48 | # list the features that are included 49 | # skipped features are tagged as such to avoid warnings 50 | 51 | AggregateError 52 | Array.prototype.flat 53 | Array.prototype.flatMap 54 | Array.prototype.flatten 55 | Array.prototype.values 56 | ArrayBuffer 57 | arrow-function 58 | async-functions 59 | async-iteration 60 | Atomics 61 | Atomics.waitAsync=skip 62 | BigInt 63 | caller 64 | class 65 | class-fields-private 66 | class-fields-public 67 | class-methods-private 68 | class-static-fields-public 69 | class-static-fields-private 70 | class-static-methods-private 71 | coalesce-expression 72 | computed-property-names 73 | const 74 | cross-realm 75 | DataView 76 | DataView.prototype.getFloat32 77 | DataView.prototype.getFloat64 78 | DataView.prototype.getInt16 79 | DataView.prototype.getInt32 80 | DataView.prototype.getInt8 81 | DataView.prototype.getUint16 82 | DataView.prototype.getUint32 83 | DataView.prototype.setUint8 84 | default-arg 85 | default-parameters 86 | destructuring-assignment 87 | destructuring-binding 88 | dynamic-import 89 | export-star-as-namespace-from-module 90 | FinalizationGroup=skip 91 | FinalizationRegistry=skip 92 | Float32Array 93 | Float64Array 94 | for-in-order 95 | for-of 96 | generators 97 | globalThis 98 | hashbang 99 | host-gc-required=skip 100 | import.meta 101 | Int32Array 102 | Int8Array 103 | IsHTMLDDA=skip 104 | json-superset 105 | let 106 | logical-assignment-operators=skip 107 | Map 108 | new.target 109 | numeric-separator-literal 110 | object-rest 111 | object-spread 112 | Object.fromEntries 113 | Object.is 114 | optional-catch-binding 115 | optional-chaining 116 | Promise.allSettled 117 | Promise.any 118 | Promise.prototype.finally 119 | Proxy 120 | proxy-missing-checks 121 | Reflect 122 | Reflect.construct 123 | Reflect.set 124 | Reflect.setPrototypeOf 125 | regexp-dotall 126 | regexp-lookbehind 127 | regexp-match-indices=skip 128 | regexp-named-groups 129 | regexp-unicode-property-escapes 130 | rest-parameters 131 | Set 132 | SharedArrayBuffer 133 | string-trimming 134 | String.fromCodePoint 135 | String.prototype.endsWith 136 | String.prototype.includes 137 | String.prototype.matchAll 138 | String.prototype.replaceAll 139 | String.prototype.trimEnd 140 | String.prototype.trimStart 141 | super 142 | Symbol 143 | Symbol.asyncIterator 144 | Symbol.hasInstance 145 | Symbol.isConcatSpreadable 146 | Symbol.iterator 147 | Symbol.match 148 | Symbol.matchAll 149 | Symbol.prototype.description 150 | Symbol.replace 151 | Symbol.search 152 | Symbol.species 153 | Symbol.split 154 | Symbol.toPrimitive 155 | Symbol.toStringTag 156 | Symbol.unscopables 157 | tail-call-optimization=skip 158 | template 159 | top-level-await=skip 160 | TypedArray 161 | u180e 162 | Uint16Array 163 | Uint8Array 164 | Uint8ClampedArray 165 | WeakMap 166 | WeakRef=skip 167 | WeakSet 168 | well-formed-json-stringify 169 | 170 | [exclude] 171 | # list excluded tests and directories here 172 | 173 | # intl not supported 174 | test262/test/intl402/ 175 | 176 | # incompatible with the "caller" feature 177 | test262/test/built-ins/Function/prototype/restricted-property-caller.js 178 | test262/test/built-ins/Function/prototype/restricted-property-arguments.js 179 | test262/test/built-ins/ThrowTypeError/unique-per-realm-function-proto.js 180 | 181 | # slow tests 182 | #test262/test/built-ins/RegExp/CharacterClassEscapes/ 183 | #test262/test/built-ins/RegExp/property-escapes/ 184 | 185 | # invalid tests 186 | test262/test/language/module-code/verify-dfs.js 187 | 188 | [tests] 189 | # list test files or use config.testdir 190 | -------------------------------------------------------------------------------- /tests/test_closure.js: -------------------------------------------------------------------------------- 1 | function assert(actual, expected, message) { 2 | if (arguments.length == 1) 3 | expected = true; 4 | 5 | if (actual === expected) 6 | return; 7 | 8 | if (actual !== null && expected !== null 9 | && typeof actual == 'object' && typeof expected == 'object' 10 | && actual.toString() === expected.toString()) 11 | return; 12 | 13 | throw Error("assertion failed: got |" + actual + "|" + 14 | ", expected |" + expected + "|" + 15 | (message ? " (" + message + ")" : "")); 16 | } 17 | 18 | // load more elaborate version of assert if available 19 | try { __loadScript("test_assert.js"); } catch(e) {} 20 | 21 | /*----------------*/ 22 | 23 | var log_str = ""; 24 | 25 | function log(str) 26 | { 27 | log_str += str + ","; 28 | } 29 | 30 | function f(a, b, c) 31 | { 32 | var x = 10; 33 | log("a="+a); 34 | function g(d) { 35 | function h() { 36 | log("d=" + d); 37 | log("x=" + x); 38 | } 39 | log("b=" + b); 40 | log("c=" + c); 41 | h(); 42 | } 43 | g(4); 44 | return g; 45 | } 46 | 47 | var g1 = f(1, 2, 3); 48 | g1(5); 49 | 50 | assert(log_str, "a=1,b=2,c=3,d=4,x=10,b=2,c=3,d=5,x=10,", "closure1"); 51 | 52 | function test_closure1() 53 | { 54 | function f2() 55 | { 56 | var val = 1; 57 | 58 | function set(a) { 59 | val = a; 60 | } 61 | function get(a) { 62 | return val; 63 | } 64 | return { "set": set, "get": get }; 65 | } 66 | 67 | var obj = f2(); 68 | obj.set(10); 69 | var r; 70 | r = obj.get(); 71 | assert(r, 10, "closure2"); 72 | } 73 | 74 | function test_closure2() 75 | { 76 | var expr_func = function myfunc1(n) { 77 | function myfunc2(n) { 78 | return myfunc1(n - 1); 79 | } 80 | if (n == 0) 81 | return 0; 82 | else 83 | return myfunc2(n); 84 | }; 85 | var r; 86 | r = expr_func(1); 87 | assert(r, 0, "expr_func"); 88 | } 89 | 90 | function test_closure3() 91 | { 92 | function fib(n) 93 | { 94 | if (n <= 0) 95 | return 0; 96 | else if (n == 1) 97 | return 1; 98 | else 99 | return fib(n - 1) + fib(n - 2); 100 | } 101 | 102 | var fib_func = function fib1(n) 103 | { 104 | if (n <= 0) 105 | return 0; 106 | else if (n == 1) 107 | return 1; 108 | else 109 | return fib1(n - 1) + fib1(n - 2); 110 | }; 111 | 112 | assert(fib(6), 8, "fib"); 113 | assert(fib_func(6), 8, "fib_func"); 114 | } 115 | 116 | function test_arrow_function() 117 | { 118 | "use strict"; 119 | 120 | function f1() { 121 | return (() => arguments)(); 122 | } 123 | function f2() { 124 | return (() => this)(); 125 | } 126 | function f3() { 127 | return (() => eval("this"))(); 128 | } 129 | function f4() { 130 | return (() => eval("new.target"))(); 131 | } 132 | var a; 133 | 134 | a = f1(1, 2); 135 | assert(a.length, 2); 136 | assert(a[0] === 1 && a[1] === 2); 137 | 138 | assert(f2.call("this_val") === "this_val"); 139 | assert(f3.call("this_val") === "this_val"); 140 | assert(new f4() === f4); 141 | 142 | var o1 = { f() { return this; } }; 143 | var o2 = { f() { 144 | return (() => eval("super.f()"))(); 145 | } }; 146 | o2.__proto__ = o1; 147 | 148 | assert(o2.f() === o2); 149 | } 150 | 151 | function test_with() 152 | { 153 | var o1 = { x: "o1", y: "o1" }; 154 | var x = "local"; 155 | eval('var z="var_obj";'); 156 | assert(z === "var_obj"); 157 | with (o1) { 158 | assert(x === "o1"); 159 | assert(eval("x") === "o1"); 160 | var f = function () { 161 | o2 = { x: "o2" }; 162 | with (o2) { 163 | assert(x === "o2"); 164 | assert(y === "o1"); 165 | assert(z === "var_obj"); 166 | assert(eval("x") === "o2"); 167 | assert(eval("y") === "o1"); 168 | assert(eval("z") === "var_obj"); 169 | assert(eval('eval("x")') === "o2"); 170 | } 171 | }; 172 | f(); 173 | } 174 | } 175 | 176 | function test_eval_closure() 177 | { 178 | var tab; 179 | 180 | tab = []; 181 | for(let i = 0; i < 3; i++) { 182 | eval("tab.push(function g1() { return i; })"); 183 | } 184 | for(let i = 0; i < 3; i++) { 185 | assert(tab[i]() === i); 186 | } 187 | 188 | tab = []; 189 | for(let i = 0; i < 3; i++) { 190 | let f = function f() { 191 | eval("tab.push(function g2() { return i; })"); 192 | }; 193 | f(); 194 | } 195 | for(let i = 0; i < 3; i++) { 196 | assert(tab[i]() === i); 197 | } 198 | } 199 | 200 | function test_eval_const() 201 | { 202 | const a = 1; 203 | var success = false; 204 | var f = function () { 205 | eval("a = 1"); 206 | }; 207 | try { 208 | f(); 209 | } catch(e) { 210 | success = (e instanceof TypeError); 211 | } 212 | assert(success); 213 | } 214 | 215 | test_closure1(); 216 | test_closure2(); 217 | test_closure3(); 218 | test_arrow_function(); 219 | test_with(); 220 | test_eval_closure(); 221 | test_eval_const(); 222 | -------------------------------------------------------------------------------- /examples/point.c: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS: Example of C module with a class 3 | * 4 | * Copyright (c) 2019 Fabrice Bellard 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | #include "../src/quickjs.h" 25 | #include 26 | 27 | #define countof(x) (sizeof(x) / sizeof((x)[0])) 28 | 29 | /* Point Class */ 30 | 31 | typedef struct { 32 | int x; 33 | int y; 34 | } JSPointData; 35 | 36 | static JSClassID js_point_class_id; 37 | 38 | static void js_point_finalizer(JSRuntime *rt, JSValue val) 39 | { 40 | JSPointData *s = JS_GetOpaque(val, js_point_class_id); 41 | /* Note: 's' can be NULL in case JS_SetOpaque() was not called */ 42 | js_free_rt(rt, s); 43 | } 44 | 45 | static JSValue js_point_ctor(JSContext *ctx, 46 | JSValueConst new_target, 47 | int argc, JSValueConst *argv) 48 | { 49 | JSPointData *s; 50 | JSValue obj = JS_UNDEFINED; 51 | JSValue proto; 52 | 53 | s = js_mallocz(ctx, sizeof(*s)); 54 | if (!s) 55 | return JS_EXCEPTION; 56 | if (JS_ToInt32(ctx, &s->x, argv[0])) 57 | goto fail; 58 | if (JS_ToInt32(ctx, &s->y, argv[1])) 59 | goto fail; 60 | /* using new_target to get the prototype is necessary when the 61 | class is extended. */ 62 | proto = JS_GetPropertyStr(ctx, new_target, "prototype"); 63 | if (JS_IsException(proto)) 64 | goto fail; 65 | obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id); 66 | JS_FreeValue(ctx, proto); 67 | if (JS_IsException(obj)) 68 | goto fail; 69 | JS_SetOpaque(obj, s); 70 | return obj; 71 | fail: 72 | js_free(ctx, s); 73 | JS_FreeValue(ctx, obj); 74 | return JS_EXCEPTION; 75 | } 76 | 77 | static JSValue js_point_get_xy(JSContext *ctx, JSValueConst this_val, int magic) 78 | { 79 | JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); 80 | if (!s) 81 | return JS_EXCEPTION; 82 | if (magic == 0) 83 | return JS_NewInt32(ctx, s->x); 84 | else 85 | return JS_NewInt32(ctx, s->y); 86 | } 87 | 88 | static JSValue js_point_set_xy(JSContext *ctx, JSValueConst this_val, JSValue val, int magic) 89 | { 90 | JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); 91 | int v; 92 | if (!s) 93 | return JS_EXCEPTION; 94 | if (JS_ToInt32(ctx, &v, val)) 95 | return JS_EXCEPTION; 96 | if (magic == 0) 97 | s->x = v; 98 | else 99 | s->y = v; 100 | return JS_UNDEFINED; 101 | } 102 | 103 | static JSValue js_point_norm(JSContext *ctx, JSValueConst this_val, 104 | int argc, JSValueConst *argv) 105 | { 106 | JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id); 107 | if (!s) 108 | return JS_EXCEPTION; 109 | return JS_NewFloat64(ctx, sqrt((double)s->x * s->x + (double)s->y * s->y)); 110 | } 111 | 112 | static JSClassDef js_point_class = { 113 | "Point", 114 | .finalizer = js_point_finalizer, 115 | }; 116 | 117 | static const JSCFunctionListEntry js_point_proto_funcs[] = { 118 | JS_CGETSET_MAGIC_DEF("x", js_point_get_xy, js_point_set_xy, 0), 119 | JS_CGETSET_MAGIC_DEF("y", js_point_get_xy, js_point_set_xy, 1), 120 | JS_CFUNC_DEF("norm", 0, js_point_norm), 121 | }; 122 | 123 | static int js_point_init(JSContext *ctx, JSModuleDef *m) 124 | { 125 | JSValue point_proto, point_class; 126 | 127 | /* create the Point class */ 128 | JS_NewClassID(&js_point_class_id); 129 | JS_NewClass(JS_GetRuntime(ctx), js_point_class_id, &js_point_class); 130 | 131 | point_proto = JS_NewObject(ctx); 132 | JS_SetPropertyFunctionList(ctx, point_proto, js_point_proto_funcs, countof(js_point_proto_funcs)); 133 | 134 | point_class = JS_NewCFunction2(ctx, js_point_ctor, "Point", 2, JS_CFUNC_constructor, 0); 135 | /* set proto.constructor and ctor.prototype */ 136 | JS_SetConstructor(ctx, point_class, point_proto); 137 | JS_SetClassProto(ctx, js_point_class_id, point_proto); 138 | 139 | JS_SetModuleExport(ctx, m, "Point", point_class); 140 | return 0; 141 | } 142 | 143 | JSModuleDef *js_init_module(JSContext *ctx, const char *module_name) 144 | { 145 | JSModuleDef *m; 146 | m = JS_NewCModule(ctx, module_name, js_point_init); 147 | if (!m) 148 | return NULL; 149 | JS_AddModuleExport(ctx, m, "Point"); 150 | return m; 151 | } 152 | -------------------------------------------------------------------------------- /tests/test_op_overloading.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function assert(actual, expected, message) { 4 | if (arguments.length == 1) 5 | expected = true; 6 | 7 | if (actual === expected) 8 | return; 9 | 10 | if (actual !== null && expected !== null 11 | && typeof actual == 'object' && typeof expected == 'object' 12 | && actual.toString() === expected.toString()) 13 | return; 14 | 15 | throw Error("assertion failed: got |" + actual + "|" + 16 | ", expected |" + expected + "|" + 17 | (message ? " (" + message + ")" : "")); 18 | } 19 | 20 | /* operators overloading with Operators.create() */ 21 | function test_operators_create() { 22 | class Vec2 23 | { 24 | constructor(x, y) { 25 | this.x = x; 26 | this.y = y; 27 | } 28 | static mul_scalar(p1, a) { 29 | var r = new Vec2(); 30 | r.x = p1.x * a; 31 | r.y = p1.y * a; 32 | return r; 33 | } 34 | toString() { 35 | return "Vec2(" + this.x + "," + this.y + ")"; 36 | } 37 | } 38 | 39 | Vec2.prototype[Symbol.operatorSet] = Operators.create( 40 | { 41 | "+"(p1, p2) { 42 | var r = new Vec2(); 43 | r.x = p1.x + p2.x; 44 | r.y = p1.y + p2.y; 45 | return r; 46 | }, 47 | "-"(p1, p2) { 48 | var r = new Vec2(); 49 | r.x = p1.x - p2.x; 50 | r.y = p1.y - p2.y; 51 | return r; 52 | }, 53 | "=="(a, b) { 54 | return a.x == b.x && a.y == b.y; 55 | }, 56 | "<"(a, b) { 57 | var r; 58 | /* lexicographic order */ 59 | if (a.x == b.x) 60 | r = (a.y < b.y); 61 | else 62 | r = (a.x < b.x); 63 | return r; 64 | }, 65 | "++"(a) { 66 | var r = new Vec2(); 67 | r.x = a.x + 1; 68 | r.y = a.y + 1; 69 | return r; 70 | } 71 | }, 72 | { 73 | left: Number, 74 | "*"(a, b) { 75 | return Vec2.mul_scalar(b, a); 76 | } 77 | }, 78 | { 79 | right: Number, 80 | "*"(a, b) { 81 | return Vec2.mul_scalar(a, b); 82 | } 83 | }); 84 | 85 | var a = new Vec2(1, 2); 86 | var b = new Vec2(3, 4); 87 | var r; 88 | 89 | r = a * 2 + 3 * b; 90 | assert(r.x === 11 && r.y === 16); 91 | assert(a == a, true); 92 | assert(a == b, false); 93 | assert(a != a, false); 94 | assert(a < b, true); 95 | assert(a <= b, true); 96 | assert(b < a, false); 97 | assert(b <= a, false); 98 | assert(a <= a, true); 99 | assert(a >= a, true); 100 | a++; 101 | assert(a.x === 2 && a.y === 3); 102 | r = ++a; 103 | assert(a.x === 3 && a.y === 4); 104 | assert(r === a); 105 | } 106 | 107 | /* operators overloading thru inheritance */ 108 | function test_operators() 109 | { 110 | var Vec2; 111 | 112 | function mul_scalar(p1, a) { 113 | var r = new Vec2(); 114 | r.x = p1.x * a; 115 | r.y = p1.y * a; 116 | return r; 117 | } 118 | 119 | var vec2_ops = Operators({ 120 | "+"(p1, p2) { 121 | var r = new Vec2(); 122 | r.x = p1.x + p2.x; 123 | r.y = p1.y + p2.y; 124 | return r; 125 | }, 126 | "-"(p1, p2) { 127 | var r = new Vec2(); 128 | r.x = p1.x - p2.x; 129 | r.y = p1.y - p2.y; 130 | return r; 131 | }, 132 | "=="(a, b) { 133 | return a.x == b.x && a.y == b.y; 134 | }, 135 | "<"(a, b) { 136 | var r; 137 | /* lexicographic order */ 138 | if (a.x == b.x) 139 | r = (a.y < b.y); 140 | else 141 | r = (a.x < b.x); 142 | return r; 143 | }, 144 | "++"(a) { 145 | var r = new Vec2(); 146 | r.x = a.x + 1; 147 | r.y = a.y + 1; 148 | return r; 149 | } 150 | }, 151 | { 152 | left: Number, 153 | "*"(a, b) { 154 | return mul_scalar(b, a); 155 | } 156 | }, 157 | { 158 | right: Number, 159 | "*"(a, b) { 160 | return mul_scalar(a, b); 161 | } 162 | }); 163 | 164 | Vec2 = class Vec2 extends vec2_ops 165 | { 166 | constructor(x, y) { 167 | super(); 168 | this.x = x; 169 | this.y = y; 170 | } 171 | toString() { 172 | return "Vec2(" + this.x + "," + this.y + ")"; 173 | } 174 | } 175 | 176 | var a = new Vec2(1, 2); 177 | var b = new Vec2(3, 4); 178 | var r; 179 | 180 | r = a * 2 + 3 * b; 181 | assert(r.x === 11 && r.y === 16); 182 | assert(a == a, true); 183 | assert(a == b, false); 184 | assert(a != a, false); 185 | assert(a < b, true); 186 | assert(a <= b, true); 187 | assert(b < a, false); 188 | assert(b <= a, false); 189 | assert(a <= a, true); 190 | assert(a >= a, true); 191 | a++; 192 | assert(a.x === 2 && a.y === 3); 193 | r = ++a; 194 | assert(a.x === 3 && a.y === 4); 195 | assert(r === a); 196 | } 197 | 198 | function test_default_op() 199 | { 200 | assert(Object(1) + 2, 3); 201 | assert(Object(1) + true, 2); 202 | assert(-Object(1), -1); 203 | } 204 | 205 | test_operators_create(); 206 | test_operators(); 207 | test_default_op(); 208 | -------------------------------------------------------------------------------- /tests/test_bjson.js: -------------------------------------------------------------------------------- 1 | import * as bjson from "./bjson.so"; 2 | 3 | function assert(actual, expected, message) { 4 | if (arguments.length == 1) 5 | expected = true; 6 | 7 | if (actual === expected) 8 | return; 9 | 10 | if (actual !== null && expected !== null 11 | && typeof actual == 'object' && typeof expected == 'object' 12 | && actual.toString() === expected.toString()) 13 | return; 14 | 15 | throw Error("assertion failed: got |" + actual + "|" + 16 | ", expected |" + expected + "|" + 17 | (message ? " (" + message + ")" : "")); 18 | } 19 | 20 | function toHex(a) 21 | { 22 | var i, s = "", tab, v; 23 | tab = new Uint8Array(a); 24 | for(i = 0; i < tab.length; i++) { 25 | v = tab[i].toString(16); 26 | if (v.length < 2) 27 | v = "0" + v; 28 | if (i !== 0) 29 | s += " "; 30 | s += v; 31 | } 32 | return s; 33 | } 34 | 35 | function isArrayLike(a) 36 | { 37 | return Array.isArray(a) || 38 | (a instanceof Uint8ClampedArray) || 39 | (a instanceof Uint8Array) || 40 | (a instanceof Uint16Array) || 41 | (a instanceof Uint32Array) || 42 | (a instanceof Int8Array) || 43 | (a instanceof Int16Array) || 44 | (a instanceof Int32Array) || 45 | (a instanceof Float32Array) || 46 | (a instanceof Float64Array); 47 | } 48 | 49 | function toStr(a) 50 | { 51 | var s, i, props, prop; 52 | 53 | switch(typeof(a)) { 54 | case "object": 55 | if (a === null) 56 | return "null"; 57 | if (a instanceof Date) { 58 | s = "Date(" + toStr(a.valueOf()) + ")"; 59 | } else if (a instanceof Number) { 60 | s = "Number(" + toStr(a.valueOf()) + ")"; 61 | } else if (a instanceof String) { 62 | s = "String(" + toStr(a.valueOf()) + ")"; 63 | } else if (a instanceof Boolean) { 64 | s = "Boolean(" + toStr(a.valueOf()) + ")"; 65 | } else if (isArrayLike(a)) { 66 | s = "["; 67 | for(i = 0; i < a.length; i++) { 68 | if (i != 0) 69 | s += ","; 70 | s += toStr(a[i]); 71 | } 72 | s += "]"; 73 | } else { 74 | props = Object.keys(a); 75 | s = "{"; 76 | for(i = 0; i < props.length; i++) { 77 | if (i != 0) 78 | s += ","; 79 | prop = props[i]; 80 | s += prop + ":" + toStr(a[prop]); 81 | } 82 | s += "}"; 83 | } 84 | return s; 85 | case "undefined": 86 | return "undefined"; 87 | case "string": 88 | return a.__quote(); 89 | case "number": 90 | case "bigfloat": 91 | if (a == 0 && 1 / a < 0) 92 | return "-0"; 93 | else 94 | return a.toString(); 95 | break; 96 | default: 97 | return a.toString(); 98 | } 99 | } 100 | 101 | function bjson_test(a) 102 | { 103 | var buf, r, a_str, r_str; 104 | a_str = toStr(a); 105 | buf = bjson.write(a); 106 | if (0) { 107 | print(a_str, "->", toHex(buf)); 108 | } 109 | r = bjson.read(buf, 0, buf.byteLength); 110 | r_str = toStr(r); 111 | if (a_str != r_str) { 112 | print(a_str); 113 | print(r_str); 114 | assert(false); 115 | } 116 | } 117 | 118 | /* test multiple references to an object including circular 119 | references */ 120 | function bjson_test_reference() 121 | { 122 | var array, buf, i, n, array_buffer; 123 | n = 16; 124 | array = []; 125 | for(i = 0; i < n; i++) 126 | array[i] = {}; 127 | array_buffer = new ArrayBuffer(n); 128 | for(i = 0; i < n; i++) { 129 | array[i].next = array[(i + 1) % n]; 130 | array[i].idx = i; 131 | array[i].typed_array = new Uint8Array(array_buffer, i, 1); 132 | } 133 | buf = bjson.write(array, true); 134 | 135 | array = bjson.read(buf, 0, buf.byteLength, true); 136 | 137 | /* check the result */ 138 | for(i = 0; i < n; i++) { 139 | assert(array[i].next, array[(i + 1) % n]); 140 | assert(array[i].idx, i); 141 | assert(array[i].typed_array.buffer, array_buffer); 142 | assert(array[i].typed_array.length, 1); 143 | assert(array[i].typed_array.byteOffset, i); 144 | } 145 | } 146 | 147 | function bjson_test_all() 148 | { 149 | var obj; 150 | 151 | bjson_test({x:1, y:2, if:3}); 152 | bjson_test([1, 2, 3]); 153 | bjson_test([1.0, "aa", true, false, undefined, null, NaN, -Infinity, -0.0]); 154 | if (typeof BigInt !== "undefined") { 155 | bjson_test([BigInt("1"), -BigInt("0x123456789"), 156 | BigInt("0x123456789abcdef123456789abcdef")]); 157 | } 158 | if (typeof BigFloat !== "undefined") { 159 | BigFloatEnv.setPrec(function () { 160 | bjson_test([BigFloat("0.1"), BigFloat("-1e30"), BigFloat("0"), 161 | BigFloat("-0"), BigFloat("Infinity"), BigFloat("-Infinity"), 162 | 0.0 / BigFloat("0"), BigFloat.MAX_VALUE, 163 | BigFloat.MIN_VALUE]); 164 | }, 113, 15); 165 | } 166 | if (typeof BigDecimal !== "undefined") { 167 | bjson_test([BigDecimal("0"), 168 | BigDecimal("0.8"), BigDecimal("123321312321321e100"), 169 | BigDecimal("-1233213123213214332333223332e100"), 170 | BigDecimal("1.233e-1000")]); 171 | } 172 | 173 | bjson_test([new Date(1234), new String("abc"), new Number(-12.1), new Boolean(true)]); 174 | 175 | bjson_test(new Int32Array([123123, 222111, -32222])); 176 | bjson_test(new Float64Array([123123, 222111.5])); 177 | 178 | /* tested with a circular reference */ 179 | obj = {}; 180 | obj.x = obj; 181 | try { 182 | bjson.write(obj); 183 | assert(false); 184 | } catch(e) { 185 | assert(e instanceof TypeError); 186 | } 187 | 188 | bjson_test_reference(); 189 | } 190 | 191 | bjson_test_all(); 192 | -------------------------------------------------------------------------------- /tests/test_qjscalc.js: -------------------------------------------------------------------------------- 1 | "use math"; 2 | "use strict"; 3 | 4 | function assert(actual, expected, message) { 5 | if (arguments.length == 1) 6 | expected = true; 7 | 8 | if (actual === expected) 9 | return; 10 | 11 | if (actual !== null && expected !== null 12 | && typeof actual == 'object' && typeof expected == 'object' 13 | && actual.toString() === expected.toString()) 14 | return; 15 | 16 | throw Error("assertion failed: got |" + actual + "|" + 17 | ", expected |" + expected + "|" + 18 | (message ? " (" + message + ")" : "")); 19 | } 20 | 21 | function assertThrows(err, func) 22 | { 23 | var ex; 24 | ex = false; 25 | try { 26 | func(); 27 | } catch(e) { 28 | ex = true; 29 | assert(e instanceof err); 30 | } 31 | assert(ex, true, "exception expected"); 32 | } 33 | 34 | // load more elaborate version of assert if available 35 | try { __loadScript("test_assert.js"); } catch(e) {} 36 | 37 | /*----------------*/ 38 | 39 | function pow(a, n) 40 | { 41 | var r, i; 42 | r = 1; 43 | for(i = 0; i < n; i++) 44 | r *= a; 45 | return r; 46 | } 47 | 48 | function test_integer() 49 | { 50 | var a, r; 51 | a = pow(3, 100); 52 | assert((a - 1) != a); 53 | assert(a == 515377520732011331036461129765621272702107522001); 54 | assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1); 55 | assert(Integer.isInteger(1) === true); 56 | assert(Integer.isInteger(1.0) === false); 57 | 58 | assert(Integer.floorLog2(0) === -1); 59 | assert(Integer.floorLog2(7) === 2); 60 | 61 | r = 1 << 31; 62 | assert(r, 2147483648, "1 << 31 === 2147483648"); 63 | 64 | r = 1 << 32; 65 | assert(r, 4294967296, "1 << 32 === 4294967296"); 66 | 67 | r = (1 << 31) < 0; 68 | assert(r, false, "(1 << 31) < 0 === false"); 69 | 70 | assert(typeof 1 === "number"); 71 | assert(typeof 9007199254740991 === "number"); 72 | assert(typeof 9007199254740992 === "bigint"); 73 | } 74 | 75 | function test_float() 76 | { 77 | assert(typeof 1.0 === "bigfloat"); 78 | assert(1 == 1.0); 79 | assert(1 !== 1.0); 80 | } 81 | 82 | /* jscalc tests */ 83 | 84 | function test_modulo() 85 | { 86 | var i, p, a, b; 87 | 88 | /* Euclidian modulo operator */ 89 | assert((-3) % 2 == 1); 90 | assert(3 % (-2) == 1); 91 | 92 | p = 101; 93 | for(i = 1; i < p; i++) { 94 | a = Integer.invmod(i, p); 95 | assert(a >= 0 && a < p); 96 | assert((i * a) % p == 1); 97 | } 98 | 99 | assert(Integer.isPrime(2^107-1)); 100 | assert(!Integer.isPrime((2^107-1) * (2^89-1))); 101 | a = Integer.factor((2^89-1)*2^3*11*13^2*1009); 102 | assert(a == [ 2,2,2,11,13,13,1009,618970019642690137449562111 ]); 103 | } 104 | 105 | function test_fraction() 106 | { 107 | assert((1/3 + 1).toString(), "4/3") 108 | assert((2/3)^30, 1073741824/205891132094649); 109 | assert(1/3 < 2/3); 110 | assert(1/3 < 1); 111 | assert(1/3 == 1.0/3); 112 | assert(1.0/3 < 2/3); 113 | } 114 | 115 | function test_mod() 116 | { 117 | var a, b, p; 118 | 119 | a = Mod(3, 101); 120 | b = Mod(-1, 101); 121 | assert((a + b) == Mod(2, 101)); 122 | assert(a ^ 100 == Mod(1, 101)); 123 | 124 | p = 2 ^ 607 - 1; /* mersenne prime */ 125 | a = Mod(3, p) ^ (p - 1); 126 | assert(a == Mod(1, p)); 127 | } 128 | 129 | function test_polynomial() 130 | { 131 | var a, b, q, r, t, i; 132 | a = (1 + X) ^ 4; 133 | assert(a == X^4+4*X^3+6*X^2+4*X+1); 134 | 135 | r = (1 + X); 136 | q = (1+X+X^2); 137 | b = (1 - X^2); 138 | a = q * b + r; 139 | t = Polynomial.divrem(a, b); 140 | assert(t[0] == q); 141 | assert(t[1] == r); 142 | 143 | a = 1 + 2*X + 3*X^2; 144 | assert(a.apply(0.1) == 1.23); 145 | 146 | a = 1-2*X^2+2*X^3; 147 | assert(deriv(a) == (6*X^2-4*X)); 148 | assert(deriv(integ(a)) == a); 149 | 150 | a = (X-1)*(X-2)*(X-3)*(X-4)*(X-0.1); 151 | r = polroots(a); 152 | for(i = 0; i < r.length; i++) { 153 | b = abs(a.apply(r[i])); 154 | assert(b <= 1e-13); 155 | } 156 | } 157 | 158 | function test_poly_mod() 159 | { 160 | var a, p; 161 | 162 | /* modulo using polynomials */ 163 | p = X^2 + X + 1; 164 | a = PolyMod(3+X, p) ^ 10; 165 | assert(a == PolyMod(-3725*X-18357, p)); 166 | 167 | a = PolyMod(1/X, 1+X^2); 168 | assert(a == PolyMod(-X, X^2+1)); 169 | } 170 | 171 | function test_rfunc() 172 | { 173 | var a; 174 | a = (X+1)/((X+1)*(X-1)); 175 | assert(a == 1/(X-1)); 176 | a = (X + 2) / (X - 2); 177 | assert(a.apply(1/3) == -7/5); 178 | 179 | assert(deriv((X^2-X+1)/(X-1)) == (X^2-2*X)/(X^2-2*X+1)); 180 | } 181 | 182 | function test_series() 183 | { 184 | var a, b; 185 | a = 1+X+O(X^5); 186 | b = a.inverse(); 187 | assert(b == 1-X+X^2-X^3+X^4+O(X^5)); 188 | assert(deriv(b) == -1+2*X-3*X^2+4*X^3+O(X^4)); 189 | assert(deriv(integ(b)) == b); 190 | 191 | a = Series(1/(1-X), 5); 192 | assert(a == 1+X+X^2+X^3+X^4+O(X^5)); 193 | b = a.apply(0.1); 194 | assert(b == 1.1111); 195 | 196 | assert(exp(3*X^2+O(X^10)) == 1+3*X^2+9/2*X^4+9/2*X^6+27/8*X^8+O(X^10)); 197 | assert(sin(X+O(X^6)) == X-1/6*X^3+1/120*X^5+O(X^6)); 198 | assert(cos(X+O(X^6)) == 1-1/2*X^2+1/24*X^4+O(X^6)); 199 | assert(tan(X+O(X^8)) == X+1/3*X^3+2/15*X^5+17/315*X^7+O(X^8)); 200 | assert((1+X+O(X^6))^(2+X) == 1+2*X+2*X^2+3/2*X^3+5/6*X^4+5/12*X^5+O(X^6)); 201 | } 202 | 203 | function test_matrix() 204 | { 205 | var a, b, r; 206 | a = [[1, 2],[3, 4]]; 207 | b = [3, 4]; 208 | r = a * b; 209 | assert(r == [11, 25]); 210 | r = (a^-1) * 2; 211 | assert(r == [[-4, 2],[3, -1]]); 212 | 213 | assert(norm2([1,2,3]) == 14); 214 | 215 | assert(diag([1,2,3]) == [ [ 1, 0, 0 ], [ 0, 2, 0 ], [ 0, 0, 3 ] ]); 216 | assert(trans(a) == [ [ 1, 3 ], [ 2, 4 ] ]); 217 | assert(trans([1,2,3]) == [[1,2,3]]); 218 | assert(trace(a) == 5); 219 | 220 | assert(charpoly(Matrix.hilbert(4)) == X^4-176/105*X^3+3341/12600*X^2-41/23625*X+1/6048000); 221 | assert(det(Matrix.hilbert(4)) == 1/6048000); 222 | 223 | a = [[1,2,1],[-2,-3,1],[3,5,0]]; 224 | assert(rank(a) == 2); 225 | assert(ker(a) == [ [ 5 ], [ -3 ], [ 1 ] ]); 226 | 227 | assert(dp([1, 2, 3], [3, -4, -7]) === -26); 228 | assert(cp([1, 2, 3], [3, -4, -7]) == [ -2, 16, -10 ]); 229 | } 230 | 231 | function assert_eq(a, ref) 232 | { 233 | assert(abs(a / ref - 1.0) <= 1e-15); 234 | } 235 | 236 | function test_trig() 237 | { 238 | assert_eq(sin(1/2), 0.479425538604203); 239 | assert_eq(sin(2+3*I), 9.154499146911428-4.168906959966565*I); 240 | assert_eq(cos(2+3*I), -4.189625690968807-9.109227893755337*I); 241 | assert_eq((2+0.5*I)^(1.1-0.5*I), 2.494363021357619-0.23076804554558092*I); 242 | assert_eq(sqrt(2*I), 1 + I); 243 | } 244 | 245 | test_integer(); 246 | test_float(); 247 | 248 | test_modulo(); 249 | test_fraction(); 250 | test_mod(); 251 | test_polynomial(); 252 | test_poly_mod(); 253 | test_rfunc(); 254 | test_series(); 255 | test_matrix(); 256 | test_trig(); 257 | -------------------------------------------------------------------------------- /tests/test_std.js: -------------------------------------------------------------------------------- 1 | import * as std from "std"; 2 | import * as os from "os"; 3 | 4 | function assert(actual, expected, message) { 5 | if (arguments.length == 1) 6 | expected = true; 7 | 8 | if (actual === expected) 9 | return; 10 | 11 | if (actual !== null && expected !== null 12 | && typeof actual == 'object' && typeof expected == 'object' 13 | && actual.toString() === expected.toString()) 14 | return; 15 | 16 | throw Error("assertion failed: got |" + actual + "|" + 17 | ", expected |" + expected + "|" + 18 | (message ? " (" + message + ")" : "")); 19 | } 20 | 21 | // load more elaborate version of assert if available 22 | try { std.loadScript("test_assert.js"); } catch(e) {} 23 | 24 | /*----------------*/ 25 | 26 | function test_printf() 27 | { 28 | assert(std.sprintf("a=%d s=%s", 123, "abc"), "a=123 s=abc"); 29 | assert(std.sprintf("%010d", 123), "0000000123"); 30 | assert(std.sprintf("%x", -2), "fffffffe"); 31 | assert(std.sprintf("%lx", -2), "fffffffffffffffe"); 32 | assert(std.sprintf("%10.1f", 2.1), " 2.1"); 33 | assert(std.sprintf("%*.*f", 10, 2, -2.13), " -2.13"); 34 | assert(std.sprintf("%#lx", 0x7fffffffffffffffn), "0x7fffffffffffffff"); 35 | } 36 | 37 | function test_file1() 38 | { 39 | var f, len, str, size, buf, ret, i, str1; 40 | 41 | f = std.tmpfile(); 42 | str = "hello world\n"; 43 | f.puts(str); 44 | 45 | f.seek(0, std.SEEK_SET); 46 | str1 = f.readAsString(); 47 | assert(str1 === str); 48 | 49 | f.seek(0, std.SEEK_END); 50 | size = f.tell(); 51 | assert(size === str.length); 52 | 53 | f.seek(0, std.SEEK_SET); 54 | 55 | buf = new Uint8Array(size); 56 | ret = f.read(buf.buffer, 0, size); 57 | assert(ret === size); 58 | for(i = 0; i < size; i++) 59 | assert(buf[i] === str.charCodeAt(i)); 60 | 61 | f.close(); 62 | } 63 | 64 | function test_file2() 65 | { 66 | var f, str, i, size; 67 | f = std.tmpfile(); 68 | str = "hello world\n"; 69 | size = str.length; 70 | for(i = 0; i < size; i++) 71 | f.putByte(str.charCodeAt(i)); 72 | f.seek(0, std.SEEK_SET); 73 | for(i = 0; i < size; i++) { 74 | assert(str.charCodeAt(i) === f.getByte()); 75 | } 76 | assert(f.getByte() === -1); 77 | f.close(); 78 | } 79 | 80 | function test_getline() 81 | { 82 | var f, line, line_count, lines, i; 83 | 84 | lines = ["hello world", "line 1", "line 2" ]; 85 | f = std.tmpfile(); 86 | for(i = 0; i < lines.length; i++) { 87 | f.puts(lines[i], "\n"); 88 | } 89 | 90 | f.seek(0, std.SEEK_SET); 91 | assert(!f.eof()); 92 | line_count = 0; 93 | for(;;) { 94 | line = f.getline(); 95 | if (line === null) 96 | break; 97 | assert(line == lines[line_count]); 98 | line_count++; 99 | } 100 | assert(f.eof()); 101 | assert(line_count === lines.length); 102 | 103 | f.close(); 104 | } 105 | 106 | function test_popen() 107 | { 108 | var str, f, fname = "tmp_file.txt"; 109 | var content = "hello world"; 110 | 111 | f = std.open(fname, "w"); 112 | f.puts(content); 113 | f.close(); 114 | 115 | /* test loadFile */ 116 | assert(std.loadFile(fname), content); 117 | 118 | /* execute the 'cat' shell command */ 119 | f = std.popen("cat " + fname, "r"); 120 | str = f.readAsString(); 121 | f.close(); 122 | 123 | assert(str, content); 124 | 125 | os.remove(fname); 126 | } 127 | 128 | function test_ext_json() 129 | { 130 | var expected, input, obj; 131 | expected = '{"x":false,"y":true,"z2":null,"a":[1,8,160],"s":"str"}'; 132 | input = `{ "x":false, /*comments are allowed */ 133 | "y":true, // also a comment 134 | z2:null, // unquoted property names 135 | "a":[+1,0o10,0xa0,], // plus prefix, octal, hexadecimal 136 | "s":"str",} // trailing comma in objects and arrays 137 | `; 138 | obj = std.parseExtJSON(input); 139 | assert(JSON.stringify(obj), expected); 140 | } 141 | 142 | function test_os() 143 | { 144 | var fd, fpath, fname, fdir, buf, buf2, i, files, err, fdate, st, link_path; 145 | 146 | assert(os.isatty(0)); 147 | 148 | fdir = "test_tmp_dir"; 149 | fname = "tmp_file.txt"; 150 | fpath = fdir + "/" + fname; 151 | link_path = fdir + "/test_link"; 152 | 153 | os.remove(link_path); 154 | os.remove(fpath); 155 | os.remove(fdir); 156 | 157 | err = os.mkdir(fdir, 0o755); 158 | assert(err === 0); 159 | 160 | fd = os.open(fpath, os.O_RDWR | os.O_CREAT | os.O_TRUNC); 161 | assert(fd >= 0); 162 | 163 | buf = new Uint8Array(10); 164 | for(i = 0; i < buf.length; i++) 165 | buf[i] = i; 166 | assert(os.write(fd, buf.buffer, 0, buf.length) === buf.length); 167 | 168 | assert(os.seek(fd, 0, std.SEEK_SET) === 0); 169 | buf2 = new Uint8Array(buf.length); 170 | assert(os.read(fd, buf2.buffer, 0, buf2.length) === buf2.length); 171 | 172 | for(i = 0; i < buf.length; i++) 173 | assert(buf[i] == buf2[i]); 174 | 175 | if (typeof BigInt !== "undefined") { 176 | assert(os.seek(fd, BigInt(6), std.SEEK_SET), BigInt(6)); 177 | assert(os.read(fd, buf2.buffer, 0, 1) === 1); 178 | assert(buf[6] == buf2[0]); 179 | } 180 | 181 | assert(os.close(fd) === 0); 182 | 183 | [files, err] = os.readdir(fdir); 184 | assert(err, 0); 185 | assert(files.indexOf(fname) >= 0); 186 | 187 | fdate = 10000; 188 | 189 | err = os.utimes(fpath, fdate, fdate); 190 | assert(err, 0); 191 | 192 | [st, err] = os.stat(fpath); 193 | assert(err, 0); 194 | assert(st.mode & os.S_IFMT, os.S_IFREG); 195 | assert(st.mtime, fdate); 196 | 197 | err = os.symlink(fname, link_path); 198 | assert(err === 0); 199 | 200 | [st, err] = os.lstat(link_path); 201 | assert(err, 0); 202 | assert(st.mode & os.S_IFMT, os.S_IFLNK); 203 | 204 | [buf, err] = os.readlink(link_path); 205 | assert(err, 0); 206 | assert(buf, fname); 207 | 208 | assert(os.remove(link_path) === 0); 209 | 210 | [buf, err] = os.getcwd(); 211 | assert(err, 0); 212 | 213 | [buf2, err] = os.realpath("."); 214 | assert(err, 0); 215 | 216 | assert(buf, buf2); 217 | 218 | assert(os.remove(fpath) === 0); 219 | 220 | fd = os.open(fpath, os.O_RDONLY); 221 | assert(fd < 0); 222 | 223 | assert(os.remove(fdir) === 0); 224 | } 225 | 226 | function test_os_exec() 227 | { 228 | var ret, fds, pid, f, status; 229 | 230 | ret = os.exec(["true"]); 231 | assert(ret, 0); 232 | 233 | ret = os.exec(["/bin/sh", "-c", "exit 1"], { usePath: false }); 234 | assert(ret, 1); 235 | 236 | fds = os.pipe(); 237 | pid = os.exec(["sh", "-c", "echo $FOO"], { 238 | stdout: fds[1], 239 | block: false, 240 | env: { FOO: "hello" }, 241 | } ); 242 | assert(pid >= 0); 243 | os.close(fds[1]); /* close the write end (as it is only in the child) */ 244 | f = std.fdopen(fds[0], "r"); 245 | assert(f.getline(), "hello"); 246 | assert(f.getline(), null); 247 | f.close(); 248 | [ret, status] = os.waitpid(pid, 0); 249 | assert(ret, pid); 250 | assert(status & 0x7f, 0); /* exited */ 251 | assert(status >> 8, 0); /* exit code */ 252 | 253 | pid = os.exec(["cat"], { block: false } ); 254 | assert(pid >= 0); 255 | os.kill(pid, os.SIGQUIT); 256 | [ret, status] = os.waitpid(pid, 0); 257 | assert(ret, pid); 258 | assert(status & 0x7f, os.SIGQUIT); 259 | } 260 | 261 | function test_timer() 262 | { 263 | var th, i; 264 | 265 | /* just test that a timer can be inserted and removed */ 266 | th = []; 267 | for(i = 0; i < 3; i++) 268 | th[i] = os.setTimeout(function () { }, 1000); 269 | for(i = 0; i < 3; i++) 270 | os.clearTimeout(th[i]); 271 | } 272 | 273 | test_printf(); 274 | test_file1(); 275 | test_file2(); 276 | test_getline(); 277 | test_popen(); 278 | test_os(); 279 | test_os_exec(); 280 | test_timer(); 281 | test_ext_json(); 282 | -------------------------------------------------------------------------------- /tests/test_loop.js: -------------------------------------------------------------------------------- 1 | function assert(actual, expected, message) { 2 | if (arguments.length == 1) 3 | expected = true; 4 | 5 | if (actual === expected) 6 | return; 7 | 8 | if (actual !== null && expected !== null 9 | && typeof actual == 'object' && typeof expected == 'object' 10 | && actual.toString() === expected.toString()) 11 | return; 12 | 13 | throw Error("assertion failed: got |" + actual + "|" + 14 | ", expected |" + expected + "|" + 15 | (message ? " (" + message + ")" : "")); 16 | } 17 | 18 | // load more elaborate version of assert if available 19 | try { __loadScript("test_assert.js"); } catch(e) {} 20 | 21 | /*----------------*/ 22 | 23 | function test_while() 24 | { 25 | var i, c; 26 | i = 0; 27 | c = 0; 28 | while (i < 3) { 29 | c++; 30 | i++; 31 | } 32 | assert(c === 3); 33 | } 34 | 35 | function test_while_break() 36 | { 37 | var i, c; 38 | i = 0; 39 | c = 0; 40 | while (i < 3) { 41 | c++; 42 | if (i == 1) 43 | break; 44 | i++; 45 | } 46 | assert(c === 2 && i === 1); 47 | } 48 | 49 | function test_do_while() 50 | { 51 | var i, c; 52 | i = 0; 53 | c = 0; 54 | do { 55 | c++; 56 | i++; 57 | } while (i < 3); 58 | assert(c === 3 && i === 3); 59 | } 60 | 61 | function test_for() 62 | { 63 | var i, c; 64 | c = 0; 65 | for(i = 0; i < 3; i++) { 66 | c++; 67 | } 68 | assert(c === 3 && i === 3); 69 | 70 | c = 0; 71 | for(var j = 0; j < 3; j++) { 72 | c++; 73 | } 74 | assert(c === 3 && j === 3); 75 | } 76 | 77 | function test_for_in() 78 | { 79 | var i, tab, a, b; 80 | 81 | tab = []; 82 | for(i in {x:1, y: 2}) { 83 | tab.push(i); 84 | } 85 | assert(tab.toString(), "x,y", "for_in"); 86 | 87 | /* prototype chain test */ 88 | a = {x:2, y: 2, "1": 3}; 89 | b = {"4" : 3 }; 90 | Object.setPrototypeOf(a, b); 91 | tab = []; 92 | for(i in a) { 93 | tab.push(i); 94 | } 95 | assert(tab.toString(), "1,x,y,4", "for_in"); 96 | 97 | /* non enumerable properties hide enumerables ones in the 98 | prototype chain */ 99 | a = {y: 2, "1": 3}; 100 | Object.defineProperty(a, "x", { value: 1 }); 101 | b = {"x" : 3 }; 102 | Object.setPrototypeOf(a, b); 103 | tab = []; 104 | for(i in a) { 105 | tab.push(i); 106 | } 107 | assert(tab.toString(), "1,y", "for_in"); 108 | 109 | /* array optimization */ 110 | a = []; 111 | for(i = 0; i < 10; i++) 112 | a.push(i); 113 | tab = []; 114 | for(i in a) { 115 | tab.push(i); 116 | } 117 | assert(tab.toString(), "0,1,2,3,4,5,6,7,8,9", "for_in"); 118 | 119 | /* iterate with a field */ 120 | a={x:0}; 121 | tab = []; 122 | for(a.x in {x:1, y: 2}) { 123 | tab.push(a.x); 124 | } 125 | assert(tab.toString(), "x,y", "for_in"); 126 | 127 | /* iterate with a variable field */ 128 | a=[0]; 129 | tab = []; 130 | for(a[0] in {x:1, y: 2}) { 131 | tab.push(a[0]); 132 | } 133 | assert(tab.toString(), "x,y", "for_in"); 134 | 135 | /* variable definition in the for in */ 136 | tab = []; 137 | for(var j in {x:1, y: 2}) { 138 | tab.push(j); 139 | } 140 | assert(tab.toString(), "x,y", "for_in"); 141 | 142 | /* variable assigment in the for in */ 143 | tab = []; 144 | for(var k = 2 in {x:1, y: 2}) { 145 | tab.push(k); 146 | } 147 | assert(tab.toString(), "x,y", "for_in"); 148 | } 149 | 150 | function test_for_in2() 151 | { 152 | var i; 153 | tab = []; 154 | for(i in {x:1, y: 2, z:3}) { 155 | if (i === "y") 156 | continue; 157 | tab.push(i); 158 | } 159 | assert(tab.toString() == "x,z"); 160 | 161 | tab = []; 162 | for(i in {x:1, y: 2, z:3}) { 163 | if (i === "z") 164 | break; 165 | tab.push(i); 166 | } 167 | assert(tab.toString() == "x,y"); 168 | } 169 | 170 | function test_for_break() 171 | { 172 | var i, c; 173 | c = 0; 174 | L1: for(i = 0; i < 3; i++) { 175 | c++; 176 | if (i == 0) 177 | continue; 178 | while (1) { 179 | break L1; 180 | } 181 | } 182 | assert(c === 2 && i === 1); 183 | } 184 | 185 | function test_switch1() 186 | { 187 | var i, a, s; 188 | s = ""; 189 | for(i = 0; i < 3; i++) { 190 | a = "?"; 191 | switch(i) { 192 | case 0: 193 | a = "a"; 194 | break; 195 | case 1: 196 | a = "b"; 197 | break; 198 | default: 199 | a = "c"; 200 | break; 201 | } 202 | s += a; 203 | } 204 | assert(s === "abc" && i === 3); 205 | } 206 | 207 | function test_switch2() 208 | { 209 | var i, a, s; 210 | s = ""; 211 | for(i = 0; i < 4; i++) { 212 | a = "?"; 213 | switch(i) { 214 | case 0: 215 | a = "a"; 216 | break; 217 | case 1: 218 | a = "b"; 219 | break; 220 | case 2: 221 | continue; 222 | default: 223 | a = "" + i; 224 | break; 225 | } 226 | s += a; 227 | } 228 | assert(s === "ab3" && i === 4); 229 | } 230 | 231 | function test_try_catch1() 232 | { 233 | try { 234 | throw "hello"; 235 | } catch (e) { 236 | assert(e, "hello", "catch"); 237 | return; 238 | } 239 | assert(false, "catch"); 240 | } 241 | 242 | function test_try_catch2() 243 | { 244 | var a; 245 | try { 246 | a = 1; 247 | } catch (e) { 248 | a = 2; 249 | } 250 | assert(a, 1, "catch"); 251 | } 252 | 253 | function test_try_catch3() 254 | { 255 | var s; 256 | s = ""; 257 | try { 258 | s += "t"; 259 | } catch (e) { 260 | s += "c"; 261 | } finally { 262 | s += "f"; 263 | } 264 | assert(s, "tf", "catch"); 265 | } 266 | 267 | function test_try_catch4() 268 | { 269 | var s; 270 | s = ""; 271 | try { 272 | s += "t"; 273 | throw "c"; 274 | } catch (e) { 275 | s += e; 276 | } finally { 277 | s += "f"; 278 | } 279 | assert(s, "tcf", "catch"); 280 | } 281 | 282 | function test_try_catch5() 283 | { 284 | var s; 285 | s = ""; 286 | for(;;) { 287 | try { 288 | s += "t"; 289 | break; 290 | s += "b"; 291 | } finally { 292 | s += "f"; 293 | } 294 | } 295 | assert(s, "tf", "catch"); 296 | } 297 | 298 | function test_try_catch6() 299 | { 300 | function f() { 301 | try { 302 | s += 't'; 303 | return 1; 304 | } finally { 305 | s += "f"; 306 | } 307 | } 308 | var s = ""; 309 | assert(f() === 1); 310 | assert(s, "tf", "catch6"); 311 | } 312 | 313 | function test_try_catch7() 314 | { 315 | var s; 316 | s = ""; 317 | 318 | try { 319 | try { 320 | s += "t"; 321 | throw "a"; 322 | } finally { 323 | s += "f"; 324 | } 325 | } catch(e) { 326 | s += e; 327 | } finally { 328 | s += "g"; 329 | } 330 | assert(s, "tfag", "catch"); 331 | } 332 | 333 | function test_try_catch8() 334 | { 335 | var i, s; 336 | 337 | s = ""; 338 | for(var i in {x:1, y:2}) { 339 | try { 340 | s += i; 341 | throw "a"; 342 | } catch (e) { 343 | s += e; 344 | } finally { 345 | s += "f"; 346 | } 347 | } 348 | assert(s === "xafyaf"); 349 | } 350 | 351 | test_while(); 352 | test_while_break(); 353 | test_do_while(); 354 | test_for(); 355 | test_for_break(); 356 | test_switch1(); 357 | test_switch2(); 358 | test_for_in(); 359 | test_for_in2(); 360 | 361 | test_try_catch1(); 362 | test_try_catch2(); 363 | test_try_catch3(); 364 | test_try_catch4(); 365 | test_try_catch5(); 366 | test_try_catch6(); 367 | test_try_catch7(); 368 | test_try_catch8(); 369 | -------------------------------------------------------------------------------- /src/utils/unicode_gen_def.h: -------------------------------------------------------------------------------- 1 | #ifdef UNICODE_GENERAL_CATEGORY 2 | DEF(Cn, "Unassigned") /* must be zero */ 3 | DEF(Lu, "Uppercase_Letter") 4 | DEF(Ll, "Lowercase_Letter") 5 | DEF(Lt, "Titlecase_Letter") 6 | DEF(Lm, "Modifier_Letter") 7 | DEF(Lo, "Other_Letter") 8 | DEF(Mn, "Nonspacing_Mark") 9 | DEF(Mc, "Spacing_Mark") 10 | DEF(Me, "Enclosing_Mark") 11 | DEF(Nd, "Decimal_Number,digit") 12 | DEF(Nl, "Letter_Number") 13 | DEF(No, "Other_Number") 14 | DEF(Sm, "Math_Symbol") 15 | DEF(Sc, "Currency_Symbol") 16 | DEF(Sk, "Modifier_Symbol") 17 | DEF(So, "Other_Symbol") 18 | DEF(Pc, "Connector_Punctuation") 19 | DEF(Pd, "Dash_Punctuation") 20 | DEF(Ps, "Open_Punctuation") 21 | DEF(Pe, "Close_Punctuation") 22 | DEF(Pi, "Initial_Punctuation") 23 | DEF(Pf, "Final_Punctuation") 24 | DEF(Po, "Other_Punctuation") 25 | DEF(Zs, "Space_Separator") 26 | DEF(Zl, "Line_Separator") 27 | DEF(Zp, "Paragraph_Separator") 28 | DEF(Cc, "Control,cntrl") 29 | DEF(Cf, "Format") 30 | DEF(Cs, "Surrogate") 31 | DEF(Co, "Private_Use") 32 | /* synthetic properties */ 33 | DEF(LC, "Cased_Letter") 34 | DEF(L, "Letter") 35 | DEF(M, "Mark,Combining_Mark") 36 | DEF(N, "Number") 37 | DEF(S, "Symbol") 38 | DEF(P, "Punctuation,punct") 39 | DEF(Z, "Separator") 40 | DEF(C, "Other") 41 | #endif 42 | 43 | #ifdef UNICODE_SCRIPT 44 | /* scripts aliases names in PropertyValueAliases.txt */ 45 | DEF(Unknown, "Zzzz") 46 | DEF(Adlam, "Adlm") 47 | DEF(Ahom, "Ahom") 48 | DEF(Anatolian_Hieroglyphs, "Hluw") 49 | DEF(Arabic, "Arab") 50 | DEF(Armenian, "Armn") 51 | DEF(Avestan, "Avst") 52 | DEF(Balinese, "Bali") 53 | DEF(Bamum, "Bamu") 54 | DEF(Bassa_Vah, "Bass") 55 | DEF(Batak, "Batk") 56 | DEF(Bengali, "Beng") 57 | DEF(Bhaiksuki, "Bhks") 58 | DEF(Bopomofo, "Bopo") 59 | DEF(Brahmi, "Brah") 60 | DEF(Braille, "Brai") 61 | DEF(Buginese, "Bugi") 62 | DEF(Buhid, "Buhd") 63 | DEF(Canadian_Aboriginal, "Cans") 64 | DEF(Carian, "Cari") 65 | DEF(Caucasian_Albanian, "Aghb") 66 | DEF(Chakma, "Cakm") 67 | DEF(Cham, "Cham") 68 | DEF(Cherokee, "Cher") 69 | DEF(Chorasmian, "Chrs") 70 | DEF(Common, "Zyyy") 71 | DEF(Coptic, "Copt,Qaac") 72 | DEF(Cuneiform, "Xsux") 73 | DEF(Cypriot, "Cprt") 74 | DEF(Cyrillic, "Cyrl") 75 | DEF(Deseret, "Dsrt") 76 | DEF(Devanagari, "Deva") 77 | DEF(Dives_Akuru, "Diak") 78 | DEF(Dogra, "Dogr") 79 | DEF(Duployan, "Dupl") 80 | DEF(Egyptian_Hieroglyphs, "Egyp") 81 | DEF(Elbasan, "Elba") 82 | DEF(Elymaic, "Elym") 83 | DEF(Ethiopic, "Ethi") 84 | DEF(Georgian, "Geor") 85 | DEF(Glagolitic, "Glag") 86 | DEF(Gothic, "Goth") 87 | DEF(Grantha, "Gran") 88 | DEF(Greek, "Grek") 89 | DEF(Gujarati, "Gujr") 90 | DEF(Gunjala_Gondi, "Gong") 91 | DEF(Gurmukhi, "Guru") 92 | DEF(Han, "Hani") 93 | DEF(Hangul, "Hang") 94 | DEF(Hanifi_Rohingya, "Rohg") 95 | DEF(Hanunoo, "Hano") 96 | DEF(Hatran, "Hatr") 97 | DEF(Hebrew, "Hebr") 98 | DEF(Hiragana, "Hira") 99 | DEF(Imperial_Aramaic, "Armi") 100 | DEF(Inherited, "Zinh,Qaai") 101 | DEF(Inscriptional_Pahlavi, "Phli") 102 | DEF(Inscriptional_Parthian, "Prti") 103 | DEF(Javanese, "Java") 104 | DEF(Kaithi, "Kthi") 105 | DEF(Kannada, "Knda") 106 | DEF(Katakana, "Kana") 107 | DEF(Kayah_Li, "Kali") 108 | DEF(Kharoshthi, "Khar") 109 | DEF(Khmer, "Khmr") 110 | DEF(Khojki, "Khoj") 111 | DEF(Khitan_Small_Script, "Kits") 112 | DEF(Khudawadi, "Sind") 113 | DEF(Lao, "Laoo") 114 | DEF(Latin, "Latn") 115 | DEF(Lepcha, "Lepc") 116 | DEF(Limbu, "Limb") 117 | DEF(Linear_A, "Lina") 118 | DEF(Linear_B, "Linb") 119 | DEF(Lisu, "Lisu") 120 | DEF(Lycian, "Lyci") 121 | DEF(Lydian, "Lydi") 122 | DEF(Makasar, "Maka") 123 | DEF(Mahajani, "Mahj") 124 | DEF(Malayalam, "Mlym") 125 | DEF(Mandaic, "Mand") 126 | DEF(Manichaean, "Mani") 127 | DEF(Marchen, "Marc") 128 | DEF(Masaram_Gondi, "Gonm") 129 | DEF(Medefaidrin, "Medf") 130 | DEF(Meetei_Mayek, "Mtei") 131 | DEF(Mende_Kikakui, "Mend") 132 | DEF(Meroitic_Cursive, "Merc") 133 | DEF(Meroitic_Hieroglyphs, "Mero") 134 | DEF(Miao, "Plrd") 135 | DEF(Modi, "Modi") 136 | DEF(Mongolian, "Mong") 137 | DEF(Mro, "Mroo") 138 | DEF(Multani, "Mult") 139 | DEF(Myanmar, "Mymr") 140 | DEF(Nabataean, "Nbat") 141 | DEF(Nandinagari, "Nand") 142 | DEF(New_Tai_Lue, "Talu") 143 | DEF(Newa, "Newa") 144 | DEF(Nko, "Nkoo") 145 | DEF(Nushu, "Nshu") 146 | DEF(Nyiakeng_Puachue_Hmong, "Hmnp") 147 | DEF(Ogham, "Ogam") 148 | DEF(Ol_Chiki, "Olck") 149 | DEF(Old_Hungarian, "Hung") 150 | DEF(Old_Italic, "Ital") 151 | DEF(Old_North_Arabian, "Narb") 152 | DEF(Old_Permic, "Perm") 153 | DEF(Old_Persian, "Xpeo") 154 | DEF(Old_Sogdian, "Sogo") 155 | DEF(Old_South_Arabian, "Sarb") 156 | DEF(Old_Turkic, "Orkh") 157 | DEF(Oriya, "Orya") 158 | DEF(Osage, "Osge") 159 | DEF(Osmanya, "Osma") 160 | DEF(Pahawh_Hmong, "Hmng") 161 | DEF(Palmyrene, "Palm") 162 | DEF(Pau_Cin_Hau, "Pauc") 163 | DEF(Phags_Pa, "Phag") 164 | DEF(Phoenician, "Phnx") 165 | DEF(Psalter_Pahlavi, "Phlp") 166 | DEF(Rejang, "Rjng") 167 | DEF(Runic, "Runr") 168 | DEF(Samaritan, "Samr") 169 | DEF(Saurashtra, "Saur") 170 | DEF(Sharada, "Shrd") 171 | DEF(Shavian, "Shaw") 172 | DEF(Siddham, "Sidd") 173 | DEF(SignWriting, "Sgnw") 174 | DEF(Sinhala, "Sinh") 175 | DEF(Sogdian, "Sogd") 176 | DEF(Sora_Sompeng, "Sora") 177 | DEF(Soyombo, "Soyo") 178 | DEF(Sundanese, "Sund") 179 | DEF(Syloti_Nagri, "Sylo") 180 | DEF(Syriac, "Syrc") 181 | DEF(Tagalog, "Tglg") 182 | DEF(Tagbanwa, "Tagb") 183 | DEF(Tai_Le, "Tale") 184 | DEF(Tai_Tham, "Lana") 185 | DEF(Tai_Viet, "Tavt") 186 | DEF(Takri, "Takr") 187 | DEF(Tamil, "Taml") 188 | DEF(Tangut, "Tang") 189 | DEF(Telugu, "Telu") 190 | DEF(Thaana, "Thaa") 191 | DEF(Thai, "Thai") 192 | DEF(Tibetan, "Tibt") 193 | DEF(Tifinagh, "Tfng") 194 | DEF(Tirhuta, "Tirh") 195 | DEF(Ugaritic, "Ugar") 196 | DEF(Vai, "Vaii") 197 | DEF(Wancho, "Wcho") 198 | DEF(Warang_Citi, "Wara") 199 | DEF(Yezidi, "Yezi") 200 | DEF(Yi, "Yiii") 201 | DEF(Zanabazar_Square, "Zanb") 202 | #endif 203 | 204 | #ifdef UNICODE_PROP_LIST 205 | /* Prop list not exported to regexp */ 206 | DEF(Hyphen, "") 207 | DEF(Other_Math, "") 208 | DEF(Other_Alphabetic, "") 209 | DEF(Other_Lowercase, "") 210 | DEF(Other_Uppercase, "") 211 | DEF(Other_Grapheme_Extend, "") 212 | DEF(Other_Default_Ignorable_Code_Point, "") 213 | DEF(Other_ID_Start, "") 214 | DEF(Other_ID_Continue, "") 215 | DEF(Prepended_Concatenation_Mark, "") 216 | /* additional computed properties for smaller tables */ 217 | DEF(ID_Continue1, "") 218 | DEF(XID_Start1, "") 219 | DEF(XID_Continue1, "") 220 | DEF(Changes_When_Titlecased1, "") 221 | DEF(Changes_When_Casefolded1, "") 222 | DEF(Changes_When_NFKC_Casefolded1, "") 223 | 224 | /* Prop list exported to JS */ 225 | DEF(ASCII_Hex_Digit, "AHex") 226 | DEF(Bidi_Control, "Bidi_C") 227 | DEF(Dash, "") 228 | DEF(Deprecated, "Dep") 229 | DEF(Diacritic, "Dia") 230 | DEF(Extender, "Ext") 231 | DEF(Hex_Digit, "Hex") 232 | DEF(IDS_Binary_Operator, "IDSB") 233 | DEF(IDS_Trinary_Operator, "IDST") 234 | DEF(Ideographic, "Ideo") 235 | DEF(Join_Control, "Join_C") 236 | DEF(Logical_Order_Exception, "LOE") 237 | DEF(Noncharacter_Code_Point, "NChar") 238 | DEF(Pattern_Syntax, "Pat_Syn") 239 | DEF(Pattern_White_Space, "Pat_WS") 240 | DEF(Quotation_Mark, "QMark") 241 | DEF(Radical, "") 242 | DEF(Regional_Indicator, "RI") 243 | DEF(Sentence_Terminal, "STerm") 244 | DEF(Soft_Dotted, "SD") 245 | DEF(Terminal_Punctuation, "Term") 246 | DEF(Unified_Ideograph, "UIdeo") 247 | DEF(Variation_Selector, "VS") 248 | DEF(White_Space, "space") 249 | DEF(Bidi_Mirrored, "Bidi_M") 250 | DEF(Emoji, "") 251 | DEF(Emoji_Component, "EComp") 252 | DEF(Emoji_Modifier, "EMod") 253 | DEF(Emoji_Modifier_Base, "EBase") 254 | DEF(Emoji_Presentation, "EPres") 255 | DEF(Extended_Pictographic, "ExtPict") 256 | DEF(Default_Ignorable_Code_Point, "DI") 257 | DEF(ID_Start, "IDS") 258 | DEF(Case_Ignorable, "CI") 259 | 260 | /* other binary properties */ 261 | DEF(ASCII,"") 262 | DEF(Alphabetic, "Alpha") 263 | DEF(Any, "") 264 | DEF(Assigned,"") 265 | DEF(Cased, "") 266 | DEF(Changes_When_Casefolded, "CWCF") 267 | DEF(Changes_When_Casemapped, "CWCM") 268 | DEF(Changes_When_Lowercased, "CWL") 269 | DEF(Changes_When_NFKC_Casefolded, "CWKCF") 270 | DEF(Changes_When_Titlecased, "CWT") 271 | DEF(Changes_When_Uppercased, "CWU") 272 | DEF(Grapheme_Base, "Gr_Base") 273 | DEF(Grapheme_Extend, "Gr_Ext") 274 | DEF(ID_Continue, "IDC") 275 | DEF(Lowercase, "Lower") 276 | DEF(Math, "") 277 | DEF(Uppercase, "Upper") 278 | DEF(XID_Continue, "XIDC") 279 | DEF(XID_Start, "XIDS") 280 | 281 | /* internal tables with index */ 282 | DEF(Cased1, "") 283 | 284 | #endif 285 | -------------------------------------------------------------------------------- /src/quickjs-parser-atom.h: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS atom definitions 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * Copyright (c) 2017-2018 Charlie Gordon 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining a copy 8 | * of this software and associated documentation files (the "Software"), to deal 9 | * in the Software without restriction, including without limitation the rights 10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | * copies of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included in 15 | * all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | * THE SOFTWARE. 24 | */ 25 | 26 | #ifdef DEF 27 | 28 | /* Note: first atoms are considered as keywords in the parser */ 29 | DEF(null, "null") /* must be first */ 30 | DEF(false, "false") 31 | DEF(true, "true") 32 | DEF(if, "if") 33 | DEF(else, "else") 34 | DEF(return, "return") 35 | DEF(var, "var") 36 | DEF(this, "this") 37 | DEF(delete, "delete") 38 | DEF(void, "void") 39 | DEF(typeof, "typeof") 40 | DEF(new, "new") 41 | DEF(in, "in") 42 | DEF(instanceof, "instanceof") 43 | DEF(do, "do") 44 | DEF(while, "while") 45 | DEF(for, "for") 46 | DEF(break, "break") 47 | DEF(continue, "continue") 48 | DEF(switch, "switch") 49 | DEF(case, "case") 50 | DEF(default, "default") 51 | DEF(throw, "throw") 52 | DEF(try, "try") 53 | DEF(catch, "catch") 54 | DEF(finally, "finally") 55 | DEF(function, "function") 56 | DEF(debugger, "debugger") 57 | DEF(with, "with") 58 | /* FutureReservedWord */ 59 | DEF(class, "class") 60 | DEF(const, "const") 61 | DEF(enum, "enum") 62 | DEF(export, "export") 63 | DEF(extends, "extends") 64 | DEF(import, "import") 65 | DEF(super, "super") 66 | /* FutureReservedWords when parsing strict mode code */ 67 | DEF(implements, "implements") 68 | DEF(interface, "interface") 69 | DEF(let, "let") 70 | DEF(package, "package") 71 | DEF(private, "private") 72 | DEF(protected, "protected") 73 | DEF(public, "public") 74 | DEF(static, "static") 75 | DEF(yield, "yield") 76 | DEF(await, "await") 77 | 78 | /* empty string */ 79 | DEF(empty_string, "") 80 | /* identifiers */ 81 | DEF(length, "length") 82 | DEF(fileName, "fileName") 83 | DEF(lineNumber, "lineNumber") 84 | DEF(message, "message") 85 | DEF(errors, "errors") 86 | DEF(stack, "stack") 87 | DEF(name, "name") 88 | DEF(toString, "toString") 89 | DEF(toLocaleString, "toLocaleString") 90 | DEF(valueOf, "valueOf") 91 | DEF(eval, "eval") 92 | DEF(prototype, "prototype") 93 | DEF(constructor, "constructor") 94 | DEF(configurable, "configurable") 95 | DEF(writable, "writable") 96 | DEF(enumerable, "enumerable") 97 | DEF(value, "value") 98 | DEF(get, "get") 99 | DEF(set, "set") 100 | DEF(of, "of") 101 | DEF(__proto__, "__proto__") 102 | DEF(undefined, "undefined") 103 | DEF(number, "number") 104 | DEF(boolean, "boolean") 105 | DEF(string, "string") 106 | DEF(object, "object") 107 | DEF(symbol, "symbol") 108 | DEF(integer, "integer") 109 | DEF(unknown, "unknown") 110 | DEF(arguments, "arguments") 111 | DEF(callee, "callee") 112 | DEF(caller, "caller") 113 | DEF(_eval_, "") 114 | DEF(_ret_, "") 115 | DEF(_var_, "") 116 | DEF(_with_, "") 117 | DEF(lastIndex, "lastIndex") 118 | DEF(target, "target") 119 | DEF(index, "index") 120 | DEF(input, "input") 121 | DEF(defineProperties, "defineProperties") 122 | DEF(apply, "apply") 123 | DEF(join, "join") 124 | DEF(concat, "concat") 125 | DEF(split, "split") 126 | DEF(construct, "construct") 127 | DEF(getPrototypeOf, "getPrototypeOf") 128 | DEF(setPrototypeOf, "setPrototypeOf") 129 | DEF(isExtensible, "isExtensible") 130 | DEF(preventExtensions, "preventExtensions") 131 | DEF(has, "has") 132 | DEF(deleteProperty, "deleteProperty") 133 | DEF(defineProperty, "defineProperty") 134 | DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor") 135 | DEF(ownKeys, "ownKeys") 136 | DEF(add, "add") 137 | DEF(done, "done") 138 | DEF(next, "next") 139 | DEF(values, "values") 140 | DEF(source, "source") 141 | DEF(flags, "flags") 142 | DEF(global, "global") 143 | DEF(unicode, "unicode") 144 | DEF(raw, "raw") 145 | DEF(new_target, "new.target") 146 | DEF(this_active_func, "this.active_func") 147 | DEF(home_object, "") 148 | DEF(computed_field, "") 149 | DEF(static_computed_field, "") /* must come after computed_fields */ 150 | DEF(class_fields_init, "") 151 | DEF(brand, "") 152 | DEF(hash_constructor, "#constructor") 153 | DEF(as, "as") 154 | DEF(from, "from") 155 | DEF(meta, "meta") 156 | DEF(_default_, "*default*") 157 | DEF(_star_, "*") 158 | DEF(Module, "Module") 159 | DEF(then, "then") 160 | DEF(resolve, "resolve") 161 | DEF(reject, "reject") 162 | DEF(promise, "promise") 163 | DEF(proxy, "proxy") 164 | DEF(revoke, "revoke") 165 | DEF(async, "async") 166 | DEF(exec, "exec") 167 | DEF(groups, "groups") 168 | DEF(status, "status") 169 | DEF(reason, "reason") 170 | DEF(globalThis, "globalThis") 171 | #ifdef CONFIG_BIGNUM 172 | DEF(bigint, "bigint") 173 | DEF(bigfloat, "bigfloat") 174 | DEF(bigdecimal, "bigdecimal") 175 | DEF(roundingMode, "roundingMode") 176 | DEF(maximumSignificantDigits, "maximumSignificantDigits") 177 | DEF(maximumFractionDigits, "maximumFractionDigits") 178 | #endif 179 | #ifdef CONFIG_ATOMICS 180 | DEF(not_equal, "not-equal") 181 | DEF(timed_out, "timed-out") 182 | DEF(ok, "ok") 183 | #endif 184 | DEF(toJSON, "toJSON") 185 | /* class names */ 186 | DEF(Object, "Object") 187 | DEF(Array, "Array") 188 | DEF(Error, "Error") 189 | DEF(Number, "Number") 190 | DEF(String, "String") 191 | DEF(Boolean, "Boolean") 192 | DEF(Symbol, "Symbol") 193 | DEF(Arguments, "Arguments") 194 | DEF(Math, "Math") 195 | DEF(JSON, "JSON") 196 | DEF(Date, "Date") 197 | DEF(Function, "Function") 198 | DEF(GeneratorFunction, "GeneratorFunction") 199 | DEF(ForInIterator, "ForInIterator") 200 | DEF(RegExp, "RegExp") 201 | DEF(ArrayBuffer, "ArrayBuffer") 202 | DEF(SharedArrayBuffer, "SharedArrayBuffer") 203 | /* must keep same order as class IDs for typed arrays */ 204 | DEF(Uint8ClampedArray, "Uint8ClampedArray") 205 | DEF(Int8Array, "Int8Array") 206 | DEF(Uint8Array, "Uint8Array") 207 | DEF(Int16Array, "Int16Array") 208 | DEF(Uint16Array, "Uint16Array") 209 | DEF(Int32Array, "Int32Array") 210 | DEF(Uint32Array, "Uint32Array") 211 | #ifdef CONFIG_BIGNUM 212 | DEF(BigInt64Array, "BigInt64Array") 213 | DEF(BigUint64Array, "BigUint64Array") 214 | #endif 215 | DEF(Float32Array, "Float32Array") 216 | DEF(Float64Array, "Float64Array") 217 | DEF(DataView, "DataView") 218 | #ifdef CONFIG_BIGNUM 219 | DEF(BigInt, "BigInt") 220 | DEF(BigFloat, "BigFloat") 221 | DEF(BigFloatEnv, "BigFloatEnv") 222 | DEF(BigDecimal, "BigDecimal") 223 | DEF(OperatorSet, "OperatorSet") 224 | DEF(Operators, "Operators") 225 | #endif 226 | DEF(Map, "Map") 227 | DEF(Set, "Set") /* Map + 1 */ 228 | DEF(WeakMap, "WeakMap") /* Map + 2 */ 229 | DEF(WeakSet, "WeakSet") /* Map + 3 */ 230 | DEF(Map_Iterator, "Map Iterator") 231 | DEF(Set_Iterator, "Set Iterator") 232 | DEF(Array_Iterator, "Array Iterator") 233 | DEF(String_Iterator, "String Iterator") 234 | DEF(RegExp_String_Iterator, "RegExp String Iterator") 235 | DEF(Generator, "Generator") 236 | DEF(Proxy, "Proxy") 237 | DEF(Promise, "Promise") 238 | DEF(PromiseResolveFunction, "PromiseResolveFunction") 239 | DEF(PromiseRejectFunction, "PromiseRejectFunction") 240 | DEF(AsyncFunction, "AsyncFunction") 241 | DEF(AsyncFunctionResolve, "AsyncFunctionResolve") 242 | DEF(AsyncFunctionReject, "AsyncFunctionReject") 243 | DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction") 244 | DEF(AsyncGenerator, "AsyncGenerator") 245 | DEF(EvalError, "EvalError") 246 | DEF(RangeError, "RangeError") 247 | DEF(ReferenceError, "ReferenceError") 248 | DEF(SyntaxError, "SyntaxError") 249 | DEF(TypeError, "TypeError") 250 | DEF(URIError, "URIError") 251 | DEF(InternalError, "InternalError") 252 | /* private symbols */ 253 | DEF(Private_brand, "") 254 | /* symbols */ 255 | DEF(Symbol_toPrimitive, "Symbol.toPrimitive") 256 | DEF(Symbol_iterator, "Symbol.iterator") 257 | DEF(Symbol_match, "Symbol.match") 258 | DEF(Symbol_matchAll, "Symbol.matchAll") 259 | DEF(Symbol_replace, "Symbol.replace") 260 | DEF(Symbol_search, "Symbol.search") 261 | DEF(Symbol_split, "Symbol.split") 262 | DEF(Symbol_toStringTag, "Symbol.toStringTag") 263 | DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable") 264 | DEF(Symbol_hasInstance, "Symbol.hasInstance") 265 | DEF(Symbol_species, "Symbol.species") 266 | DEF(Symbol_unscopables, "Symbol.unscopables") 267 | DEF(Symbol_asyncIterator, "Symbol.asyncIterator") 268 | #ifdef CONFIG_BIGNUM 269 | DEF(Symbol_operatorSet, "Symbol.operatorSet") 270 | #endif 271 | 272 | #endif /* DEF */ 273 | -------------------------------------------------------------------------------- /tests/test_language.js: -------------------------------------------------------------------------------- 1 | function assert(actual, expected, message) { 2 | if (arguments.length == 1) 3 | expected = true; 4 | 5 | if (actual === expected) 6 | return; 7 | 8 | if (actual !== null && expected !== null 9 | && typeof actual == 'object' && typeof expected == 'object' 10 | && actual.toString() === expected.toString()) 11 | return; 12 | 13 | throw Error("assertion failed: got |" + actual + "|" + 14 | ", expected |" + expected + "|" + 15 | (message ? " (" + message + ")" : "")); 16 | } 17 | 18 | // load more elaborate version of assert if available 19 | try { __loadScript("test_assert.js"); } catch(e) {} 20 | 21 | /*----------------*/ 22 | 23 | function test_op1() 24 | { 25 | var r, a; 26 | r = 1 + 2; 27 | assert(r, 3, "1 + 2 === 3"); 28 | 29 | r = 1 - 2; 30 | assert(r, -1, "1 - 2 === -1"); 31 | 32 | r = -1; 33 | assert(r, -1, "-1 === -1"); 34 | 35 | r = +2; 36 | assert(r, 2, "+2 === 2"); 37 | 38 | r = 2 * 3; 39 | assert(r, 6, "2 * 3 === 6"); 40 | 41 | r = 4 / 2; 42 | assert(r, 2, "4 / 2 === 2"); 43 | 44 | r = 4 % 3; 45 | assert(r, 1, "4 % 3 === 3"); 46 | 47 | r = 4 << 2; 48 | assert(r, 16, "4 << 2 === 16"); 49 | 50 | r = 1 << 0; 51 | assert(r, 1, "1 << 0 === 1"); 52 | 53 | r = 1 << 31; 54 | assert(r, -2147483648, "1 << 31 === -2147483648"); 55 | 56 | r = 1 << 32; 57 | assert(r, 1, "1 << 32 === 1"); 58 | 59 | r = (1 << 31) < 0; 60 | assert(r, true, "(1 << 31) < 0 === true"); 61 | 62 | r = -4 >> 1; 63 | assert(r, -2, "-4 >> 1 === -2"); 64 | 65 | r = -4 >>> 1; 66 | assert(r, 0x7ffffffe, "-4 >>> 1 === 0x7ffffffe"); 67 | 68 | r = 1 & 1; 69 | assert(r, 1, "1 & 1 === 1"); 70 | 71 | r = 0 | 1; 72 | assert(r, 1, "0 | 1 === 1"); 73 | 74 | r = 1 ^ 1; 75 | assert(r, 0, "1 ^ 1 === 0"); 76 | 77 | r = ~1; 78 | assert(r, -2, "~1 === -2"); 79 | 80 | r = !1; 81 | assert(r, false, "!1 === false"); 82 | 83 | assert((1 < 2), true, "(1 < 2) === true"); 84 | 85 | assert((2 > 1), true, "(2 > 1) === true"); 86 | 87 | assert(('b' > 'a'), true, "('b' > 'a') === true"); 88 | 89 | assert(2 ** 8, 256, "2 ** 8 === 256"); 90 | } 91 | 92 | function test_cvt() 93 | { 94 | assert((NaN | 0) === 0); 95 | assert((Infinity | 0) === 0); 96 | assert(((-Infinity) | 0) === 0); 97 | assert(("12345" | 0) === 12345); 98 | assert(("0x12345" | 0) === 0x12345); 99 | assert(((4294967296 * 3 - 4) | 0) === -4); 100 | 101 | assert(("12345" >>> 0) === 12345); 102 | assert(("0x12345" >>> 0) === 0x12345); 103 | assert((NaN >>> 0) === 0); 104 | assert((Infinity >>> 0) === 0); 105 | assert(((-Infinity) >>> 0) === 0); 106 | assert(((4294967296 * 3 - 4) >>> 0) === (4294967296 - 4)); 107 | } 108 | 109 | function test_eq() 110 | { 111 | assert(null == undefined); 112 | assert(undefined == null); 113 | assert(true == 1); 114 | assert(0 == false); 115 | assert("" == 0); 116 | assert("123" == 123); 117 | assert("122" != 123); 118 | assert((new Number(1)) == 1); 119 | assert(2 == (new Number(2))); 120 | assert((new String("abc")) == "abc"); 121 | assert({} != "abc"); 122 | } 123 | 124 | function test_inc_dec() 125 | { 126 | var a, r; 127 | 128 | a = 1; 129 | r = a++; 130 | assert(r === 1 && a === 2, true, "++"); 131 | 132 | a = 1; 133 | r = ++a; 134 | assert(r === 2 && a === 2, true, "++"); 135 | 136 | a = 1; 137 | r = a--; 138 | assert(r === 1 && a === 0, true, "--"); 139 | 140 | a = 1; 141 | r = --a; 142 | assert(r === 0 && a === 0, true, "--"); 143 | 144 | a = {x:true}; 145 | a.x++; 146 | assert(a.x, 2, "++"); 147 | 148 | a = {x:true}; 149 | a.x--; 150 | assert(a.x, 0, "--"); 151 | 152 | a = [true]; 153 | a[0]++; 154 | assert(a[0], 2, "++"); 155 | 156 | a = {x:true}; 157 | r = a.x++; 158 | assert(r === 1 && a.x === 2, true, "++"); 159 | 160 | a = {x:true}; 161 | r = a.x--; 162 | assert(r === 1 && a.x === 0, true, "--"); 163 | 164 | a = [true]; 165 | r = a[0]++; 166 | assert(r === 1 && a[0] === 2, true, "++"); 167 | 168 | a = [true]; 169 | r = a[0]--; 170 | assert(r === 1 && a[0] === 0, true, "--"); 171 | } 172 | 173 | function F(x) 174 | { 175 | this.x = x; 176 | } 177 | 178 | function test_op2() 179 | { 180 | var a, b; 181 | a = new Object; 182 | a.x = 1; 183 | assert(a.x, 1, "new"); 184 | b = new F(2); 185 | assert(b.x, 2, "new"); 186 | 187 | a = {x : 2}; 188 | assert(("x" in a), true, "in"); 189 | assert(("y" in a), false, "in"); 190 | 191 | a = {}; 192 | assert((a instanceof Object), true, "instanceof"); 193 | assert((a instanceof String), false, "instanceof"); 194 | 195 | assert((typeof 1), "number", "typeof"); 196 | assert((typeof Object), "function", "typeof"); 197 | assert((typeof null), "object", "typeof"); 198 | assert((typeof unknown_var), "undefined", "typeof"); 199 | 200 | a = {x: 1, if: 2, async: 3}; 201 | assert(a.if === 2); 202 | assert(a.async === 3); 203 | } 204 | 205 | function test_delete() 206 | { 207 | var a, err; 208 | 209 | a = {x: 1, y: 1}; 210 | assert((delete a.x), true, "delete"); 211 | assert(("x" in a), false, "delete"); 212 | 213 | /* the following are not tested by test262 */ 214 | assert(delete "abc"[100], true); 215 | 216 | err = false; 217 | try { 218 | delete null.a; 219 | } catch(e) { 220 | err = (e instanceof TypeError); 221 | } 222 | assert(err, true, "delete"); 223 | 224 | err = false; 225 | try { 226 | a = { f() { delete super.a; } }; 227 | a.f(); 228 | } catch(e) { 229 | err = (e instanceof ReferenceError); 230 | } 231 | assert(err, true, "delete"); 232 | } 233 | 234 | function test_prototype() 235 | { 236 | function f() { } 237 | assert(f.prototype.constructor, f, "prototype"); 238 | } 239 | 240 | function test_arguments() 241 | { 242 | function f2() { 243 | assert(arguments.length, 2, "arguments"); 244 | assert(arguments[0], 1, "arguments"); 245 | assert(arguments[1], 3, "arguments"); 246 | } 247 | f2(1, 3); 248 | } 249 | 250 | function test_class() 251 | { 252 | var o; 253 | class C { 254 | constructor() { 255 | this.x = 10; 256 | } 257 | f() { 258 | return 1; 259 | } 260 | static F() { 261 | return -1; 262 | } 263 | get y() { 264 | return 12; 265 | } 266 | }; 267 | class D extends C { 268 | constructor() { 269 | super(); 270 | this.z = 20; 271 | } 272 | g() { 273 | return 2; 274 | } 275 | static G() { 276 | return -2; 277 | } 278 | h() { 279 | return super.f(); 280 | } 281 | static H() { 282 | return super["F"](); 283 | } 284 | } 285 | 286 | assert(C.F() === -1); 287 | assert(Object.getOwnPropertyDescriptor(C.prototype, "y").get.name === "get y"); 288 | 289 | o = new C(); 290 | assert(o.f() === 1); 291 | assert(o.x === 10); 292 | 293 | assert(D.F() === -1); 294 | assert(D.G() === -2); 295 | assert(D.H() === -1); 296 | 297 | o = new D(); 298 | assert(o.f() === 1); 299 | assert(o.g() === 2); 300 | assert(o.x === 10); 301 | assert(o.z === 20); 302 | assert(o.h() === 1); 303 | 304 | /* test class name scope */ 305 | var E1 = class E { static F() { return E; } }; 306 | assert(E1 === E1.F()); 307 | }; 308 | 309 | function test_template() 310 | { 311 | var a, b; 312 | b = 123; 313 | a = `abc${b}d`; 314 | assert(a, "abc123d"); 315 | 316 | a = String.raw `abc${b}d`; 317 | assert(a, "abc123d"); 318 | 319 | a = "aaa"; 320 | b = "bbb"; 321 | assert(`aaa${a, b}ccc`, "aaabbbccc"); 322 | } 323 | 324 | function test_template_skip() 325 | { 326 | var a = "Bar"; 327 | var { b = `${a + `a${a}` }baz` } = {}; 328 | assert(b, "BaraBarbaz"); 329 | } 330 | 331 | function test_object_literal() 332 | { 333 | var x = 0, get = 1, set = 2; async = 3; 334 | a = { get: 2, set: 3, async: 4 }; 335 | assert(JSON.stringify(a), '{"get":2,"set":3,"async":4}'); 336 | 337 | a = { x, get, set, async }; 338 | assert(JSON.stringify(a), '{"x":0,"get":1,"set":2,"async":3}'); 339 | } 340 | 341 | function test_regexp_skip() 342 | { 343 | var a, b; 344 | [a, b = /abc\(/] = [1]; 345 | assert(a === 1); 346 | 347 | [a, b =/abc\(/] = [2]; 348 | assert(a === 2); 349 | } 350 | 351 | function test_labels() 352 | { 353 | do x: { break x; } while(0); 354 | if (1) 355 | x: { break x; } 356 | else 357 | x: { break x; } 358 | with ({}) x: { break x; }; 359 | while (0) x: { break x; }; 360 | } 361 | 362 | test_op1(); 363 | test_cvt(); 364 | test_eq(); 365 | test_inc_dec(); 366 | test_op2(); 367 | test_delete(); 368 | test_prototype(); 369 | test_arguments(); 370 | test_class(); 371 | test_template(); 372 | test_template_skip(); 373 | test_object_literal(); 374 | test_regexp_skip(); 375 | test_labels(); 376 | -------------------------------------------------------------------------------- /src/runtime/quickjs-js-math.h: -------------------------------------------------------------------------------- 1 | #ifndef QUICKJS_QUICKJS_JS_MATH_H 2 | #define QUICKJS_QUICKJS_JS_MATH_H 3 | /* precondition: a and b are not NaN */ 4 | static double js_fmin(double a, double b) 5 | { 6 | if (a == 0 && b == 0) { 7 | JSFloat64Union a1, b1; 8 | a1.d = a; 9 | b1.d = b; 10 | a1.u64 |= b1.u64; 11 | return a1.d; 12 | } else { 13 | return fmin(a, b); 14 | } 15 | } 16 | 17 | /* precondition: a and b are not NaN */ 18 | static double js_fmax(double a, double b) 19 | { 20 | if (a == 0 && b == 0) { 21 | JSFloat64Union a1, b1; 22 | a1.d = a; 23 | b1.d = b; 24 | a1.u64 &= b1.u64; 25 | return a1.d; 26 | } else { 27 | return fmax(a, b); 28 | } 29 | } 30 | 31 | static JSValue js_math_min_max(JSContext *ctx, JSValueConst this_val, 32 | int argc, JSValueConst *argv, int magic) 33 | { 34 | BOOL is_max = magic; 35 | double r, a; 36 | int i; 37 | uint32_t tag; 38 | 39 | if (unlikely(argc == 0)) { 40 | #ifdef _MSC_VER 41 | return __JS_NewFloat64(ctx, is_max ? INFINITY : INFINITY); 42 | #else 43 | return __JS_NewFloat64(ctx, is_max ? -1.0 / 0.0 : 1.0 / 0.0); 44 | #endif 45 | } 46 | 47 | tag = JS_VALUE_GET_TAG(argv[0]); 48 | if (tag == JS_TAG_INT) { 49 | int a1, r1 = JS_VALUE_GET_INT(argv[0]); 50 | for(i = 1; i < argc; i++) { 51 | tag = JS_VALUE_GET_TAG(argv[i]); 52 | if (tag != JS_TAG_INT) { 53 | r = r1; 54 | goto generic_case; 55 | } 56 | a1 = JS_VALUE_GET_INT(argv[i]); 57 | if (is_max) 58 | r1 = max_int(r1, a1); 59 | else 60 | r1 = min_int(r1, a1); 61 | 62 | } 63 | return JS_NewInt32(ctx, r1); 64 | } else { 65 | if (JS_ToFloat64(ctx, &r, argv[0])) 66 | return JS_EXCEPTION; 67 | i = 1; 68 | generic_case: 69 | while (i < argc) { 70 | if (JS_ToFloat64(ctx, &a, argv[i])) 71 | return JS_EXCEPTION; 72 | if (!isnan(r)) { 73 | if (isnan(a)) { 74 | r = a; 75 | } else { 76 | if (is_max) 77 | r = js_fmax(r, a); 78 | else 79 | r = js_fmin(r, a); 80 | } 81 | } 82 | i++; 83 | } 84 | return JS_NewFloat64(ctx, r); 85 | } 86 | } 87 | 88 | static double js_math_sign(double a) 89 | { 90 | if (isnan(a) || a == 0.0) 91 | return a; 92 | if (a < 0) 93 | return -1; 94 | else 95 | return 1; 96 | } 97 | 98 | static double js_math_round(double a) 99 | { 100 | JSFloat64Union u; 101 | uint64_t frac_mask, one; 102 | unsigned int e, s; 103 | 104 | u.d = a; 105 | e = (u.u64 >> 52) & 0x7ff; 106 | if (e < 1023) { 107 | /* abs(a) < 1 */ 108 | if (e == (1023 - 1) && u.u64 != 0xbfe0000000000000) { 109 | /* abs(a) > 0.5 or a = 0.5: return +/-1.0 */ 110 | u.u64 = (u.u64 & ((uint64_t)1 << 63)) | ((uint64_t)1023 << 52); 111 | } else { 112 | /* return +/-0.0 */ 113 | u.u64 &= (uint64_t)1 << 63; 114 | } 115 | } else if (e < (1023 + 52)) { 116 | s = u.u64 >> 63; 117 | one = (uint64_t)1 << (52 - (e - 1023)); 118 | frac_mask = one - 1; 119 | u.u64 += (one >> 1) - s; 120 | u.u64 &= ~frac_mask; /* truncate to an integer */ 121 | } 122 | /* otherwise: abs(a) >= 2^52, or NaN, +/-Infinity: no change */ 123 | return u.d; 124 | } 125 | 126 | static JSValue js_math_hypot(JSContext *ctx, JSValueConst this_val, 127 | int argc, JSValueConst *argv) 128 | { 129 | double r, a; 130 | int i; 131 | 132 | r = 0; 133 | if (argc > 0) { 134 | if (JS_ToFloat64(ctx, &r, argv[0])) 135 | return JS_EXCEPTION; 136 | if (argc == 1) { 137 | r = fabs(r); 138 | } else { 139 | /* use the built-in function to minimize precision loss */ 140 | for (i = 1; i < argc; i++) { 141 | if (JS_ToFloat64(ctx, &a, argv[i])) 142 | return JS_EXCEPTION; 143 | r = hypot(r, a); 144 | } 145 | } 146 | } 147 | return JS_NewFloat64(ctx, r); 148 | } 149 | 150 | static double js_math_fround(double a) 151 | { 152 | return (float)a; 153 | } 154 | 155 | static JSValue js_math_imul(JSContext *ctx, JSValueConst this_val, 156 | int argc, JSValueConst *argv) 157 | { 158 | int a, b; 159 | 160 | if (JS_ToInt32(ctx, &a, argv[0])) 161 | return JS_EXCEPTION; 162 | if (JS_ToInt32(ctx, &b, argv[1])) 163 | return JS_EXCEPTION; 164 | /* purposely ignoring overflow */ 165 | return JS_NewInt32(ctx, a * b); 166 | } 167 | 168 | static JSValue js_math_clz32(JSContext *ctx, JSValueConst this_val, 169 | int argc, JSValueConst *argv) 170 | { 171 | uint32_t a, r; 172 | 173 | if (JS_ToUint32(ctx, &a, argv[0])) 174 | return JS_EXCEPTION; 175 | if (a == 0) 176 | r = 32; 177 | else 178 | r = clz32(a); 179 | return JS_NewInt32(ctx, r); 180 | } 181 | 182 | /* xorshift* random number generator by Marsaglia */ 183 | static uint64_t xorshift64star(uint64_t *pstate) 184 | { 185 | uint64_t x; 186 | x = *pstate; 187 | x ^= x >> 12; 188 | x ^= x << 25; 189 | x ^= x >> 27; 190 | *pstate = x; 191 | return x * 0x2545F4914F6CDD1D; 192 | } 193 | 194 | static void js_random_init(JSContext *ctx) 195 | { 196 | struct timeval tv; 197 | gettimeofday(&tv, NULL); 198 | ctx->random_state = ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec; 199 | /* the state must be non zero */ 200 | if (ctx->random_state == 0) 201 | ctx->random_state = 1; 202 | } 203 | 204 | static JSValue js_math_random(JSContext *ctx, JSValueConst this_val, 205 | int argc, JSValueConst *argv) 206 | { 207 | JSFloat64Union u; 208 | uint64_t v; 209 | 210 | v = xorshift64star(&ctx->random_state); 211 | /* 1.0 <= u.d < 2 */ 212 | u.u64 = ((uint64_t)0x3ff << 52) | (v >> 12); 213 | return __JS_NewFloat64(ctx, u.d - 1.0); 214 | } 215 | 216 | static const JSCFunctionListEntry js_math_funcs[] = { 217 | JS_CFUNC_MAGIC_DEF("min", 2, js_math_min_max, 0 ), 218 | JS_CFUNC_MAGIC_DEF("max", 2, js_math_min_max, 1 ), 219 | JS_CFUNC_SPECIAL_DEF("abs", 1, f_f, fabs ), 220 | JS_CFUNC_SPECIAL_DEF("floor", 1, f_f, floor ), 221 | JS_CFUNC_SPECIAL_DEF("ceil", 1, f_f, ceil ), 222 | JS_CFUNC_SPECIAL_DEF("round", 1, f_f, js_math_round ), 223 | JS_CFUNC_SPECIAL_DEF("sqrt", 1, f_f, sqrt ), 224 | 225 | JS_CFUNC_SPECIAL_DEF("acos", 1, f_f, acos ), 226 | JS_CFUNC_SPECIAL_DEF("asin", 1, f_f, asin ), 227 | JS_CFUNC_SPECIAL_DEF("atan", 1, f_f, atan ), 228 | JS_CFUNC_SPECIAL_DEF("atan2", 2, f_f_f, atan2 ), 229 | JS_CFUNC_SPECIAL_DEF("cos", 1, f_f, cos ), 230 | JS_CFUNC_SPECIAL_DEF("exp", 1, f_f, exp ), 231 | JS_CFUNC_SPECIAL_DEF("log", 1, f_f, log ), 232 | JS_CFUNC_SPECIAL_DEF("pow", 2, f_f_f, js_pow ), 233 | JS_CFUNC_SPECIAL_DEF("sin", 1, f_f, sin ), 234 | JS_CFUNC_SPECIAL_DEF("tan", 1, f_f, tan ), 235 | /* ES6 */ 236 | JS_CFUNC_SPECIAL_DEF("trunc", 1, f_f, trunc ), 237 | JS_CFUNC_SPECIAL_DEF("sign", 1, f_f, js_math_sign ), 238 | JS_CFUNC_SPECIAL_DEF("cosh", 1, f_f, cosh ), 239 | JS_CFUNC_SPECIAL_DEF("sinh", 1, f_f, sinh ), 240 | JS_CFUNC_SPECIAL_DEF("tanh", 1, f_f, tanh ), 241 | JS_CFUNC_SPECIAL_DEF("acosh", 1, f_f, acosh ), 242 | JS_CFUNC_SPECIAL_DEF("asinh", 1, f_f, asinh ), 243 | JS_CFUNC_SPECIAL_DEF("atanh", 1, f_f, atanh ), 244 | JS_CFUNC_SPECIAL_DEF("expm1", 1, f_f, expm1 ), 245 | JS_CFUNC_SPECIAL_DEF("log1p", 1, f_f, log1p ), 246 | JS_CFUNC_SPECIAL_DEF("log2", 1, f_f, log2 ), 247 | JS_CFUNC_SPECIAL_DEF("log10", 1, f_f, log10 ), 248 | JS_CFUNC_SPECIAL_DEF("cbrt", 1, f_f, cbrt ), 249 | JS_CFUNC_DEF("hypot", 2, js_math_hypot ), 250 | JS_CFUNC_DEF("random", 0, js_math_random ), 251 | JS_CFUNC_SPECIAL_DEF("fround", 1, f_f, js_math_fround ), 252 | JS_CFUNC_DEF("imul", 2, js_math_imul ), 253 | JS_CFUNC_DEF("clz32", 1, js_math_clz32 ), 254 | JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Math", JS_PROP_CONFIGURABLE ), 255 | JS_PROP_DOUBLE_DEF("E", 2.718281828459045, 0 ), 256 | JS_PROP_DOUBLE_DEF("LN10", 2.302585092994046, 0 ), 257 | JS_PROP_DOUBLE_DEF("LN2", 0.6931471805599453, 0 ), 258 | JS_PROP_DOUBLE_DEF("LOG2E", 1.4426950408889634, 0 ), 259 | JS_PROP_DOUBLE_DEF("LOG10E", 0.4342944819032518, 0 ), 260 | JS_PROP_DOUBLE_DEF("PI", 3.141592653589793, 0 ), 261 | JS_PROP_DOUBLE_DEF("SQRT1_2", 0.7071067811865476, 0 ), 262 | JS_PROP_DOUBLE_DEF("SQRT2", 1.4142135623730951, 0 ), 263 | }; 264 | 265 | static const JSCFunctionListEntry js_math_obj[] = { 266 | JS_OBJECT_DEF("Math", js_math_funcs, countof(js_math_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ), 267 | }; 268 | 269 | #endif //QUICKJS_QUICKJS_JS_MATH_H 270 | -------------------------------------------------------------------------------- /src/quickjs-generator.h: -------------------------------------------------------------------------------- 1 | #ifndef QUICKJS_QUICKJS_GENERATOR_H 2 | #define QUICKJS_QUICKJS_GENERATOR_H 3 | typedef enum JSGeneratorStateEnum { 4 | JS_GENERATOR_STATE_SUSPENDED_START, 5 | JS_GENERATOR_STATE_SUSPENDED_YIELD, 6 | JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR, 7 | JS_GENERATOR_STATE_EXECUTING, 8 | JS_GENERATOR_STATE_COMPLETED, 9 | } JSGeneratorStateEnum; 10 | 11 | typedef struct JSGeneratorData { 12 | JSGeneratorStateEnum state; 13 | JSAsyncFunctionState func_state; 14 | } JSGeneratorData; 15 | 16 | static void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s) 17 | { 18 | if (s->state == JS_GENERATOR_STATE_COMPLETED) 19 | return; 20 | async_func_free(rt, &s->func_state); 21 | s->state = JS_GENERATOR_STATE_COMPLETED; 22 | } 23 | 24 | static void js_generator_finalizer(JSRuntime *rt, JSValue obj) 25 | { 26 | JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR); 27 | 28 | if (s) { 29 | free_generator_stack_rt(rt, s); 30 | js_free_rt(rt, s); 31 | } 32 | } 33 | 34 | static void free_generator_stack(JSContext *ctx, JSGeneratorData *s) 35 | { 36 | free_generator_stack_rt(ctx->rt, s); 37 | } 38 | 39 | static void js_generator_mark(JSRuntime *rt, JSValueConst val, 40 | JS_MarkFunc *mark_func) 41 | { 42 | JSObject *p = JS_VALUE_GET_OBJ(val); 43 | JSGeneratorData *s = p->u.generator_data; 44 | 45 | if (!s || s->state == JS_GENERATOR_STATE_COMPLETED) 46 | return; 47 | async_func_mark(rt, &s->func_state, mark_func); 48 | } 49 | 50 | /* XXX: use enum */ 51 | #define GEN_MAGIC_NEXT 0 52 | #define GEN_MAGIC_RETURN 1 53 | #define GEN_MAGIC_THROW 2 54 | 55 | static JSValue js_generator_next(JSContext *ctx, JSValueConst this_val, 56 | int argc, JSValueConst *argv, 57 | BOOL *pdone, int magic) 58 | { 59 | JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR); 60 | JSStackFrame *sf; 61 | JSValue ret, func_ret; 62 | JSValueConst iter_args[1]; 63 | 64 | *pdone = TRUE; 65 | if (!s) 66 | return JS_ThrowTypeError(ctx, "not a generator"); 67 | sf = &s->func_state.frame; 68 | redo: 69 | switch(s->state) { 70 | default: 71 | case JS_GENERATOR_STATE_SUSPENDED_START: 72 | if (magic == GEN_MAGIC_NEXT) { 73 | goto exec_no_arg; 74 | } else { 75 | free_generator_stack(ctx, s); 76 | goto done; 77 | } 78 | break; 79 | case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR: 80 | { 81 | int done; 82 | JSValue method, iter_obj; 83 | 84 | iter_obj = sf->cur_sp[-2]; 85 | if (magic == GEN_MAGIC_NEXT) { 86 | method = JS_DupValue(ctx, sf->cur_sp[-1]); 87 | } else { 88 | method = JS_GetProperty(ctx, iter_obj, 89 | magic == GEN_MAGIC_RETURN ? 90 | JS_ATOM_return : JS_ATOM_throw); 91 | if (JS_IsException(method)) 92 | goto iter_exception; 93 | } 94 | if (magic != GEN_MAGIC_NEXT && 95 | (JS_IsUndefined(method) || JS_IsNull(method))) { 96 | /* default action */ 97 | if (magic == GEN_MAGIC_RETURN) { 98 | ret = JS_DupValue(ctx, argv[0]); 99 | goto iter_done; 100 | } else { 101 | if (JS_IteratorClose(ctx, iter_obj, FALSE)) 102 | goto iter_exception; 103 | JS_ThrowTypeError(ctx, "iterator does not have a throw method"); 104 | goto iter_exception; 105 | } 106 | } 107 | ret = JS_IteratorNext2(ctx, iter_obj, method, argc, argv, &done); 108 | JS_FreeValue(ctx, method); 109 | if (JS_IsException(ret)) { 110 | iter_exception: 111 | goto exec_throw; 112 | } 113 | /* if not done, the iterator returns the exact object 114 | returned by 'method' */ 115 | if (done == 2) { 116 | JSValue done_val, value; 117 | done_val = JS_GetProperty(ctx, ret, JS_ATOM_done); 118 | if (JS_IsException(done_val)) { 119 | JS_FreeValue(ctx, ret); 120 | goto iter_exception; 121 | } 122 | done = JS_ToBoolFree(ctx, done_val); 123 | if (done) { 124 | value = JS_GetProperty(ctx, ret, JS_ATOM_value); 125 | JS_FreeValue(ctx, ret); 126 | if (JS_IsException(value)) 127 | goto iter_exception; 128 | ret = value; 129 | goto iter_done; 130 | } else { 131 | *pdone = 2; 132 | } 133 | } else { 134 | if (done) { 135 | /* 'yield *' returns the value associated to done = true */ 136 | iter_done: 137 | JS_FreeValue(ctx, sf->cur_sp[-2]); 138 | JS_FreeValue(ctx, sf->cur_sp[-1]); 139 | sf->cur_sp--; 140 | goto exec_arg; 141 | } else { 142 | *pdone = FALSE; 143 | } 144 | } 145 | break; 146 | } 147 | break; 148 | case JS_GENERATOR_STATE_SUSPENDED_YIELD: 149 | /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */ 150 | ret = JS_DupValue(ctx, argv[0]); 151 | if (magic == GEN_MAGIC_THROW) { 152 | JS_Throw(ctx, ret); 153 | exec_throw: 154 | s->func_state.throw_flag = TRUE; 155 | } else { 156 | exec_arg: 157 | sf->cur_sp[-1] = ret; 158 | sf->cur_sp[0] = JS_NewBool(ctx, (magic == GEN_MAGIC_RETURN)); 159 | sf->cur_sp++; 160 | exec_no_arg: 161 | s->func_state.throw_flag = FALSE; 162 | } 163 | s->state = JS_GENERATOR_STATE_EXECUTING; 164 | func_ret = async_func_resume(ctx, &s->func_state); 165 | s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD; 166 | if (JS_IsException(func_ret)) { 167 | /* finalize the execution in case of exception */ 168 | free_generator_stack(ctx, s); 169 | return func_ret; 170 | } 171 | if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) { 172 | if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) { 173 | /* 'yield *' */ 174 | s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR; 175 | iter_args[0] = JS_UNDEFINED; 176 | argc = 1; 177 | argv = iter_args; 178 | goto redo; 179 | } else { 180 | /* get the return the yield value at the top of the stack */ 181 | ret = sf->cur_sp[-1]; 182 | sf->cur_sp[-1] = JS_UNDEFINED; 183 | *pdone = FALSE; 184 | } 185 | } else { 186 | /* end of iterator */ 187 | ret = sf->cur_sp[-1]; 188 | sf->cur_sp[-1] = JS_UNDEFINED; 189 | JS_FreeValue(ctx, func_ret); 190 | free_generator_stack(ctx, s); 191 | } 192 | break; 193 | case JS_GENERATOR_STATE_COMPLETED: 194 | done: 195 | /* execution is finished */ 196 | switch(magic) { 197 | default: 198 | case GEN_MAGIC_NEXT: 199 | ret = JS_UNDEFINED; 200 | break; 201 | case GEN_MAGIC_RETURN: 202 | ret = JS_DupValue(ctx, argv[0]); 203 | break; 204 | case GEN_MAGIC_THROW: 205 | ret = JS_Throw(ctx, JS_DupValue(ctx, argv[0])); 206 | break; 207 | } 208 | break; 209 | case JS_GENERATOR_STATE_EXECUTING: 210 | ret = JS_ThrowTypeError(ctx, "cannot invoke a running generator"); 211 | break; 212 | } 213 | return ret; 214 | } 215 | 216 | static JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj, 217 | JSValueConst this_obj, 218 | int argc, JSValueConst *argv, 219 | int flags) 220 | { 221 | JSValue obj, func_ret; 222 | JSGeneratorData *s; 223 | 224 | s = js_mallocz(ctx, sizeof(*s)); 225 | if (!s) 226 | return JS_EXCEPTION; 227 | s->state = JS_GENERATOR_STATE_SUSPENDED_START; 228 | if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { 229 | s->state = JS_GENERATOR_STATE_COMPLETED; 230 | goto fail; 231 | } 232 | 233 | /* execute the function up to 'OP_initial_yield' */ 234 | func_ret = async_func_resume(ctx, &s->func_state); 235 | if (JS_IsException(func_ret)) 236 | goto fail; 237 | JS_FreeValue(ctx, func_ret); 238 | 239 | obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR); 240 | if (JS_IsException(obj)) 241 | goto fail; 242 | JS_SetOpaque(obj, s); 243 | return obj; 244 | fail: 245 | free_generator_stack_rt(ctx->rt, s); 246 | js_free(ctx, s); 247 | return JS_EXCEPTION; 248 | } 249 | #endif //QUICKJS_QUICKJS_GENERATOR_H 250 | -------------------------------------------------------------------------------- /src/utils/cutils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * C utilities 3 | * 4 | * Copyright (c) 2017 Fabrice Bellard 5 | * Copyright (c) 2018 Charlie Gordon 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining a copy 8 | * of this software and associated documentation files (the "Software"), to deal 9 | * in the Software without restriction, including without limitation the rights 10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | * copies of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included in 15 | * all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | * THE SOFTWARE. 24 | */ 25 | #ifndef CUTILS_H 26 | #define CUTILS_H 27 | 28 | #include 29 | #include 30 | 31 | #ifdef _MSC_VER 32 | #include 33 | #endif 34 | 35 | #ifdef _MSC_VER 36 | #define ssize_t size_t 37 | #endif 38 | /* set if CPU is big endian */ 39 | #undef WORDS_BIGENDIAN 40 | 41 | #ifdef _MSC_VER 42 | #define likely(x) (x) 43 | #define unlikely(x) (x) 44 | #define force_inline __forceinline 45 | #define no_inline __declspec(noinline) 46 | #define __maybe_unused 47 | #else 48 | #define likely(x) __builtin_expect(!!(x), 1) 49 | #define unlikely(x) __builtin_expect(!!(x), 0) 50 | #define force_inline inline __attribute__((always_inline)) 51 | #define no_inline __attribute__((noinline)) 52 | #define __maybe_unused __attribute__((unused)) 53 | #endif 54 | 55 | #define xglue(x, y) x ## y 56 | #define glue(x, y) xglue(x, y) 57 | #define stringify(s) tostring(s) 58 | #define tostring(s) #s 59 | 60 | #ifndef offsetof 61 | #define offsetof(type, field) ((size_t) &((type *)0)->field) 62 | #endif 63 | #ifndef countof 64 | #define countof(x) (sizeof(x) / sizeof((x)[0])) 65 | #endif 66 | 67 | typedef int BOOL; 68 | 69 | #ifndef FALSE 70 | enum { 71 | FALSE = 0, 72 | TRUE = 1, 73 | }; 74 | #endif 75 | 76 | void pstrcpy(char *buf, int buf_size, const char *str); 77 | char *pstrcat(char *buf, int buf_size, const char *s); 78 | int strstart(const char *str, const char *val, const char **ptr); 79 | int has_suffix(const char *str, const char *suffix); 80 | 81 | static inline int max_int(int a, int b) 82 | { 83 | if (a > b) 84 | return a; 85 | else 86 | return b; 87 | } 88 | 89 | static inline int min_int(int a, int b) 90 | { 91 | if (a < b) 92 | return a; 93 | else 94 | return b; 95 | } 96 | 97 | static inline uint32_t max_uint32(uint32_t a, uint32_t b) 98 | { 99 | if (a > b) 100 | return a; 101 | else 102 | return b; 103 | } 104 | 105 | static inline uint32_t min_uint32(uint32_t a, uint32_t b) 106 | { 107 | if (a < b) 108 | return a; 109 | else 110 | return b; 111 | } 112 | 113 | static inline int64_t max_int64(int64_t a, int64_t b) 114 | { 115 | if (a > b) 116 | return a; 117 | else 118 | return b; 119 | } 120 | 121 | static inline int64_t min_int64(int64_t a, int64_t b) 122 | { 123 | if (a < b) 124 | return a; 125 | else 126 | return b; 127 | } 128 | 129 | /* WARNING: undefined if a = 0 */ 130 | static inline int clz32(unsigned int a) 131 | { 132 | #ifdef _MSC_VER 133 | unsigned long idx; 134 | _BitScanReverse(&idx, a); 135 | return 31 ^ idx; 136 | #else 137 | return __builtin_clz(a); 138 | #endif 139 | } 140 | 141 | /* WARNING: undefined if a = 0 */ 142 | static inline int clz64(uint64_t a) 143 | { 144 | #ifdef _MSC_VER 145 | unsigned long idx; 146 | _BitScanReverse64(&idx, a); 147 | return 63 ^ idx; 148 | #else 149 | return __builtin_clzll(a); 150 | #endif 151 | } 152 | 153 | /* WARNING: undefined if a = 0 */ 154 | static inline int ctz32(unsigned int a) 155 | { 156 | #ifdef _MSC_VER 157 | unsigned long idx; 158 | _BitScanForward(&idx, a); 159 | return 31 ^ idx; 160 | #else 161 | return __builtin_ctz(a); 162 | #endif 163 | } 164 | 165 | /* WARNING: undefined if a = 0 */ 166 | static inline int ctz64(uint64_t a) 167 | { 168 | #ifdef _MSC_VER 169 | unsigned long idx; 170 | _BitScanForward64(&idx, a); 171 | return 63 ^ idx; 172 | #else 173 | return __builtin_ctzll(a); 174 | #endif 175 | } 176 | 177 | #ifdef _MSC_VER 178 | #pragma pack(push, 1) 179 | struct packed_u64 { 180 | uint64_t v; 181 | }; 182 | 183 | struct packed_u32 { 184 | uint32_t v; 185 | }; 186 | 187 | struct packed_u16 { 188 | uint16_t v; 189 | }; 190 | #pragma pack(pop) 191 | #else 192 | struct __attribute__((packed)) packed_u64 { 193 | uint64_t v; 194 | }; 195 | 196 | struct __attribute__((packed)) packed_u32 { 197 | uint32_t v; 198 | }; 199 | 200 | struct __attribute__((packed)) packed_u16 { 201 | uint16_t v; 202 | }; 203 | #endif 204 | 205 | static inline uint64_t get_u64(const uint8_t *tab) 206 | { 207 | return ((const struct packed_u64 *)tab)->v; 208 | } 209 | 210 | static inline int64_t get_i64(const uint8_t *tab) 211 | { 212 | return (int64_t)((const struct packed_u64 *)tab)->v; 213 | } 214 | 215 | static inline void put_u64(uint8_t *tab, uint64_t val) 216 | { 217 | ((struct packed_u64 *)tab)->v = val; 218 | } 219 | 220 | static inline uint32_t get_u32(const uint8_t *tab) 221 | { 222 | return ((const struct packed_u32 *)tab)->v; 223 | } 224 | 225 | static inline int32_t get_i32(const uint8_t *tab) 226 | { 227 | return (int32_t)((const struct packed_u32 *)tab)->v; 228 | } 229 | 230 | static inline void put_u32(uint8_t *tab, uint32_t val) 231 | { 232 | ((struct packed_u32 *)tab)->v = val; 233 | } 234 | 235 | static inline uint32_t get_u16(const uint8_t *tab) 236 | { 237 | return ((const struct packed_u16 *)tab)->v; 238 | } 239 | 240 | static inline int32_t get_i16(const uint8_t *tab) 241 | { 242 | return (int16_t)((const struct packed_u16 *)tab)->v; 243 | } 244 | 245 | static inline void put_u16(uint8_t *tab, uint16_t val) 246 | { 247 | ((struct packed_u16 *)tab)->v = val; 248 | } 249 | 250 | static inline uint32_t get_u8(const uint8_t *tab) 251 | { 252 | return *tab; 253 | } 254 | 255 | static inline int32_t get_i8(const uint8_t *tab) 256 | { 257 | return (int8_t)*tab; 258 | } 259 | 260 | static inline void put_u8(uint8_t *tab, uint8_t val) 261 | { 262 | *tab = val; 263 | } 264 | 265 | static inline uint16_t bswap16(uint16_t x) 266 | { 267 | return (x >> 8) | (x << 8); 268 | } 269 | 270 | static inline uint32_t bswap32(uint32_t v) 271 | { 272 | return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >> 8) | 273 | ((v & 0x0000ff00) << 8) | ((v & 0x000000ff) << 24); 274 | } 275 | 276 | static inline uint64_t bswap64(uint64_t v) 277 | { 278 | return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) | 279 | ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) | 280 | ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) | 281 | ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) | 282 | ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) | 283 | ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) | 284 | ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) | 285 | ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8)); 286 | } 287 | 288 | /* XXX: should take an extra argument to pass slack information to the caller */ 289 | typedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size); 290 | 291 | typedef struct DynBuf { 292 | uint8_t *buf; 293 | size_t size; 294 | size_t allocated_size; 295 | BOOL error; /* true if a memory allocation error occurred */ 296 | DynBufReallocFunc *realloc_func; 297 | void *opaque; /* for realloc_func */ 298 | } DynBuf; 299 | 300 | void dbuf_init(DynBuf *s); 301 | void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func); 302 | int dbuf_realloc(DynBuf *s, size_t new_size); 303 | int dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len); 304 | int dbuf_put(DynBuf *s, const uint8_t *data, size_t len); 305 | int dbuf_put_self(DynBuf *s, size_t offset, size_t len); 306 | int dbuf_putc(DynBuf *s, uint8_t c); 307 | int dbuf_putstr(DynBuf *s, const char *str); 308 | static inline int dbuf_put_u16(DynBuf *s, uint16_t val) 309 | { 310 | return dbuf_put(s, (uint8_t *)&val, 2); 311 | } 312 | static inline int dbuf_put_u32(DynBuf *s, uint32_t val) 313 | { 314 | return dbuf_put(s, (uint8_t *)&val, 4); 315 | } 316 | static inline int dbuf_put_u64(DynBuf *s, uint64_t val) 317 | { 318 | return dbuf_put(s, (uint8_t *)&val, 8); 319 | } 320 | 321 | int 322 | #ifndef _MSC_VER 323 | __attribute__((format(printf, 2, 3))) 324 | #endif 325 | dbuf_printf(DynBuf *s, const char *fmt, ...); 326 | 327 | void dbuf_free(DynBuf *s); 328 | static inline BOOL dbuf_error(DynBuf *s) { 329 | return s->error; 330 | } 331 | 332 | #define UTF8_CHAR_LEN_MAX 6 333 | 334 | int unicode_to_utf8(uint8_t *buf, unsigned int c); 335 | int unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp); 336 | 337 | static inline int from_hex(int c) 338 | { 339 | if (c >= '0' && c <= '9') 340 | return c - '0'; 341 | else if (c >= 'A' && c <= 'F') 342 | return c - 'A' + 10; 343 | else if (c >= 'a' && c <= 'f') 344 | return c - 'a' + 10; 345 | else 346 | return -1; 347 | } 348 | 349 | void rqsort(void *base, size_t nmemb, size_t size, 350 | int (*cmp)(const void *, const void *, void *), 351 | void *arg); 352 | 353 | #endif /* CUTILS_H */ 354 | -------------------------------------------------------------------------------- /tests/test_bignum.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function assert(actual, expected, message) { 4 | if (arguments.length == 1) 5 | expected = true; 6 | 7 | if (actual === expected) 8 | return; 9 | 10 | if (actual !== null && expected !== null 11 | && typeof actual == 'object' && typeof expected == 'object' 12 | && actual.toString() === expected.toString()) 13 | return; 14 | 15 | throw Error("assertion failed: got |" + actual + "|" + 16 | ", expected |" + expected + "|" + 17 | (message ? " (" + message + ")" : "")); 18 | } 19 | 20 | function assertThrows(err, func) 21 | { 22 | var ex; 23 | ex = false; 24 | try { 25 | func(); 26 | } catch(e) { 27 | ex = true; 28 | assert(e instanceof err); 29 | } 30 | assert(ex, true, "exception expected"); 31 | } 32 | 33 | // load more elaborate version of assert if available 34 | try { __loadScript("test_assert.js"); } catch(e) {} 35 | 36 | /*----------------*/ 37 | 38 | function bigint_pow(a, n) 39 | { 40 | var r, i; 41 | r = 1n; 42 | for(i = 0n; i < n; i++) 43 | r *= a; 44 | return r; 45 | } 46 | 47 | /* a must be < b */ 48 | function test_less(a, b) 49 | { 50 | assert(a < b); 51 | assert(!(b < a)); 52 | assert(a <= b); 53 | assert(!(b <= a)); 54 | assert(b > a); 55 | assert(!(a > b)); 56 | assert(b >= a); 57 | assert(!(a >= b)); 58 | assert(a != b); 59 | assert(!(a == b)); 60 | } 61 | 62 | /* a must be numerically equal to b */ 63 | function test_eq(a, b) 64 | { 65 | assert(a == b); 66 | assert(b == a); 67 | assert(!(a != b)); 68 | assert(!(b != a)); 69 | assert(a <= b); 70 | assert(b <= a); 71 | assert(!(a < b)); 72 | assert(a >= b); 73 | assert(b >= a); 74 | assert(!(a > b)); 75 | } 76 | 77 | function test_bigint1() 78 | { 79 | var a, r; 80 | 81 | test_less(2n, 3n); 82 | test_eq(3n, 3n); 83 | 84 | test_less(2, 3n); 85 | test_eq(3, 3n); 86 | 87 | test_less(2.1, 3n); 88 | test_eq(Math.sqrt(4), 2n); 89 | 90 | a = bigint_pow(3n, 100n); 91 | assert((a - 1n) != a); 92 | assert(a == 515377520732011331036461129765621272702107522001n); 93 | assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1n); 94 | 95 | r = 1n << 31n; 96 | assert(r, 2147483648n, "1 << 31n === 2147483648n"); 97 | 98 | r = 1n << 32n; 99 | assert(r, 4294967296n, "1 << 32n === 4294967296n"); 100 | } 101 | 102 | function test_bigint2() 103 | { 104 | assert(BigInt(""), 0n); 105 | assert(BigInt(" 123"), 123n); 106 | assert(BigInt(" 123 "), 123n); 107 | assertThrows(SyntaxError, () => { BigInt("+") } ); 108 | assertThrows(SyntaxError, () => { BigInt("-") } ); 109 | assertThrows(SyntaxError, () => { BigInt("\x00a") } ); 110 | assertThrows(SyntaxError, () => { BigInt(" 123 r") } ); 111 | } 112 | 113 | function test_divrem(div1, a, b, q) 114 | { 115 | var div, divrem, t; 116 | div = BigInt[div1]; 117 | divrem = BigInt[div1 + "rem"]; 118 | assert(div(a, b) == q); 119 | t = divrem(a, b); 120 | assert(t[0] == q); 121 | assert(a == b * q + t[1]); 122 | } 123 | 124 | function test_idiv1(div, a, b, r) 125 | { 126 | test_divrem(div, a, b, r[0]); 127 | test_divrem(div, -a, b, r[1]); 128 | test_divrem(div, a, -b, r[2]); 129 | test_divrem(div, -a, -b, r[3]); 130 | } 131 | 132 | /* QuickJS BigInt extensions */ 133 | function test_bigint_ext() 134 | { 135 | var r; 136 | assert(BigInt.floorLog2(0n) === -1n); 137 | assert(BigInt.floorLog2(7n) === 2n); 138 | 139 | assert(BigInt.sqrt(0xffffffc000000000000000n) === 17592185913343n); 140 | r = BigInt.sqrtrem(0xffffffc000000000000000n); 141 | assert(r[0] === 17592185913343n); 142 | assert(r[1] === 35167191957503n); 143 | 144 | test_idiv1("tdiv", 3n, 2n, [1n, -1n, -1n, 1n]); 145 | test_idiv1("fdiv", 3n, 2n, [1n, -2n, -2n, 1n]); 146 | test_idiv1("cdiv", 3n, 2n, [2n, -1n, -1n, 2n]); 147 | test_idiv1("ediv", 3n, 2n, [1n, -2n, -1n, 2n]); 148 | } 149 | 150 | function test_bigfloat() 151 | { 152 | var e, a, b, sqrt2; 153 | 154 | assert(typeof 1n === "bigint"); 155 | assert(typeof 1l === "bigfloat"); 156 | assert(1 == 1.0l); 157 | assert(1 !== 1.0l); 158 | 159 | test_less(2l, 3l); 160 | test_eq(3l, 3l); 161 | 162 | test_less(2, 3l); 163 | test_eq(3, 3l); 164 | 165 | test_less(2.1, 3l); 166 | test_eq(Math.sqrt(9), 3l); 167 | 168 | test_less(2n, 3l); 169 | test_eq(3n, 3l); 170 | 171 | e = new BigFloatEnv(128); 172 | assert(e.prec == 128); 173 | a = BigFloat.sqrt(2l, e); 174 | assert(a === BigFloat.parseFloat("0x1.6a09e667f3bcc908b2fb1366ea957d3e", 0, e)); 175 | assert(e.inexact === true); 176 | assert(BigFloat.fpRound(a) == 0x1.6a09e667f3bcc908b2fb1366ea95l); 177 | 178 | b = BigFloatEnv.setPrec(BigFloat.sqrt.bind(null, 2), 128); 179 | assert(a === b); 180 | 181 | assert(BigFloat.isNaN(BigFloat(NaN))); 182 | assert(BigFloat.isFinite(1l)); 183 | assert(!BigFloat.isFinite(1l/0l)); 184 | 185 | assert(BigFloat.abs(-3l) === 3l); 186 | assert(BigFloat.sign(-3l) === -1l); 187 | 188 | assert(BigFloat.exp(0.2l) === 1.2214027581601698339210719946396742l); 189 | assert(BigFloat.log(3l) === 1.0986122886681096913952452369225256l); 190 | assert(BigFloat.pow(2.1l, 1.6l) === 3.277561666451861947162828744873745l); 191 | 192 | assert(BigFloat.sin(-1l) === -0.841470984807896506652502321630299l); 193 | assert(BigFloat.cos(1l) === 0.5403023058681397174009366074429766l); 194 | assert(BigFloat.tan(0.1l) === 0.10033467208545054505808004578111154l); 195 | 196 | assert(BigFloat.asin(0.3l) === 0.30469265401539750797200296122752915l); 197 | assert(BigFloat.acos(0.4l) === 1.1592794807274085998465837940224159l); 198 | assert(BigFloat.atan(0.7l) === 0.610725964389208616543758876490236l); 199 | assert(BigFloat.atan2(7.1l, -5.1l) === 2.1937053809751415549388104628759813l); 200 | 201 | assert(BigFloat.floor(2.5l) === 2l); 202 | assert(BigFloat.ceil(2.5l) === 3l); 203 | assert(BigFloat.trunc(-2.5l) === -2l); 204 | assert(BigFloat.round(2.5l) === 3l); 205 | 206 | assert(BigFloat.fmod(3l,2l) === 1l); 207 | assert(BigFloat.remainder(3l,2l) === -1l); 208 | 209 | /* string conversion */ 210 | assert((1234.125l).toString(), "1234.125"); 211 | assert((1234.125l).toFixed(2), "1234.13"); 212 | assert((1234.125l).toFixed(2, "down"), "1234.12"); 213 | assert((1234.125l).toExponential(), "1.234125e+3"); 214 | assert((1234.125l).toExponential(5), "1.23413e+3"); 215 | assert((1234.125l).toExponential(5, BigFloatEnv.RNDZ), "1.23412e+3"); 216 | assert((1234.125l).toPrecision(6), "1234.13"); 217 | assert((1234.125l).toPrecision(6, BigFloatEnv.RNDZ), "1234.12"); 218 | 219 | /* string conversion with binary base */ 220 | assert((0x123.438l).toString(16), "123.438"); 221 | assert((0x323.438l).toString(16), "323.438"); 222 | assert((0x723.438l).toString(16), "723.438"); 223 | assert((0xf23.438l).toString(16), "f23.438"); 224 | assert((0x123.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "123.44"); 225 | assert((0x323.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "323.44"); 226 | assert((0x723.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "723.44"); 227 | assert((0xf23.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "f23.44"); 228 | assert((0x0.0000438l).toFixed(6, BigFloatEnv.RNDNA, 16), "0.000044"); 229 | assert((0x1230000000l).toFixed(1, BigFloatEnv.RNDNA, 16), "1230000000.0"); 230 | assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "123.44"); 231 | assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDZ, 16), "123.43"); 232 | assert((0x323.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "323.44"); 233 | assert((0x723.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "723.44"); 234 | assert((-0xf23.438l).toPrecision(5, BigFloatEnv.RNDD, 16), "-f23.44"); 235 | assert((0x123.438l).toExponential(4, BigFloatEnv.RNDNA, 16), "1.2344p+8"); 236 | } 237 | 238 | function test_bigdecimal() 239 | { 240 | assert(1m === 1m); 241 | assert(1m !== 2m); 242 | test_less(1m, 2m); 243 | test_eq(2m, 2m); 244 | 245 | test_less(1, 2m); 246 | test_eq(2, 2m); 247 | 248 | test_less(1.1, 2m); 249 | test_eq(Math.sqrt(4), 2m); 250 | 251 | test_less(2n, 3m); 252 | test_eq(3n, 3m); 253 | 254 | assert(BigDecimal("1234.1") === 1234.1m); 255 | assert(BigDecimal(" 1234.1") === 1234.1m); 256 | assert(BigDecimal(" 1234.1 ") === 1234.1m); 257 | 258 | assert(BigDecimal(0.1) === 0.1m); 259 | assert(BigDecimal(123) === 123m); 260 | assert(BigDecimal(true) === 1m); 261 | 262 | assert(123m + 1m === 124m); 263 | assert(123m - 1m === 122m); 264 | 265 | assert(3.2m * 3m === 9.6m); 266 | assert(10m / 2m === 5m); 267 | assertThrows(RangeError, () => { 10m / 3m } ); 268 | 269 | assert(10m % 3m === 1m); 270 | assert(-10m % 3m === -1m); 271 | 272 | assert(1234.5m ** 3m === 1881365963.625m); 273 | assertThrows(RangeError, () => { 2m ** 3.1m } ); 274 | assertThrows(RangeError, () => { 2m ** -3m } ); 275 | 276 | assert(BigDecimal.sqrt(2m, 277 | { roundingMode: "half-even", 278 | maximumSignificantDigits: 4 }) === 1.414m); 279 | assert(BigDecimal.sqrt(101m, 280 | { roundingMode: "half-even", 281 | maximumFractionDigits: 3 }) === 10.050m); 282 | assert(BigDecimal.sqrt(0.002m, 283 | { roundingMode: "half-even", 284 | maximumFractionDigits: 3 }) === 0.045m); 285 | 286 | assert(BigDecimal.round(3.14159m, 287 | { roundingMode: "half-even", 288 | maximumFractionDigits: 3 }) === 3.142m); 289 | 290 | assert(BigDecimal.add(3.14159m, 0.31212m, 291 | { roundingMode: "half-even", 292 | maximumFractionDigits: 2 }) === 3.45m); 293 | assert(BigDecimal.sub(3.14159m, 0.31212m, 294 | { roundingMode: "down", 295 | maximumFractionDigits: 2 }) === 2.82m); 296 | assert(BigDecimal.mul(3.14159m, 0.31212m, 297 | { roundingMode: "half-even", 298 | maximumFractionDigits: 3 }) === 0.981m); 299 | assert(BigDecimal.mod(3.14159m, 0.31211m, 300 | { roundingMode: "half-even", 301 | maximumFractionDigits: 4 }) === 0.0205m); 302 | assert(BigDecimal.div(20m, 3m, 303 | { roundingMode: "half-even", 304 | maximumSignificantDigits: 3 }) === 6.67m); 305 | assert(BigDecimal.div(20m, 3m, 306 | { roundingMode: "half-even", 307 | maximumFractionDigits: 50 }) === 308 | 6.66666666666666666666666666666666666666666666666667m); 309 | 310 | /* string conversion */ 311 | assert((1234.125m).toString(), "1234.125"); 312 | assert((1234.125m).toFixed(2), "1234.13"); 313 | assert((1234.125m).toFixed(2, "down"), "1234.12"); 314 | assert((1234.125m).toExponential(), "1.234125e+3"); 315 | assert((1234.125m).toExponential(5), "1.23413e+3"); 316 | assert((1234.125m).toExponential(5, "down"), "1.23412e+3"); 317 | assert((1234.125m).toPrecision(6), "1234.13"); 318 | assert((1234.125m).toPrecision(6, "down"), "1234.12"); 319 | assert((-1234.125m).toPrecision(6, "floor"), "-1234.13"); 320 | } 321 | 322 | test_bigint1(); 323 | test_bigint2(); 324 | test_bigint_ext(); 325 | test_bigfloat(); 326 | test_bigdecimal(); 327 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # QuickJS Javascript Engine 3 | # 4 | # Copyright (c) 2017-2020 Fabrice Bellard 5 | # Copyright (c) 2017-2020 Charlie Gordon 6 | # 7 | # Permission is hereby granted, free of charge, to any person obtaining a copy 8 | # of this software and associated documentation files (the "Software"), to deal 9 | # in the Software without restriction, including without limitation the rights 10 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | # copies of the Software, and to permit persons to whom the Software is 12 | # furnished to do so, subject to the following conditions: 13 | # 14 | # The above copyright notice and this permission notice shall be included in 15 | # all copies or substantial portions of the Software. 16 | # 17 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | # THE SOFTWARE. 24 | 25 | ifeq ($(shell uname -s),Darwin) 26 | CONFIG_DARWIN=y 27 | endif 28 | # Windows cross compilation from Linux 29 | #CONFIG_WIN32=y 30 | # use link time optimization (smaller and faster executables but slower build) 31 | CONFIG_LTO=y 32 | # consider warnings as errors (for development) 33 | #CONFIG_WERROR=y 34 | # force 32 bit build for some utilities 35 | #CONFIG_M32=y 36 | 37 | ifdef CONFIG_DARWIN 38 | # use clang instead of gcc 39 | CONFIG_CLANG=y 40 | CONFIG_DEFAULT_AR=y 41 | endif 42 | 43 | # installation directory 44 | prefix=/usr/local 45 | 46 | # use the gprof profiler 47 | #CONFIG_PROFILE=y 48 | # use address sanitizer 49 | #CONFIG_ASAN=y 50 | # include the code for BigInt/BigFloat/BigDecimal and math mode 51 | CONFIG_BIGNUM=y 52 | 53 | OBJDIR=.obj 54 | 55 | ifdef CONFIG_WIN32 56 | CROSS_PREFIX=i686-w64-mingw32- 57 | EXE=.exe 58 | else 59 | CROSS_PREFIX= 60 | EXE= 61 | endif 62 | ifdef CONFIG_CLANG 63 | HOST_CC=clang 64 | CC=$(CROSS_PREFIX)clang 65 | CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d 66 | CFLAGS += -Wextra 67 | CFLAGS += -Wno-sign-compare 68 | CFLAGS += -Wno-missing-field-initializers 69 | CFLAGS += -Wundef -Wuninitialized 70 | CFLAGS += -Wunused -Wno-unused-parameter 71 | CFLAGS += -Wwrite-strings 72 | CFLAGS += -Wchar-subscripts -funsigned-char 73 | CFLAGS += -MMD -MF $(OBJDIR)/$(@F).d 74 | ifdef CONFIG_DEFAULT_AR 75 | AR=$(CROSS_PREFIX)ar 76 | else 77 | ifdef CONFIG_LTO 78 | AR=$(CROSS_PREFIX)llvm-ar 79 | else 80 | AR=$(CROSS_PREFIX)ar 81 | endif 82 | endif 83 | else 84 | HOST_CC=gcc 85 | CC=$(CROSS_PREFIX)gcc 86 | CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d 87 | CFLAGS += -Wno-array-bounds -Wno-format-truncation 88 | ifdef CONFIG_LTO 89 | AR=$(CROSS_PREFIX)gcc-ar 90 | else 91 | AR=$(CROSS_PREFIX)ar 92 | endif 93 | endif 94 | STRIP=$(CROSS_PREFIX)strip 95 | ifdef CONFIG_WERROR 96 | CFLAGS+=-Werror 97 | endif 98 | DEFINES:=-D_GNU_SOURCE -DCONFIG_VERSION=\"$(shell cat VERSION)\" 99 | ifdef CONFIG_BIGNUM 100 | DEFINES+=-DCONFIG_BIGNUM 101 | endif 102 | ifdef CONFIG_WIN32 103 | DEFINES+=-D__USE_MINGW_ANSI_STDIO # for standard snprintf behavior 104 | endif 105 | 106 | CFLAGS+=$(DEFINES) 107 | CFLAGS_DEBUG=$(CFLAGS) -O0 108 | CFLAGS_SMALL=$(CFLAGS) -Os 109 | CFLAGS_OPT=$(CFLAGS) -O2 110 | CFLAGS_NOLTO:=$(CFLAGS_OPT) 111 | LDFLAGS=-g 112 | ifdef CONFIG_LTO 113 | CFLAGS_SMALL+=-flto 114 | CFLAGS_OPT+=-flto 115 | LDFLAGS+=-flto 116 | endif 117 | ifdef CONFIG_PROFILE 118 | CFLAGS+=-p 119 | LDFLAGS+=-p 120 | endif 121 | ifdef CONFIG_ASAN 122 | CFLAGS+=-fsanitize=address -fno-omit-frame-pointer 123 | LDFLAGS+=-fsanitize=address -fno-omit-frame-pointer 124 | endif 125 | ifdef CONFIG_WIN32 126 | LDEXPORT= 127 | else 128 | LDEXPORT=-rdynamic 129 | endif 130 | 131 | PROGS=qjs$(EXE) qjsc$(EXE) run-test262 132 | ifneq ($(CROSS_PREFIX),) 133 | QJSC_CC=gcc 134 | QJSC=./host-qjsc 135 | PROGS+=$(QJSC) 136 | else 137 | QJSC_CC=$(CC) 138 | QJSC=./qjsc$(EXE) 139 | endif 140 | ifndef CONFIG_WIN32 141 | PROGS+=qjscalc 142 | endif 143 | ifdef CONFIG_M32 144 | PROGS+=qjs32 qjs32_s 145 | endif 146 | PROGS+=libquickjs.a 147 | ifdef CONFIG_LTO 148 | PROGS+=libquickjs.lto.a 149 | endif 150 | 151 | # examples 152 | ifeq ($(CROSS_PREFIX),) 153 | ifdef CONFIG_ASAN 154 | PROGS+= 155 | else 156 | PROGS+=examples/hello examples/hello_module examples/test_fib 157 | ifndef CONFIG_DARWIN 158 | PROGS+=examples/fib.so examples/point.so 159 | endif 160 | endif 161 | endif 162 | 163 | all: $(OBJDIR) $(OBJDIR)/quickjs.check.o $(OBJDIR)/qjs.check.o $(PROGS) 164 | 165 | QJS_LIB_OBJS=$(OBJDIR)/quickjs.o $(OBJDIR)/libregexp.o $(OBJDIR)/libunicode.o $(OBJDIR)/cutils.o $(OBJDIR)/quickjs-libc.o 166 | 167 | QJS_OBJS=$(OBJDIR)/qjs.o $(OBJDIR)/repl.o $(QJS_LIB_OBJS) 168 | ifdef CONFIG_BIGNUM 169 | QJS_LIB_OBJS+=$(OBJDIR)/libbf.o 170 | QJS_OBJS+=$(OBJDIR)/qjscalc.o 171 | endif 172 | 173 | HOST_LIBS=-lm -ldl -lpthread 174 | LIBS=-lm 175 | ifndef CONFIG_WIN32 176 | LIBS+=-ldl -lpthread 177 | endif 178 | 179 | $(OBJDIR): 180 | mkdir -p $(OBJDIR) $(OBJDIR)/examples $(OBJDIR)/tests 181 | 182 | qjs$(EXE): $(QJS_OBJS) 183 | $(CC) $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS) 184 | 185 | qjs-debug$(EXE): $(patsubst %.o, %.debug.o, $(QJS_OBJS)) 186 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 187 | 188 | qjsc$(EXE): $(OBJDIR)/qjsc.o $(QJS_LIB_OBJS) 189 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 190 | 191 | ifneq ($(CROSS_PREFIX),) 192 | 193 | $(QJSC): $(OBJDIR)/qjsc.host.o \ 194 | $(patsubst %.o, %.host.o, $(QJS_LIB_OBJS)) 195 | $(HOST_CC) $(LDFLAGS) -o $@ $^ $(HOST_LIBS) 196 | 197 | endif #CROSS_PREFIX 198 | 199 | QJSC_DEFINES:=-DCONFIG_CC=\"$(QJSC_CC)\" -DCONFIG_PREFIX=\"$(prefix)\" 200 | ifdef CONFIG_LTO 201 | QJSC_DEFINES+=-DCONFIG_LTO 202 | endif 203 | QJSC_HOST_DEFINES:=-DCONFIG_CC=\"$(HOST_CC)\" -DCONFIG_PREFIX=\"$(prefix)\" 204 | 205 | $(OBJDIR)/qjsc.o: CFLAGS+=$(QJSC_DEFINES) 206 | $(OBJDIR)/qjsc.host.o: CFLAGS+=$(QJSC_HOST_DEFINES) 207 | 208 | qjs32: $(patsubst %.o, %.m32.o, $(QJS_OBJS)) 209 | $(CC) -m32 $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS) 210 | 211 | qjs32_s: $(patsubst %.o, %.m32s.o, $(QJS_OBJS)) 212 | $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) 213 | @size $@ 214 | 215 | qjscalc: qjs 216 | ln -sf $< $@ 217 | 218 | ifdef CONFIG_LTO 219 | LTOEXT=.lto 220 | else 221 | LTOEXT= 222 | endif 223 | 224 | libquickjs$(LTOEXT).a: $(QJS_LIB_OBJS) 225 | $(AR) rcs $@ $^ 226 | 227 | ifdef CONFIG_LTO 228 | libquickjs.a: $(patsubst %.o, %.nolto.o, $(QJS_LIB_OBJS)) 229 | $(AR) rcs $@ $^ 230 | endif # CONFIG_LTO 231 | 232 | repl.c: $(QJSC) repl.js 233 | $(QJSC) -c -o $@ -m repl.js 234 | 235 | qjscalc.c: $(QJSC) qjscalc.js 236 | $(QJSC) -fbignum -c -o $@ qjscalc.js 237 | 238 | ifneq ($(wildcard unicode/UnicodeData.txt),) 239 | $(OBJDIR)/libunicode.o $(OBJDIR)/libunicode.m32.o $(OBJDIR)/libunicode.m32s.o \ 240 | $(OBJDIR)/libunicode.nolto.o: libunicode-table.h 241 | 242 | libunicode-table.h: unicode_gen 243 | ./unicode_gen unicode $@ 244 | endif 245 | 246 | run-test262: $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS) 247 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 248 | 249 | run-test262-debug: $(patsubst %.o, %.debug.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)) 250 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 251 | 252 | run-test262-32: $(patsubst %.o, %.m32.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)) 253 | $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) 254 | 255 | # object suffix order: nolto, [m32|m32s] 256 | 257 | $(OBJDIR)/%.o: %.c | $(OBJDIR) 258 | $(CC) $(CFLAGS_OPT) -c -o $@ $< 259 | 260 | $(OBJDIR)/%.host.o: %.c | $(OBJDIR) 261 | $(HOST_CC) $(CFLAGS_OPT) -c -o $@ $< 262 | 263 | $(OBJDIR)/%.pic.o: %.c | $(OBJDIR) 264 | $(CC) $(CFLAGS_OPT) -fPIC -DJS_SHARED_LIBRARY -c -o $@ $< 265 | 266 | $(OBJDIR)/%.nolto.o: %.c | $(OBJDIR) 267 | $(CC) $(CFLAGS_NOLTO) -c -o $@ $< 268 | 269 | $(OBJDIR)/%.m32.o: %.c | $(OBJDIR) 270 | $(CC) -m32 $(CFLAGS_OPT) -c -o $@ $< 271 | 272 | $(OBJDIR)/%.m32s.o: %.c | $(OBJDIR) 273 | $(CC) -m32 $(CFLAGS_SMALL) -c -o $@ $< 274 | 275 | $(OBJDIR)/%.debug.o: %.c | $(OBJDIR) 276 | $(CC) $(CFLAGS_DEBUG) -c -o $@ $< 277 | 278 | $(OBJDIR)/%.check.o: %.c | $(OBJDIR) 279 | $(CC) $(CFLAGS) -DCONFIG_CHECK_JSVALUE -c -o $@ $< 280 | 281 | regexp_test: libregexp.c libunicode.c cutils.c 282 | $(CC) $(LDFLAGS) $(CFLAGS) -DTEST -o $@ libregexp.c libunicode.c cutils.c $(LIBS) 283 | 284 | jscompress: jscompress.c 285 | $(CC) $(LDFLAGS) $(CFLAGS) -o $@ jscompress.c 286 | 287 | unicode_gen: $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o libunicode.c unicode_gen_def.h 288 | $(HOST_CC) $(LDFLAGS) $(CFLAGS) -o $@ $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o 289 | 290 | clean: 291 | rm -f repl.c qjscalc.c out.c 292 | rm -f *.a *.o *.d *~ jscompress unicode_gen regexp_test $(PROGS) 293 | rm -f hello.c test_fib.c 294 | rm -f examples/*.so tests/*.so 295 | rm -rf $(OBJDIR)/ *.dSYM/ qjs-debug 296 | rm -rf run-test262-debug run-test262-32 297 | 298 | install: all 299 | mkdir -p "$(DESTDIR)$(prefix)/bin" 300 | $(STRIP) qjs qjsc 301 | install -m755 qjs qjsc "$(DESTDIR)$(prefix)/bin" 302 | ln -sf qjs "$(DESTDIR)$(prefix)/bin/qjscalc" 303 | mkdir -p "$(DESTDIR)$(prefix)/lib/quickjs" 304 | install -m644 libquickjs.a "$(DESTDIR)$(prefix)/lib/quickjs" 305 | ifdef CONFIG_LTO 306 | install -m644 libquickjs.lto.a "$(DESTDIR)$(prefix)/lib/quickjs" 307 | endif 308 | mkdir -p "$(DESTDIR)$(prefix)/include/quickjs" 309 | install -m644 quickjs.h quickjs-libc.h "$(DESTDIR)$(prefix)/include/quickjs" 310 | 311 | ############################################################################### 312 | # examples 313 | 314 | # example of static JS compilation 315 | HELLO_SRCS=examples/hello.js 316 | HELLO_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \ 317 | -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \ 318 | -fno-date -fno-module-loader 319 | ifdef CONFIG_BIGNUM 320 | HELLO_OPTS+=-fno-bigint 321 | endif 322 | 323 | hello.c: $(QJSC) $(HELLO_SRCS) 324 | $(QJSC) -e $(HELLO_OPTS) -o $@ $(HELLO_SRCS) 325 | 326 | ifdef CONFIG_M32 327 | examples/hello: $(OBJDIR)/hello.m32s.o $(patsubst %.o, %.m32s.o, $(QJS_LIB_OBJS)) 328 | $(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS) 329 | else 330 | examples/hello: $(OBJDIR)/hello.o $(QJS_LIB_OBJS) 331 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 332 | endif 333 | 334 | # example of static JS compilation with modules 335 | HELLO_MODULE_SRCS=examples/hello_module.js 336 | HELLO_MODULE_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \ 337 | -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \ 338 | -fno-date -m 339 | examples/hello_module: $(QJSC) libquickjs$(LTOEXT).a $(HELLO_MODULE_SRCS) 340 | $(QJSC) $(HELLO_MODULE_OPTS) -o $@ $(HELLO_MODULE_SRCS) 341 | 342 | # use of an external C module (static compilation) 343 | 344 | test_fib.c: $(QJSC) examples/test_fib.js 345 | $(QJSC) -e -M examples/fib.so,fib -m -o $@ examples/test_fib.js 346 | 347 | examples/test_fib: $(OBJDIR)/test_fib.o $(OBJDIR)/examples/fib.o libquickjs$(LTOEXT).a 348 | $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) 349 | 350 | examples/fib.so: $(OBJDIR)/examples/fib.pic.o 351 | $(CC) $(LDFLAGS) -shared -o $@ $^ 352 | 353 | examples/point.so: $(OBJDIR)/examples/point.pic.o 354 | $(CC) $(LDFLAGS) -shared -o $@ $^ 355 | 356 | ############################################################################### 357 | # documentation 358 | 359 | DOCS=doc/quickjs.pdf doc/quickjs.html doc/jsbignum.pdf doc/jsbignum.html 360 | 361 | build_doc: $(DOCS) 362 | 363 | clean_doc: 364 | rm -f $(DOCS) 365 | 366 | doc/%.pdf: doc/%.texi 367 | texi2pdf --clean -o $@ -q $< 368 | 369 | doc/%.html.pre: doc/%.texi 370 | makeinfo --html --no-headers --no-split --number-sections -o $@ $< 371 | 372 | doc/%.html: doc/%.html.pre 373 | sed -e 's||\n|' < $< > $@ 374 | 375 | ############################################################################### 376 | # tests 377 | 378 | ifndef CONFIG_DARWIN 379 | test: tests/bjson.so examples/point.so 380 | endif 381 | ifdef CONFIG_M32 382 | test: qjs32 383 | endif 384 | 385 | test: qjs 386 | ./qjs tests/test_closure.js 387 | ./qjs tests/test_language.js 388 | ./qjs tests/test_builtin.js 389 | ./qjs tests/test_loop.js 390 | ./qjs tests/test_std.js 391 | ./qjs tests/test_worker.js 392 | ifndef CONFIG_DARWIN 393 | ifdef CONFIG_BIGNUM 394 | ./qjs --bignum tests/test_bjson.js 395 | else 396 | ./qjs tests/test_bjson.js 397 | endif 398 | ./qjs examples/test_point.js 399 | endif 400 | ifdef CONFIG_BIGNUM 401 | ./qjs --bignum tests/test_op_overloading.js 402 | ./qjs --bignum tests/test_bignum.js 403 | ./qjs --qjscalc tests/test_qjscalc.js 404 | endif 405 | ifdef CONFIG_M32 406 | ./qjs32 tests/test_closure.js 407 | ./qjs32 tests/test_language.js 408 | ./qjs32 tests/test_builtin.js 409 | ./qjs32 tests/test_loop.js 410 | ./qjs32 tests/test_std.js 411 | ./qjs32 tests/test_worker.js 412 | ifdef CONFIG_BIGNUM 413 | ./qjs32 --bignum tests/test_op_overloading.js 414 | ./qjs32 --bignum tests/test_bignum.js 415 | ./qjs32 --qjscalc tests/test_qjscalc.js 416 | endif 417 | endif 418 | 419 | stats: qjs qjs32 420 | ./qjs -qd 421 | ./qjs32 -qd 422 | 423 | microbench: qjs 424 | ./qjs tests/microbench.js 425 | 426 | microbench-32: qjs32 427 | ./qjs32 tests/microbench.js 428 | 429 | # ES5 tests (obsolete) 430 | test2o: run-test262 431 | time ./run-test262 -m -c test262o.conf 432 | 433 | test2o-32: run-test262-32 434 | time ./run-test262-32 -m -c test262o.conf 435 | 436 | test2o-update: run-test262 437 | ./run-test262 -u -c test262o.conf 438 | 439 | # Test262 tests 440 | test2-default: run-test262 441 | time ./run-test262 -m -c test262.conf 442 | 443 | test2: run-test262 444 | time ./run-test262 -m -c test262.conf -a 445 | 446 | test2-32: run-test262-32 447 | time ./run-test262-32 -m -c test262.conf -a 448 | 449 | test2-update: run-test262 450 | ./run-test262 -u -c test262.conf -a 451 | 452 | test2-check: run-test262 453 | time ./run-test262 -m -c test262.conf -E -a 454 | 455 | testall: all test microbench test2o test2 456 | 457 | testall-32: all test-32 microbench-32 test2o-32 test2-32 458 | 459 | testall-complete: testall testall-32 460 | 461 | bench-v8: qjs 462 | make -C tests/bench-v8 463 | ./qjs -d tests/bench-v8/combined.js 464 | 465 | tests/bjson.so: $(OBJDIR)/tests/bjson.pic.o 466 | $(CC) $(LDFLAGS) -shared -o $@ $^ $(LIBS) 467 | 468 | -include $(wildcard $(OBJDIR)/*.d) 469 | -------------------------------------------------------------------------------- /src/quickjs-private.h: -------------------------------------------------------------------------------- 1 | #ifndef QUICKJS_QUICKJS_PRIVATE_H 2 | #define QUICKJS_QUICKJS_PRIVATE_H 3 | 4 | #include "quickjs-data-structure.h" 5 | static int JS_InitAtoms(JSRuntime *rt); 6 | static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len, 7 | int atom_type); 8 | static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p); 9 | static void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b); 10 | static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj, 11 | JSValueConst this_obj, 12 | int argc, JSValueConst *argv, int flags); 13 | static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj, 14 | JSValueConst this_obj, 15 | int argc, JSValueConst *argv, int flags); 16 | static JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj, 17 | JSValueConst this_obj, JSValueConst new_target, 18 | int argc, JSValue *argv, int flags); 19 | static JSValue JS_CallConstructorInternal(JSContext *ctx, 20 | JSValueConst func_obj, 21 | JSValueConst new_target, 22 | int argc, JSValue *argv, int flags); 23 | static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj, 24 | int argc, JSValueConst *argv); 25 | static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom, 26 | int argc, JSValueConst *argv); 27 | static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen, 28 | JSValue val); 29 | static JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj, 30 | JSValueConst val, int flags, int scope_idx); 31 | JSValue 32 | #ifndef _MSC_VER 33 | __js_printf_like(2, 3) 34 | #endif 35 | JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...); 36 | static __maybe_unused void JS_DumpAtoms(JSRuntime *rt); 37 | static __maybe_unused void JS_DumpString(JSRuntime *rt, 38 | const JSString *p); 39 | static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt); 40 | static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p); 41 | static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p); 42 | static __maybe_unused void JS_DumpValueShort(JSRuntime *rt, 43 | JSValueConst val); 44 | static __maybe_unused void JS_DumpValue(JSContext *ctx, JSValueConst val); 45 | static __maybe_unused void JS_PrintValue(JSContext *ctx, 46 | const char *str, 47 | JSValueConst val); 48 | static __maybe_unused void JS_DumpShapes(JSRuntime *rt); 49 | static JSValue js_function_apply(JSContext *ctx, JSValueConst this_val, 50 | int argc, JSValueConst *argv, int magic); 51 | static void js_array_finalizer(JSRuntime *rt, JSValue val); 52 | static void js_array_mark(JSRuntime *rt, JSValueConst val, 53 | JS_MarkFunc *mark_func); 54 | static void js_object_data_finalizer(JSRuntime *rt, JSValue val); 55 | static void js_object_data_mark(JSRuntime *rt, JSValueConst val, 56 | JS_MarkFunc *mark_func); 57 | static void js_c_function_finalizer(JSRuntime *rt, JSValue val); 58 | static void js_c_function_mark(JSRuntime *rt, JSValueConst val, 59 | JS_MarkFunc *mark_func); 60 | static void js_bytecode_function_finalizer(JSRuntime *rt, JSValue val); 61 | static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val, 62 | JS_MarkFunc *mark_func); 63 | static void js_bound_function_finalizer(JSRuntime *rt, JSValue val); 64 | static void js_bound_function_mark(JSRuntime *rt, JSValueConst val, 65 | JS_MarkFunc *mark_func); 66 | static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValue val); 67 | static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val, 68 | JS_MarkFunc *mark_func); 69 | static void js_regexp_finalizer(JSRuntime *rt, JSValue val); 70 | static void js_array_buffer_finalizer(JSRuntime *rt, JSValue val); 71 | static void js_typed_array_finalizer(JSRuntime *rt, JSValue val); 72 | static void js_typed_array_mark(JSRuntime *rt, JSValueConst val, 73 | JS_MarkFunc *mark_func); 74 | static void js_proxy_finalizer(JSRuntime *rt, JSValue val); 75 | static void js_proxy_mark(JSRuntime *rt, JSValueConst val, 76 | JS_MarkFunc *mark_func); 77 | static void js_map_finalizer(JSRuntime *rt, JSValue val); 78 | static void js_map_mark(JSRuntime *rt, JSValueConst val, 79 | JS_MarkFunc *mark_func); 80 | static void js_map_iterator_finalizer(JSRuntime *rt, JSValue val); 81 | static void js_map_iterator_mark(JSRuntime *rt, JSValueConst val, 82 | JS_MarkFunc *mark_func); 83 | static void js_array_iterator_finalizer(JSRuntime *rt, JSValue val); 84 | static void js_array_iterator_mark(JSRuntime *rt, JSValueConst val, 85 | JS_MarkFunc *mark_func); 86 | static void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValue val); 87 | static void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val, 88 | JS_MarkFunc *mark_func); 89 | static void js_generator_finalizer(JSRuntime *rt, JSValue obj); 90 | static void js_generator_mark(JSRuntime *rt, JSValueConst val, 91 | JS_MarkFunc *mark_func); 92 | static void js_promise_finalizer(JSRuntime *rt, JSValue val); 93 | static void js_promise_mark(JSRuntime *rt, JSValueConst val, 94 | JS_MarkFunc *mark_func); 95 | static void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValue val); 96 | static void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val, 97 | JS_MarkFunc *mark_func); 98 | #ifdef CONFIG_BIGNUM 99 | static void js_operator_set_finalizer(JSRuntime *rt, JSValue val); 100 | static void js_operator_set_mark(JSRuntime *rt, JSValueConst val, 101 | JS_MarkFunc *mark_func); 102 | #endif 103 | static JSValue JS_ToStringFree(JSContext *ctx, JSValue val); 104 | static int JS_ToBoolFree(JSContext *ctx, JSValue val); 105 | static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val); 106 | static int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val); 107 | static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val); 108 | static JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern, 109 | JSValueConst flags); 110 | static JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor, 111 | JSValue pattern, JSValue bc); 112 | static void gc_decref(JSRuntime *rt); 113 | static int JS_NewClass1(JSRuntime *rt, JSClassID class_id, 114 | const JSClassDef *class_def, JSAtom name); 115 | 116 | static BOOL js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2, 117 | JSStrictEqModeEnum eq_mode); 118 | static BOOL js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2); 119 | static BOOL js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2); 120 | static BOOL js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2); 121 | static JSValue JS_ToObject(JSContext *ctx, JSValueConst val); 122 | static JSValue JS_ToObjectFree(JSContext *ctx, JSValue val); 123 | static JSProperty *add_property(JSContext *ctx, 124 | JSObject *p, JSAtom prop, int prop_flags); 125 | #ifdef CONFIG_BIGNUM 126 | static void js_float_env_finalizer(JSRuntime *rt, JSValue val); 127 | static JSValue JS_NewBigFloat(JSContext *ctx); 128 | static inline bf_t *JS_GetBigFloat(JSValueConst val) 129 | { 130 | JSBigFloat *p = JS_VALUE_GET_PTR(val); 131 | return &p->num; 132 | } 133 | static JSValue JS_NewBigDecimal(JSContext *ctx); 134 | static inline bfdec_t *JS_GetBigDecimal(JSValueConst val) 135 | { 136 | JSBigDecimal *p = JS_VALUE_GET_PTR(val); 137 | return &p->num; 138 | } 139 | static JSValue JS_NewBigInt(JSContext *ctx); 140 | static inline bf_t *JS_GetBigInt(JSValueConst val) 141 | { 142 | JSBigFloat *p = JS_VALUE_GET_PTR(val); 143 | return &p->num; 144 | } 145 | static JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val, 146 | BOOL convert_to_safe_integer); 147 | static JSValue JS_CompactBigInt(JSContext *ctx, JSValue val); 148 | static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val); 149 | static bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val); 150 | static void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf); 151 | static bf_t *JS_ToBigFloat(JSContext *ctx, bf_t *buf, JSValueConst val); 152 | static JSValue JS_ToBigDecimalFree(JSContext *ctx, JSValue val, 153 | BOOL allow_null_or_undefined); 154 | static bfdec_t *JS_ToBigDecimal(JSContext *ctx, JSValueConst val); 155 | #endif 156 | JSValue JS_ThrowOutOfMemory(JSContext *ctx); 157 | static JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx); 158 | static JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj); 159 | static int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj, 160 | JSValueConst proto_val, BOOL throw_flag); 161 | static int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj); 162 | static int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj); 163 | static int js_proxy_isArray(JSContext *ctx, JSValueConst obj); 164 | static int JS_CreateProperty(JSContext *ctx, JSObject *p, 165 | JSAtom prop, JSValueConst val, 166 | JSValueConst getter, JSValueConst setter, 167 | int flags); 168 | static int js_string_memcmp(const JSString *p1, const JSString *p2, int len); 169 | static void reset_weak_ref(JSRuntime *rt, JSObject *p); 170 | static JSValue js_array_buffer_constructor3(JSContext *ctx, 171 | JSValueConst new_target, 172 | uint64_t len, JSClassID class_id, 173 | uint8_t *buf, 174 | JSFreeArrayBufferDataFunc *free_func, 175 | void *opaque, BOOL alloc_flag); 176 | static JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj); 177 | static JSValue js_typed_array_constructor(JSContext *ctx, 178 | JSValueConst this_val, 179 | int argc, JSValueConst *argv, 180 | int classid); 181 | static BOOL typed_array_is_detached(JSContext *ctx, JSObject *p); 182 | static uint32_t typed_array_get_length(JSContext *ctx, JSObject *p); 183 | static JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx); 184 | static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx, 185 | BOOL is_arg); 186 | static JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj, 187 | JSValueConst this_obj, 188 | int argc, JSValueConst *argv, 189 | int flags); 190 | static void js_async_function_resolve_finalizer(JSRuntime *rt, JSValue val); 191 | static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val, 192 | JS_MarkFunc *mark_func); 193 | static JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj, 194 | const char *input, size_t input_len, 195 | const char *filename, int flags, int scope_idx); 196 | static void js_free_module_def(JSContext *ctx, JSModuleDef *m); 197 | static void js_mark_module_def(JSRuntime *rt, JSModuleDef *m, 198 | JS_MarkFunc *mark_func); 199 | static JSValue js_import_meta(JSContext *ctx); 200 | static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier); 201 | static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref); 202 | static JSValue js_new_promise_capability(JSContext *ctx, 203 | JSValue *resolving_funcs, 204 | JSValueConst ctor); 205 | static __exception int perform_promise_then(JSContext *ctx, 206 | JSValueConst promise, 207 | JSValueConst *resolve_reject, 208 | JSValueConst *cap_resolving_funcs); 209 | static JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val, 210 | int argc, JSValueConst *argv, int magic); 211 | static int js_string_compare(JSContext *ctx, 212 | const JSString *p1, const JSString *p2); 213 | static JSValue JS_ToNumber(JSContext *ctx, JSValueConst val); 214 | static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj, 215 | JSValue prop, JSValue val, int flags); 216 | static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val); 217 | static BOOL JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val); 218 | static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val); 219 | static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc, 220 | JSObject *p, JSAtom prop); 221 | static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc); 222 | static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s, 223 | JS_MarkFunc *mark_func); 224 | static void JS_AddIntrinsicBasicObjects(JSContext *ctx); 225 | static void js_free_shape(JSRuntime *rt, JSShape *sh); 226 | static void js_free_shape_null(JSRuntime *rt, JSShape *sh); 227 | static int js_shape_prepare_update(JSContext *ctx, JSObject *p, 228 | JSShapeProperty **pprs); 229 | static int init_shape_hash(JSRuntime *rt); 230 | static __exception int js_get_length32(JSContext *ctx, uint32_t *pres, 231 | JSValueConst obj); 232 | static __exception int js_get_length64(JSContext *ctx, int64_t *pres, 233 | JSValueConst obj); 234 | static void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len); 235 | static JSValue *build_arg_list(JSContext *ctx, uint32_t *plen, 236 | JSValueConst array_arg); 237 | static BOOL js_get_fast_array(JSContext *ctx, JSValueConst obj, 238 | JSValue **arrpp, uint32_t *countp); 239 | static JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx, 240 | JSValueConst sync_iter); 241 | static void js_c_function_data_finalizer(JSRuntime *rt, JSValue val); 242 | static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val, 243 | JS_MarkFunc *mark_func); 244 | static JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj, 245 | JSValueConst this_val, 246 | int argc, JSValueConst *argv, int flags); 247 | static JSAtom js_symbol_to_atom(JSContext *ctx, JSValue val); 248 | static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h, 249 | JSGCObjectTypeEnum type); 250 | static void remove_gc_object(JSGCObjectHeader *h); 251 | static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s); 252 | static int js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); 253 | static int js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom, 254 | void *opaque); 255 | static int JS_InstantiateFunctionListItem(JSContext *ctx, JSObject *p, 256 | JSAtom atom, void *opaque); 257 | void JS_SetUncatchableError(JSContext *ctx, JSValueConst val, BOOL flag); 258 | 259 | #endif //QUICKJS_QUICKJS_PRIVATE_H 260 | -------------------------------------------------------------------------------- /src/quickjs-opcode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * QuickJS opcode definitions 3 | * 4 | * Copyright (c) 2017-2018 Fabrice Bellard 5 | * Copyright (c) 2017-2018 Charlie Gordon 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining a copy 8 | * of this software and associated documentation files (the "Software"), to deal 9 | * in the Software without restriction, including without limitation the rights 10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | * copies of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included in 15 | * all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | * THE SOFTWARE. 24 | */ 25 | 26 | #ifdef FMT 27 | FMT(none) 28 | FMT(none_int) 29 | FMT(none_loc) 30 | FMT(none_arg) 31 | FMT(none_var_ref) 32 | FMT(u8) 33 | FMT(i8) 34 | FMT(loc8) 35 | FMT(const8) 36 | FMT(label8) 37 | FMT(u16) 38 | FMT(i16) 39 | FMT(label16) 40 | FMT(npop) 41 | FMT(npopx) 42 | FMT(npop_u16) 43 | FMT(loc) 44 | FMT(arg) 45 | FMT(var_ref) 46 | FMT(u32) 47 | FMT(i32) 48 | FMT(const) 49 | FMT(label) 50 | FMT(atom) 51 | FMT(atom_u8) 52 | FMT(atom_u16) 53 | FMT(atom_label_u8) 54 | FMT(atom_label_u16) 55 | FMT(label_u16) 56 | #undef FMT 57 | #endif /* FMT */ 58 | 59 | #ifdef DEF 60 | 61 | #ifndef def 62 | #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) 63 | #endif 64 | 65 | DEF(invalid, 1, 0, 0, none) /* never emitted */ 66 | 67 | /* push values */ 68 | DEF( push_i32, 5, 0, 1, i32) 69 | DEF( push_const, 5, 0, 1, const) 70 | DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ 71 | DEF(push_atom_value, 5, 0, 1, atom) 72 | DEF( private_symbol, 5, 0, 1, atom) 73 | DEF( undefined, 1, 0, 1, none) 74 | DEF( null, 1, 0, 1, none) 75 | DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ 76 | DEF( push_false, 1, 0, 1, none) 77 | DEF( push_true, 1, 0, 1, none) 78 | DEF( object, 1, 0, 1, none) 79 | DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ 80 | DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ 81 | 82 | DEF( drop, 1, 1, 0, none) /* a -> */ 83 | DEF( nip, 1, 2, 1, none) /* a b -> b */ 84 | DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ 85 | DEF( dup, 1, 1, 2, none) /* a -> a a */ 86 | DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ 87 | DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ 88 | DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ 89 | DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ 90 | DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ 91 | DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ 92 | DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ 93 | DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ 94 | DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ 95 | DEF( swap, 1, 2, 2, none) /* a b -> b a */ 96 | DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ 97 | DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ 98 | DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ 99 | DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ 100 | DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ 101 | 102 | DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ 103 | DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ 104 | DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ 105 | DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ 106 | DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ 107 | DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ 108 | DEF( apply, 3, 3, 1, u16) 109 | DEF( return, 1, 1, 0, none) 110 | DEF( return_undef, 1, 0, 0, none) 111 | DEF(check_ctor_return, 1, 1, 2, none) 112 | DEF( check_ctor, 1, 0, 0, none) 113 | DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ 114 | DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ 115 | DEF( return_async, 1, 1, 0, none) 116 | DEF( throw, 1, 1, 0, none) 117 | DEF( throw_var, 6, 0, 0, atom_u8) 118 | DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ 119 | DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ 120 | DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a 121 | bytecode string */ 122 | DEF( get_super, 1, 1, 1, none) 123 | DEF( import, 1, 1, 1, none) /* dynamic module import */ 124 | 125 | DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */ 126 | DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ 127 | DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ 128 | DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ 129 | DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ 130 | DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */ 131 | 132 | DEF( get_ref_value, 1, 2, 3, none) 133 | DEF( put_ref_value, 1, 3, 0, none) 134 | 135 | DEF( define_var, 6, 0, 0, atom_u8) 136 | DEF(check_define_var, 6, 0, 0, atom_u8) 137 | DEF( define_func, 6, 1, 0, atom_u8) 138 | DEF( get_field, 5, 1, 1, atom) 139 | DEF( get_field2, 5, 1, 2, atom) 140 | DEF( put_field, 5, 2, 0, atom) 141 | DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ 142 | DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ 143 | DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ 144 | DEF( get_array_el, 1, 2, 1, none) 145 | DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ 146 | DEF( put_array_el, 1, 3, 0, none) 147 | DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ 148 | DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ 149 | DEF( define_field, 5, 2, 1, atom) 150 | DEF( set_name, 5, 1, 1, atom) 151 | DEF(set_name_computed, 1, 2, 2, none) 152 | DEF( set_proto, 1, 2, 1, none) 153 | DEF(set_home_object, 1, 2, 2, none) 154 | DEF(define_array_el, 1, 3, 2, none) 155 | DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ 156 | DEF(copy_data_properties, 2, 3, 3, u8) 157 | DEF( define_method, 6, 2, 1, atom_u8) 158 | DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ 159 | DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ 160 | DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ 161 | 162 | DEF( get_loc, 3, 0, 1, loc) 163 | DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ 164 | DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ 165 | DEF( get_arg, 3, 0, 1, arg) 166 | DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ 167 | DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ 168 | DEF( get_var_ref, 3, 0, 1, var_ref) 169 | DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ 170 | DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ 171 | DEF(set_loc_uninitialized, 3, 0, 0, loc) 172 | DEF( get_loc_check, 3, 0, 1, loc) 173 | DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ 174 | DEF( put_loc_check_init, 3, 1, 0, loc) 175 | DEF(get_var_ref_check, 3, 0, 1, var_ref) 176 | DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ 177 | DEF(put_var_ref_check_init, 3, 1, 0, var_ref) 178 | DEF( close_loc, 3, 0, 0, loc) 179 | DEF( if_false, 5, 1, 0, label) 180 | DEF( if_true, 5, 1, 0, label) /* must come after if_false */ 181 | DEF( goto, 5, 0, 0, label) /* must come after if_true */ 182 | DEF( catch, 5, 0, 1, label) 183 | DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ 184 | DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ 185 | 186 | DEF( to_object, 1, 1, 1, none) 187 | //DEF( to_string, 1, 1, 1, none) 188 | DEF( to_propkey, 1, 1, 1, none) 189 | DEF( to_propkey2, 1, 2, 2, none) 190 | 191 | DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ 192 | DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ 193 | DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ 194 | DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ 195 | DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ 196 | DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) 197 | 198 | DEF( make_loc_ref, 7, 0, 2, atom_u16) 199 | DEF( make_arg_ref, 7, 0, 2, atom_u16) 200 | DEF(make_var_ref_ref, 7, 0, 2, atom_u16) 201 | DEF( make_var_ref, 5, 0, 2, atom) 202 | 203 | DEF( for_in_start, 1, 1, 1, none) 204 | DEF( for_of_start, 1, 1, 3, none) 205 | DEF(for_await_of_start, 1, 1, 3, none) 206 | DEF( for_in_next, 1, 1, 3, none) 207 | DEF( for_of_next, 2, 3, 5, u8) 208 | DEF(for_await_of_next, 1, 3, 4, none) 209 | DEF(iterator_get_value_done, 1, 1, 2, none) 210 | DEF( iterator_close, 1, 3, 0, none) 211 | DEF(iterator_close_return, 1, 4, 4, none) 212 | DEF(async_iterator_close, 1, 3, 2, none) 213 | DEF(async_iterator_next, 1, 4, 4, none) 214 | DEF(async_iterator_get, 2, 4, 5, u8) 215 | DEF( initial_yield, 1, 0, 0, none) 216 | DEF( yield, 1, 1, 2, none) 217 | DEF( yield_star, 1, 2, 2, none) 218 | DEF(async_yield_star, 1, 1, 2, none) 219 | DEF( await, 1, 1, 1, none) 220 | 221 | /* arithmetic/logic operations */ 222 | DEF( neg, 1, 1, 1, none) 223 | DEF( plus, 1, 1, 1, none) 224 | DEF( dec, 1, 1, 1, none) 225 | DEF( inc, 1, 1, 1, none) 226 | DEF( post_dec, 1, 1, 2, none) 227 | DEF( post_inc, 1, 1, 2, none) 228 | DEF( dec_loc, 2, 0, 0, loc8) 229 | DEF( inc_loc, 2, 0, 0, loc8) 230 | DEF( add_loc, 2, 1, 0, loc8) 231 | DEF( not, 1, 1, 1, none) 232 | DEF( lnot, 1, 1, 1, none) 233 | DEF( typeof, 1, 1, 1, none) 234 | DEF( delete, 1, 2, 1, none) 235 | DEF( delete_var, 5, 0, 1, atom) 236 | 237 | DEF( mul, 1, 2, 1, none) 238 | DEF( div, 1, 2, 1, none) 239 | DEF( mod, 1, 2, 1, none) 240 | DEF( add, 1, 2, 1, none) 241 | DEF( sub, 1, 2, 1, none) 242 | DEF( pow, 1, 2, 1, none) 243 | DEF( shl, 1, 2, 1, none) 244 | DEF( sar, 1, 2, 1, none) 245 | DEF( shr, 1, 2, 1, none) 246 | DEF( lt, 1, 2, 1, none) 247 | DEF( lte, 1, 2, 1, none) 248 | DEF( gt, 1, 2, 1, none) 249 | DEF( gte, 1, 2, 1, none) 250 | DEF( instanceof, 1, 2, 1, none) 251 | DEF( in, 1, 2, 1, none) 252 | DEF( eq, 1, 2, 1, none) 253 | DEF( neq, 1, 2, 1, none) 254 | DEF( strict_eq, 1, 2, 1, none) 255 | DEF( strict_neq, 1, 2, 1, none) 256 | DEF( and, 1, 2, 1, none) 257 | DEF( xor, 1, 2, 1, none) 258 | DEF( or, 1, 2, 1, none) 259 | DEF(is_undefined_or_null, 1, 1, 1, none) 260 | #ifdef CONFIG_BIGNUM 261 | DEF( mul_pow10, 1, 2, 1, none) 262 | DEF( math_mod, 1, 2, 1, none) 263 | #endif 264 | /* must be the last non short and non temporary opcode */ 265 | DEF( nop, 1, 0, 0, none) 266 | 267 | /* temporary opcodes: never emitted in the final bytecode */ 268 | 269 | def(set_arg_valid_upto, 3, 0, 0, arg) /* emitted in phase 1, removed in phase 2 */ 270 | 271 | def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ 272 | def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ 273 | 274 | def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ 275 | 276 | def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ 277 | def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ 278 | def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ 279 | def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ 280 | def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ 281 | def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ 282 | def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ 283 | def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ 284 | def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ 285 | def(scope_put_private_field, 7, 1, 1, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ 286 | 287 | def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ 288 | 289 | def( line_num, 5, 0, 0, u32) /* emitted in phase 1, removed in phase 3 */ 290 | 291 | #if SHORT_OPCODES 292 | DEF( push_minus1, 1, 0, 1, none_int) 293 | DEF( push_0, 1, 0, 1, none_int) 294 | DEF( push_1, 1, 0, 1, none_int) 295 | DEF( push_2, 1, 0, 1, none_int) 296 | DEF( push_3, 1, 0, 1, none_int) 297 | DEF( push_4, 1, 0, 1, none_int) 298 | DEF( push_5, 1, 0, 1, none_int) 299 | DEF( push_6, 1, 0, 1, none_int) 300 | DEF( push_7, 1, 0, 1, none_int) 301 | DEF( push_i8, 2, 0, 1, i8) 302 | DEF( push_i16, 3, 0, 1, i16) 303 | DEF( push_const8, 2, 0, 1, const8) 304 | DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ 305 | DEF(push_empty_string, 1, 0, 1, none) 306 | 307 | DEF( get_loc8, 2, 0, 1, loc8) 308 | DEF( put_loc8, 2, 1, 0, loc8) 309 | DEF( set_loc8, 2, 1, 1, loc8) 310 | 311 | DEF( get_loc0, 1, 0, 1, none_loc) 312 | DEF( get_loc1, 1, 0, 1, none_loc) 313 | DEF( get_loc2, 1, 0, 1, none_loc) 314 | DEF( get_loc3, 1, 0, 1, none_loc) 315 | DEF( put_loc0, 1, 1, 0, none_loc) 316 | DEF( put_loc1, 1, 1, 0, none_loc) 317 | DEF( put_loc2, 1, 1, 0, none_loc) 318 | DEF( put_loc3, 1, 1, 0, none_loc) 319 | DEF( set_loc0, 1, 1, 1, none_loc) 320 | DEF( set_loc1, 1, 1, 1, none_loc) 321 | DEF( set_loc2, 1, 1, 1, none_loc) 322 | DEF( set_loc3, 1, 1, 1, none_loc) 323 | DEF( get_arg0, 1, 0, 1, none_arg) 324 | DEF( get_arg1, 1, 0, 1, none_arg) 325 | DEF( get_arg2, 1, 0, 1, none_arg) 326 | DEF( get_arg3, 1, 0, 1, none_arg) 327 | DEF( put_arg0, 1, 1, 0, none_arg) 328 | DEF( put_arg1, 1, 1, 0, none_arg) 329 | DEF( put_arg2, 1, 1, 0, none_arg) 330 | DEF( put_arg3, 1, 1, 0, none_arg) 331 | DEF( set_arg0, 1, 1, 1, none_arg) 332 | DEF( set_arg1, 1, 1, 1, none_arg) 333 | DEF( set_arg2, 1, 1, 1, none_arg) 334 | DEF( set_arg3, 1, 1, 1, none_arg) 335 | DEF( get_var_ref0, 1, 0, 1, none_var_ref) 336 | DEF( get_var_ref1, 1, 0, 1, none_var_ref) 337 | DEF( get_var_ref2, 1, 0, 1, none_var_ref) 338 | DEF( get_var_ref3, 1, 0, 1, none_var_ref) 339 | DEF( put_var_ref0, 1, 1, 0, none_var_ref) 340 | DEF( put_var_ref1, 1, 1, 0, none_var_ref) 341 | DEF( put_var_ref2, 1, 1, 0, none_var_ref) 342 | DEF( put_var_ref3, 1, 1, 0, none_var_ref) 343 | DEF( set_var_ref0, 1, 1, 1, none_var_ref) 344 | DEF( set_var_ref1, 1, 1, 1, none_var_ref) 345 | DEF( set_var_ref2, 1, 1, 1, none_var_ref) 346 | DEF( set_var_ref3, 1, 1, 1, none_var_ref) 347 | 348 | DEF( get_length, 1, 1, 1, none) 349 | 350 | DEF( if_false8, 2, 1, 0, label8) 351 | DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ 352 | DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ 353 | DEF( goto16, 3, 0, 0, label16) 354 | 355 | DEF( call0, 1, 1, 1, npopx) 356 | DEF( call1, 1, 1, 1, npopx) 357 | DEF( call2, 1, 1, 1, npopx) 358 | DEF( call3, 1, 1, 1, npopx) 359 | 360 | DEF( is_undefined, 1, 1, 1, none) 361 | DEF( is_null, 1, 1, 1, none) 362 | DEF( is_function, 1, 1, 1, none) 363 | #endif 364 | 365 | #undef DEF 366 | #undef def 367 | #endif /* DEF */ 368 | --------------------------------------------------------------------------------