code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * Tiny arbitrary precision floating point library * * Copyright (c) 2017-2020 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <math.h> #include <string.h> #include <assert.h> #ifdef __AVX2__ #include <immintrin.h> #endif #include "cutils.h" #include "libbf.h" /* enable it to check the multiplication result */ //#define USE_MUL_CHECK /* enable it to use FFT/NTT multiplication */ #define USE_FFT_MUL /* enable decimal floating point support */ #define USE_BF_DEC //#define inline __attribute__((always_inline)) #ifdef __AVX2__ #define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */ #else #define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */ #endif /* XXX: adjust */ #define DIVNORM_LARGE_THRESHOLD 50 #define UDIV1NORM_THRESHOLD 3 #if LIMB_BITS == 64 #define FMT_LIMB1 "%" PRIx64 #define FMT_LIMB "%016" PRIx64 #define PRId_LIMB PRId64 #define PRIu_LIMB PRIu64 #else #define FMT_LIMB1 "%x" #define FMT_LIMB "%08x" #define PRId_LIMB "d" #define PRIu_LIMB "u" #endif typedef intptr_t mp_size_t; typedef int bf_op2_func_t(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags); #ifdef USE_FFT_MUL #define FFT_MUL_R_OVERLAP_A (1 << 0) #define FFT_MUL_R_OVERLAP_B (1 << 1) #define FFT_MUL_R_NORESIZE (1 << 2) static no_inline int fft_mul(bf_context_t *s, bf_t *res, limb_t *a_tab, limb_t a_len, limb_t *b_tab, limb_t b_len, int mul_flags); static void fft_clear_cache(bf_context_t *s); #endif #ifdef USE_BF_DEC static limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos); #endif /* could leading zeros */ static inline int clz(limb_t a) { if (a == 0) { return LIMB_BITS; } else { #if LIMB_BITS == 64 return clz64(a); #else return clz32(a); #endif } } static inline int ctz(limb_t a) { if (a == 0) { return LIMB_BITS; } else { #if LIMB_BITS == 64 return ctz64(a); #else return ctz32(a); #endif } } static inline int ceil_log2(limb_t a) { if (a <= 1) return 0; else return LIMB_BITS - clz(a - 1); } /* b must be >= 1 */ static inline slimb_t ceil_div(slimb_t a, slimb_t b) { if (a >= 0) return (a + b - 1) / b; else return a / b; } /* b must be >= 1 */ static inline slimb_t floor_div(slimb_t a, slimb_t b) { if (a >= 0) { return a / b; } else { return (a - b + 1) / b; } } /* return r = a modulo b (0 <= r <= b - 1. b must be >= 1 */ static inline limb_t smod(slimb_t a, slimb_t b) { a = a % (slimb_t)b; if (a < 0) a += b; return a; } /* signed addition with saturation */ static inline slimb_t sat_add(slimb_t a, slimb_t b) { slimb_t r; r = a + b; /* overflow ? */ if (((a ^ r) & (b ^ r)) < 0) r = (a >> (LIMB_BITS - 1)) ^ (((limb_t)1 << (LIMB_BITS - 1)) - 1); return r; } #define malloc(s) malloc_is_forbidden(s) #define free(p) free_is_forbidden(p) #define realloc(p, s) realloc_is_forbidden(p, s) void bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func, void *realloc_opaque) { memset(s, 0, sizeof(*s)); s->realloc_func = realloc_func; s->realloc_opaque = realloc_opaque; } void bf_context_end(bf_context_t *s) { bf_clear_cache(s); } void bf_init(bf_context_t *s, bf_t *r) { r->ctx = s; r->sign = 0; r->expn = BF_EXP_ZERO; r->len = 0; r->tab = NULL; } /* return 0 if OK, -1 if alloc error */ int bf_resize(bf_t *r, limb_t len) { limb_t *tab; if (len != r->len) { tab = bf_realloc(r->ctx, r->tab, len * sizeof(limb_t)); if (!tab && len != 0) return -1; r->tab = tab; r->len = len; } return 0; } /* return 0 or BF_ST_MEM_ERROR */ int bf_set_ui(bf_t *r, uint64_t a) { r->sign = 0; if (a == 0) { r->expn = BF_EXP_ZERO; bf_resize(r, 0); /* cannot fail */ } #if LIMB_BITS == 32 else if (a <= 0xffffffff) #else else #endif { int shift; if (bf_resize(r, 1)) goto fail; shift = clz(a); r->tab[0] = a << shift; r->expn = LIMB_BITS - shift; } #if LIMB_BITS == 32 else { uint32_t a1, a0; int shift; if (bf_resize(r, 2)) goto fail; a0 = a; a1 = a >> 32; shift = clz(a1); r->tab[0] = a0 << shift; r->tab[1] = (a1 << shift) | (a0 >> (LIMB_BITS - shift)); r->expn = 2 * LIMB_BITS - shift; } #endif return 0; fail: bf_set_nan(r); return BF_ST_MEM_ERROR; } /* return 0 or BF_ST_MEM_ERROR */ int bf_set_si(bf_t *r, int64_t a) { int ret; if (a < 0) { ret = bf_set_ui(r, -a); r->sign = 1; } else { ret = bf_set_ui(r, a); } return ret; } void bf_set_nan(bf_t *r) { bf_resize(r, 0); /* cannot fail */ r->expn = BF_EXP_NAN; r->sign = 0; } void bf_set_zero(bf_t *r, int is_neg) { bf_resize(r, 0); /* cannot fail */ r->expn = BF_EXP_ZERO; r->sign = is_neg; } void bf_set_inf(bf_t *r, int is_neg) { bf_resize(r, 0); /* cannot fail */ r->expn = BF_EXP_INF; r->sign = is_neg; } /* return 0 or BF_ST_MEM_ERROR */ int bf_set(bf_t *r, const bf_t *a) { if (r == a) return 0; if (bf_resize(r, a->len)) { bf_set_nan(r); return BF_ST_MEM_ERROR; } r->sign = a->sign; r->expn = a->expn; memcpy(r->tab, a->tab, a->len * sizeof(limb_t)); return 0; } /* equivalent to bf_set(r, a); bf_delete(a) */ void bf_move(bf_t *r, bf_t *a) { bf_context_t *s = r->ctx; if (r == a) return; bf_free(s, r->tab); *r = *a; } static limb_t get_limbz(const bf_t *a, limb_t idx) { if (idx >= a->len) return 0; else return a->tab[idx]; } /* get LIMB_BITS at bit position 'pos' in tab */ static inline limb_t get_bits(const limb_t *tab, limb_t len, slimb_t pos) { limb_t i, a0, a1; int p; i = pos >> LIMB_LOG2_BITS; p = pos & (LIMB_BITS - 1); if (i < len) a0 = tab[i]; else a0 = 0; if (p == 0) { return a0; } else { i++; if (i < len) a1 = tab[i]; else a1 = 0; return (a0 >> p) | (a1 << (LIMB_BITS - p)); } } static inline limb_t get_bit(const limb_t *tab, limb_t len, slimb_t pos) { slimb_t i; i = pos >> LIMB_LOG2_BITS; if (i < 0 || i >= len) return 0; return (tab[i] >> (pos & (LIMB_BITS - 1))) & 1; } static inline limb_t limb_mask(int start, int last) { limb_t v; int n; n = last - start + 1; if (n == LIMB_BITS) v = -1; else v = (((limb_t)1 << n) - 1) << start; return v; } static limb_t mp_scan_nz(const limb_t *tab, mp_size_t n) { mp_size_t i; for(i = 0; i < n; i++) { if (tab[i] != 0) return 1; } return 0; } /* return != 0 if one bit between 0 and bit_pos inclusive is not zero. */ static inline limb_t scan_bit_nz(const bf_t *r, slimb_t bit_pos) { slimb_t pos; limb_t v; pos = bit_pos >> LIMB_LOG2_BITS; if (pos < 0) return 0; v = r->tab[pos] & limb_mask(0, bit_pos & (LIMB_BITS - 1)); if (v != 0) return 1; pos--; while (pos >= 0) { if (r->tab[pos] != 0) return 1; pos--; } return 0; } /* return the addend for rounding. Note that prec can be <= 0 (for BF_FLAG_RADPNT_PREC) */ static int bf_get_rnd_add(int *pret, const bf_t *r, limb_t l, slimb_t prec, int rnd_mode) { int add_one, inexact; limb_t bit1, bit0; if (rnd_mode == BF_RNDF) { bit0 = 1; /* faithful rounding does not honor the INEXACT flag */ } else { /* starting limb for bit 'prec + 1' */ bit0 = scan_bit_nz(r, l * LIMB_BITS - 1 - bf_max(0, prec + 1)); } /* get the bit at 'prec' */ bit1 = get_bit(r->tab, l, l * LIMB_BITS - 1 - prec); inexact = (bit1 | bit0) != 0; add_one = 0; switch(rnd_mode) { case BF_RNDZ: break; case BF_RNDN: if (bit1) { if (bit0) { add_one = 1; } else { /* round to even */ add_one = get_bit(r->tab, l, l * LIMB_BITS - 1 - (prec - 1)); } } break; case BF_RNDD: case BF_RNDU: if (r->sign == (rnd_mode == BF_RNDD)) add_one = inexact; break; case BF_RNDA: add_one = inexact; break; case BF_RNDNA: case BF_RNDF: add_one = bit1; break; default: abort(); } if (inexact) *pret |= BF_ST_INEXACT; return add_one; } static int bf_set_overflow(bf_t *r, int sign, limb_t prec, bf_flags_t flags) { slimb_t i, l, e_max; int rnd_mode; rnd_mode = flags & BF_RND_MASK; if (prec == BF_PREC_INF || rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA || rnd_mode == BF_RNDA || (rnd_mode == BF_RNDD && sign == 1) || (rnd_mode == BF_RNDU && sign == 0)) { bf_set_inf(r, sign); } else { /* set to maximum finite number */ l = (prec + LIMB_BITS - 1) / LIMB_BITS; if (bf_resize(r, l)) { bf_set_nan(r); return BF_ST_MEM_ERROR; } r->tab[0] = limb_mask((-prec) & (LIMB_BITS - 1), LIMB_BITS - 1); for(i = 1; i < l; i++) r->tab[i] = (limb_t)-1; e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1); r->expn = e_max; r->sign = sign; } return BF_ST_OVERFLOW | BF_ST_INEXACT; } /* round to prec1 bits assuming 'r' is non zero and finite. 'r' is assumed to have length 'l' (1 <= l <= r->len). Note: 'prec1' can be infinite (BF_PREC_INF). 'ret' is 0 or BF_ST_INEXACT if the result is known to be inexact. Can fail with BF_ST_MEM_ERROR in case of overflow not returning infinity. */ static int __bf_round(bf_t *r, limb_t prec1, bf_flags_t flags, limb_t l, int ret) { limb_t v, a; int shift, add_one, rnd_mode; slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec; /* e_min and e_max are computed to match the IEEE 754 conventions */ e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1); e_min = -e_range + 3; e_max = e_range; if (flags & BF_FLAG_RADPNT_PREC) { /* 'prec' is the precision after the radix point */ if (prec1 != BF_PREC_INF) prec = r->expn + prec1; else prec = prec1; } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) { /* restrict the precision in case of potentially subnormal result */ assert(prec1 != BF_PREC_INF); prec = prec1 - (e_min - r->expn); } else { prec = prec1; } /* round to prec bits */ rnd_mode = flags & BF_RND_MASK; add_one = bf_get_rnd_add(&ret, r, l, prec, rnd_mode); if (prec <= 0) { if (add_one) { bf_resize(r, 1); /* cannot fail */ r->tab[0] = (limb_t)1 << (LIMB_BITS - 1); r->expn += 1 - prec; ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT; return ret; } else { goto underflow; } } else if (add_one) { limb_t carry; /* add one starting at digit 'prec - 1' */ bit_pos = l * LIMB_BITS - 1 - (prec - 1); pos = bit_pos >> LIMB_LOG2_BITS; carry = (limb_t)1 << (bit_pos & (LIMB_BITS - 1)); for(i = pos; i < l; i++) { v = r->tab[i] + carry; carry = (v < carry); r->tab[i] = v; if (carry == 0) break; } if (carry) { /* shift right by one digit */ v = 1; for(i = l - 1; i >= pos; i--) { a = r->tab[i]; r->tab[i] = (a >> 1) | (v << (LIMB_BITS - 1)); v = a; } r->expn++; } } /* check underflow */ if (unlikely(r->expn < e_min)) { if (flags & BF_FLAG_SUBNORMAL) { /* if inexact, also set the underflow flag */ if (ret & BF_ST_INEXACT) ret |= BF_ST_UNDERFLOW; } else { underflow: ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT; bf_set_zero(r, r->sign); return ret; } } /* check overflow */ if (unlikely(r->expn > e_max)) return bf_set_overflow(r, r->sign, prec1, flags); /* keep the bits starting at 'prec - 1' */ bit_pos = l * LIMB_BITS - 1 - (prec - 1); i = bit_pos >> LIMB_LOG2_BITS; if (i >= 0) { shift = bit_pos & (LIMB_BITS - 1); if (shift != 0) r->tab[i] &= limb_mask(shift, LIMB_BITS - 1); } else { i = 0; } /* remove trailing zeros */ while (r->tab[i] == 0) i++; if (i > 0) { l -= i; memmove(r->tab, r->tab + i, l * sizeof(limb_t)); } bf_resize(r, l); /* cannot fail */ return ret; } /* 'r' must be a finite number. */ int bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags) { limb_t l, v, a; int shift, ret; slimb_t i; // bf_print_str("bf_renorm", r); l = r->len; while (l > 0 && r->tab[l - 1] == 0) l--; if (l == 0) { /* zero */ r->expn = BF_EXP_ZERO; bf_resize(r, 0); /* cannot fail */ ret = 0; } else { r->expn -= (r->len - l) * LIMB_BITS; /* shift to have the MSB set to '1' */ v = r->tab[l - 1]; shift = clz(v); if (shift != 0) { v = 0; for(i = 0; i < l; i++) { a = r->tab[i]; r->tab[i] = (a << shift) | (v >> (LIMB_BITS - shift)); v = a; } r->expn -= shift; } ret = __bf_round(r, prec1, flags, l, 0); } // bf_print_str("r_final", r); return ret; } /* return true if rounding can be done at precision 'prec' assuming the exact result r is such that |r-a| <= 2^(EXP(a)-k). */ /* XXX: check the case where the exponent would be incremented by the rounding */ int bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k) { BOOL is_rndn; slimb_t bit_pos, n; limb_t bit; if (a->expn == BF_EXP_INF || a->expn == BF_EXP_NAN) return FALSE; if (rnd_mode == BF_RNDF) { return (k >= (prec + 1)); } if (a->expn == BF_EXP_ZERO) return FALSE; is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA); if (k < (prec + 2)) return FALSE; bit_pos = a->len * LIMB_BITS - 1 - prec; n = k - prec; /* bit pattern for RNDN or RNDNA: 0111.. or 1000... for other rounding modes: 000... or 111... */ bit = get_bit(a->tab, a->len, bit_pos); bit_pos--; n--; bit ^= is_rndn; /* XXX: slow, but a few iterations on average */ while (n != 0) { if (get_bit(a->tab, a->len, bit_pos) != bit) return TRUE; bit_pos--; n--; } return FALSE; } /* Cannot fail with BF_ST_MEM_ERROR. */ int bf_round(bf_t *r, limb_t prec, bf_flags_t flags) { if (r->len == 0) return 0; return __bf_round(r, prec, flags, r->len, 0); } /* for debugging */ static __maybe_unused void dump_limbs(const char *str, const limb_t *tab, limb_t n) { limb_t i; printf("%s: len=%" PRId_LIMB "\n", str, n); for(i = 0; i < n; i++) { printf("%" PRId_LIMB ": " FMT_LIMB "\n", i, tab[i]); } } void mp_print_str_a(const char *str, const limb_t *tab, limb_t n) { slimb_t i; printf("%s= 0x", str); for(i = n - 1; i >= 0; i--) { if (i != (n - 1)) printf("_"); printf(FMT_LIMB, tab[i]); } printf("\n"); } static __maybe_unused void mp_print_str_h(const char *str, const limb_t *tab, limb_t n, limb_t high) { slimb_t i; printf("%s= 0x", str); printf(FMT_LIMB, high); for(i = n - 1; i >= 0; i--) { printf("_"); printf(FMT_LIMB, tab[i]); } printf("\n"); } /* for debugging */ void bf_print_str(const char *str, const bf_t *a) { slimb_t i; printf("%s=", str); if (a->expn == BF_EXP_NAN) { printf("NaN"); } else { if (a->sign) putchar('-'); if (a->expn == BF_EXP_ZERO) { putchar('0'); } else if (a->expn == BF_EXP_INF) { printf("Inf"); } else { printf("0x0."); for(i = a->len - 1; i >= 0; i--) printf(FMT_LIMB, a->tab[i]); printf("p%" PRId_LIMB, a->expn); } } printf("\n"); } /* compare the absolute value of 'a' and 'b'. Return < 0 if a < b, 0 if a = b and > 0 otherwise. */ int bf_cmpu(const bf_t *a, const bf_t *b) { slimb_t i; limb_t len, v1, v2; if (a->expn != b->expn) { if (a->expn < b->expn) return -1; else return 1; } len = bf_max(a->len, b->len); for(i = len - 1; i >= 0; i--) { v1 = get_limbz(a, a->len - len + i); v2 = get_limbz(b, b->len - len + i); if (v1 != v2) { if (v1 < v2) return -1; else return 1; } } return 0; } /* Full order: -0 < 0, NaN == NaN and NaN is larger than all other numbers */ int bf_cmp_full(const bf_t *a, const bf_t *b) { int res; if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { if (a->expn == b->expn) res = 0; else if (a->expn == BF_EXP_NAN) res = 1; else res = -1; } else if (a->sign != b->sign) { res = 1 - 2 * a->sign; } else { res = bf_cmpu(a, b); if (a->sign) res = -res; } return res; } /* Standard floating point comparison: return 2 if one of the operands is NaN (unordered) or -1, 0, 1 depending on the ordering assuming -0 == +0 */ int bf_cmp(const bf_t *a, const bf_t *b) { int res; if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { res = 2; } else if (a->sign != b->sign) { if (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO) res = 0; else res = 1 - 2 * a->sign; } else { res = bf_cmpu(a, b); if (a->sign) res = -res; } return res; } /* Compute the number of bits 'n' matching the pattern: a= X1000..0 b= X0111..1 When computing a-b, the result will have at least n leading zero bits. Precondition: a > b and a.expn - b.expn = 0 or 1 */ static limb_t count_cancelled_bits(const bf_t *a, const bf_t *b) { slimb_t bit_offset, b_offset, n; int p, p1; limb_t v1, v2, mask; bit_offset = a->len * LIMB_BITS - 1; b_offset = (b->len - a->len) * LIMB_BITS - (LIMB_BITS - 1) + a->expn - b->expn; n = 0; /* first search the equals bits */ for(;;) { v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS); v2 = get_bits(b->tab, b->len, bit_offset + b_offset); // printf("v1=" FMT_LIMB " v2=" FMT_LIMB "\n", v1, v2); if (v1 != v2) break; n += LIMB_BITS; bit_offset -= LIMB_BITS; } /* find the position of the first different bit */ p = clz(v1 ^ v2) + 1; n += p; /* then search for '0' in a and '1' in b */ p = LIMB_BITS - p; if (p > 0) { /* search in the trailing p bits of v1 and v2 */ mask = limb_mask(0, p - 1); p1 = bf_min(clz(v1 & mask), clz((~v2) & mask)) - (LIMB_BITS - p); n += p1; if (p1 != p) goto done; } bit_offset -= LIMB_BITS; for(;;) { v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS); v2 = get_bits(b->tab, b->len, bit_offset + b_offset); // printf("v1=" FMT_LIMB " v2=" FMT_LIMB "\n", v1, v2); if (v1 != 0 || v2 != -1) { /* different: count the matching bits */ p1 = bf_min(clz(v1), clz(~v2)); n += p1; break; } n += LIMB_BITS; bit_offset -= LIMB_BITS; } done: return n; } static int bf_add_internal(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int b_neg) { const bf_t *tmp; int is_sub, ret, cmp_res, a_sign, b_sign; a_sign = a->sign; b_sign = b->sign ^ b_neg; is_sub = a_sign ^ b_sign; cmp_res = bf_cmpu(a, b); if (cmp_res < 0) { tmp = a; a = b; b = tmp; a_sign = b_sign; /* b_sign is never used later */ } /* abs(a) >= abs(b) */ if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) { /* zero result */ bf_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD); ret = 0; } else if (a->len == 0 || b->len == 0) { ret = 0; if (a->expn >= BF_EXP_INF) { if (a->expn == BF_EXP_NAN) { /* at least one operand is NaN */ bf_set_nan(r); } else if (b->expn == BF_EXP_INF && is_sub) { /* infinities with different signs */ bf_set_nan(r); ret = BF_ST_INVALID_OP; } else { bf_set_inf(r, a_sign); } } else { /* at least one zero and not subtract */ bf_set(r, a); r->sign = a_sign; goto renorm; } } else { slimb_t d, a_offset, b_bit_offset, i, cancelled_bits; limb_t carry, v1, v2, u, r_len, carry1, precl, tot_len, z, sub_mask; r->sign = a_sign; r->expn = a->expn; d = a->expn - b->expn; /* must add more precision for the leading cancelled bits in subtraction */ if (is_sub) { if (d <= 1) cancelled_bits = count_cancelled_bits(a, b); else cancelled_bits = 1; } else { cancelled_bits = 0; } /* add two extra bits for rounding */ precl = (cancelled_bits + prec + 2 + LIMB_BITS - 1) / LIMB_BITS; tot_len = bf_max(a->len, b->len + (d + LIMB_BITS - 1) / LIMB_BITS); r_len = bf_min(precl, tot_len); if (bf_resize(r, r_len)) goto fail; a_offset = a->len - r_len; b_bit_offset = (b->len - r_len) * LIMB_BITS + d; /* compute the bits before for the rounding */ carry = is_sub; z = 0; sub_mask = -is_sub; i = r_len - tot_len; while (i < 0) { slimb_t ap, bp; BOOL inflag; ap = a_offset + i; bp = b_bit_offset + i * LIMB_BITS; inflag = FALSE; if (ap >= 0 && ap < a->len) { v1 = a->tab[ap]; inflag = TRUE; } else { v1 = 0; } if (bp + LIMB_BITS > 0 && bp < (slimb_t)(b->len * LIMB_BITS)) { v2 = get_bits(b->tab, b->len, bp); inflag = TRUE; } else { v2 = 0; } if (!inflag) { /* outside 'a' and 'b': go directly to the next value inside a or b so that the running time does not depend on the exponent difference */ i = 0; if (ap < 0) i = bf_min(i, -a_offset); /* b_bit_offset + i * LIMB_BITS + LIMB_BITS >= 1 equivalent to i >= ceil(-b_bit_offset + 1 - LIMB_BITS) / LIMB_BITS) */ if (bp + LIMB_BITS <= 0) i = bf_min(i, (-b_bit_offset) >> LIMB_LOG2_BITS); } else { i++; } v2 ^= sub_mask; u = v1 + v2; carry1 = u < v1; u += carry; carry = (u < carry) | carry1; z |= u; } /* and the result */ for(i = 0; i < r_len; i++) { v1 = get_limbz(a, a_offset + i); v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS); v2 ^= sub_mask; u = v1 + v2; carry1 = u < v1; u += carry; carry = (u < carry) | carry1; r->tab[i] = u; } /* set the extra bits for the rounding */ r->tab[0] |= (z != 0); /* carry is only possible in add case */ if (!is_sub && carry) { if (bf_resize(r, r_len + 1)) goto fail; r->tab[r_len] = 1; r->expn += LIMB_BITS; } renorm: ret = bf_normalize_and_round(r, prec, flags); } return ret; fail: bf_set_nan(r); return BF_ST_MEM_ERROR; } static int __bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { return bf_add_internal(r, a, b, prec, flags, 0); } static int __bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { return bf_add_internal(r, a, b, prec, flags, 1); } limb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, limb_t n, limb_t carry) { slimb_t i; limb_t k, a, v, k1; k = carry; for(i=0;i<n;i++) { v = op1[i]; a = v + op2[i]; k1 = a < v; a = a + k; k = (a < k) | k1; res[i] = a; } return k; } limb_t mp_add_ui(limb_t *tab, limb_t b, size_t n) { size_t i; limb_t k, a; k=b; for(i=0;i<n;i++) { if (k == 0) break; a = tab[i] + k; k = (a < k); tab[i] = a; } return k; } limb_t mp_sub(limb_t *res, const limb_t *op1, const limb_t *op2, mp_size_t n, limb_t carry) { int i; limb_t k, a, v, k1; k = carry; for(i=0;i<n;i++) { v = op1[i]; a = v - op2[i]; k1 = a > v; v = a - k; k = (v > a) | k1; res[i] = v; } return k; } /* compute 0 - op2 */ static limb_t mp_neg(limb_t *res, const limb_t *op2, mp_size_t n, limb_t carry) { int i; limb_t k, a, v, k1; k = carry; for(i=0;i<n;i++) { v = 0; a = v - op2[i]; k1 = a > v; v = a - k; k = (v > a) | k1; res[i] = v; } return k; } limb_t mp_sub_ui(limb_t *tab, limb_t b, mp_size_t n) { mp_size_t i; limb_t k, a, v; k=b; for(i=0;i<n;i++) { v = tab[i]; a = v - k; k = a > v; tab[i] = a; if (k == 0) break; } return k; } /* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). 1 <= shift <= LIMB_BITS - 1 */ static limb_t mp_shr(limb_t *tab_r, const limb_t *tab, mp_size_t n, int shift, limb_t high) { mp_size_t i; limb_t l, a; assert(shift >= 1 && shift < LIMB_BITS); l = high; for(i = n - 1; i >= 0; i--) { a = tab[i]; tab_r[i] = (a >> shift) | (l << (LIMB_BITS - shift)); l = a; } return l & (((limb_t)1 << shift) - 1); } /* tabr[] = taba[] * b + l. Return the high carry */ static limb_t mp_mul1(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b, limb_t l) { limb_t i; dlimb_t t; for(i = 0; i < n; i++) { t = (dlimb_t)taba[i] * (dlimb_t)b + l; tabr[i] = t; l = t >> LIMB_BITS; } return l; } /* tabr[] += taba[] * b, return the high word. */ static limb_t mp_add_mul1(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b) { limb_t i, l; dlimb_t t; l = 0; for(i = 0; i < n; i++) { t = (dlimb_t)taba[i] * (dlimb_t)b + l + tabr[i]; tabr[i] = t; l = t >> LIMB_BITS; } return l; } /* size of the result : op1_size + op2_size. */ static void mp_mul_basecase(limb_t *result, const limb_t *op1, limb_t op1_size, const limb_t *op2, limb_t op2_size) { limb_t i, r; result[op1_size] = mp_mul1(result, op1, op1_size, op2[0], 0); for(i=1;i<op2_size;i++) { r = mp_add_mul1(result + i, op1, op1_size, op2[i]); result[i + op1_size] = r; } } /* return 0 if OK, -1 if memory error */ /* XXX: change API so that result can be allocated */ int mp_mul(bf_context_t *s, limb_t *result, const limb_t *op1, limb_t op1_size, const limb_t *op2, limb_t op2_size) { #ifdef USE_FFT_MUL if (unlikely(bf_min(op1_size, op2_size) >= FFT_MUL_THRESHOLD)) { bf_t r_s, *r = &r_s; r->tab = result; /* XXX: optimize memory usage in API */ if (fft_mul(s, r, (limb_t *)op1, op1_size, (limb_t *)op2, op2_size, FFT_MUL_R_NORESIZE)) return -1; } else #endif { mp_mul_basecase(result, op1, op1_size, op2, op2_size); } return 0; } /* tabr[] -= taba[] * b. Return the value to substract to the high word. */ static limb_t mp_sub_mul1(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b) { limb_t i, l; dlimb_t t; l = 0; for(i = 0; i < n; i++) { t = tabr[i] - (dlimb_t)taba[i] * (dlimb_t)b - l; tabr[i] = t; l = -(t >> LIMB_BITS); } return l; } /* WARNING: d must be >= 2^(LIMB_BITS-1) */ static inline limb_t udiv1norm_init(limb_t d) { limb_t a0, a1; a1 = -d - 1; a0 = -1; return (((dlimb_t)a1 << LIMB_BITS) | a0) / d; } /* return the quotient and the remainder in '*pr'of 'a1*2^LIMB_BITS+a0 / d' with 0 <= a1 < d. */ static inline limb_t udiv1norm(limb_t *pr, limb_t a1, limb_t a0, limb_t d, limb_t d_inv) { limb_t n1m, n_adj, q, r, ah; dlimb_t a; n1m = ((slimb_t)a0 >> (LIMB_BITS - 1)); n_adj = a0 + (n1m & d); a = (dlimb_t)d_inv * (a1 - n1m) + n_adj; q = (a >> LIMB_BITS) + a1; /* compute a - q * r and update q so that the remainder is\ between 0 and d - 1 */ a = ((dlimb_t)a1 << LIMB_BITS) | a0; a = a - (dlimb_t)q * d - d; ah = a >> LIMB_BITS; q += 1 + ah; r = (limb_t)a + (ah & d); *pr = r; return q; } /* b must be >= 1 << (LIMB_BITS - 1) */ static limb_t mp_div1norm(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b, limb_t r) { slimb_t i; if (n >= UDIV1NORM_THRESHOLD) { limb_t b_inv; b_inv = udiv1norm_init(b); for(i = n - 1; i >= 0; i--) { tabr[i] = udiv1norm(&r, r, taba[i], b, b_inv); } } else { dlimb_t a1; for(i = n - 1; i >= 0; i--) { a1 = ((dlimb_t)r << LIMB_BITS) | taba[i]; tabr[i] = a1 / b; r = a1 % b; } } return r; } static int mp_divnorm_large(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na, const limb_t *tabb, limb_t nb); /* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb - 1] must be >= 1 << (LIMB_BITS - 1). na - nb must be >= 0. 'taba' is modified and contains the remainder (nb limbs). tabq[0..na-nb] contains the quotient with tabq[na - nb] <= 1. */ static int mp_divnorm(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na, const limb_t *tabb, limb_t nb) { limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r; slimb_t i, j; b1 = tabb[nb - 1]; if (nb == 1) { taba[0] = mp_div1norm(tabq, taba, na, b1, 0); return 0; } n = na - nb; if (bf_min(n, nb) >= DIVNORM_LARGE_THRESHOLD) { return mp_divnorm_large(s, tabq, taba, na, tabb, nb); } if (n >= UDIV1NORM_THRESHOLD) b1_inv = udiv1norm_init(b1); else b1_inv = 0; /* first iteration: the quotient is only 0 or 1 */ q = 1; for(j = nb - 1; j >= 0; j--) { if (taba[n + j] != tabb[j]) { if (taba[n + j] < tabb[j]) q = 0; break; } } tabq[n] = q; if (q) { mp_sub(taba + n, taba + n, tabb, nb, 0); } for(i = n - 1; i >= 0; i--) { if (unlikely(taba[i + nb] >= b1)) { q = -1; } else if (b1_inv) { q = udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv); } else { dlimb_t al; al = ((dlimb_t)taba[i + nb] << LIMB_BITS) | taba[i + nb - 1]; q = al / b1; r = al % b1; } r = mp_sub_mul1(taba + i, tabb, nb, q); v = taba[i + nb]; a = v - r; c = (a > v); taba[i + nb] = a; if (c != 0) { /* negative result */ for(;;) { q--; c = mp_add(taba + i, taba + i, tabb, nb, 0); /* propagate carry and test if positive result */ if (c != 0) { if (++taba[i + nb] == 0) { break; } } } } tabq[i] = q; } return 0; } /* compute r=B^(2*n)/a such as a*r < B^(2*n) < a*r + 2 with n >= 1. 'a' has n limbs with a[n-1] >= B/2 and 'r' has n+1 limbs with r[n] = 1. See Modern Computer Arithmetic by Richard P. Brent and Paul Zimmermann, algorithm 3.5 */ int mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n) { mp_size_t l, h, k, i; limb_t *tabxh, *tabt, c, *tabu; if (n <= 2) { /* return ceil(B^(2*n)/a) - 1 */ /* XXX: could avoid allocation */ tabu = bf_malloc(s, sizeof(limb_t) * (2 * n + 1)); tabt = bf_malloc(s, sizeof(limb_t) * (n + 2)); if (!tabt || !tabu) goto fail; for(i = 0; i < 2 * n; i++) tabu[i] = 0; tabu[2 * n] = 1; if (mp_divnorm(s, tabt, tabu, 2 * n + 1, taba, n)) goto fail; for(i = 0; i < n + 1; i++) tabr[i] = tabt[i]; if (mp_scan_nz(tabu, n) == 0) { /* only happens for a=B^n/2 */ mp_sub_ui(tabr, 1, n + 1); } } else { l = (n - 1) / 2; h = n - l; /* n=2p -> l=p-1, h = p + 1, k = p + 3 n=2p+1-> l=p, h = p + 1; k = p + 2 */ tabt = bf_malloc(s, sizeof(limb_t) * (n + h + 1)); tabu = bf_malloc(s, sizeof(limb_t) * (n + 2 * h - l + 2)); if (!tabt || !tabu) goto fail; tabxh = tabr + l; if (mp_recip(s, tabxh, taba + l, h)) goto fail; if (mp_mul(s, tabt, taba, n, tabxh, h + 1)) /* n + h + 1 limbs */ goto fail; while (tabt[n + h] != 0) { mp_sub_ui(tabxh, 1, h + 1); c = mp_sub(tabt, tabt, taba, n, 0); mp_sub_ui(tabt + n, c, h + 1); } /* T = B^(n+h) - T */ mp_neg(tabt, tabt, n + h + 1, 0); tabt[n + h]++; if (mp_mul(s, tabu, tabt + l, n + h + 1 - l, tabxh, h + 1)) goto fail; /* n + 2*h - l + 2 limbs */ k = 2 * h - l; for(i = 0; i < l; i++) tabr[i] = tabu[i + k]; mp_add(tabr + l, tabr + l, tabu + 2 * h, h, 0); } bf_free(s, tabt); bf_free(s, tabu); return 0; fail: bf_free(s, tabt); bf_free(s, tabu); return -1; } /* return -1, 0 or 1 */ static int mp_cmp(const limb_t *taba, const limb_t *tabb, mp_size_t n) { mp_size_t i; for(i = n - 1; i >= 0; i--) { if (taba[i] != tabb[i]) { if (taba[i] < tabb[i]) return -1; else return 1; } } return 0; } //#define DEBUG_DIVNORM_LARGE //#define DEBUG_DIVNORM_LARGE2 /* subquadratic divnorm */ static int mp_divnorm_large(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na, const limb_t *tabb, limb_t nb) { limb_t *tabb_inv, nq, *tabt, i, n; nq = na - nb; #ifdef DEBUG_DIVNORM_LARGE printf("na=%d nb=%d nq=%d\n", (int)na, (int)nb, (int)nq); mp_print_str_a("a", taba, na); mp_print_str_a("b", tabb, nb); #endif assert(nq >= 1); n = nq; if (nq < nb) n++; tabb_inv = bf_malloc(s, sizeof(limb_t) * (n + 1)); tabt = bf_malloc(s, sizeof(limb_t) * 2 * (n + 1)); if (!tabb_inv || !tabt) goto fail; if (n >= nb) { for(i = 0; i < n - nb; i++) tabt[i] = 0; for(i = 0; i < nb; i++) tabt[i + n - nb] = tabb[i]; } else { /* truncate B: need to increment it so that the approximate inverse is smaller that the exact inverse */ for(i = 0; i < n; i++) tabt[i] = tabb[i + nb - n]; if (mp_add_ui(tabt, 1, n)) { /* tabt = B^n : tabb_inv = B^n */ memset(tabb_inv, 0, n * sizeof(limb_t)); tabb_inv[n] = 1; goto recip_done; } } if (mp_recip(s, tabb_inv, tabt, n)) goto fail; recip_done: /* Q=A*B^-1 */ if (mp_mul(s, tabt, tabb_inv, n + 1, taba + na - (n + 1), n + 1)) goto fail; for(i = 0; i < nq + 1; i++) tabq[i] = tabt[i + 2 * (n + 1) - (nq + 1)]; #ifdef DEBUG_DIVNORM_LARGE mp_print_str_a("q", tabq, nq + 1); #endif bf_free(s, tabt); bf_free(s, tabb_inv); tabb_inv = NULL; /* R=A-B*Q */ tabt = bf_malloc(s, sizeof(limb_t) * (na + 1)); if (!tabt) goto fail; if (mp_mul(s, tabt, tabq, nq + 1, tabb, nb)) goto fail; /* we add one more limb for the result */ mp_sub(taba, taba, tabt, nb + 1, 0); bf_free(s, tabt); /* the approximated quotient is smaller than than the exact one, hence we may have to increment it */ #ifdef DEBUG_DIVNORM_LARGE2 int cnt = 0; static int cnt_max; #endif for(;;) { if (taba[nb] == 0 && mp_cmp(taba, tabb, nb) < 0) break; taba[nb] -= mp_sub(taba, taba, tabb, nb, 0); mp_add_ui(tabq, 1, nq + 1); #ifdef DEBUG_DIVNORM_LARGE2 cnt++; #endif } #ifdef DEBUG_DIVNORM_LARGE2 if (cnt > cnt_max) { cnt_max = cnt; printf("\ncnt=%d nq=%d nb=%d\n", cnt_max, (int)nq, (int)nb); } #endif return 0; fail: bf_free(s, tabb_inv); bf_free(s, tabt); return -1; } int bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { int ret, r_sign; if (a->len < b->len) { const bf_t *tmp = a; a = b; b = tmp; } r_sign = a->sign ^ b->sign; /* here b->len <= a->len */ if (b->len == 0) { if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bf_set_nan(r); ret = 0; } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) { if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) || (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) { bf_set_nan(r); ret = BF_ST_INVALID_OP; } else { bf_set_inf(r, r_sign); ret = 0; } } else { bf_set_zero(r, r_sign); ret = 0; } } else { bf_t tmp, *r1 = NULL; limb_t a_len, b_len, precl; limb_t *a_tab, *b_tab; a_len = a->len; b_len = b->len; if ((flags & BF_RND_MASK) == BF_RNDF) { /* faithful rounding does not require using the full inputs */ precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS; a_len = bf_min(a_len, precl); b_len = bf_min(b_len, precl); } a_tab = a->tab + a->len - a_len; b_tab = b->tab + b->len - b_len; #ifdef USE_FFT_MUL if (b_len >= FFT_MUL_THRESHOLD) { int mul_flags = 0; if (r == a) mul_flags |= FFT_MUL_R_OVERLAP_A; if (r == b) mul_flags |= FFT_MUL_R_OVERLAP_B; if (fft_mul(r->ctx, r, a_tab, a_len, b_tab, b_len, mul_flags)) goto fail; } else #endif { if (r == a || r == b) { bf_init(r->ctx, &tmp); r1 = r; r = &tmp; } if (bf_resize(r, a_len + b_len)) { fail: bf_set_nan(r); ret = BF_ST_MEM_ERROR; goto done; } mp_mul_basecase(r->tab, a_tab, a_len, b_tab, b_len); } r->sign = r_sign; r->expn = a->expn + b->expn; ret = bf_normalize_and_round(r, prec, flags); done: if (r == &tmp) bf_move(r1, &tmp); } return ret; } /* multiply 'r' by 2^e */ int bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags) { slimb_t e_max; if (r->len == 0) return 0; e_max = ((limb_t)1 << BF_EXT_EXP_BITS_MAX) - 1; e = bf_max(e, -e_max); e = bf_min(e, e_max); r->expn += e; return __bf_round(r, prec, flags, r->len, 0); } /* Return e such as a=m*2^e with m odd integer. return 0 if a is zero, Infinite or Nan. */ slimb_t bf_get_exp_min(const bf_t *a) { slimb_t i; limb_t v; int k; for(i = 0; i < a->len; i++) { v = a->tab[i]; if (v != 0) { k = ctz(v); return a->expn - (a->len - i) * LIMB_BITS + k; } } return 0; } /* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the integer defined as floor(a/b) and r = a - q * b. */ static void bf_tdivremu(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b) { if (bf_cmpu(a, b) < 0) { bf_set_ui(q, 0); bf_set(r, a); } else { bf_div(q, a, b, bf_max(a->expn - b->expn + 1, 2), BF_RNDZ); bf_rint(q, BF_RNDZ); bf_mul(r, q, b, BF_PREC_INF, BF_RNDZ); bf_sub(r, a, r, BF_PREC_INF, BF_RNDZ); } } static int __bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; int ret, r_sign; limb_t n, nb, precl; r_sign = a->sign ^ b->sign; if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) { if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else if (a->expn == BF_EXP_INF) { bf_set_inf(r, r_sign); return 0; } else { bf_set_zero(r, r_sign); return 0; } } else if (a->expn == BF_EXP_ZERO) { if (b->expn == BF_EXP_ZERO) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_zero(r, r_sign); return 0; } } else if (b->expn == BF_EXP_ZERO) { bf_set_inf(r, r_sign); return BF_ST_DIVIDE_ZERO; } /* number of limbs of the quotient (2 extra bits for rounding) */ precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS; nb = b->len; n = bf_max(a->len, precl); { limb_t *taba, na; slimb_t d; na = n + nb; taba = bf_malloc(s, (na + 1) * sizeof(limb_t)); if (!taba) goto fail; d = na - a->len; memset(taba, 0, d * sizeof(limb_t)); memcpy(taba + d, a->tab, a->len * sizeof(limb_t)); if (bf_resize(r, n + 1)) goto fail1; if (mp_divnorm(s, r->tab, taba, na, b->tab, nb)) { fail1: bf_free(s, taba); goto fail; } /* see if non zero remainder */ if (mp_scan_nz(taba, nb)) r->tab[0] |= 1; bf_free(r->ctx, taba); r->expn = a->expn - b->expn + LIMB_BITS; r->sign = r_sign; ret = bf_normalize_and_round(r, prec, flags); } return ret; fail: bf_set_nan(r); return BF_ST_MEM_ERROR; } /* division and remainder. rnd_mode is the rounding mode for the quotient. The additional rounding mode BF_RND_EUCLIDIAN is supported. 'q' is an integer. 'r' is rounded with prec and flags (prec can be BF_PREC_INF). */ int bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode) { bf_t a1_s, *a1 = &a1_s; bf_t b1_s, *b1 = &b1_s; int q_sign, ret; BOOL is_ceil, is_rndn; assert(q != a && q != b); assert(r != a && r != b); assert(q != r); if (a->len == 0 || b->len == 0) { bf_set_zero(q, 0); if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set(r, a); return bf_round(r, prec, flags); } } q_sign = a->sign ^ b->sign; is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA); switch(rnd_mode) { default: case BF_RNDZ: case BF_RNDN: case BF_RNDNA: is_ceil = FALSE; break; case BF_RNDD: is_ceil = q_sign; break; case BF_RNDU: is_ceil = q_sign ^ 1; break; case BF_RNDA: is_ceil = TRUE; break; case BF_DIVREM_EUCLIDIAN: is_ceil = a->sign; break; } a1->expn = a->expn; a1->tab = a->tab; a1->len = a->len; a1->sign = 0; b1->expn = b->expn; b1->tab = b->tab; b1->len = b->len; b1->sign = 0; /* XXX: could improve to avoid having a large 'q' */ bf_tdivremu(q, r, a1, b1); if (bf_is_nan(q) || bf_is_nan(r)) goto fail; if (r->len != 0) { if (is_rndn) { int res; b1->expn--; res = bf_cmpu(r, b1); b1->expn++; if (res > 0 || (res == 0 && (rnd_mode == BF_RNDNA || get_bit(q->tab, q->len, q->len * LIMB_BITS - q->expn)))) { goto do_sub_r; } } else if (is_ceil) { do_sub_r: ret = bf_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ); ret |= bf_sub(r, r, b1, BF_PREC_INF, BF_RNDZ); if (ret & BF_ST_MEM_ERROR) goto fail; } } r->sign ^= a->sign; q->sign = q_sign; return bf_round(r, prec, flags); fail: bf_set_nan(q); bf_set_nan(r); return BF_ST_MEM_ERROR; } int bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode) { bf_t q_s, *q = &q_s; int ret; bf_init(r->ctx, q); ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode); bf_delete(q); return ret; } static inline int bf_get_limb(slimb_t *pres, const bf_t *a, int flags) { #if LIMB_BITS == 32 return bf_get_int32(pres, a, flags); #else return bf_get_int64(pres, a, flags); #endif } int bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode) { bf_t q_s, *q = &q_s; int ret; bf_init(r->ctx, q); ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode); bf_get_limb(pq, q, BF_GET_INT_MOD); bf_delete(q); return ret; } static __maybe_unused inline limb_t mul_mod(limb_t a, limb_t b, limb_t m) { dlimb_t t; t = (dlimb_t)a * (dlimb_t)b; return t % m; } #if defined(USE_MUL_CHECK) static limb_t mp_mod1(const limb_t *tab, limb_t n, limb_t m, limb_t r) { slimb_t i; dlimb_t t; for(i = n - 1; i >= 0; i--) { t = ((dlimb_t)r << LIMB_BITS) | tab[i]; r = t % m; } return r; } #endif static const uint16_t sqrt_table[192] = { 128,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,150,151,152,153,154,155,155,156,157,158,159,160,160,161,162,163,163,164,165,166,167,167,168,169,170,170,171,172,173,173,174,175,176,176,177,178,178,179,180,181,181,182,183,183,184,185,185,186,187,187,188,189,189,190,191,192,192,193,193,194,195,195,196,197,197,198,199,199,200,201,201,202,203,203,204,204,205,206,206,207,208,208,209,209,210,211,211,212,212,213,214,214,215,215,216,217,217,218,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,227,228,229,229,230,230,231,231,232,232,233,234,234,235,235,236,236,237,237,238,238,239,240,240,241,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255, }; /* a >= 2^(LIMB_BITS - 2). Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s */ static limb_t mp_sqrtrem1(limb_t *pr, limb_t a) { limb_t s1, r1, s, r, q, u, num; /* use a table for the 16 -> 8 bit sqrt */ s1 = sqrt_table[(a >> (LIMB_BITS - 8)) - 64]; r1 = (a >> (LIMB_BITS - 16)) - s1 * s1; if (r1 > 2 * s1) { r1 -= 2 * s1 + 1; s1++; } /* one iteration to get a 32 -> 16 bit sqrt */ num = (r1 << 8) | ((a >> (LIMB_BITS - 32 + 8)) & 0xff); q = num / (2 * s1); /* q <= 2^8 */ u = num % (2 * s1); s = (s1 << 8) + q; r = (u << 8) | ((a >> (LIMB_BITS - 32)) & 0xff); r -= q * q; if ((slimb_t)r < 0) { s--; r += 2 * s + 1; } #if LIMB_BITS == 64 s1 = s; r1 = r; /* one more iteration for 64 -> 32 bit sqrt */ num = (r1 << 16) | ((a >> (LIMB_BITS - 64 + 16)) & 0xffff); q = num / (2 * s1); /* q <= 2^16 */ u = num % (2 * s1); s = (s1 << 16) + q; r = (u << 16) | ((a >> (LIMB_BITS - 64)) & 0xffff); r -= q * q; if ((slimb_t)r < 0) { s--; r += 2 * s + 1; } #endif *pr = r; return s; } /* return floor(sqrt(a)) */ limb_t bf_isqrt(limb_t a) { limb_t s, r; int k; if (a == 0) return 0; k = clz(a) & ~1; s = mp_sqrtrem1(&r, a << k); s >>= (k >> 1); return s; } static limb_t mp_sqrtrem2(limb_t *tabs, limb_t *taba) { limb_t s1, r1, s, q, u, a0, a1; dlimb_t r, num; int l; a0 = taba[0]; a1 = taba[1]; s1 = mp_sqrtrem1(&r1, a1); l = LIMB_BITS / 2; num = ((dlimb_t)r1 << l) | (a0 >> l); q = num / (2 * s1); u = num % (2 * s1); s = (s1 << l) + q; r = ((dlimb_t)u << l) | (a0 & (((limb_t)1 << l) - 1)); if (unlikely((q >> l) != 0)) r -= (dlimb_t)1 << LIMB_BITS; /* special case when q=2^l */ else r -= q * q; if ((slimb_t)(r >> LIMB_BITS) < 0) { s--; r += 2 * (dlimb_t)s + 1; } tabs[0] = s; taba[0] = r; return r >> LIMB_BITS; } //#define DEBUG_SQRTREM /* tmp_buf must contain (n / 2 + 1 limbs). *prh contains the highest limb of the remainder. */ static int mp_sqrtrem_rec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n, limb_t *tmp_buf, limb_t *prh) { limb_t l, h, rh, ql, qh, c, i; if (n == 1) { *prh = mp_sqrtrem2(tabs, taba); return 0; } #ifdef DEBUG_SQRTREM mp_print_str_a("a", taba, 2 * n); #endif l = n / 2; h = n - l; if (mp_sqrtrem_rec(s, tabs + l, taba + 2 * l, h, tmp_buf, &qh)) return -1; #ifdef DEBUG_SQRTREM mp_print_str_a("s1", tabs + l, h); mp_print_str_h("r1", taba + 2 * l, h, qh); mp_print_str_h("r2", taba + l, n, qh); #endif /* the remainder is in taba + 2 * l. Its high bit is in qh */ if (qh) { mp_sub(taba + 2 * l, taba + 2 * l, tabs + l, h, 0); } /* instead of dividing by 2*s, divide by s (which is normalized) and update q and r */ if (mp_divnorm(s, tmp_buf, taba + l, n, tabs + l, h)) return -1; qh += tmp_buf[l]; for(i = 0; i < l; i++) tabs[i] = tmp_buf[i]; ql = mp_shr(tabs, tabs, l, 1, qh & 1); qh = qh >> 1; /* 0 or 1 */ if (ql) rh = mp_add(taba + l, taba + l, tabs + l, h, 0); else rh = 0; #ifdef DEBUG_SQRTREM mp_print_str_h("q", tabs, l, qh); mp_print_str_h("u", taba + l, h, rh); #endif mp_add_ui(tabs + l, qh, h); #ifdef DEBUG_SQRTREM mp_print_str_h("s2", tabs, n, sh); #endif /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */ /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */ if (qh) { c = qh; } else { if (mp_mul(s, taba + n, tabs, l, tabs, l)) return -1; c = mp_sub(taba, taba, taba + n, 2 * l, 0); } rh -= mp_sub_ui(taba + 2 * l, c, n - 2 * l); if ((slimb_t)rh < 0) { mp_sub_ui(tabs, 1, n); rh += mp_add_mul1(taba, tabs, n, 2); rh += mp_add_ui(taba, 1, n); } *prh = rh; return 0; } /* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= 2 ^ (LIMB_BITS - 2). Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s. tabs has n limbs. r is returned in the lower n limbs of taba. Its r[n] is the returned value of the function. */ /* Algorithm from the article "Karatsuba Square Root" by Paul Zimmermann and inspirated from its GMP implementation */ int mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n) { limb_t tmp_buf1[8]; limb_t *tmp_buf; mp_size_t n2; int ret; n2 = n / 2 + 1; if (n2 <= countof(tmp_buf1)) { tmp_buf = tmp_buf1; } else { tmp_buf = bf_malloc(s, sizeof(limb_t) * n2); if (!tmp_buf) return -1; } ret = mp_sqrtrem_rec(s, tabs, taba, n, tmp_buf, taba + n); if (tmp_buf != tmp_buf1) bf_free(s, tmp_buf); return ret; } /* Integer square root with remainder. 'a' must be an integer. r = floor(sqrt(a)) and rem = a - r^2. BF_ST_INEXACT is set if the result is inexact. 'rem' can be NULL if the remainder is not needed. */ int bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a) { int ret; if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); } else if (a->expn == BF_EXP_INF && a->sign) { goto invalid_op; } else { bf_set(r, a); } if (rem1) bf_set_ui(rem1, 0); ret = 0; } else if (a->sign) { invalid_op: bf_set_nan(r); if (rem1) bf_set_ui(rem1, 0); ret = BF_ST_INVALID_OP; } else { bf_t rem_s, *rem; bf_sqrt(r, a, (a->expn + 1) / 2, BF_RNDZ); bf_rint(r, BF_RNDZ); /* see if the result is exact by computing the remainder */ if (rem1) { rem = rem1; } else { rem = &rem_s; bf_init(r->ctx, rem); } /* XXX: could avoid recomputing the remainder */ bf_mul(rem, r, r, BF_PREC_INF, BF_RNDZ); bf_neg(rem); bf_add(rem, rem, a, BF_PREC_INF, BF_RNDZ); if (bf_is_nan(rem)) { ret = BF_ST_MEM_ERROR; goto done; } if (rem->len != 0) { ret = BF_ST_INEXACT; } else { ret = 0; } done: if (!rem1) bf_delete(rem); } return ret; } int bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = a->ctx; int ret; assert(r != a); if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); } else if (a->expn == BF_EXP_INF && a->sign) { goto invalid_op; } else { bf_set(r, a); } ret = 0; } else if (a->sign) { invalid_op: bf_set_nan(r); ret = BF_ST_INVALID_OP; } else { limb_t *a1; slimb_t n, n1; limb_t res; /* convert the mantissa to an integer with at least 2 * prec + 4 bits */ n = (2 * (prec + 2) + 2 * LIMB_BITS - 1) / (2 * LIMB_BITS); if (bf_resize(r, n)) goto fail; a1 = bf_malloc(s, sizeof(limb_t) * 2 * n); if (!a1) goto fail; n1 = bf_min(2 * n, a->len); memset(a1, 0, (2 * n - n1) * sizeof(limb_t)); memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t)); if (a->expn & 1) { res = mp_shr(a1, a1, 2 * n, 1, 0); } else { res = 0; } if (mp_sqrtrem(s, r->tab, a1, n)) { bf_free(s, a1); goto fail; } if (!res) { res = mp_scan_nz(a1, n + 1); } bf_free(s, a1); if (!res) { res = mp_scan_nz(a->tab, a->len - n1); } if (res != 0) r->tab[0] |= 1; r->sign = 0; r->expn = (a->expn + 1) >> 1; ret = bf_round(r, prec, flags); } return ret; fail: bf_set_nan(r); return BF_ST_MEM_ERROR; } static no_inline int bf_op2(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, bf_op2_func_t *func) { bf_t tmp; int ret; if (r == a || r == b) { bf_init(r->ctx, &tmp); ret = func(&tmp, a, b, prec, flags); bf_move(r, &tmp); } else { ret = func(r, a, b, prec, flags); } return ret; } int bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { return bf_op2(r, a, b, prec, flags, __bf_add); } int bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { return bf_op2(r, a, b, prec, flags, __bf_sub); } int bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags) { return bf_op2(r, a, b, prec, flags, __bf_div); } int bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec, bf_flags_t flags) { bf_t b; int ret; bf_init(r->ctx, &b); ret = bf_set_ui(&b, b1); ret |= bf_mul(r, a, &b, prec, flags); bf_delete(&b); return ret; } int bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags) { bf_t b; int ret; bf_init(r->ctx, &b); ret = bf_set_si(&b, b1); ret |= bf_mul(r, a, &b, prec, flags); bf_delete(&b); return ret; } int bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags) { bf_t b; int ret; bf_init(r->ctx, &b); ret = bf_set_si(&b, b1); ret |= bf_add(r, a, &b, prec, flags); bf_delete(&b); return ret; } static int bf_pow_ui(bf_t *r, const bf_t *a, limb_t b, limb_t prec, bf_flags_t flags) { int ret, n_bits, i; assert(r != a); if (b == 0) return bf_set_ui(r, 1); ret = bf_set(r, a); n_bits = LIMB_BITS - clz(b); for(i = n_bits - 2; i >= 0; i--) { ret |= bf_mul(r, r, r, prec, flags); if ((b >> i) & 1) ret |= bf_mul(r, r, a, prec, flags); } return ret; } static int bf_pow_ui_ui(bf_t *r, limb_t a1, limb_t b, limb_t prec, bf_flags_t flags) { bf_t a; int ret; if (a1 == 10 && b <= LIMB_DIGITS) { /* use precomputed powers. We do not round at this point because we expect the caller to do it */ ret = bf_set_ui(r, mp_pow_dec[b]); } else { bf_init(r->ctx, &a); ret = bf_set_ui(&a, a1); ret |= bf_pow_ui(r, &a, b, prec, flags); bf_delete(&a); } return ret; } /* convert to integer (infinite precision) */ int bf_rint(bf_t *r, int rnd_mode) { return bf_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC); } /* logical operations */ #define BF_LOGIC_OR 0 #define BF_LOGIC_XOR 1 #define BF_LOGIC_AND 2 static inline limb_t bf_logic_op1(limb_t a, limb_t b, int op) { switch(op) { case BF_LOGIC_OR: return a | b; case BF_LOGIC_XOR: return a ^ b; default: case BF_LOGIC_AND: return a & b; } } static int bf_logic_op(bf_t *r, const bf_t *a1, const bf_t *b1, int op) { bf_t b1_s, a1_s, *a, *b; limb_t a_sign, b_sign, r_sign; slimb_t l, i, a_bit_offset, b_bit_offset; limb_t v1, v2, v1_mask, v2_mask, r_mask; int ret; assert(r != a1 && r != b1); if (a1->expn <= 0) a_sign = 0; /* minus zero is considered as positive */ else a_sign = a1->sign; if (b1->expn <= 0) b_sign = 0; /* minus zero is considered as positive */ else b_sign = b1->sign; if (a_sign) { a = &a1_s; bf_init(r->ctx, a); if (bf_add_si(a, a1, 1, BF_PREC_INF, BF_RNDZ)) { b = NULL; goto fail; } } else { a = (bf_t *)a1; } if (b_sign) { b = &b1_s; bf_init(r->ctx, b); if (bf_add_si(b, b1, 1, BF_PREC_INF, BF_RNDZ)) goto fail; } else { b = (bf_t *)b1; } r_sign = bf_logic_op1(a_sign, b_sign, op); if (op == BF_LOGIC_AND && r_sign == 0) { /* no need to compute extra zeros for and */ if (a_sign == 0 && b_sign == 0) l = bf_min(a->expn, b->expn); else if (a_sign == 0) l = a->expn; else l = b->expn; } else { l = bf_max(a->expn, b->expn); } /* Note: a or b can be zero */ l = (bf_max(l, 1) + LIMB_BITS - 1) / LIMB_BITS; if (bf_resize(r, l)) goto fail; a_bit_offset = a->len * LIMB_BITS - a->expn; b_bit_offset = b->len * LIMB_BITS - b->expn; v1_mask = -a_sign; v2_mask = -b_sign; r_mask = -r_sign; for(i = 0; i < l; i++) { v1 = get_bits(a->tab, a->len, a_bit_offset + i * LIMB_BITS) ^ v1_mask; v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS) ^ v2_mask; r->tab[i] = bf_logic_op1(v1, v2, op) ^ r_mask; } r->expn = l * LIMB_BITS; r->sign = r_sign; bf_normalize_and_round(r, BF_PREC_INF, BF_RNDZ); /* cannot fail */ if (r_sign) { if (bf_add_si(r, r, -1, BF_PREC_INF, BF_RNDZ)) goto fail; } ret = 0; done: if (a == &a1_s) bf_delete(a); if (b == &b1_s) bf_delete(b); return ret; fail: bf_set_nan(r); ret = BF_ST_MEM_ERROR; goto done; } /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */ int bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b) { return bf_logic_op(r, a, b, BF_LOGIC_OR); } /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */ int bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b) { return bf_logic_op(r, a, b, BF_LOGIC_XOR); } /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */ int bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b) { return bf_logic_op(r, a, b, BF_LOGIC_AND); } /* conversion between fixed size types */ typedef union { double d; uint64_t u; } Float64Union; int bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode) { Float64Union u; int e, ret; uint64_t m; ret = 0; if (a->expn == BF_EXP_NAN) { u.u = 0x7ff8000000000000; /* quiet nan */ } else { bf_t b_s, *b = &b_s; bf_init(a->ctx, b); bf_set(b, a); if (bf_is_finite(b)) { ret = bf_round(b, 53, rnd_mode | BF_FLAG_SUBNORMAL | bf_set_exp_bits(11)); } if (b->expn == BF_EXP_INF) { e = (1 << 11) - 1; m = 0; } else if (b->expn == BF_EXP_ZERO) { e = 0; m = 0; } else { e = b->expn + 1023 - 1; #if LIMB_BITS == 32 if (b->len == 2) { m = ((uint64_t)b->tab[1] << 32) | b->tab[0]; } else { m = ((uint64_t)b->tab[0] << 32); } #else m = b->tab[0]; #endif if (e <= 0) { /* subnormal */ m = m >> (12 - e); e = 0; } else { m = (m << 1) >> 12; } } u.u = m | ((uint64_t)e << 52) | ((uint64_t)b->sign << 63); bf_delete(b); } *pres = u.d; return ret; } int bf_set_float64(bf_t *a, double d) { Float64Union u; uint64_t m; int shift, e, sgn; u.d = d; sgn = u.u >> 63; e = (u.u >> 52) & ((1 << 11) - 1); m = u.u & (((uint64_t)1 << 52) - 1); if (e == ((1 << 11) - 1)) { if (m != 0) { bf_set_nan(a); } else { bf_set_inf(a, sgn); } } else if (e == 0) { if (m == 0) { bf_set_zero(a, sgn); } else { /* subnormal number */ m <<= 12; shift = clz64(m); m <<= shift; e = -shift; goto norm; } } else { m = (m << 11) | ((uint64_t)1 << 63); norm: a->expn = e - 1023 + 1; #if LIMB_BITS == 32 if (bf_resize(a, 2)) goto fail; a->tab[0] = m; a->tab[1] = m >> 32; #else if (bf_resize(a, 1)) goto fail; a->tab[0] = m; #endif a->sign = sgn; } return 0; fail: bf_set_nan(a); return BF_ST_MEM_ERROR; } /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there is an overflow and 0 otherwise. */ int bf_get_int32(int *pres, const bf_t *a, int flags) { uint32_t v; int ret; if (a->expn >= BF_EXP_INF) { ret = BF_ST_INVALID_OP; if (flags & BF_GET_INT_MOD) { v = 0; } else if (a->expn == BF_EXP_INF) { v = (uint32_t)INT32_MAX + a->sign; } else { v = INT32_MAX; } } else if (a->expn <= 0) { v = 0; ret = 0; } else if (a->expn <= 31) { v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn); if (a->sign) v = -v; ret = 0; } else if (!(flags & BF_GET_INT_MOD)) { ret = BF_ST_INVALID_OP; if (a->sign) { v = (uint32_t)INT32_MAX + 1; if (a->expn == 32 && (a->tab[a->len - 1] >> (LIMB_BITS - 32)) == v) { ret = 0; } } else { v = INT32_MAX; } } else { v = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn); if (a->sign) v = -v; ret = 0; } *pres = v; return ret; } /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there is an overflow and 0 otherwise. */ int bf_get_int64(int64_t *pres, const bf_t *a, int flags) { uint64_t v; int ret; if (a->expn >= BF_EXP_INF) { ret = BF_ST_INVALID_OP; if (flags & BF_GET_INT_MOD) { v = 0; } else if (a->expn == BF_EXP_INF) { v = (uint64_t)INT64_MAX + a->sign; } else { v = INT64_MAX; } } else if (a->expn <= 0) { v = 0; ret = 0; } else if (a->expn <= 63) { #if LIMB_BITS == 32 if (a->expn <= 32) v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn); else v = (((uint64_t)a->tab[a->len - 1] << 32) | get_limbz(a, a->len - 2)) >> (64 - a->expn); #else v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn); #endif if (a->sign) v = -v; ret = 0; } else if (!(flags & BF_GET_INT_MOD)) { ret = BF_ST_INVALID_OP; if (a->sign) { uint64_t v1; v = (uint64_t)INT64_MAX + 1; if (a->expn == 64) { v1 = a->tab[a->len - 1]; #if LIMB_BITS == 32 v1 = (v1 << 32) | get_limbz(a, a->len - 2); #endif if (v1 == v) ret = 0; } } else { v = INT64_MAX; } } else { slimb_t bit_pos = a->len * LIMB_BITS - a->expn; v = get_bits(a->tab, a->len, bit_pos); #if LIMB_BITS == 32 v |= (uint64_t)get_bits(a->tab, a->len, bit_pos + 32) << 32; #endif if (a->sign) v = -v; ret = 0; } *pres = v; return ret; } /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there is an overflow and 0 otherwise. */ int bf_get_uint64(uint64_t *pres, const bf_t *a) { uint64_t v; int ret; if (a->expn == BF_EXP_NAN) { goto overflow; } else if (a->expn <= 0) { v = 0; ret = 0; } else if (a->sign) { v = 0; ret = BF_ST_INVALID_OP; } else if (a->expn <= 64) { #if LIMB_BITS == 32 if (a->expn <= 32) v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn); else v = (((uint64_t)a->tab[a->len - 1] << 32) | get_limbz(a, a->len - 2)) >> (64 - a->expn); #else v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn); #endif ret = 0; } else { overflow: v = UINT64_MAX; ret = BF_ST_INVALID_OP; } *pres = v; return ret; } /* base conversion from radix */ static const uint8_t digits_per_limb_table[BF_RADIX_MAX - 1] = { #if LIMB_BITS == 32 32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, #else 64,40,32,27,24,22,21,20,19,18,17,17,16,16,16,15,15,15,14,14,14,14,13,13,13,13,13,13,13,12,12,12,12,12,12, #endif }; static limb_t get_limb_radix(int radix) { int i, k; limb_t radixl; k = digits_per_limb_table[radix - 2]; radixl = radix; for(i = 1; i < k; i++) radixl *= radix; return radixl; } /* return != 0 if error */ static int bf_integer_from_radix_rec(bf_t *r, const limb_t *tab, limb_t n, int level, limb_t n0, limb_t radix, bf_t *pow_tab) { int ret; if (n == 1) { ret = bf_set_ui(r, tab[0]); } else { bf_t T_s, *T = &T_s, *B; limb_t n1, n2; n2 = (((n0 * 2) >> (level + 1)) + 1) / 2; n1 = n - n2; // printf("level=%d n0=%ld n1=%ld n2=%ld\n", level, n0, n1, n2); B = &pow_tab[level]; if (B->len == 0) { ret = bf_pow_ui_ui(B, radix, n2, BF_PREC_INF, BF_RNDZ); if (ret) return ret; } ret = bf_integer_from_radix_rec(r, tab + n2, n1, level + 1, n0, radix, pow_tab); if (ret) return ret; ret = bf_mul(r, r, B, BF_PREC_INF, BF_RNDZ); if (ret) return ret; bf_init(r->ctx, T); ret = bf_integer_from_radix_rec(T, tab, n2, level + 1, n0, radix, pow_tab); if (!ret) ret = bf_add(r, r, T, BF_PREC_INF, BF_RNDZ); bf_delete(T); } return ret; // bf_print_str(" r=", r); } /* return 0 if OK != 0 if memory error */ static int bf_integer_from_radix(bf_t *r, const limb_t *tab, limb_t n, limb_t radix) { bf_context_t *s = r->ctx; int pow_tab_len, i, ret; limb_t radixl; bf_t *pow_tab; radixl = get_limb_radix(radix); pow_tab_len = ceil_log2(n) + 2; /* XXX: check */ pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len); if (!pow_tab) return -1; for(i = 0; i < pow_tab_len; i++) bf_init(r->ctx, &pow_tab[i]); ret = bf_integer_from_radix_rec(r, tab, n, 0, n, radixl, pow_tab); for(i = 0; i < pow_tab_len; i++) { bf_delete(&pow_tab[i]); } bf_free(s, pow_tab); return ret; } /* compute and round T * radix^expn. */ int bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix, slimb_t expn, limb_t prec, bf_flags_t flags) { int ret, expn_sign, overflow; slimb_t e, extra_bits, prec1, ziv_extra_bits; bf_t B_s, *B = &B_s; if (T->len == 0) { return bf_set(r, T); } else if (expn == 0) { ret = bf_set(r, T); ret |= bf_round(r, prec, flags); return ret; } e = expn; expn_sign = 0; if (e < 0) { e = -e; expn_sign = 1; } bf_init(r->ctx, B); if (prec == BF_PREC_INF) { /* infinite precision: only used if the result is known to be exact */ ret = bf_pow_ui_ui(B, radix, e, BF_PREC_INF, BF_RNDN); if (expn_sign) { ret |= bf_div(r, T, B, T->len * LIMB_BITS, BF_RNDN); } else { ret |= bf_mul(r, T, B, BF_PREC_INF, BF_RNDN); } } else { ziv_extra_bits = 16; for(;;) { prec1 = prec + ziv_extra_bits; /* XXX: correct overflow/underflow handling */ /* XXX: rigorous error analysis needed */ extra_bits = ceil_log2(e) * 2 + 1; ret = bf_pow_ui_ui(B, radix, e, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); overflow = !bf_is_finite(B); /* XXX: if bf_pow_ui_ui returns an exact result, can stop after the next operation */ if (expn_sign) ret |= bf_div(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); else ret |= bf_mul(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); if (ret & BF_ST_MEM_ERROR) break; if ((ret & BF_ST_INEXACT) && !bf_can_round(r, prec, flags & BF_RND_MASK, prec1) && !overflow) { /* and more precision and retry */ ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2); } else { /* XXX: need to use __bf_round() to pass the inexact flag for the subnormal case */ ret = bf_round(r, prec, flags) | (ret & BF_ST_INEXACT); break; } } } bf_delete(B); return ret; } static inline int to_digit(int c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'Z') return c - 'A' + 10; else if (c >= 'a' && c <= 'z') return c - 'a' + 10; else return 36; } /* add a limb at 'pos' and decrement pos. new space is created if needed. Return 0 if OK, -1 if memory error */ static int bf_add_limb(bf_t *a, slimb_t *ppos, limb_t v) { slimb_t pos; pos = *ppos; if (unlikely(pos < 0)) { limb_t new_size, d, *new_tab; new_size = bf_max(a->len + 1, a->len * 3 / 2); new_tab = bf_realloc(a->ctx, a->tab, sizeof(limb_t) * new_size); if (!new_tab) return -1; a->tab = new_tab; d = new_size - a->len; memmove(a->tab + d, a->tab, a->len * sizeof(limb_t)); a->len = new_size; pos += d; } a->tab[pos--] = v; *ppos = pos; return 0; } static int bf_tolower(int c) { if (c >= 'A' && c <= 'Z') c = c - 'A' + 'a'; return c; } static int strcasestart(const char *str, const char *val, const char **ptr) { const char *p, *q; p = str; q = val; while (*q != '\0') { if (bf_tolower(*p) != *q) return 0; p++; q++; } if (ptr) *ptr = p; return 1; } static int bf_atof_internal(bf_t *r, slimb_t *pexponent, const char *str, const char **pnext, int radix, limb_t prec, bf_flags_t flags, BOOL is_dec) { const char *p, *p_start; int is_neg, radix_bits, exp_is_neg, ret, digits_per_limb, shift; limb_t cur_limb; slimb_t pos, expn, int_len, digit_count; BOOL has_decpt, is_bin_exp; bf_t a_s, *a; *pexponent = 0; p = str; if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 && strcasestart(p, "nan", &p)) { bf_set_nan(r); ret = 0; goto done; } is_neg = 0; if (p[0] == '+') { p++; p_start = p; } else if (p[0] == '-') { is_neg = 1; p++; p_start = p; } else { p_start = p; } if (p[0] == '0') { if ((p[1] == 'x' || p[1] == 'X') && (radix == 0 || radix == 16) && !(flags & BF_ATOF_NO_HEX)) { radix = 16; p += 2; } else if ((p[1] == 'o' || p[1] == 'O') && radix == 0 && (flags & BF_ATOF_BIN_OCT)) { p += 2; radix = 8; } else if ((p[1] == 'b' || p[1] == 'B') && radix == 0 && (flags & BF_ATOF_BIN_OCT)) { p += 2; radix = 2; } else { goto no_prefix; } /* there must be a digit after the prefix */ if (to_digit((uint8_t)*p) >= radix) { bf_set_nan(r); ret = 0; goto done; } no_prefix: ; } else { if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 && strcasestart(p, "inf", &p)) { bf_set_inf(r, is_neg); ret = 0; goto done; } } if (radix == 0) radix = 10; if (is_dec) { assert(radix == 10); radix_bits = 0; a = r; } else if ((radix & (radix - 1)) != 0) { radix_bits = 0; /* base is not a power of two */ a = &a_s; bf_init(r->ctx, a); } else { radix_bits = ceil_log2(radix); a = r; } /* skip leading zeros */ /* XXX: could also skip zeros after the decimal point */ while (*p == '0') p++; if (radix_bits) { shift = digits_per_limb = LIMB_BITS; } else { radix_bits = 0; shift = digits_per_limb = digits_per_limb_table[radix - 2]; } cur_limb = 0; bf_resize(a, 1); pos = 0; has_decpt = FALSE; int_len = digit_count = 0; for(;;) { limb_t c; if (*p == '.' && (p > p_start || to_digit(p[1]) < radix)) { if (has_decpt) break; has_decpt = TRUE; int_len = digit_count; p++; } c = to_digit(*p); if (c >= radix) break; digit_count++; p++; if (radix_bits) { shift -= radix_bits; if (shift <= 0) { cur_limb |= c >> (-shift); if (bf_add_limb(a, &pos, cur_limb)) goto mem_error; if (shift < 0) cur_limb = c << (LIMB_BITS + shift); else cur_limb = 0; shift += LIMB_BITS; } else { cur_limb |= c << shift; } } else { cur_limb = cur_limb * radix + c; shift--; if (shift == 0) { if (bf_add_limb(a, &pos, cur_limb)) goto mem_error; shift = digits_per_limb; cur_limb = 0; } } } if (!has_decpt) int_len = digit_count; /* add the last limb and pad with zeros */ if (shift != digits_per_limb) { if (radix_bits == 0) { while (shift != 0) { cur_limb *= radix; shift--; } } if (bf_add_limb(a, &pos, cur_limb)) { mem_error: ret = BF_ST_MEM_ERROR; if (!radix_bits) bf_delete(a); bf_set_nan(r); goto done; } } /* reset the next limbs to zero (we prefer to reallocate in the renormalization) */ memset(a->tab, 0, (pos + 1) * sizeof(limb_t)); if (p == p_start) { ret = 0; if (!radix_bits) bf_delete(a); bf_set_nan(r); goto done; } /* parse the exponent, if any */ expn = 0; is_bin_exp = FALSE; if (((radix == 10 && (*p == 'e' || *p == 'E')) || (radix != 10 && (*p == '@' || (radix_bits && (*p == 'p' || *p == 'P'))))) && p > p_start) { is_bin_exp = (*p == 'p' || *p == 'P'); p++; exp_is_neg = 0; if (*p == '+') { p++; } else if (*p == '-') { exp_is_neg = 1; p++; } for(;;) { int c; c = to_digit(*p); if (c >= 10) break; if (unlikely(expn > ((BF_RAW_EXP_MAX - 2 - 9) / 10))) { /* exponent overflow */ if (exp_is_neg) { bf_set_zero(r, is_neg); ret = BF_ST_UNDERFLOW | BF_ST_INEXACT; } else { bf_set_inf(r, is_neg); ret = BF_ST_OVERFLOW | BF_ST_INEXACT; } goto done; } p++; expn = expn * 10 + c; } if (exp_is_neg) expn = -expn; } if (is_dec) { a->expn = expn + int_len; a->sign = is_neg; ret = bfdec_normalize_and_round((bfdec_t *)a, prec, flags); } else if (radix_bits) { /* XXX: may overflow */ if (!is_bin_exp) expn *= radix_bits; a->expn = expn + (int_len * radix_bits); a->sign = is_neg; ret = bf_normalize_and_round(a, prec, flags); } else { limb_t l; pos++; l = a->len - pos; /* number of limbs */ if (l == 0) { bf_set_zero(r, is_neg); ret = 0; } else { bf_t T_s, *T = &T_s; expn -= l * digits_per_limb - int_len; bf_init(r->ctx, T); if (bf_integer_from_radix(T, a->tab + pos, l, radix)) { bf_set_nan(r); ret = BF_ST_MEM_ERROR; } else { T->sign = is_neg; if (flags & BF_ATOF_EXPONENT) { /* return the exponent */ *pexponent = expn; ret = bf_set(r, T); } else { ret = bf_mul_pow_radix(r, T, radix, expn, prec, flags); } } bf_delete(T); } bf_delete(a); } done: if (pnext) *pnext = p; return ret; } /* Return (status, n, exp). 'status' is the floating point status. 'n' is the parsed number. If (flags & BF_ATOF_EXPONENT) and if the radix is not a power of two, the parsed number is equal to r * (*pexponent)^radix. Otherwise *pexponent = 0. */ int bf_atof2(bf_t *r, slimb_t *pexponent, const char *str, const char **pnext, int radix, limb_t prec, bf_flags_t flags) { return bf_atof_internal(r, pexponent, str, pnext, radix, prec, flags, FALSE); } int bf_atof(bf_t *r, const char *str, const char **pnext, int radix, limb_t prec, bf_flags_t flags) { slimb_t dummy_exp; return bf_atof_internal(r, &dummy_exp, str, pnext, radix, prec, flags, FALSE); } /* base conversion to radix */ #if LIMB_BITS == 64 #define RADIXL_10 UINT64_C(10000000000000000000) #else #define RADIXL_10 UINT64_C(1000000000) #endif static const uint32_t inv_log2_radix[BF_RADIX_MAX - 1][LIMB_BITS / 32 + 1] = { #if LIMB_BITS == 32 { 0x80000000, 0x00000000,}, { 0x50c24e60, 0xd4d4f4a7,}, { 0x40000000, 0x00000000,}, { 0x372068d2, 0x0a1ee5ca,}, { 0x3184648d, 0xb8153e7a,}, { 0x2d983275, 0x9d5369c4,}, { 0x2aaaaaaa, 0xaaaaaaab,}, { 0x28612730, 0x6a6a7a54,}, { 0x268826a1, 0x3ef3fde6,}, { 0x25001383, 0xbac8a744,}, { 0x23b46706, 0x82c0c709,}, { 0x229729f1, 0xb2c83ded,}, { 0x219e7ffd, 0xa5ad572b,}, { 0x20c33b88, 0xda7c29ab,}, { 0x20000000, 0x00000000,}, { 0x1f50b57e, 0xac5884b3,}, { 0x1eb22cc6, 0x8aa6e26f,}, { 0x1e21e118, 0x0c5daab2,}, { 0x1d9dcd21, 0x439834e4,}, { 0x1d244c78, 0x367a0d65,}, { 0x1cb40589, 0xac173e0c,}, { 0x1c4bd95b, 0xa8d72b0d,}, { 0x1bead768, 0x98f8ce4c,}, { 0x1b903469, 0x050f72e5,}, { 0x1b3b433f, 0x2eb06f15,}, { 0x1aeb6f75, 0x9c46fc38,}, { 0x1aa038eb, 0x0e3bfd17,}, { 0x1a593062, 0xb38d8c56,}, { 0x1a15f4c3, 0x2b95a2e6,}, { 0x19d630dc, 0xcc7ddef9,}, { 0x19999999, 0x9999999a,}, { 0x195fec80, 0x8a609431,}, { 0x1928ee7b, 0x0b4f22f9,}, { 0x18f46acf, 0x8c06e318,}, { 0x18c23246, 0xdc0a9f3d,}, #else { 0x80000000, 0x00000000, 0x00000000,}, { 0x50c24e60, 0xd4d4f4a7, 0x021f57bc,}, { 0x40000000, 0x00000000, 0x00000000,}, { 0x372068d2, 0x0a1ee5ca, 0x19ea911b,}, { 0x3184648d, 0xb8153e7a, 0x7fc2d2e1,}, { 0x2d983275, 0x9d5369c4, 0x4dec1661,}, { 0x2aaaaaaa, 0xaaaaaaaa, 0xaaaaaaab,}, { 0x28612730, 0x6a6a7a53, 0x810fabde,}, { 0x268826a1, 0x3ef3fde6, 0x23e2566b,}, { 0x25001383, 0xbac8a744, 0x385a3349,}, { 0x23b46706, 0x82c0c709, 0x3f891718,}, { 0x229729f1, 0xb2c83ded, 0x15fba800,}, { 0x219e7ffd, 0xa5ad572a, 0xe169744b,}, { 0x20c33b88, 0xda7c29aa, 0x9bddee52,}, { 0x20000000, 0x00000000, 0x00000000,}, { 0x1f50b57e, 0xac5884b3, 0x70e28eee,}, { 0x1eb22cc6, 0x8aa6e26f, 0x06d1a2a2,}, { 0x1e21e118, 0x0c5daab1, 0x81b4f4bf,}, { 0x1d9dcd21, 0x439834e3, 0x81667575,}, { 0x1d244c78, 0x367a0d64, 0xc8204d6d,}, { 0x1cb40589, 0xac173e0c, 0x3b7b16ba,}, { 0x1c4bd95b, 0xa8d72b0d, 0x5879f25a,}, { 0x1bead768, 0x98f8ce4c, 0x66cc2858,}, { 0x1b903469, 0x050f72e5, 0x0cf5488e,}, { 0x1b3b433f, 0x2eb06f14, 0x8c89719c,}, { 0x1aeb6f75, 0x9c46fc37, 0xab5fc7e9,}, { 0x1aa038eb, 0x0e3bfd17, 0x1bd62080,}, { 0x1a593062, 0xb38d8c56, 0x7998ab45,}, { 0x1a15f4c3, 0x2b95a2e6, 0x46aed6a0,}, { 0x19d630dc, 0xcc7ddef9, 0x5aadd61b,}, { 0x19999999, 0x99999999, 0x9999999a,}, { 0x195fec80, 0x8a609430, 0xe1106014,}, { 0x1928ee7b, 0x0b4f22f9, 0x5f69791d,}, { 0x18f46acf, 0x8c06e318, 0x4d2aeb2c,}, { 0x18c23246, 0xdc0a9f3d, 0x3fe16970,}, #endif }; static const limb_t log2_radix[BF_RADIX_MAX - 1] = { #if LIMB_BITS == 32 0x20000000, 0x32b80347, 0x40000000, 0x4a4d3c26, 0x52b80347, 0x59d5d9fd, 0x60000000, 0x6570068e, 0x6a4d3c26, 0x6eb3a9f0, 0x72b80347, 0x766a008e, 0x79d5d9fd, 0x7d053f6d, 0x80000000, 0x82cc7edf, 0x8570068e, 0x87ef05ae, 0x8a4d3c26, 0x8c8ddd45, 0x8eb3a9f0, 0x90c10501, 0x92b80347, 0x949a784c, 0x966a008e, 0x982809d6, 0x99d5d9fd, 0x9b74948f, 0x9d053f6d, 0x9e88c6b3, 0xa0000000, 0xa16bad37, 0xa2cc7edf, 0xa4231623, 0xa570068e, #else 0x2000000000000000, 0x32b803473f7ad0f4, 0x4000000000000000, 0x4a4d3c25e68dc57f, 0x52b803473f7ad0f4, 0x59d5d9fd5010b366, 0x6000000000000000, 0x6570068e7ef5a1e8, 0x6a4d3c25e68dc57f, 0x6eb3a9f01975077f, 0x72b803473f7ad0f4, 0x766a008e4788cbcd, 0x79d5d9fd5010b366, 0x7d053f6d26089673, 0x8000000000000000, 0x82cc7edf592262d0, 0x8570068e7ef5a1e8, 0x87ef05ae409a0289, 0x8a4d3c25e68dc57f, 0x8c8ddd448f8b845a, 0x8eb3a9f01975077f, 0x90c10500d63aa659, 0x92b803473f7ad0f4, 0x949a784bcd1b8afe, 0x966a008e4788cbcd, 0x982809d5be7072dc, 0x99d5d9fd5010b366, 0x9b74948f5532da4b, 0x9d053f6d26089673, 0x9e88c6b3626a72aa, 0xa000000000000000, 0xa16bad3758efd873, 0xa2cc7edf592262d0, 0xa4231623369e78e6, 0xa570068e7ef5a1e8, #endif }; /* compute floor(a*b) or ceil(a*b) with b = log2(radix) or b=1/log2(radix). For is_inv = 0, strict accuracy is not guaranteed when radix is not a power of two. */ slimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv, int is_ceil1) { int is_neg; limb_t a; BOOL is_ceil; is_ceil = is_ceil1; a = a1; if (a1 < 0) { a = -a; is_neg = 1; } else { is_neg = 0; } is_ceil ^= is_neg; if ((radix & (radix - 1)) == 0) { int radix_bits; /* radix is a power of two */ radix_bits = ceil_log2(radix); if (is_inv) { if (is_ceil) a += radix_bits - 1; a = a / radix_bits; } else { a = a * radix_bits; } } else { const uint32_t *tab; limb_t b0, b1; dlimb_t t; if (is_inv) { tab = inv_log2_radix[radix - 2]; #if LIMB_BITS == 32 b1 = tab[0]; b0 = tab[1]; #else b1 = ((limb_t)tab[0] << 32) | tab[1]; b0 = (limb_t)tab[2] << 32; #endif t = (dlimb_t)b0 * (dlimb_t)a; t = (dlimb_t)b1 * (dlimb_t)a + (t >> LIMB_BITS); a = t >> (LIMB_BITS - 1); } else { b0 = log2_radix[radix - 2]; t = (dlimb_t)b0 * (dlimb_t)a; a = t >> (LIMB_BITS - 3); } /* a = floor(result) and 'result' cannot be an integer */ a += is_ceil; } if (is_neg) a = -a; return a; } /* 'n' is the number of output limbs */ static int bf_integer_to_radix_rec(bf_t *pow_tab, limb_t *out, const bf_t *a, limb_t n, int level, limb_t n0, limb_t radixl, unsigned int radixl_bits) { limb_t n1, n2, q_prec; int ret; assert(n >= 1); if (n == 1) { out[0] = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn); } else if (n == 2) { dlimb_t t; slimb_t pos; pos = a->len * LIMB_BITS - a->expn; t = ((dlimb_t)get_bits(a->tab, a->len, pos + LIMB_BITS) << LIMB_BITS) | get_bits(a->tab, a->len, pos); if (likely(radixl == RADIXL_10)) { /* use division by a constant when possible */ out[0] = t % RADIXL_10; out[1] = t / RADIXL_10; } else { out[0] = t % radixl; out[1] = t / radixl; } } else { bf_t Q, R, *B, *B_inv; int q_add; bf_init(a->ctx, &Q); bf_init(a->ctx, &R); n2 = (((n0 * 2) >> (level + 1)) + 1) / 2; n1 = n - n2; B = &pow_tab[2 * level]; B_inv = &pow_tab[2 * level + 1]; ret = 0; if (B->len == 0) { /* compute BASE^n2 */ ret |= bf_pow_ui_ui(B, radixl, n2, BF_PREC_INF, BF_RNDZ); /* we use enough bits for the maximum possible 'n1' value, i.e. n2 + 1 */ ret |= bf_set_ui(&R, 1); ret |= bf_div(B_inv, &R, B, (n2 + 1) * radixl_bits + 2, BF_RNDN); } // printf("%d: n1=% " PRId64 " n2=%" PRId64 "\n", level, n1, n2); q_prec = n1 * radixl_bits; ret |= bf_mul(&Q, a, B_inv, q_prec, BF_RNDN); ret |= bf_rint(&Q, BF_RNDZ); ret |= bf_mul(&R, &Q, B, BF_PREC_INF, BF_RNDZ); ret |= bf_sub(&R, a, &R, BF_PREC_INF, BF_RNDZ); if (ret & BF_ST_MEM_ERROR) goto fail; /* adjust if necessary */ q_add = 0; while (R.sign && R.len != 0) { if (bf_add(&R, &R, B, BF_PREC_INF, BF_RNDZ)) goto fail; q_add--; } while (bf_cmpu(&R, B) >= 0) { if (bf_sub(&R, &R, B, BF_PREC_INF, BF_RNDZ)) goto fail; q_add++; } if (q_add != 0) { if (bf_add_si(&Q, &Q, q_add, BF_PREC_INF, BF_RNDZ)) goto fail; } if (bf_integer_to_radix_rec(pow_tab, out + n2, &Q, n1, level + 1, n0, radixl, radixl_bits)) goto fail; if (bf_integer_to_radix_rec(pow_tab, out, &R, n2, level + 1, n0, radixl, radixl_bits)) { fail: bf_delete(&Q); bf_delete(&R); return -1; } bf_delete(&Q); bf_delete(&R); } return 0; } /* return 0 if OK != 0 if memory error */ static int bf_integer_to_radix(bf_t *r, const bf_t *a, limb_t radixl) { bf_context_t *s = r->ctx; limb_t r_len; bf_t *pow_tab; int i, pow_tab_len, ret; r_len = r->len; pow_tab_len = (ceil_log2(r_len) + 2) * 2; /* XXX: check */ pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len); if (!pow_tab) return -1; for(i = 0; i < pow_tab_len; i++) bf_init(r->ctx, &pow_tab[i]); ret = bf_integer_to_radix_rec(pow_tab, r->tab, a, r_len, 0, r_len, radixl, ceil_log2(radixl)); for(i = 0; i < pow_tab_len; i++) { bf_delete(&pow_tab[i]); } bf_free(s, pow_tab); return ret; } /* a must be >= 0. 'P' is the wanted number of digits in radix 'radix'. 'r' is the mantissa represented as an integer. *pE contains the exponent. Return != 0 if memory error. */ static int bf_convert_to_radix(bf_t *r, slimb_t *pE, const bf_t *a, int radix, limb_t P, bf_rnd_t rnd_mode, BOOL is_fixed_exponent) { slimb_t E, e, prec, extra_bits, ziv_extra_bits, prec0; bf_t B_s, *B = &B_s; int e_sign, ret, res; if (a->len == 0) { /* zero case */ *pE = 0; return bf_set(r, a); } if (is_fixed_exponent) { E = *pE; } else { /* compute the new exponent */ E = 1 + bf_mul_log2_radix(a->expn - 1, radix, TRUE, FALSE); } // bf_print_str("a", a); // printf("E=%ld P=%ld radix=%d\n", E, P, radix); for(;;) { e = P - E; e_sign = 0; if (e < 0) { e = -e; e_sign = 1; } /* Note: precision for log2(radix) is not critical here */ prec0 = bf_mul_log2_radix(P, radix, FALSE, TRUE); ziv_extra_bits = 16; for(;;) { prec = prec0 + ziv_extra_bits; /* XXX: rigorous error analysis needed */ extra_bits = ceil_log2(e) * 2 + 1; ret = bf_pow_ui_ui(r, radix, e, prec + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); if (!e_sign) ret |= bf_mul(r, r, a, prec + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); else ret |= bf_div(r, a, r, prec + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP); if (ret & BF_ST_MEM_ERROR) return BF_ST_MEM_ERROR; /* if the result is not exact, check that it can be safely rounded to an integer */ if ((ret & BF_ST_INEXACT) && !bf_can_round(r, r->expn, rnd_mode, prec)) { /* and more precision and retry */ ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2); continue; } else { ret = bf_rint(r, rnd_mode); if (ret & BF_ST_MEM_ERROR) return BF_ST_MEM_ERROR; break; } } if (is_fixed_exponent) break; /* check that the result is < B^P */ /* XXX: do a fast approximate test first ? */ bf_init(r->ctx, B); ret = bf_pow_ui_ui(B, radix, P, BF_PREC_INF, BF_RNDZ); if (ret) { bf_delete(B); return ret; } res = bf_cmpu(r, B); bf_delete(B); if (res < 0) break; /* try a larger exponent */ E++; } *pE = E; return 0; } static void limb_to_a(char *buf, limb_t n, unsigned int radix, int len) { int digit, i; if (radix == 10) { /* specific case with constant divisor */ for(i = len - 1; i >= 0; i--) { digit = (limb_t)n % 10; n = (limb_t)n / 10; buf[i] = digit + '0'; } } else { for(i = len - 1; i >= 0; i--) { digit = (limb_t)n % radix; n = (limb_t)n / radix; if (digit < 10) digit += '0'; else digit += 'a' - 10; buf[i] = digit; } } } /* for power of 2 radixes */ static void limb_to_a2(char *buf, limb_t n, unsigned int radix_bits, int len) { int digit, i; unsigned int mask; mask = (1 << radix_bits) - 1; for(i = len - 1; i >= 0; i--) { digit = n & mask; n >>= radix_bits; if (digit < 10) digit += '0'; else digit += 'a' - 10; buf[i] = digit; } } /* 'a' must be an integer if the is_dec = FALSE or if the radix is not a power of two. A dot is added before the 'dot_pos' digit. dot_pos = n_digits does not display the dot. 0 <= dot_pos <= n_digits. n_digits >= 1. */ static void output_digits(DynBuf *s, const bf_t *a1, int radix, limb_t n_digits, limb_t dot_pos, BOOL is_dec) { limb_t i, v, l; slimb_t pos, pos_incr; int digits_per_limb, buf_pos, radix_bits, first_buf_pos; char buf[65]; bf_t a_s, *a; if (is_dec) { digits_per_limb = LIMB_DIGITS; a = (bf_t *)a1; radix_bits = 0; pos = a->len; pos_incr = 1; first_buf_pos = 0; } else if ((radix & (radix - 1)) == 0) { a = (bf_t *)a1; radix_bits = ceil_log2(radix); digits_per_limb = LIMB_BITS / radix_bits; pos_incr = digits_per_limb * radix_bits; /* digits are aligned relative to the radix point */ pos = a->len * LIMB_BITS + smod(-a->expn, radix_bits); first_buf_pos = 0; } else { limb_t n, radixl; digits_per_limb = digits_per_limb_table[radix - 2]; radixl = get_limb_radix(radix); a = &a_s; bf_init(a1->ctx, a); n = (n_digits + digits_per_limb - 1) / digits_per_limb; if (bf_resize(a, n)) { dbuf_set_error(s); goto done; } if (bf_integer_to_radix(a, a1, radixl)) { dbuf_set_error(s); goto done; } radix_bits = 0; pos = n; pos_incr = 1; first_buf_pos = pos * digits_per_limb - n_digits; } buf_pos = digits_per_limb; i = 0; while (i < n_digits) { if (buf_pos == digits_per_limb) { pos -= pos_incr; if (radix_bits == 0) { v = get_limbz(a, pos); limb_to_a(buf, v, radix, digits_per_limb); } else { v = get_bits(a->tab, a->len, pos); limb_to_a2(buf, v, radix_bits, digits_per_limb); } buf_pos = first_buf_pos; first_buf_pos = 0; } if (i < dot_pos) { l = dot_pos; } else { if (i == dot_pos) dbuf_putc(s, '.'); l = n_digits; } l = bf_min(digits_per_limb - buf_pos, l - i); dbuf_put(s, (uint8_t *)(buf + buf_pos), l); buf_pos += l; i += l; } done: if (a != a1) bf_delete(a); } static void *bf_dbuf_realloc(void *opaque, void *ptr, size_t size) { bf_context_t *s = opaque; return bf_realloc(s, ptr, size); } /* return the length in bytes. A trailing '\0' is added */ static char *bf_ftoa_internal(size_t *plen, const bf_t *a2, int radix, limb_t prec, bf_flags_t flags, BOOL is_dec) { bf_context_t *ctx = a2->ctx; DynBuf s_s, *s = &s_s; int radix_bits; // bf_print_str("ftoa", a2); // printf("radix=%d\n", radix); dbuf_init2(s, ctx, bf_dbuf_realloc); if (a2->expn == BF_EXP_NAN) { dbuf_putstr(s, "NaN"); } else { if (a2->sign) dbuf_putc(s, '-'); if (a2->expn == BF_EXP_INF) { if (flags & BF_FTOA_JS_QUIRKS) dbuf_putstr(s, "Infinity"); else dbuf_putstr(s, "Inf"); } else { int fmt, ret; slimb_t n_digits, n, i, n_max, n1; bf_t a1_s, *a1 = &a1_s; if ((radix & (radix - 1)) != 0) radix_bits = 0; else radix_bits = ceil_log2(radix); fmt = flags & BF_FTOA_FORMAT_MASK; bf_init(ctx, a1); if (fmt == BF_FTOA_FORMAT_FRAC) { if (is_dec || radix_bits != 0) { if (bf_set(a1, a2)) goto fail1; #ifdef USE_BF_DEC if (is_dec) { if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR) goto fail1; n = a1->expn; } else #endif { if (bf_round(a1, prec * radix_bits, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR) goto fail1; n = ceil_div(a1->expn, radix_bits); } if (flags & BF_FTOA_ADD_PREFIX) { if (radix == 16) dbuf_putstr(s, "0x"); else if (radix == 8) dbuf_putstr(s, "0o"); else if (radix == 2) dbuf_putstr(s, "0b"); } if (a1->expn == BF_EXP_ZERO) { dbuf_putstr(s, "0"); if (prec > 0) { dbuf_putstr(s, "."); for(i = 0; i < prec; i++) { dbuf_putc(s, '0'); } } } else { n_digits = prec + n; if (n <= 0) { /* 0.x */ dbuf_putstr(s, "0."); for(i = 0; i < -n; i++) { dbuf_putc(s, '0'); } if (n_digits > 0) { output_digits(s, a1, radix, n_digits, n_digits, is_dec); } } else { output_digits(s, a1, radix, n_digits, n, is_dec); } } } else { size_t pos, start; bf_t a_s, *a = &a_s; /* make a positive number */ a->tab = a2->tab; a->len = a2->len; a->expn = a2->expn; a->sign = 0; /* one more digit for the rounding */ n = 1 + bf_mul_log2_radix(bf_max(a->expn, 0), radix, TRUE, TRUE); n_digits = n + prec; n1 = n; if (bf_convert_to_radix(a1, &n1, a, radix, n_digits, flags & BF_RND_MASK, TRUE)) goto fail1; start = s->size; output_digits(s, a1, radix, n_digits, n, is_dec); /* remove leading zeros because we allocated one more digit */ pos = start; while ((pos + 1) < s->size && s->buf[pos] == '0' && s->buf[pos + 1] != '.') pos++; if (pos > start) { memmove(s->buf + start, s->buf + pos, s->size - pos); s->size -= (pos - start); } } } else { #ifdef USE_BF_DEC if (is_dec) { if (bf_set(a1, a2)) goto fail1; if (fmt == BF_FTOA_FORMAT_FIXED) { n_digits = prec; n_max = n_digits; if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR) goto fail1; } else { /* prec is ignored */ prec = n_digits = a1->len * LIMB_DIGITS; /* remove the trailing zero digits */ while (n_digits > 1 && get_digit(a1->tab, a1->len, prec - n_digits) == 0) { n_digits--; } n_max = n_digits + 4; } n = a1->expn; } else #endif if (radix_bits != 0) { if (bf_set(a1, a2)) goto fail1; if (fmt == BF_FTOA_FORMAT_FIXED) { slimb_t prec_bits; n_digits = prec; n_max = n_digits; /* align to the radix point */ prec_bits = prec * radix_bits - smod(-a1->expn, radix_bits); if (bf_round(a1, prec_bits, (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR) goto fail1; } else { limb_t digit_mask; slimb_t pos; /* position of the digit before the most significant digit in bits */ pos = a1->len * LIMB_BITS + smod(-a1->expn, radix_bits); n_digits = ceil_div(pos, radix_bits); /* remove the trailing zero digits */ digit_mask = ((limb_t)1 << radix_bits) - 1; while (n_digits > 1 && (get_bits(a1->tab, a1->len, pos - n_digits * radix_bits) & digit_mask) == 0) { n_digits--; } n_max = n_digits + 4; } n = ceil_div(a1->expn, radix_bits); } else { bf_t a_s, *a = &a_s; /* make a positive number */ a->tab = a2->tab; a->len = a2->len; a->expn = a2->expn; a->sign = 0; if (fmt == BF_FTOA_FORMAT_FIXED) { n_digits = prec; n_max = n_digits; } else { slimb_t n_digits_max, n_digits_min; assert(prec != BF_PREC_INF); n_digits = 1 + bf_mul_log2_radix(prec, radix, TRUE, TRUE); /* max number of digits for non exponential notation. The rational is to have the same rule as JS i.e. n_max = 21 for 64 bit float in base 10. */ n_max = n_digits + 4; if (fmt == BF_FTOA_FORMAT_FREE_MIN) { bf_t b_s, *b = &b_s; /* find the minimum number of digits by dichotomy. */ /* XXX: inefficient */ n_digits_max = n_digits; n_digits_min = 1; bf_init(ctx, b); while (n_digits_min < n_digits_max) { n_digits = (n_digits_min + n_digits_max) / 2; if (bf_convert_to_radix(a1, &n, a, radix, n_digits, flags & BF_RND_MASK, FALSE)) { bf_delete(b); goto fail1; } /* convert back to a number and compare */ ret = bf_mul_pow_radix(b, a1, radix, n - n_digits, prec, (flags & ~BF_RND_MASK) | BF_RNDN); if (ret & BF_ST_MEM_ERROR) { bf_delete(b); goto fail1; } if (bf_cmpu(b, a) == 0) { n_digits_max = n_digits; } else { n_digits_min = n_digits + 1; } } bf_delete(b); n_digits = n_digits_max; } } if (bf_convert_to_radix(a1, &n, a, radix, n_digits, flags & BF_RND_MASK, FALSE)) { fail1: bf_delete(a1); goto fail; } } if (a1->expn == BF_EXP_ZERO && fmt != BF_FTOA_FORMAT_FIXED && !(flags & BF_FTOA_FORCE_EXP)) { /* just output zero */ dbuf_putstr(s, "0"); } else { if (flags & BF_FTOA_ADD_PREFIX) { if (radix == 16) dbuf_putstr(s, "0x"); else if (radix == 8) dbuf_putstr(s, "0o"); else if (radix == 2) dbuf_putstr(s, "0b"); } if (a1->expn == BF_EXP_ZERO) n = 1; if ((flags & BF_FTOA_FORCE_EXP) || n <= -6 || n > n_max) { const char *fmt; /* exponential notation */ output_digits(s, a1, radix, n_digits, 1, is_dec); if (radix_bits != 0 && radix <= 16) { if (flags & BF_FTOA_JS_QUIRKS) fmt = "p%+" PRId_LIMB; else fmt = "p%" PRId_LIMB; dbuf_printf(s, fmt, (n - 1) * radix_bits); } else { if (flags & BF_FTOA_JS_QUIRKS) fmt = "%c%+" PRId_LIMB; else fmt = "%c%" PRId_LIMB; dbuf_printf(s, fmt, radix <= 10 ? 'e' : '@', n - 1); } } else if (n <= 0) { /* 0.x */ dbuf_putstr(s, "0."); for(i = 0; i < -n; i++) { dbuf_putc(s, '0'); } output_digits(s, a1, radix, n_digits, n_digits, is_dec); } else { if (n_digits <= n) { /* no dot */ output_digits(s, a1, radix, n_digits, n_digits, is_dec); for(i = 0; i < (n - n_digits); i++) dbuf_putc(s, '0'); } else { output_digits(s, a1, radix, n_digits, n, is_dec); } } } } bf_delete(a1); } } dbuf_putc(s, '\0'); if (dbuf_error(s)) goto fail; if (plen) *plen = s->size - 1; return (char *)s->buf; fail: bf_free(ctx, s->buf); if (plen) *plen = 0; return NULL; } char *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec, bf_flags_t flags) { return bf_ftoa_internal(plen, a, radix, prec, flags, FALSE); } /***************************************************************/ /* transcendental functions */ /* Note: the algorithm is from MPFR */ static void bf_const_log2_rec(bf_t *T, bf_t *P, bf_t *Q, limb_t n1, limb_t n2, BOOL need_P) { bf_context_t *s = T->ctx; if ((n2 - n1) == 1) { if (n1 == 0) { bf_set_ui(P, 3); } else { bf_set_ui(P, n1); P->sign = 1; } bf_set_ui(Q, 2 * n1 + 1); Q->expn += 2; bf_set(T, P); } else { limb_t m; bf_t T1_s, *T1 = &T1_s; bf_t P1_s, *P1 = &P1_s; bf_t Q1_s, *Q1 = &Q1_s; m = n1 + ((n2 - n1) >> 1); bf_const_log2_rec(T, P, Q, n1, m, TRUE); bf_init(s, T1); bf_init(s, P1); bf_init(s, Q1); bf_const_log2_rec(T1, P1, Q1, m, n2, need_P); bf_mul(T, T, Q1, BF_PREC_INF, BF_RNDZ); bf_mul(T1, T1, P, BF_PREC_INF, BF_RNDZ); bf_add(T, T, T1, BF_PREC_INF, BF_RNDZ); if (need_P) bf_mul(P, P, P1, BF_PREC_INF, BF_RNDZ); bf_mul(Q, Q, Q1, BF_PREC_INF, BF_RNDZ); bf_delete(T1); bf_delete(P1); bf_delete(Q1); } } /* compute log(2) with faithful rounding at precision 'prec' */ static void bf_const_log2_internal(bf_t *T, limb_t prec) { limb_t w, N; bf_t P_s, *P = &P_s; bf_t Q_s, *Q = &Q_s; w = prec + 15; N = w / 3 + 1; bf_init(T->ctx, P); bf_init(T->ctx, Q); bf_const_log2_rec(T, P, Q, 0, N, FALSE); bf_div(T, T, Q, prec, BF_RNDN); bf_delete(P); bf_delete(Q); } /* PI constant */ #define CHUD_A 13591409 #define CHUD_B 545140134 #define CHUD_C 640320 #define CHUD_BITS_PER_TERM 47 static void chud_bs(bf_t *P, bf_t *Q, bf_t *G, int64_t a, int64_t b, int need_g, limb_t prec) { bf_context_t *s = P->ctx; int64_t c; if (a == (b - 1)) { bf_t T0, T1; bf_init(s, &T0); bf_init(s, &T1); bf_set_ui(G, 2 * b - 1); bf_mul_ui(G, G, 6 * b - 1, prec, BF_RNDN); bf_mul_ui(G, G, 6 * b - 5, prec, BF_RNDN); bf_set_ui(&T0, CHUD_B); bf_mul_ui(&T0, &T0, b, prec, BF_RNDN); bf_set_ui(&T1, CHUD_A); bf_add(&T0, &T0, &T1, prec, BF_RNDN); bf_mul(P, G, &T0, prec, BF_RNDN); P->sign = b & 1; bf_set_ui(Q, b); bf_mul_ui(Q, Q, b, prec, BF_RNDN); bf_mul_ui(Q, Q, b, prec, BF_RNDN); bf_mul_ui(Q, Q, (uint64_t)CHUD_C * CHUD_C * CHUD_C / 24, prec, BF_RNDN); bf_delete(&T0); bf_delete(&T1); } else { bf_t P2, Q2, G2; bf_init(s, &P2); bf_init(s, &Q2); bf_init(s, &G2); c = (a + b) / 2; chud_bs(P, Q, G, a, c, 1, prec); chud_bs(&P2, &Q2, &G2, c, b, need_g, prec); /* Q = Q1 * Q2 */ /* G = G1 * G2 */ /* P = P1 * Q2 + P2 * G1 */ bf_mul(&P2, &P2, G, prec, BF_RNDN); if (!need_g) bf_set_ui(G, 0); bf_mul(P, P, &Q2, prec, BF_RNDN); bf_add(P, P, &P2, prec, BF_RNDN); bf_delete(&P2); bf_mul(Q, Q, &Q2, prec, BF_RNDN); bf_delete(&Q2); if (need_g) bf_mul(G, G, &G2, prec, BF_RNDN); bf_delete(&G2); } } /* compute Pi with faithful rounding at precision 'prec' using the Chudnovsky formula */ static void bf_const_pi_internal(bf_t *Q, limb_t prec) { bf_context_t *s = Q->ctx; int64_t n, prec1; bf_t P, G; /* number of serie terms */ n = prec / CHUD_BITS_PER_TERM + 1; /* XXX: precision analysis */ prec1 = prec + 32; bf_init(s, &P); bf_init(s, &G); chud_bs(&P, Q, &G, 0, n, 0, BF_PREC_INF); bf_mul_ui(&G, Q, CHUD_A, prec1, BF_RNDN); bf_add(&P, &G, &P, prec1, BF_RNDN); bf_div(Q, Q, &P, prec1, BF_RNDF); bf_set_ui(&P, CHUD_C); bf_sqrt(&G, &P, prec1, BF_RNDF); bf_mul_ui(&G, &G, (uint64_t)CHUD_C / 12, prec1, BF_RNDF); bf_mul(Q, Q, &G, prec, BF_RNDN); bf_delete(&P); bf_delete(&G); } static int bf_const_get(bf_t *T, limb_t prec, bf_flags_t flags, BFConstCache *c, void (*func)(bf_t *res, limb_t prec), int sign) { limb_t ziv_extra_bits, prec1; ziv_extra_bits = 32; for(;;) { prec1 = prec + ziv_extra_bits; if (c->prec < prec1) { if (c->val.len == 0) bf_init(T->ctx, &c->val); func(&c->val, prec1); c->prec = prec1; } else { prec1 = c->prec; } bf_set(T, &c->val); T->sign = sign; if (!bf_can_round(T, prec, flags & BF_RND_MASK, prec1)) { /* and more precision and retry */ ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2); } else { break; } } return bf_round(T, prec, flags); } static void bf_const_free(BFConstCache *c) { bf_delete(&c->val); memset(c, 0, sizeof(*c)); } int bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags) { bf_context_t *s = T->ctx; return bf_const_get(T, prec, flags, &s->log2_cache, bf_const_log2_internal, 0); } /* return rounded pi * (1 - 2 * sign) */ static int bf_const_pi_signed(bf_t *T, int sign, limb_t prec, bf_flags_t flags) { bf_context_t *s = T->ctx; return bf_const_get(T, prec, flags, &s->pi_cache, bf_const_pi_internal, sign); } int bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags) { return bf_const_pi_signed(T, 0, prec, flags); } void bf_clear_cache(bf_context_t *s) { #ifdef USE_FFT_MUL fft_clear_cache(s); #endif bf_const_free(&s->log2_cache); bf_const_free(&s->pi_cache); } /* ZivFunc should compute the result 'r' with faithful rounding at precision 'prec'. For efficiency purposes, the final bf_round() does not need to be done in the function. */ typedef int ZivFunc(bf_t *r, const bf_t *a, limb_t prec, void *opaque); static int bf_ziv_rounding(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags, ZivFunc *f, void *opaque) { int rnd_mode, ret; slimb_t prec1, ziv_extra_bits; rnd_mode = flags & BF_RND_MASK; if (rnd_mode == BF_RNDF) { /* no need to iterate */ f(r, a, prec, opaque); ret = 0; } else { ziv_extra_bits = 32; for(;;) { prec1 = prec + ziv_extra_bits; ret = f(r, a, prec1, opaque); if (ret & (BF_ST_OVERFLOW | BF_ST_UNDERFLOW | BF_ST_MEM_ERROR)) { /* overflow or underflow should never happen because it indicates the rounding cannot be done correctly, but we do not catch all the cases */ return ret; } /* if the result is exact, we can stop */ if (!(ret & BF_ST_INEXACT)) { ret = 0; break; } if (bf_can_round(r, prec, rnd_mode, prec1)) { ret = BF_ST_INEXACT; break; } ziv_extra_bits = ziv_extra_bits * 2; // printf("ziv_extra_bits=%" PRId64 "\n", (int64_t)ziv_extra_bits); } } if (r->len == 0) return ret; else return __bf_round(r, prec, flags, r->len, ret); } /* add (1 - 2*e_sign) * 2^e */ static int bf_add_epsilon(bf_t *r, const bf_t *a, slimb_t e, int e_sign, limb_t prec, int flags) { bf_t T_s, *T = &T_s; int ret; /* small argument case: result = 1 + epsilon * sign(x) */ bf_init(a->ctx, T); bf_set_ui(T, 1); T->sign = e_sign; T->expn += e; ret = bf_add(r, r, T, prec, flags); bf_delete(T); return ret; } /* Compute the exponential using faithful rounding at precision 'prec'. Note: the algorithm is from MPFR */ static int bf_exp_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; slimb_t n, K, l, i, prec1; assert(r != a); /* argument reduction: T = a - n*log(2) with 0 <= T < log(2) and n integer. */ bf_init(s, T); if (a->expn <= -1) { /* 0 <= abs(a) <= 0.5 */ if (a->sign) n = -1; else n = 0; } else { bf_const_log2(T, LIMB_BITS, BF_RNDZ); bf_div(T, a, T, LIMB_BITS, BF_RNDD); bf_get_limb(&n, T, 0); } K = bf_isqrt((prec + 1) / 2); l = (prec - 1) / K + 1; /* XXX: precision analysis ? */ prec1 = prec + (K + 2 * l + 18) + K + 8; if (a->expn > 0) prec1 += a->expn; // printf("n=%ld K=%ld prec1=%ld\n", n, K, prec1); bf_const_log2(T, prec1, BF_RNDF); bf_mul_si(T, T, n, prec1, BF_RNDN); bf_sub(T, a, T, prec1, BF_RNDN); /* reduce the range of T */ bf_mul_2exp(T, -K, BF_PREC_INF, BF_RNDZ); /* Taylor expansion around zero : 1 + x + x^2/2 + ... + x^n/n! = (1 + x * (1 + x/2 * (1 + ... (x/n)))) */ { bf_t U_s, *U = &U_s; bf_init(s, U); bf_set_ui(r, 1); for(i = l ; i >= 1; i--) { bf_set_ui(U, i); bf_div(U, T, U, prec1, BF_RNDN); bf_mul(r, r, U, prec1, BF_RNDN); bf_add_si(r, r, 1, prec1, BF_RNDN); } bf_delete(U); } bf_delete(T); /* undo the range reduction */ for(i = 0; i < K; i++) { bf_mul(r, r, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP); } /* undo the argument reduction */ bf_mul_2exp(r, n, BF_PREC_INF, BF_RNDZ | BF_FLAG_EXT_EXP); return BF_ST_INEXACT; } /* crude overflow and underflow tests for exp(a). a_low <= a <= a_high */ static int check_exp_underflow_overflow(bf_context_t *s, bf_t *r, const bf_t *a_low, const bf_t *a_high, limb_t prec, bf_flags_t flags) { bf_t T_s, *T = &T_s; bf_t log2_s, *log2 = &log2_s; slimb_t e_min, e_max; if (a_high->expn <= 0) return 0; e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1); e_min = -e_max + 3; if (flags & BF_FLAG_SUBNORMAL) e_min -= (prec - 1); bf_init(s, T); bf_init(s, log2); bf_const_log2(log2, LIMB_BITS, BF_RNDU); bf_mul_ui(T, log2, e_max, LIMB_BITS, BF_RNDU); /* a_low > e_max * log(2) implies exp(a) > e_max */ if (bf_cmp_lt(T, a_low) > 0) { /* overflow */ bf_delete(T); bf_delete(log2); return bf_set_overflow(r, 0, prec, flags); } /* a_high < (e_min - 2) * log(2) implies exp(a) < (e_min - 2) */ bf_const_log2(log2, LIMB_BITS, BF_RNDD); bf_mul_si(T, log2, e_min - 2, LIMB_BITS, BF_RNDD); if (bf_cmp_lt(a_high, T)) { int rnd_mode = flags & BF_RND_MASK; /* underflow */ bf_delete(T); bf_delete(log2); if (rnd_mode == BF_RNDU) { /* set the smallest value */ bf_set_ui(r, 1); r->expn = e_min; } else { bf_set_zero(r, 0); } return BF_ST_UNDERFLOW | BF_ST_INEXACT; } bf_delete(log2); bf_delete(T); return 0; } int bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; int ret; assert(r != a); if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); } else if (a->expn == BF_EXP_INF) { if (a->sign) bf_set_zero(r, 0); else bf_set_inf(r, 0); } else { bf_set_ui(r, 1); } return 0; } ret = check_exp_underflow_overflow(s, r, a, a, prec, flags); if (ret) return ret; if (a->expn < 0 && (-a->expn) >= (prec + 2)) { /* small argument case: result = 1 + epsilon * sign(x) */ bf_set_ui(r, 1); return bf_add_epsilon(r, r, -(prec + 2), a->sign, prec, flags); } return bf_ziv_rounding(r, a, prec, flags, bf_exp_internal, NULL); } static int bf_log_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; bf_t U_s, *U = &U_s; bf_t V_s, *V = &V_s; slimb_t n, prec1, l, i, K; assert(r != a); bf_init(s, T); /* argument reduction 1 */ /* T=a*2^n with 2/3 <= T <= 4/3 */ { bf_t U_s, *U = &U_s; bf_set(T, a); n = T->expn; T->expn = 0; /* U= ~ 2/3 */ bf_init(s, U); bf_set_ui(U, 0xaaaaaaaa); U->expn = 0; if (bf_cmp_lt(T, U)) { T->expn++; n--; } bf_delete(U); } // printf("n=%ld\n", n); // bf_print_str("T", T); /* XXX: precision analysis */ /* number of iterations for argument reduction 2 */ K = bf_isqrt((prec + 1) / 2); /* order of Taylor expansion */ l = prec / (2 * K) + 1; /* precision of the intermediate computations */ prec1 = prec + K + 2 * l + 32; bf_init(s, U); bf_init(s, V); /* Note: cancellation occurs here, so we use more precision (XXX: reduce the precision by computing the exact cancellation) */ bf_add_si(T, T, -1, BF_PREC_INF, BF_RNDN); /* argument reduction 2 */ for(i = 0; i < K; i++) { /* T = T / (1 + sqrt(1 + T)) */ bf_add_si(U, T, 1, prec1, BF_RNDN); bf_sqrt(V, U, prec1, BF_RNDF); bf_add_si(U, V, 1, prec1, BF_RNDN); bf_div(T, T, U, prec1, BF_RNDN); } { bf_t Y_s, *Y = &Y_s; bf_t Y2_s, *Y2 = &Y2_s; bf_init(s, Y); bf_init(s, Y2); /* compute ln(1+x) = ln((1+y)/(1-y)) with y=x/(2+x) = y + y^3/3 + ... + y^(2*l + 1) / (2*l+1) with Y=Y^2 = y*(1+Y/3+Y^2/5+...) = y*(1+Y*(1/3+Y*(1/5 + ...))) */ bf_add_si(Y, T, 2, prec1, BF_RNDN); bf_div(Y, T, Y, prec1, BF_RNDN); bf_mul(Y2, Y, Y, prec1, BF_RNDN); bf_set_ui(r, 0); for(i = l; i >= 1; i--) { bf_set_ui(U, 1); bf_set_ui(V, 2 * i + 1); bf_div(U, U, V, prec1, BF_RNDN); bf_add(r, r, U, prec1, BF_RNDN); bf_mul(r, r, Y2, prec1, BF_RNDN); } bf_add_si(r, r, 1, prec1, BF_RNDN); bf_mul(r, r, Y, prec1, BF_RNDN); bf_delete(Y); bf_delete(Y2); } bf_delete(V); bf_delete(U); /* multiplication by 2 for the Taylor expansion and undo the argument reduction 2*/ bf_mul_2exp(r, K + 1, BF_PREC_INF, BF_RNDZ); /* undo the argument reduction 1 */ bf_const_log2(T, prec1, BF_RNDF); bf_mul_si(T, T, n, prec1, BF_RNDN); bf_add(r, r, T, prec1, BF_RNDN); bf_delete(T); return BF_ST_INEXACT; } int bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; assert(r != a); if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { if (a->sign) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_inf(r, 0); return 0; } } else { bf_set_inf(r, 1); return 0; } } if (a->sign) { bf_set_nan(r); return BF_ST_INVALID_OP; } bf_init(s, T); bf_set_ui(T, 1); if (bf_cmp_eq(a, T)) { bf_set_zero(r, 0); bf_delete(T); return 0; } bf_delete(T); return bf_ziv_rounding(r, a, prec, flags, bf_log_internal, NULL); } /* x and y finite and x > 0 */ static int bf_pow_generic(bf_t *r, const bf_t *x, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; const bf_t *y = opaque; bf_t T_s, *T = &T_s; limb_t prec1; bf_init(s, T); /* XXX: proof for the added precision */ prec1 = prec + 32; bf_log(T, x, prec1, BF_RNDF | BF_FLAG_EXT_EXP); bf_mul(T, T, y, prec1, BF_RNDF | BF_FLAG_EXT_EXP); if (bf_is_nan(T)) bf_set_nan(r); else bf_exp_internal(r, T, prec1, NULL); /* no overflow/underlow test needed */ bf_delete(T); return BF_ST_INEXACT; } /* x and y finite, x > 0, y integer and y fits on one limb */ static int bf_pow_int(bf_t *r, const bf_t *x, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; const bf_t *y = opaque; bf_t T_s, *T = &T_s; limb_t prec1; int ret; slimb_t y1; bf_get_limb(&y1, y, 0); if (y1 < 0) y1 = -y1; /* XXX: proof for the added precision */ prec1 = prec + ceil_log2(y1) * 2 + 8; ret = bf_pow_ui(r, x, y1 < 0 ? -y1 : y1, prec1, BF_RNDN | BF_FLAG_EXT_EXP); if (y->sign) { bf_init(s, T); bf_set_ui(T, 1); ret |= bf_div(r, T, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP); bf_delete(T); } return ret; } /* x must be a finite non zero float. Return TRUE if there is a floating point number r such as x=r^(2^n) and return this floating point number 'r'. Otherwise return FALSE and r is undefined. */ static BOOL check_exact_power2n(bf_t *r, const bf_t *x, slimb_t n) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; slimb_t e, i, er; limb_t v; /* x = m*2^e with m odd integer */ e = bf_get_exp_min(x); /* fast check on the exponent */ if (n > (LIMB_BITS - 1)) { if (e != 0) return FALSE; er = 0; } else { if ((e & (((limb_t)1 << n) - 1)) != 0) return FALSE; er = e >> n; } /* every perfect odd square = 1 modulo 8 */ v = get_bits(x->tab, x->len, x->len * LIMB_BITS - x->expn + e); if ((v & 7) != 1) return FALSE; bf_init(s, T); bf_set(T, x); T->expn -= e; for(i = 0; i < n; i++) { if (i != 0) bf_set(T, r); if (bf_sqrtrem(r, NULL, T) != 0) return FALSE; } r->expn += er; return TRUE; } /* prec = BF_PREC_INF is accepted for x and y integers and y >= 0 */ int bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; bf_t ytmp_s; BOOL y_is_int, y_is_odd; int r_sign, ret, rnd_mode; slimb_t y_emin; if (x->len == 0 || y->len == 0) { if (y->expn == BF_EXP_ZERO) { /* pow(x, 0) = 1 */ bf_set_ui(r, 1); } else if (x->expn == BF_EXP_NAN) { bf_set_nan(r); } else { int cmp_x_abs_1; bf_set_ui(r, 1); cmp_x_abs_1 = bf_cmpu(x, r); if (cmp_x_abs_1 == 0 && (flags & BF_POW_JS_QUIRKS) && (y->expn >= BF_EXP_INF)) { bf_set_nan(r); } else if (cmp_x_abs_1 == 0 && (!x->sign || y->expn != BF_EXP_NAN)) { /* pow(1, y) = 1 even if y = NaN */ /* pow(-1, +/-inf) = 1 */ } else if (y->expn == BF_EXP_NAN) { bf_set_nan(r); } else if (y->expn == BF_EXP_INF) { if (y->sign == (cmp_x_abs_1 > 0)) { bf_set_zero(r, 0); } else { bf_set_inf(r, 0); } } else { y_emin = bf_get_exp_min(y); y_is_odd = (y_emin == 0); if (y->sign == (x->expn == BF_EXP_ZERO)) { bf_set_inf(r, y_is_odd & x->sign); if (y->sign) { /* pow(0, y) with y < 0 */ return BF_ST_DIVIDE_ZERO; } } else { bf_set_zero(r, y_is_odd & x->sign); } } } return 0; } bf_init(s, T); bf_set(T, x); y_emin = bf_get_exp_min(y); y_is_int = (y_emin >= 0); rnd_mode = flags & BF_RND_MASK; if (x->sign) { if (!y_is_int) { bf_set_nan(r); bf_delete(T); return BF_ST_INVALID_OP; } y_is_odd = (y_emin == 0); r_sign = y_is_odd; /* change the directed rounding mode if the sign of the result is changed */ if (r_sign && (rnd_mode == BF_RNDD || rnd_mode == BF_RNDU)) flags ^= 1; bf_neg(T); } else { r_sign = 0; } bf_set_ui(r, 1); if (bf_cmp_eq(T, r)) { /* abs(x) = 1: nothing more to do */ ret = 0; } else { /* check the overflow/underflow cases */ { bf_t al_s, *al = &al_s; bf_t ah_s, *ah = &ah_s; limb_t precl = LIMB_BITS; bf_init(s, al); bf_init(s, ah); /* compute bounds of log(abs(x)) * y with a low precision */ /* XXX: compute bf_log() once */ /* XXX: add a fast test before this slow test */ bf_log(al, T, precl, BF_RNDD); bf_log(ah, T, precl, BF_RNDU); bf_mul(al, al, y, precl, BF_RNDD ^ y->sign); bf_mul(ah, ah, y, precl, BF_RNDU ^ y->sign); ret = check_exp_underflow_overflow(s, r, al, ah, prec, flags); bf_delete(al); bf_delete(ah); if (ret) goto done; } if (y_is_int) { slimb_t T_bits, e; int_pow: T_bits = T->expn - bf_get_exp_min(T); if (T_bits == 1) { /* pow(2^b, y) = 2^(b*y) */ bf_mul_si(T, y, T->expn - 1, LIMB_BITS, BF_RNDZ); bf_get_limb(&e, T, 0); bf_set_ui(r, 1); ret = bf_mul_2exp(r, e, prec, flags); } else if (prec == BF_PREC_INF) { slimb_t y1; /* specific case for infinite precision (integer case) */ bf_get_limb(&y1, y, 0); assert(!y->sign); /* x must be an integer, so abs(x) >= 2 */ if (y1 >= ((slimb_t)1 << BF_EXP_BITS_MAX)) { bf_delete(T); return bf_set_overflow(r, 0, BF_PREC_INF, flags); } ret = bf_pow_ui(r, T, y1, BF_PREC_INF, BF_RNDZ); } else { if (y->expn <= 31) { /* small enough power: use exponentiation in all cases */ } else if (y->sign) { /* cannot be exact */ goto general_case; } else { if (rnd_mode == BF_RNDF) goto general_case; /* no need to track exact results */ /* see if the result has a chance to be exact: if x=a*2^b (a odd), x^y=a^y*2^(b*y) x^y needs a precision of at least floor_log2(a)*y bits */ bf_mul_si(r, y, T_bits - 1, LIMB_BITS, BF_RNDZ); bf_get_limb(&e, r, 0); if (prec < e) goto general_case; } ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_int, (void *)y); } } else { if (rnd_mode != BF_RNDF) { bf_t *y1; if (y_emin < 0 && check_exact_power2n(r, T, -y_emin)) { /* the problem is reduced to a power to an integer */ #if 0 printf("\nn=%" PRId64 "\n", -(int64_t)y_emin); bf_print_str("T", T); bf_print_str("r", r); #endif bf_set(T, r); y1 = &ytmp_s; y1->tab = y->tab; y1->len = y->len; y1->sign = y->sign; y1->expn = y->expn - y_emin; y = y1; goto int_pow; } } general_case: ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_generic, (void *)y); } } done: bf_delete(T); r->sign = r_sign; return ret; } /* compute sqrt(-2*x-x^2) to get |sin(x)| from cos(x) - 1. */ static void bf_sqrt_sin(bf_t *r, const bf_t *x, limb_t prec1) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; bf_init(s, T); bf_set(T, x); bf_mul(r, T, T, prec1, BF_RNDN); bf_mul_2exp(T, 1, BF_PREC_INF, BF_RNDZ); bf_add(T, T, r, prec1, BF_RNDN); bf_neg(T); bf_sqrt(r, T, prec1, BF_RNDF); bf_delete(T); } static int bf_sincos(bf_t *s, bf_t *c, const bf_t *a, limb_t prec) { bf_context_t *s1 = a->ctx; bf_t T_s, *T = &T_s; bf_t U_s, *U = &U_s; bf_t r_s, *r = &r_s; slimb_t K, prec1, i, l, mod, prec2; int is_neg; assert(c != a && s != a); bf_init(s1, T); bf_init(s1, U); bf_init(s1, r); /* XXX: precision analysis */ K = bf_isqrt(prec / 2); l = prec / (2 * K) + 1; prec1 = prec + 2 * K + l + 8; /* after the modulo reduction, -pi/4 <= T <= pi/4 */ if (a->expn <= -1) { /* abs(a) <= 0.25: no modulo reduction needed */ bf_set(T, a); mod = 0; } else { slimb_t cancel; cancel = 0; for(;;) { prec2 = prec1 + a->expn + cancel; bf_const_pi(U, prec2, BF_RNDF); bf_mul_2exp(U, -1, BF_PREC_INF, BF_RNDZ); bf_remquo(&mod, T, a, U, prec2, BF_RNDN, BF_RNDN); // printf("T.expn=%ld prec2=%ld\n", T->expn, prec2); if (mod == 0 || (T->expn != BF_EXP_ZERO && (T->expn + prec2) >= (prec1 - 1))) break; /* increase the number of bits until the precision is good enough */ cancel = bf_max(-T->expn, (cancel + 1) * 3 / 2); } mod &= 3; } is_neg = T->sign; /* compute cosm1(x) = cos(x) - 1 */ bf_mul(T, T, T, prec1, BF_RNDN); bf_mul_2exp(T, -2 * K, BF_PREC_INF, BF_RNDZ); /* Taylor expansion: -x^2/2 + x^4/4! - x^6/6! + ... */ bf_set_ui(r, 1); for(i = l ; i >= 1; i--) { bf_set_ui(U, 2 * i - 1); bf_mul_ui(U, U, 2 * i, BF_PREC_INF, BF_RNDZ); bf_div(U, T, U, prec1, BF_RNDN); bf_mul(r, r, U, prec1, BF_RNDN); bf_neg(r); if (i != 1) bf_add_si(r, r, 1, prec1, BF_RNDN); } bf_delete(U); /* undo argument reduction: cosm1(2*x)= 2*(2*cosm1(x)+cosm1(x)^2) */ for(i = 0; i < K; i++) { bf_mul(T, r, r, prec1, BF_RNDN); bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ); bf_add(r, r, T, prec1, BF_RNDN); bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ); } bf_delete(T); if (c) { if ((mod & 1) == 0) { bf_add_si(c, r, 1, prec1, BF_RNDN); } else { bf_sqrt_sin(c, r, prec1); c->sign = is_neg ^ 1; } c->sign ^= mod >> 1; } if (s) { if ((mod & 1) == 0) { bf_sqrt_sin(s, r, prec1); s->sign = is_neg; } else { bf_add_si(s, r, 1, prec1, BF_RNDN); } s->sign ^= mod >> 1; } bf_delete(r); return BF_ST_INEXACT; } static int bf_cos_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { return bf_sincos(NULL, r, a, prec); } int bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_ui(r, 1); return 0; } } /* small argument case: result = 1+r(x) with r(x) = -x^2/2 + O(X^4). We assume r(x) < 2^(2*EXP(x) - 1). */ if (a->expn < 0) { slimb_t e; e = 2 * a->expn - 1; if (e < -(prec + 2)) { bf_set_ui(r, 1); return bf_add_epsilon(r, r, e, 1, prec, flags); } } return bf_ziv_rounding(r, a, prec, flags, bf_cos_internal, NULL); } static int bf_sin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { return bf_sincos(r, NULL, a, prec); } int bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_zero(r, a->sign); return 0; } } /* small argument case: result = x+r(x) with r(x) = -x^3/6 + O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */ if (a->expn < 0) { slimb_t e; e = sat_add(2 * a->expn, a->expn - 2); if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) { bf_set(r, a); return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags); } } return bf_ziv_rounding(r, a, prec, flags, bf_sin_internal, NULL); } static int bf_tan_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; limb_t prec1; /* XXX: precision analysis */ prec1 = prec + 8; bf_init(s, T); bf_sincos(r, T, a, prec1); bf_div(r, r, T, prec1, BF_RNDF); bf_delete(T); return BF_ST_INEXACT; } int bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { assert(r != a); if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_zero(r, a->sign); return 0; } } /* small argument case: result = x+r(x) with r(x) = x^3/3 + O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */ if (a->expn < 0) { slimb_t e; e = sat_add(2 * a->expn, a->expn - 1); if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) { bf_set(r, a); return bf_add_epsilon(r, r, e, a->sign, prec, flags); } } return bf_ziv_rounding(r, a, prec, flags, bf_tan_internal, NULL); } /* if add_pi2 is true, add pi/2 to the result (used for acos(x) to avoid cancellation) */ static int bf_atan_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; BOOL add_pi2 = (BOOL)(intptr_t)opaque; bf_t T_s, *T = &T_s; bf_t U_s, *U = &U_s; bf_t V_s, *V = &V_s; bf_t X2_s, *X2 = &X2_s; int cmp_1; slimb_t prec1, i, K, l; /* XXX: precision analysis */ K = bf_isqrt((prec + 1) / 2); l = prec / (2 * K) + 1; prec1 = prec + K + 2 * l + 32; // printf("prec=%d K=%d l=%d prec1=%d\n", (int)prec, (int)K, (int)l, (int)prec1); bf_init(s, T); cmp_1 = (a->expn >= 1); /* a >= 1 */ if (cmp_1) { bf_set_ui(T, 1); bf_div(T, T, a, prec1, BF_RNDN); } else { bf_set(T, a); } /* abs(T) <= 1 */ /* argument reduction */ bf_init(s, U); bf_init(s, V); bf_init(s, X2); for(i = 0; i < K; i++) { /* T = T / (1 + sqrt(1 + T^2)) */ bf_mul(U, T, T, prec1, BF_RNDN); bf_add_si(U, U, 1, prec1, BF_RNDN); bf_sqrt(V, U, prec1, BF_RNDN); bf_add_si(V, V, 1, prec1, BF_RNDN); bf_div(T, T, V, prec1, BF_RNDN); } /* Taylor series: x - x^3/3 + ... + (-1)^ l * y^(2*l + 1) / (2*l+1) */ bf_mul(X2, T, T, prec1, BF_RNDN); bf_set_ui(r, 0); for(i = l; i >= 1; i--) { bf_set_si(U, 1); bf_set_ui(V, 2 * i + 1); bf_div(U, U, V, prec1, BF_RNDN); bf_neg(r); bf_add(r, r, U, prec1, BF_RNDN); bf_mul(r, r, X2, prec1, BF_RNDN); } bf_neg(r); bf_add_si(r, r, 1, prec1, BF_RNDN); bf_mul(r, r, T, prec1, BF_RNDN); /* undo the argument reduction */ bf_mul_2exp(r, K, BF_PREC_INF, BF_RNDZ); bf_delete(U); bf_delete(V); bf_delete(X2); i = add_pi2; if (cmp_1 > 0) { /* undo the inversion : r = sign(a)*PI/2 - r */ bf_neg(r); i += 1 - 2 * a->sign; } /* add i*(pi/2) with -1 <= i <= 2 */ if (i != 0) { bf_const_pi(T, prec1, BF_RNDF); if (i != 2) bf_mul_2exp(T, -1, BF_PREC_INF, BF_RNDZ); T->sign = (i < 0); bf_add(r, T, r, prec1, BF_RNDN); } bf_delete(T); return BF_ST_INEXACT; } int bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; int res; if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { /* -PI/2 or PI/2 */ bf_const_pi_signed(r, a->sign, prec, flags); bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ); return BF_ST_INEXACT; } else { bf_set_zero(r, a->sign); return 0; } } bf_init(s, T); bf_set_ui(T, 1); res = bf_cmpu(a, T); bf_delete(T); if (res == 0) { /* short cut: abs(a) == 1 -> +/-pi/4 */ bf_const_pi_signed(r, a->sign, prec, flags); bf_mul_2exp(r, -2, BF_PREC_INF, BF_RNDZ); return BF_ST_INEXACT; } /* small argument case: result = x+r(x) with r(x) = -x^3/3 + O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */ if (a->expn < 0) { slimb_t e; e = sat_add(2 * a->expn, a->expn - 1); if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) { bf_set(r, a); return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags); } } return bf_ziv_rounding(r, a, prec, flags, bf_atan_internal, (void *)FALSE); } static int bf_atan2_internal(bf_t *r, const bf_t *y, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; const bf_t *x = opaque; bf_t T_s, *T = &T_s; limb_t prec1; int ret; if (y->expn == BF_EXP_NAN || x->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } /* compute atan(y/x) assumming inf/inf = 1 and 0/0 = 0 */ bf_init(s, T); prec1 = prec + 32; if (y->expn == BF_EXP_INF && x->expn == BF_EXP_INF) { bf_set_ui(T, 1); T->sign = y->sign ^ x->sign; } else if (y->expn == BF_EXP_ZERO && x->expn == BF_EXP_ZERO) { bf_set_zero(T, y->sign ^ x->sign); } else { bf_div(T, y, x, prec1, BF_RNDF); } ret = bf_atan(r, T, prec1, BF_RNDF); if (x->sign) { /* if x < 0 (it includes -0), return sign(y)*pi + atan(y/x) */ bf_const_pi(T, prec1, BF_RNDF); T->sign = y->sign; bf_add(r, r, T, prec1, BF_RNDN); ret |= BF_ST_INEXACT; } bf_delete(T); return ret; } int bf_atan2(bf_t *r, const bf_t *y, const bf_t *x, limb_t prec, bf_flags_t flags) { return bf_ziv_rounding(r, y, prec, flags, bf_atan2_internal, (void *)x); } static int bf_asin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque) { bf_context_t *s = r->ctx; BOOL is_acos = (BOOL)(intptr_t)opaque; bf_t T_s, *T = &T_s; limb_t prec1, prec2; /* asin(x) = atan(x/sqrt(1-x^2)) acos(x) = pi/2 - asin(x) */ prec1 = prec + 8; /* increase the precision in x^2 to compensate the cancellation in (1-x^2) if x is close to 1 */ /* XXX: use less precision when possible */ if (a->expn >= 0) prec2 = BF_PREC_INF; else prec2 = prec1; bf_init(s, T); bf_mul(T, a, a, prec2, BF_RNDN); bf_neg(T); bf_add_si(T, T, 1, prec2, BF_RNDN); bf_sqrt(r, T, prec1, BF_RNDN); bf_div(T, a, r, prec1, BF_RNDN); if (is_acos) bf_neg(T); bf_atan_internal(r, T, prec1, (void *)(intptr_t)is_acos); bf_delete(T); return BF_ST_INEXACT; } int bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; int res; if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_set_zero(r, a->sign); return 0; } } bf_init(s, T); bf_set_ui(T, 1); res = bf_cmpu(a, T); bf_delete(T); if (res > 0) { bf_set_nan(r); return BF_ST_INVALID_OP; } /* small argument case: result = x+r(x) with r(x) = x^3/6 + O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */ if (a->expn < 0) { slimb_t e; e = sat_add(2 * a->expn, a->expn - 2); if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) { bf_set(r, a); return bf_add_epsilon(r, r, e, a->sign, prec, flags); } } return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)FALSE); } int bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = r->ctx; bf_t T_s, *T = &T_s; int res; if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bf_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF) { bf_set_nan(r); return BF_ST_INVALID_OP; } else { bf_const_pi(r, prec, flags); bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ); return BF_ST_INEXACT; } } bf_init(s, T); bf_set_ui(T, 1); res = bf_cmpu(a, T); bf_delete(T); if (res > 0) { bf_set_nan(r); return BF_ST_INVALID_OP; } else if (res == 0 && a->sign == 0) { bf_set_zero(r, 0); return 0; } return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)TRUE); } /***************************************************************/ /* decimal floating point numbers */ #ifdef USE_BF_DEC #define adddq(r1, r0, a1, a0) \ do { \ limb_t __t = r0; \ r0 += (a0); \ r1 += (a1) + (r0 < __t); \ } while (0) #define subdq(r1, r0, a1, a0) \ do { \ limb_t __t = r0; \ r0 -= (a0); \ r1 -= (a1) + (r0 > __t); \ } while (0) #if LIMB_BITS == 64 /* Note: we assume __int128 is available */ #define muldq(r1, r0, a, b) \ do { \ unsigned __int128 __t; \ __t = (unsigned __int128)(a) * (unsigned __int128)(b); \ r0 = __t; \ r1 = __t >> 64; \ } while (0) #define divdq(q, r, a1, a0, b) \ do { \ unsigned __int128 __t; \ limb_t __b = (b); \ __t = ((unsigned __int128)(a1) << 64) | (a0); \ q = __t / __b; \ r = __t % __b; \ } while (0) #else #define muldq(r1, r0, a, b) \ do { \ uint64_t __t; \ __t = (uint64_t)(a) * (uint64_t)(b); \ r0 = __t; \ r1 = __t >> 32; \ } while (0) #define divdq(q, r, a1, a0, b) \ do { \ uint64_t __t; \ limb_t __b = (b); \ __t = ((uint64_t)(a1) << 32) | (a0); \ q = __t / __b; \ r = __t % __b; \ } while (0) #endif /* LIMB_BITS != 64 */ static inline __maybe_unused limb_t shrd(limb_t low, limb_t high, long shift) { if (shift != 0) low = (low >> shift) | (high << (LIMB_BITS - shift)); return low; } static inline __maybe_unused limb_t shld(limb_t a1, limb_t a0, long shift) { if (shift != 0) return (a1 << shift) | (a0 >> (LIMB_BITS - shift)); else return a1; } #if LIMB_DIGITS == 19 /* WARNING: hardcoded for b = 1e19. It is assumed that: 0 <= a1 < 2^63 */ #define divdq_base(q, r, a1, a0)\ do {\ uint64_t __a0, __a1, __t0, __t1, __b = BF_DEC_BASE; \ __a0 = a0;\ __a1 = a1;\ __t0 = __a1;\ __t0 = shld(__t0, __a0, 1);\ muldq(q, __t1, __t0, UINT64_C(17014118346046923173)); \ muldq(__t1, __t0, q, __b);\ subdq(__a1, __a0, __t1, __t0);\ subdq(__a1, __a0, 1, __b * 2); \ __t0 = (slimb_t)__a1 >> 1; \ q += 2 + __t0;\ adddq(__a1, __a0, 0, __b & __t0);\ q += __a1; \ __a0 += __b & __a1; \ r = __a0;\ } while(0) #elif LIMB_DIGITS == 9 /* WARNING: hardcoded for b = 1e9. It is assumed that: 0 <= a1 < 2^29 */ #define divdq_base(q, r, a1, a0)\ do {\ uint32_t __t0, __t1, __b = BF_DEC_BASE; \ __t0 = a1;\ __t1 = a0;\ __t0 = (__t0 << 3) | (__t1 >> (32 - 3)); \ muldq(q, __t1, __t0, 2305843009U);\ r = a0 - q * __b;\ __t1 = (r >= __b);\ q += __t1;\ if (__t1)\ r -= __b;\ } while(0) #endif /* fast integer division by a fixed constant */ typedef struct FastDivData { limb_t m1; /* multiplier */ int8_t shift1; int8_t shift2; } FastDivData; /* From "Division by Invariant Integers using Multiplication" by Torborn Granlund and Peter L. Montgomery */ /* d must be != 0 */ static inline __maybe_unused void fast_udiv_init(FastDivData *s, limb_t d) { int l; limb_t q, r, m1; if (d == 1) l = 0; else l = 64 - clz64(d - 1); divdq(q, r, ((limb_t)1 << l) - d, 0, d); (void)r; m1 = q + 1; // printf("d=%lu l=%d m1=0x%016lx\n", d, l, m1); s->m1 = m1; s->shift1 = l; if (s->shift1 > 1) s->shift1 = 1; s->shift2 = l - 1; if (s->shift2 < 0) s->shift2 = 0; } static inline limb_t fast_udiv(limb_t a, const FastDivData *s) { limb_t t0, t1; muldq(t1, t0, s->m1, a); t0 = (a - t1) >> s->shift1; return (t1 + t0) >> s->shift2; } /* contains 10^i */ const limb_t mp_pow_dec[LIMB_DIGITS + 1] = { 1U, 10U, 100U, 1000U, 10000U, 100000U, 1000000U, 10000000U, 100000000U, 1000000000U, #if LIMB_BITS == 64 10000000000U, 100000000000U, 1000000000000U, 10000000000000U, 100000000000000U, 1000000000000000U, 10000000000000000U, 100000000000000000U, 1000000000000000000U, 10000000000000000000U, #endif }; /* precomputed from fast_udiv_init(10^i) */ static const FastDivData mp_pow_div[LIMB_DIGITS + 1] = { #if LIMB_BITS == 32 { 0x00000001, 0, 0 }, { 0x9999999a, 1, 3 }, { 0x47ae147b, 1, 6 }, { 0x0624dd30, 1, 9 }, { 0xa36e2eb2, 1, 13 }, { 0x4f8b588f, 1, 16 }, { 0x0c6f7a0c, 1, 19 }, { 0xad7f29ac, 1, 23 }, { 0x5798ee24, 1, 26 }, { 0x12e0be83, 1, 29 }, #else { 0x0000000000000001, 0, 0 }, { 0x999999999999999a, 1, 3 }, { 0x47ae147ae147ae15, 1, 6 }, { 0x0624dd2f1a9fbe77, 1, 9 }, { 0xa36e2eb1c432ca58, 1, 13 }, { 0x4f8b588e368f0847, 1, 16 }, { 0x0c6f7a0b5ed8d36c, 1, 19 }, { 0xad7f29abcaf48579, 1, 23 }, { 0x5798ee2308c39dfa, 1, 26 }, { 0x12e0be826d694b2f, 1, 29 }, { 0xb7cdfd9d7bdbab7e, 1, 33 }, { 0x5fd7fe17964955fe, 1, 36 }, { 0x19799812dea11198, 1, 39 }, { 0xc25c268497681c27, 1, 43 }, { 0x6849b86a12b9b01f, 1, 46 }, { 0x203af9ee756159b3, 1, 49 }, { 0xcd2b297d889bc2b7, 1, 53 }, { 0x70ef54646d496893, 1, 56 }, { 0x2725dd1d243aba0f, 1, 59 }, { 0xd83c94fb6d2ac34d, 1, 63 }, #endif }; /* divide by 10^shift with 0 <= shift <= LIMB_DIGITS */ static inline limb_t fast_shr_dec(limb_t a, int shift) { return fast_udiv(a, &mp_pow_div[shift]); } /* division and remainder by 10^shift */ #define fast_shr_rem_dec(q, r, a, shift) q = fast_shr_dec(a, shift), r = a - q * mp_pow_dec[shift] limb_t mp_add_dec(limb_t *res, const limb_t *op1, const limb_t *op2, mp_size_t n, limb_t carry) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t k, a, v; k=carry; for(i=0;i<n;i++) { /* XXX: reuse the trick in add_mod */ v = op1[i]; a = v + op2[i] + k - base; k = a <= v; if (!k) a += base; res[i]=a; } return k; } limb_t mp_add_ui_dec(limb_t *tab, limb_t b, mp_size_t n) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t k, a, v; k=b; for(i=0;i<n;i++) { v = tab[i]; a = v + k - base; k = a <= v; if (!k) a += base; tab[i] = a; if (k == 0) break; } return k; } limb_t mp_sub_dec(limb_t *res, const limb_t *op1, const limb_t *op2, mp_size_t n, limb_t carry) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t k, v, a; k=carry; for(i=0;i<n;i++) { v = op1[i]; a = v - op2[i] - k; k = a > v; if (k) a += base; res[i] = a; } return k; } limb_t mp_sub_ui_dec(limb_t *tab, limb_t b, mp_size_t n) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t k, v, a; k=b; for(i=0;i<n;i++) { v = tab[i]; a = v - k; k = a > v; if (k) a += base; tab[i]=a; if (k == 0) break; } return k; } /* taba[] = taba[] * b + l. 0 <= b, l <= base - 1. Return the high carry */ limb_t mp_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n, limb_t b, limb_t l) { mp_size_t i; limb_t t0, t1, r; for(i = 0; i < n; i++) { muldq(t1, t0, taba[i], b); adddq(t1, t0, 0, l); divdq_base(l, r, t1, t0); tabr[i] = r; } return l; } /* tabr[] += taba[] * b. 0 <= b <= base - 1. Return the value to add to the high word */ limb_t mp_add_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n, limb_t b) { mp_size_t i; limb_t l, t0, t1, r; l = 0; for(i = 0; i < n; i++) { muldq(t1, t0, taba[i], b); adddq(t1, t0, 0, l); adddq(t1, t0, 0, tabr[i]); divdq_base(l, r, t1, t0); tabr[i] = r; } return l; } /* tabr[] -= taba[] * b. 0 <= b <= base - 1. Return the value to substract to the high word. */ limb_t mp_sub_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n, limb_t b) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t l, t0, t1, r, a, v, c; /* XXX: optimize */ l = 0; for(i = 0; i < n; i++) { muldq(t1, t0, taba[i], b); adddq(t1, t0, 0, l); divdq_base(l, r, t1, t0); v = tabr[i]; a = v - r; c = a > v; if (c) a += base; /* never bigger than base because r = 0 when l = base - 1 */ l += c; tabr[i] = a; } return l; } /* size of the result : op1_size + op2_size. */ void mp_mul_basecase_dec(limb_t *result, const limb_t *op1, mp_size_t op1_size, const limb_t *op2, mp_size_t op2_size) { mp_size_t i; limb_t r; result[op1_size] = mp_mul1_dec(result, op1, op1_size, op2[0], 0); for(i=1;i<op2_size;i++) { r = mp_add_mul1_dec(result + i, op1, op1_size, op2[i]); result[i + op1_size] = r; } } /* taba[] = (taba[] + r*base^na) / b. 0 <= b < base. 0 <= r < b. Return the remainder. */ limb_t mp_div1_dec(limb_t *tabr, const limb_t *taba, mp_size_t na, limb_t b, limb_t r) { limb_t base = BF_DEC_BASE; mp_size_t i; limb_t t0, t1, q; int shift; #if (BF_DEC_BASE % 2) == 0 if (b == 2) { limb_t base_div2; /* Note: only works if base is even */ base_div2 = base >> 1; if (r) r = base_div2; for(i = na - 1; i >= 0; i--) { t0 = taba[i]; tabr[i] = (t0 >> 1) + r; r = 0; if (t0 & 1) r = base_div2; } if (r) r = 1; } else #endif if (na >= UDIV1NORM_THRESHOLD) { shift = clz(b); if (shift == 0) { /* normalized case: b >= 2^(LIMB_BITS-1) */ limb_t b_inv; b_inv = udiv1norm_init(b); for(i = na - 1; i >= 0; i--) { muldq(t1, t0, r, base); adddq(t1, t0, 0, taba[i]); q = udiv1norm(&r, t1, t0, b, b_inv); tabr[i] = q; } } else { limb_t b_inv; b <<= shift; b_inv = udiv1norm_init(b); for(i = na - 1; i >= 0; i--) { muldq(t1, t0, r, base); adddq(t1, t0, 0, taba[i]); t1 = (t1 << shift) | (t0 >> (LIMB_BITS - shift)); t0 <<= shift; q = udiv1norm(&r, t1, t0, b, b_inv); r >>= shift; tabr[i] = q; } } } else { for(i = na - 1; i >= 0; i--) { muldq(t1, t0, r, base); adddq(t1, t0, 0, taba[i]); divdq(q, r, t1, t0, b); tabr[i] = q; } } return r; } static __maybe_unused void mp_print_str_dec(const char *str, const limb_t *tab, slimb_t n) { slimb_t i; printf("%s=", str); for(i = n - 1; i >= 0; i--) { if (i != n - 1) printf("_"); printf("%0*" PRIu_LIMB, LIMB_DIGITS, tab[i]); } printf("\n"); } static __maybe_unused void mp_print_str_h_dec(const char *str, const limb_t *tab, slimb_t n, limb_t high) { slimb_t i; printf("%s=", str); printf("%0*" PRIu_LIMB, LIMB_DIGITS, high); for(i = n - 1; i >= 0; i--) { printf("_"); printf("%0*" PRIu_LIMB, LIMB_DIGITS, tab[i]); } printf("\n"); } //#define DEBUG_DIV_SLOW #define DIV_STATIC_ALLOC_LEN 16 /* return q = a / b and r = a % b. taba[na] must be allocated if tabb1[nb - 1] < B / 2. tabb1[nb - 1] must be != zero. na must be >= nb. 's' can be NULL if tabb1[nb - 1] >= B / 2. The remainder is is returned in taba and contains nb libms. tabq contains na - nb + 1 limbs. No overlap is permitted. Running time of the standard method: (na - nb + 1) * nb Return 0 if OK, -1 if memory alloc error */ /* XXX: optimize */ static int mp_div_dec(bf_context_t *s, limb_t *tabq, limb_t *taba, mp_size_t na, const limb_t *tabb1, mp_size_t nb) { limb_t base = BF_DEC_BASE; limb_t r, mult, t0, t1, a, c, q, v, *tabb; mp_size_t i, j; limb_t static_tabb[DIV_STATIC_ALLOC_LEN]; #ifdef DEBUG_DIV_SLOW mp_print_str_dec("a", taba, na); mp_print_str_dec("b", tabb1, nb); #endif /* normalize tabb */ r = tabb1[nb - 1]; assert(r != 0); i = na - nb; if (r >= BF_DEC_BASE / 2) { mult = 1; tabb = (limb_t *)tabb1; q = 1; for(j = nb - 1; j >= 0; j--) { if (taba[i + j] != tabb[j]) { if (taba[i + j] < tabb[j]) q = 0; break; } } tabq[i] = q; if (q) { mp_sub_dec(taba + i, taba + i, tabb, nb, 0); } i--; } else { mult = base / (r + 1); if (likely(nb <= DIV_STATIC_ALLOC_LEN)) { tabb = static_tabb; } else { tabb = bf_malloc(s, sizeof(limb_t) * nb); if (!tabb) return -1; } mp_mul1_dec(tabb, tabb1, nb, mult, 0); taba[na] = mp_mul1_dec(taba, taba, na, mult, 0); } #ifdef DEBUG_DIV_SLOW printf("mult=" FMT_LIMB "\n", mult); mp_print_str_dec("a_norm", taba, na + 1); mp_print_str_dec("b_norm", tabb, nb); #endif for(; i >= 0; i--) { if (unlikely(taba[i + nb] >= tabb[nb - 1])) { /* XXX: check if it is really possible */ q = base - 1; } else { muldq(t1, t0, taba[i + nb], base); adddq(t1, t0, 0, taba[i + nb - 1]); divdq(q, r, t1, t0, tabb[nb - 1]); } // printf("i=%d q1=%ld\n", i, q); r = mp_sub_mul1_dec(taba + i, tabb, nb, q); // mp_dump("r1", taba + i, nb, bd); // printf("r2=%ld\n", r); v = taba[i + nb]; a = v - r; c = a > v; if (c) a += base; taba[i + nb] = a; if (c != 0) { /* negative result */ for(;;) { q--; c = mp_add_dec(taba + i, taba + i, tabb, nb, 0); /* propagate carry and test if positive result */ if (c != 0) { if (++taba[i + nb] == base) { break; } } } } tabq[i] = q; } #ifdef DEBUG_DIV_SLOW mp_print_str_dec("q", tabq, na - nb + 1); mp_print_str_dec("r", taba, nb); #endif /* remove the normalization */ if (mult != 1) { mp_div1_dec(taba, taba, nb, mult, 0); if (unlikely(tabb != static_tabb)) bf_free(s, tabb); } return 0; } /* divide by 10^shift */ static limb_t mp_shr_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, limb_t shift, limb_t high) { mp_size_t i; limb_t l, a, q, r; assert(shift >= 1 && shift < LIMB_DIGITS); l = high; for(i = n - 1; i >= 0; i--) { a = tab[i]; fast_shr_rem_dec(q, r, a, shift); tab_r[i] = q + l * mp_pow_dec[LIMB_DIGITS - shift]; l = r; } return l; } /* multiply by 10^shift */ static limb_t mp_shl_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, limb_t shift, limb_t low) { mp_size_t i; limb_t l, a, q, r; assert(shift >= 1 && shift < LIMB_DIGITS); l = low; for(i = 0; i < n; i++) { a = tab[i]; fast_shr_rem_dec(q, r, a, LIMB_DIGITS - shift); tab_r[i] = r * mp_pow_dec[shift] + l; l = q; } return l; } static limb_t mp_sqrtrem2_dec(limb_t *tabs, limb_t *taba) { int k; dlimb_t a, b, r; limb_t taba1[2], s, r0, r1; /* convert to binary and normalize */ a = (dlimb_t)taba[1] * BF_DEC_BASE + taba[0]; k = clz(a >> LIMB_BITS) & ~1; b = a << k; taba1[0] = b; taba1[1] = b >> LIMB_BITS; mp_sqrtrem2(&s, taba1); s >>= (k >> 1); /* convert the remainder back to decimal */ r = a - (dlimb_t)s * (dlimb_t)s; divdq_base(r1, r0, r >> LIMB_BITS, r); taba[0] = r0; tabs[0] = s; return r1; } //#define DEBUG_SQRTREM_DEC /* tmp_buf must contain (n / 2 + 1 limbs) */ static limb_t mp_sqrtrem_rec_dec(limb_t *tabs, limb_t *taba, limb_t n, limb_t *tmp_buf) { limb_t l, h, rh, ql, qh, c, i; if (n == 1) return mp_sqrtrem2_dec(tabs, taba); #ifdef DEBUG_SQRTREM_DEC mp_print_str_dec("a", taba, 2 * n); #endif l = n / 2; h = n - l; qh = mp_sqrtrem_rec_dec(tabs + l, taba + 2 * l, h, tmp_buf); #ifdef DEBUG_SQRTREM_DEC mp_print_str_dec("s1", tabs + l, h); mp_print_str_h_dec("r1", taba + 2 * l, h, qh); mp_print_str_h_dec("r2", taba + l, n, qh); #endif /* the remainder is in taba + 2 * l. Its high bit is in qh */ if (qh) { mp_sub_dec(taba + 2 * l, taba + 2 * l, tabs + l, h, 0); } /* instead of dividing by 2*s, divide by s (which is normalized) and update q and r */ mp_div_dec(NULL, tmp_buf, taba + l, n, tabs + l, h); qh += tmp_buf[l]; for(i = 0; i < l; i++) tabs[i] = tmp_buf[i]; ql = mp_div1_dec(tabs, tabs, l, 2, qh & 1); qh = qh >> 1; /* 0 or 1 */ if (ql) rh = mp_add_dec(taba + l, taba + l, tabs + l, h, 0); else rh = 0; #ifdef DEBUG_SQRTREM_DEC mp_print_str_h_dec("q", tabs, l, qh); mp_print_str_h_dec("u", taba + l, h, rh); #endif mp_add_ui_dec(tabs + l, qh, h); #ifdef DEBUG_SQRTREM_DEC mp_print_str_dec("s2", tabs, n); #endif /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */ /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */ if (qh) { c = qh; } else { mp_mul_basecase_dec(taba + n, tabs, l, tabs, l); c = mp_sub_dec(taba, taba, taba + n, 2 * l, 0); } rh -= mp_sub_ui_dec(taba + 2 * l, c, n - 2 * l); if ((slimb_t)rh < 0) { mp_sub_ui_dec(tabs, 1, n); rh += mp_add_mul1_dec(taba, tabs, n, 2); rh += mp_add_ui_dec(taba, 1, n); } return rh; } /* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= B/4. Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s. tabs has n limbs. r is returned in the lower n limbs of taba. Its r[n] is the returned value of the function. */ int mp_sqrtrem_dec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n) { limb_t tmp_buf1[8]; limb_t *tmp_buf; mp_size_t n2; n2 = n / 2 + 1; if (n2 <= countof(tmp_buf1)) { tmp_buf = tmp_buf1; } else { tmp_buf = bf_malloc(s, sizeof(limb_t) * n2); if (!tmp_buf) return -1; } taba[n] = mp_sqrtrem_rec_dec(tabs, taba, n, tmp_buf); if (tmp_buf != tmp_buf1) bf_free(s, tmp_buf); return 0; } /* return the number of leading zero digits, from 0 to LIMB_DIGITS */ static int clz_dec(limb_t a) { if (a == 0) return LIMB_DIGITS; switch(LIMB_BITS - 1 - clz(a)) { case 0: /* 1-1 */ return LIMB_DIGITS - 1; case 1: /* 2-3 */ return LIMB_DIGITS - 1; case 2: /* 4-7 */ return LIMB_DIGITS - 1; case 3: /* 8-15 */ if (a < 10) return LIMB_DIGITS - 1; else return LIMB_DIGITS - 2; case 4: /* 16-31 */ return LIMB_DIGITS - 2; case 5: /* 32-63 */ return LIMB_DIGITS - 2; case 6: /* 64-127 */ if (a < 100) return LIMB_DIGITS - 2; else return LIMB_DIGITS - 3; case 7: /* 128-255 */ return LIMB_DIGITS - 3; case 8: /* 256-511 */ return LIMB_DIGITS - 3; case 9: /* 512-1023 */ if (a < 1000) return LIMB_DIGITS - 3; else return LIMB_DIGITS - 4; case 10: /* 1024-2047 */ return LIMB_DIGITS - 4; case 11: /* 2048-4095 */ return LIMB_DIGITS - 4; case 12: /* 4096-8191 */ return LIMB_DIGITS - 4; case 13: /* 8192-16383 */ if (a < 10000) return LIMB_DIGITS - 4; else return LIMB_DIGITS - 5; case 14: /* 16384-32767 */ return LIMB_DIGITS - 5; case 15: /* 32768-65535 */ return LIMB_DIGITS - 5; case 16: /* 65536-131071 */ if (a < 100000) return LIMB_DIGITS - 5; else return LIMB_DIGITS - 6; case 17: /* 131072-262143 */ return LIMB_DIGITS - 6; case 18: /* 262144-524287 */ return LIMB_DIGITS - 6; case 19: /* 524288-1048575 */ if (a < 1000000) return LIMB_DIGITS - 6; else return LIMB_DIGITS - 7; case 20: /* 1048576-2097151 */ return LIMB_DIGITS - 7; case 21: /* 2097152-4194303 */ return LIMB_DIGITS - 7; case 22: /* 4194304-8388607 */ return LIMB_DIGITS - 7; case 23: /* 8388608-16777215 */ if (a < 10000000) return LIMB_DIGITS - 7; else return LIMB_DIGITS - 8; case 24: /* 16777216-33554431 */ return LIMB_DIGITS - 8; case 25: /* 33554432-67108863 */ return LIMB_DIGITS - 8; case 26: /* 67108864-134217727 */ if (a < 100000000) return LIMB_DIGITS - 8; else return LIMB_DIGITS - 9; #if LIMB_BITS == 64 case 27: /* 134217728-268435455 */ return LIMB_DIGITS - 9; case 28: /* 268435456-536870911 */ return LIMB_DIGITS - 9; case 29: /* 536870912-1073741823 */ if (a < 1000000000) return LIMB_DIGITS - 9; else return LIMB_DIGITS - 10; case 30: /* 1073741824-2147483647 */ return LIMB_DIGITS - 10; case 31: /* 2147483648-4294967295 */ return LIMB_DIGITS - 10; case 32: /* 4294967296-8589934591 */ return LIMB_DIGITS - 10; case 33: /* 8589934592-17179869183 */ if (a < 10000000000) return LIMB_DIGITS - 10; else return LIMB_DIGITS - 11; case 34: /* 17179869184-34359738367 */ return LIMB_DIGITS - 11; case 35: /* 34359738368-68719476735 */ return LIMB_DIGITS - 11; case 36: /* 68719476736-137438953471 */ if (a < 100000000000) return LIMB_DIGITS - 11; else return LIMB_DIGITS - 12; case 37: /* 137438953472-274877906943 */ return LIMB_DIGITS - 12; case 38: /* 274877906944-549755813887 */ return LIMB_DIGITS - 12; case 39: /* 549755813888-1099511627775 */ if (a < 1000000000000) return LIMB_DIGITS - 12; else return LIMB_DIGITS - 13; case 40: /* 1099511627776-2199023255551 */ return LIMB_DIGITS - 13; case 41: /* 2199023255552-4398046511103 */ return LIMB_DIGITS - 13; case 42: /* 4398046511104-8796093022207 */ return LIMB_DIGITS - 13; case 43: /* 8796093022208-17592186044415 */ if (a < 10000000000000) return LIMB_DIGITS - 13; else return LIMB_DIGITS - 14; case 44: /* 17592186044416-35184372088831 */ return LIMB_DIGITS - 14; case 45: /* 35184372088832-70368744177663 */ return LIMB_DIGITS - 14; case 46: /* 70368744177664-140737488355327 */ if (a < 100000000000000) return LIMB_DIGITS - 14; else return LIMB_DIGITS - 15; case 47: /* 140737488355328-281474976710655 */ return LIMB_DIGITS - 15; case 48: /* 281474976710656-562949953421311 */ return LIMB_DIGITS - 15; case 49: /* 562949953421312-1125899906842623 */ if (a < 1000000000000000) return LIMB_DIGITS - 15; else return LIMB_DIGITS - 16; case 50: /* 1125899906842624-2251799813685247 */ return LIMB_DIGITS - 16; case 51: /* 2251799813685248-4503599627370495 */ return LIMB_DIGITS - 16; case 52: /* 4503599627370496-9007199254740991 */ return LIMB_DIGITS - 16; case 53: /* 9007199254740992-18014398509481983 */ if (a < 10000000000000000) return LIMB_DIGITS - 16; else return LIMB_DIGITS - 17; case 54: /* 18014398509481984-36028797018963967 */ return LIMB_DIGITS - 17; case 55: /* 36028797018963968-72057594037927935 */ return LIMB_DIGITS - 17; case 56: /* 72057594037927936-144115188075855871 */ if (a < 100000000000000000) return LIMB_DIGITS - 17; else return LIMB_DIGITS - 18; case 57: /* 144115188075855872-288230376151711743 */ return LIMB_DIGITS - 18; case 58: /* 288230376151711744-576460752303423487 */ return LIMB_DIGITS - 18; case 59: /* 576460752303423488-1152921504606846975 */ if (a < 1000000000000000000) return LIMB_DIGITS - 18; else return LIMB_DIGITS - 19; #endif default: return 0; } } /* for debugging */ void bfdec_print_str(const char *str, const bfdec_t *a) { slimb_t i; printf("%s=", str); if (a->expn == BF_EXP_NAN) { printf("NaN"); } else { if (a->sign) putchar('-'); if (a->expn == BF_EXP_ZERO) { putchar('0'); } else if (a->expn == BF_EXP_INF) { printf("Inf"); } else { printf("0."); for(i = a->len - 1; i >= 0; i--) printf("%0*" PRIu_LIMB, LIMB_DIGITS, a->tab[i]); printf("e%" PRId_LIMB, a->expn); } } printf("\n"); } /* return != 0 if one digit between 0 and bit_pos inclusive is not zero. */ static inline limb_t scan_digit_nz(const bfdec_t *r, slimb_t bit_pos) { slimb_t pos; limb_t v, q; int shift; if (bit_pos < 0) return 0; pos = (limb_t)bit_pos / LIMB_DIGITS; shift = (limb_t)bit_pos % LIMB_DIGITS; fast_shr_rem_dec(q, v, r->tab[pos], shift + 1); (void)q; if (v != 0) return 1; pos--; while (pos >= 0) { if (r->tab[pos] != 0) return 1; pos--; } return 0; } static limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos) { slimb_t i; int shift; i = floor_div(pos, LIMB_DIGITS); if (i < 0 || i >= len) return 0; shift = pos - i * LIMB_DIGITS; return fast_shr_dec(tab[i], shift) % 10; } #if 0 static limb_t get_digits(const limb_t *tab, limb_t len, slimb_t pos) { limb_t a0, a1; int shift; slimb_t i; i = floor_div(pos, LIMB_DIGITS); shift = pos - i * LIMB_DIGITS; if (i >= 0 && i < len) a0 = tab[i]; else a0 = 0; if (shift == 0) { return a0; } else { i++; if (i >= 0 && i < len) a1 = tab[i]; else a1 = 0; return fast_shr_dec(a0, shift) + fast_urem(a1, &mp_pow_div[LIMB_DIGITS - shift]) * mp_pow_dec[shift]; } } #endif /* return the addend for rounding. Note that prec can be <= 0 for bf_rint() */ static int bfdec_get_rnd_add(int *pret, const bfdec_t *r, limb_t l, slimb_t prec, int rnd_mode) { int add_one, inexact; limb_t digit1, digit0; // bfdec_print_str("get_rnd_add", r); if (rnd_mode == BF_RNDF) { digit0 = 1; /* faithful rounding does not honor the INEXACT flag */ } else { /* starting limb for bit 'prec + 1' */ digit0 = scan_digit_nz(r, l * LIMB_DIGITS - 1 - bf_max(0, prec + 1)); } /* get the digit at 'prec' */ digit1 = get_digit(r->tab, l, l * LIMB_DIGITS - 1 - prec); inexact = (digit1 | digit0) != 0; add_one = 0; switch(rnd_mode) { case BF_RNDZ: break; case BF_RNDN: if (digit1 == 5) { if (digit0) { add_one = 1; } else { /* round to even */ add_one = get_digit(r->tab, l, l * LIMB_DIGITS - 1 - (prec - 1)) & 1; } } else if (digit1 > 5) { add_one = 1; } break; case BF_RNDD: case BF_RNDU: if (r->sign == (rnd_mode == BF_RNDD)) add_one = inexact; break; case BF_RNDNA: case BF_RNDF: add_one = (digit1 >= 5); break; case BF_RNDA: add_one = inexact; break; default: abort(); } if (inexact) *pret |= BF_ST_INEXACT; return add_one; } /* round to prec1 bits assuming 'r' is non zero and finite. 'r' is assumed to have length 'l' (1 <= l <= r->len). prec1 can be BF_PREC_INF. BF_FLAG_SUBNORMAL is not supported. Cannot fail with BF_ST_MEM_ERROR. */ static int __bfdec_round(bfdec_t *r, limb_t prec1, bf_flags_t flags, limb_t l) { int shift, add_one, rnd_mode, ret; slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec; /* XXX: align to IEEE 754 2008 for decimal numbers ? */ e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1); e_min = -e_range + 3; e_max = e_range; if (flags & BF_FLAG_RADPNT_PREC) { /* 'prec' is the precision after the decimal point */ if (prec1 != BF_PREC_INF) prec = r->expn + prec1; else prec = prec1; } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) { /* restrict the precision in case of potentially subnormal result */ assert(prec1 != BF_PREC_INF); prec = prec1 - (e_min - r->expn); } else { prec = prec1; } /* round to prec bits */ rnd_mode = flags & BF_RND_MASK; ret = 0; add_one = bfdec_get_rnd_add(&ret, r, l, prec, rnd_mode); if (prec <= 0) { if (add_one) { bfdec_resize(r, 1); /* cannot fail because r is non zero */ r->tab[0] = BF_DEC_BASE / 10; r->expn += 1 - prec; ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT; return ret; } else { goto underflow; } } else if (add_one) { limb_t carry; /* add one starting at digit 'prec - 1' */ bit_pos = l * LIMB_DIGITS - 1 - (prec - 1); pos = bit_pos / LIMB_DIGITS; carry = mp_pow_dec[bit_pos % LIMB_DIGITS]; carry = mp_add_ui_dec(r->tab + pos, carry, l - pos); if (carry) { /* shift right by one digit */ mp_shr_dec(r->tab + pos, r->tab + pos, l - pos, 1, 1); r->expn++; } } /* check underflow */ if (unlikely(r->expn < e_min)) { if (flags & BF_FLAG_SUBNORMAL) { /* if inexact, also set the underflow flag */ if (ret & BF_ST_INEXACT) ret |= BF_ST_UNDERFLOW; } else { underflow: bfdec_set_zero(r, r->sign); ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT; return ret; } } /* check overflow */ if (unlikely(r->expn > e_max)) { bfdec_set_inf(r, r->sign); ret |= BF_ST_OVERFLOW | BF_ST_INEXACT; return ret; } /* keep the bits starting at 'prec - 1' */ bit_pos = l * LIMB_DIGITS - 1 - (prec - 1); i = floor_div(bit_pos, LIMB_DIGITS); if (i >= 0) { shift = smod(bit_pos, LIMB_DIGITS); if (shift != 0) { r->tab[i] = fast_shr_dec(r->tab[i], shift) * mp_pow_dec[shift]; } } else { i = 0; } /* remove trailing zeros */ while (r->tab[i] == 0) i++; if (i > 0) { l -= i; memmove(r->tab, r->tab + i, l * sizeof(limb_t)); } bfdec_resize(r, l); /* cannot fail */ return ret; } /* Cannot fail with BF_ST_MEM_ERROR. */ int bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags) { if (r->len == 0) return 0; return __bfdec_round(r, prec, flags, r->len); } /* 'r' must be a finite number. Cannot fail with BF_ST_MEM_ERROR. */ int bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags) { limb_t l, v; int shift, ret; // bfdec_print_str("bf_renorm", r); l = r->len; while (l > 0 && r->tab[l - 1] == 0) l--; if (l == 0) { /* zero */ r->expn = BF_EXP_ZERO; bfdec_resize(r, 0); /* cannot fail */ ret = 0; } else { r->expn -= (r->len - l) * LIMB_DIGITS; /* shift to have the MSB set to '1' */ v = r->tab[l - 1]; shift = clz_dec(v); if (shift != 0) { mp_shl_dec(r->tab, r->tab, l, shift, 0); r->expn -= shift; } ret = __bfdec_round(r, prec1, flags, l); } // bf_print_str("r_final", r); return ret; } int bfdec_set_ui(bfdec_t *r, uint64_t v) { #if LIMB_BITS == 32 if (v >= BF_DEC_BASE * BF_DEC_BASE) { if (bfdec_resize(r, 3)) goto fail; r->tab[0] = v % BF_DEC_BASE; v /= BF_DEC_BASE; r->tab[1] = v % BF_DEC_BASE; r->tab[2] = v / BF_DEC_BASE; r->expn = 3 * LIMB_DIGITS; } else #endif if (v >= BF_DEC_BASE) { if (bfdec_resize(r, 2)) goto fail; r->tab[0] = v % BF_DEC_BASE; r->tab[1] = v / BF_DEC_BASE; r->expn = 2 * LIMB_DIGITS; } else { if (bfdec_resize(r, 1)) goto fail; r->tab[0] = v; r->expn = LIMB_DIGITS; } r->sign = 0; return bfdec_normalize_and_round(r, BF_PREC_INF, 0); fail: bfdec_set_nan(r); return BF_ST_MEM_ERROR; } int bfdec_set_si(bfdec_t *r, int64_t v) { int ret; if (v < 0) { ret = bfdec_set_ui(r, -v); r->sign = 1; } else { ret = bfdec_set_ui(r, v); } return ret; } static int bfdec_add_internal(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int b_neg) { bf_context_t *s = r->ctx; int is_sub, cmp_res, a_sign, b_sign, ret; a_sign = a->sign; b_sign = b->sign ^ b_neg; is_sub = a_sign ^ b_sign; cmp_res = bfdec_cmpu(a, b); if (cmp_res < 0) { const bfdec_t *tmp; tmp = a; a = b; b = tmp; a_sign = b_sign; /* b_sign is never used later */ } /* abs(a) >= abs(b) */ if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) { /* zero result */ bfdec_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD); ret = 0; } else if (a->len == 0 || b->len == 0) { ret = 0; if (a->expn >= BF_EXP_INF) { if (a->expn == BF_EXP_NAN) { /* at least one operand is NaN */ bfdec_set_nan(r); ret = 0; } else if (b->expn == BF_EXP_INF && is_sub) { /* infinities with different signs */ bfdec_set_nan(r); ret = BF_ST_INVALID_OP; } else { bfdec_set_inf(r, a_sign); } } else { /* at least one zero and not subtract */ if (bfdec_set(r, a)) return BF_ST_MEM_ERROR; r->sign = a_sign; goto renorm; } } else { slimb_t d, a_offset, b_offset, i, r_len; limb_t carry; limb_t *b1_tab; int b_shift; mp_size_t b1_len; d = a->expn - b->expn; /* XXX: not efficient in time and memory if the precision is not infinite */ r_len = bf_max(a->len, b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS); if (bfdec_resize(r, r_len)) goto fail; r->sign = a_sign; r->expn = a->expn; a_offset = r_len - a->len; for(i = 0; i < a_offset; i++) r->tab[i] = 0; for(i = 0; i < a->len; i++) r->tab[a_offset + i] = a->tab[i]; b_shift = d % LIMB_DIGITS; if (b_shift == 0) { b1_len = b->len; b1_tab = (limb_t *)b->tab; } else { b1_len = b->len + 1; b1_tab = bf_malloc(s, sizeof(limb_t) * b1_len); if (!b1_tab) goto fail; b1_tab[0] = mp_shr_dec(b1_tab + 1, b->tab, b->len, b_shift, 0) * mp_pow_dec[LIMB_DIGITS - b_shift]; } b_offset = r_len - (b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS); if (is_sub) { carry = mp_sub_dec(r->tab + b_offset, r->tab + b_offset, b1_tab, b1_len, 0); if (carry != 0) { carry = mp_sub_ui_dec(r->tab + b_offset + b1_len, carry, r_len - (b_offset + b1_len)); assert(carry == 0); } } else { carry = mp_add_dec(r->tab + b_offset, r->tab + b_offset, b1_tab, b1_len, 0); if (carry != 0) { carry = mp_add_ui_dec(r->tab + b_offset + b1_len, carry, r_len - (b_offset + b1_len)); } if (carry != 0) { if (bfdec_resize(r, r_len + 1)) { if (b_shift != 0) bf_free(s, b1_tab); goto fail; } r->tab[r_len] = 1; r->expn += LIMB_DIGITS; } } if (b_shift != 0) bf_free(s, b1_tab); renorm: ret = bfdec_normalize_and_round(r, prec, flags); } return ret; fail: bfdec_set_nan(r); return BF_ST_MEM_ERROR; } static int __bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { return bfdec_add_internal(r, a, b, prec, flags, 0); } static int __bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { return bfdec_add_internal(r, a, b, prec, flags, 1); } int bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags, (bf_op2_func_t *)__bfdec_add); } int bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags, (bf_op2_func_t *)__bfdec_sub); } int bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { int ret, r_sign; if (a->len < b->len) { const bfdec_t *tmp = a; a = b; b = tmp; } r_sign = a->sign ^ b->sign; /* here b->len <= a->len */ if (b->len == 0) { if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bfdec_set_nan(r); ret = 0; } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) { if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) || (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) { bfdec_set_nan(r); ret = BF_ST_INVALID_OP; } else { bfdec_set_inf(r, r_sign); ret = 0; } } else { bfdec_set_zero(r, r_sign); ret = 0; } } else { bfdec_t tmp, *r1 = NULL; limb_t a_len, b_len; limb_t *a_tab, *b_tab; a_len = a->len; b_len = b->len; a_tab = a->tab; b_tab = b->tab; if (r == a || r == b) { bfdec_init(r->ctx, &tmp); r1 = r; r = &tmp; } if (bfdec_resize(r, a_len + b_len)) { bfdec_set_nan(r); ret = BF_ST_MEM_ERROR; goto done; } mp_mul_basecase_dec(r->tab, a_tab, a_len, b_tab, b_len); r->sign = r_sign; r->expn = a->expn + b->expn; ret = bfdec_normalize_and_round(r, prec, flags); done: if (r == &tmp) bfdec_move(r1, &tmp); } return ret; } int bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec, bf_flags_t flags) { bfdec_t b; int ret; bfdec_init(r->ctx, &b); ret = bfdec_set_si(&b, b1); ret |= bfdec_mul(r, a, &b, prec, flags); bfdec_delete(&b); return ret; } int bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec, bf_flags_t flags) { bfdec_t b; int ret; bfdec_init(r->ctx, &b); ret = bfdec_set_si(&b, b1); ret |= bfdec_add(r, a, &b, prec, flags); bfdec_delete(&b); return ret; } static int __bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { int ret, r_sign; limb_t n, nb, precl; r_sign = a->sign ^ b->sign; if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) { if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bfdec_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) { bfdec_set_nan(r); return BF_ST_INVALID_OP; } else if (a->expn == BF_EXP_INF) { bfdec_set_inf(r, r_sign); return 0; } else { bfdec_set_zero(r, r_sign); return 0; } } else if (a->expn == BF_EXP_ZERO) { if (b->expn == BF_EXP_ZERO) { bfdec_set_nan(r); return BF_ST_INVALID_OP; } else { bfdec_set_zero(r, r_sign); return 0; } } else if (b->expn == BF_EXP_ZERO) { bfdec_set_inf(r, r_sign); return BF_ST_DIVIDE_ZERO; } nb = b->len; if (prec == BF_PREC_INF) { /* infinite precision: return BF_ST_INVALID_OP if not an exact result */ /* XXX: check */ precl = nb + 1; } else if (flags & BF_FLAG_RADPNT_PREC) { /* number of digits after the decimal point */ /* XXX: check (2 extra digits for rounding + 2 digits) */ precl = (bf_max(a->expn - b->expn, 0) + 2 + prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS; } else { /* number of limbs of the quotient (2 extra digits for rounding) */ precl = (prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS; } n = bf_max(a->len, precl); { limb_t *taba, na, i; slimb_t d; na = n + nb; taba = bf_malloc(r->ctx, (na + 1) * sizeof(limb_t)); if (!taba) goto fail; d = na - a->len; memset(taba, 0, d * sizeof(limb_t)); memcpy(taba + d, a->tab, a->len * sizeof(limb_t)); if (bfdec_resize(r, n + 1)) goto fail1; if (mp_div_dec(r->ctx, r->tab, taba, na, b->tab, nb)) { fail1: bf_free(r->ctx, taba); goto fail; } /* see if non zero remainder */ for(i = 0; i < nb; i++) { if (taba[i] != 0) break; } bf_free(r->ctx, taba); if (i != nb) { if (prec == BF_PREC_INF) { bfdec_set_nan(r); return BF_ST_INVALID_OP; } else { r->tab[0] |= 1; } } r->expn = a->expn - b->expn + LIMB_DIGITS; r->sign = r_sign; ret = bfdec_normalize_and_round(r, prec, flags); } return ret; fail: bfdec_set_nan(r); return BF_ST_MEM_ERROR; } int bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags) { return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags, (bf_op2_func_t *)__bfdec_div); } /* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the integer defined as floor(a/b) and r = a - q * b. */ static void bfdec_tdivremu(bf_context_t *s, bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b) { if (bfdec_cmpu(a, b) < 0) { bfdec_set_ui(q, 0); bfdec_set(r, a); } else { bfdec_div(q, a, b, 0, BF_RNDZ | BF_FLAG_RADPNT_PREC); bfdec_mul(r, q, b, BF_PREC_INF, BF_RNDZ); bfdec_sub(r, a, r, BF_PREC_INF, BF_RNDZ); } } /* division and remainder. rnd_mode is the rounding mode for the quotient. The additional rounding mode BF_RND_EUCLIDIAN is supported. 'q' is an integer. 'r' is rounded with prec and flags (prec can be BF_PREC_INF). */ int bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int rnd_mode) { bf_context_t *s = q->ctx; bfdec_t a1_s, *a1 = &a1_s; bfdec_t b1_s, *b1 = &b1_s; bfdec_t r1_s, *r1 = &r1_s; int q_sign, res; BOOL is_ceil, is_rndn; assert(q != a && q != b); assert(r != a && r != b); assert(q != r); if (a->len == 0 || b->len == 0) { bfdec_set_zero(q, 0); if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) { bfdec_set_nan(r); return 0; } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) { bfdec_set_nan(r); return BF_ST_INVALID_OP; } else { bfdec_set(r, a); return bfdec_round(r, prec, flags); } } q_sign = a->sign ^ b->sign; is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA); switch(rnd_mode) { default: case BF_RNDZ: case BF_RNDN: case BF_RNDNA: is_ceil = FALSE; break; case BF_RNDD: is_ceil = q_sign; break; case BF_RNDU: is_ceil = q_sign ^ 1; break; case BF_RNDA: is_ceil = TRUE; break; case BF_DIVREM_EUCLIDIAN: is_ceil = a->sign; break; } a1->expn = a->expn; a1->tab = a->tab; a1->len = a->len; a1->sign = 0; b1->expn = b->expn; b1->tab = b->tab; b1->len = b->len; b1->sign = 0; // bfdec_print_str("a1", a1); // bfdec_print_str("b1", b1); /* XXX: could improve to avoid having a large 'q' */ bfdec_tdivremu(s, q, r, a1, b1); if (bfdec_is_nan(q) || bfdec_is_nan(r)) goto fail; // bfdec_print_str("q", q); // bfdec_print_str("r", r); if (r->len != 0) { if (is_rndn) { bfdec_init(s, r1); if (bfdec_set(r1, r)) goto fail; if (bfdec_mul_si(r1, r1, 2, BF_PREC_INF, BF_RNDZ)) { bfdec_delete(r1); goto fail; } res = bfdec_cmpu(r1, b); bfdec_delete(r1); if (res > 0 || (res == 0 && (rnd_mode == BF_RNDNA || (get_digit(q->tab, q->len, q->len * LIMB_DIGITS - q->expn) & 1) != 0))) { goto do_sub_r; } } else if (is_ceil) { do_sub_r: res = bfdec_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ); res |= bfdec_sub(r, r, b1, BF_PREC_INF, BF_RNDZ); if (res & BF_ST_MEM_ERROR) goto fail; } } r->sign ^= a->sign; q->sign = q_sign; return bfdec_round(r, prec, flags); fail: bfdec_set_nan(q); bfdec_set_nan(r); return BF_ST_MEM_ERROR; } int bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int rnd_mode) { bfdec_t q_s, *q = &q_s; int ret; bfdec_init(r->ctx, q); ret = bfdec_divrem(q, r, a, b, prec, flags, rnd_mode); bfdec_delete(q); return ret; } /* convert to integer (infinite precision) */ int bfdec_rint(bfdec_t *r, int rnd_mode) { return bfdec_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC); } int bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags) { bf_context_t *s = a->ctx; int ret, k; limb_t *a1, v; slimb_t n, n1, prec1; limb_t res; assert(r != a); if (a->len == 0) { if (a->expn == BF_EXP_NAN) { bfdec_set_nan(r); } else if (a->expn == BF_EXP_INF && a->sign) { goto invalid_op; } else { bfdec_set(r, a); } ret = 0; } else if (a->sign || prec == BF_PREC_INF) { invalid_op: bfdec_set_nan(r); ret = BF_ST_INVALID_OP; } else { if (flags & BF_FLAG_RADPNT_PREC) { prec1 = bf_max(floor_div(a->expn + 1, 2) + prec, 1); } else { prec1 = prec; } /* convert the mantissa to an integer with at least 2 * prec + 4 digits */ n = (2 * (prec1 + 2) + 2 * LIMB_DIGITS - 1) / (2 * LIMB_DIGITS); if (bfdec_resize(r, n)) goto fail; a1 = bf_malloc(s, sizeof(limb_t) * 2 * n); if (!a1) goto fail; n1 = bf_min(2 * n, a->len); memset(a1, 0, (2 * n - n1) * sizeof(limb_t)); memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t)); if (a->expn & 1) { res = mp_shr_dec(a1, a1, 2 * n, 1, 0); } else { res = 0; } /* normalize so that a1 >= B^(2*n)/4. Not need for n = 1 because mp_sqrtrem2_dec already does it */ k = 0; if (n > 1) { v = a1[2 * n - 1]; while (v < BF_DEC_BASE / 4) { k++; v *= 4; } if (k != 0) mp_mul1_dec(a1, a1, 2 * n, 1 << (2 * k), 0); } if (mp_sqrtrem_dec(s, r->tab, a1, n)) { bf_free(s, a1); goto fail; } if (k != 0) mp_div1_dec(r->tab, r->tab, n, 1 << k, 0); if (!res) { res = mp_scan_nz(a1, n + 1); } bf_free(s, a1); if (!res) { res = mp_scan_nz(a->tab, a->len - n1); } if (res != 0) r->tab[0] |= 1; r->sign = 0; r->expn = (a->expn + 1) >> 1; ret = bfdec_round(r, prec, flags); } return ret; fail: bfdec_set_nan(r); return BF_ST_MEM_ERROR; } /* The rounding mode is always BF_RNDZ. Return BF_ST_OVERFLOW if there is an overflow and 0 otherwise. No memory error is possible. */ int bfdec_get_int32(int *pres, const bfdec_t *a) { uint32_t v; int ret; if (a->expn >= BF_EXP_INF) { ret = 0; if (a->expn == BF_EXP_INF) { v = (uint32_t)INT32_MAX + a->sign; /* XXX: return overflow ? */ } else { v = INT32_MAX; } } else if (a->expn <= 0) { v = 0; ret = 0; } else if (a->expn <= 9) { v = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn); if (a->sign) v = -v; ret = 0; } else if (a->expn == 10) { uint64_t v1; uint32_t v_max; #if LIMB_BITS == 64 v1 = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn); #else v1 = (uint64_t)a->tab[a->len - 1] * 10 + get_digit(a->tab, a->len, (a->len - 1) * LIMB_DIGITS - 1); #endif v_max = (uint32_t)INT32_MAX + a->sign; if (v1 > v_max) { v = v_max; ret = BF_ST_OVERFLOW; } else { v = v1; if (a->sign) v = -v; ret = 0; } } else { v = (uint32_t)INT32_MAX + a->sign; ret = BF_ST_OVERFLOW; } *pres = v; return ret; } /* power to an integer with infinite precision */ int bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b) { int ret, n_bits, i; assert(r != a); if (b == 0) return bfdec_set_ui(r, 1); ret = bfdec_set(r, a); n_bits = LIMB_BITS - clz(b); for(i = n_bits - 2; i >= 0; i--) { ret |= bfdec_mul(r, r, r, BF_PREC_INF, BF_RNDZ); if ((b >> i) & 1) ret |= bfdec_mul(r, r, a, BF_PREC_INF, BF_RNDZ); } return ret; } char *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags) { return bf_ftoa_internal(plen, (const bf_t *)a, 10, prec, flags, TRUE); } int bfdec_atof(bfdec_t *r, const char *str, const char **pnext, limb_t prec, bf_flags_t flags) { slimb_t dummy_exp; return bf_atof_internal((bf_t *)r, &dummy_exp, str, pnext, 10, prec, flags, TRUE); } #endif /* USE_BF_DEC */ #ifdef USE_FFT_MUL /***************************************************************/ /* Integer multiplication with FFT */ /* or LIMB_BITS at bit position 'pos' in tab */ static inline void put_bits(limb_t *tab, limb_t len, slimb_t pos, limb_t val) { limb_t i; int p; i = pos >> LIMB_LOG2_BITS; p = pos & (LIMB_BITS - 1); if (i < len) tab[i] |= val << p; if (p != 0) { i++; if (i < len) { tab[i] |= val >> (LIMB_BITS - p); } } } #if defined(__AVX2__) typedef double NTTLimb; /* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */ #define NTT_MOD_LOG2_MIN 50 #define NTT_MOD_LOG2_MAX 51 #define NB_MODS 5 #define NTT_PROOT_2EXP 39 static const int ntt_int_bits[NB_MODS] = { 254, 203, 152, 101, 50, }; static const limb_t ntt_mods[NB_MODS] = { 0x00073a8000000001, 0x0007858000000001, 0x0007a38000000001, 0x0007a68000000001, 0x0007fd8000000001, }; static const limb_t ntt_proot[2][NB_MODS] = { { 0x00056198d44332c8, 0x0002eb5d640aad39, 0x00047e31eaa35fd0, 0x0005271ac118a150, 0x00075e0ce8442bd5, }, { 0x000461169761bcc5, 0x0002dac3cb2da688, 0x0004abc97751e3bf, 0x000656778fc8c485, 0x0000dc6469c269fa, }, }; static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = { 0x00020e4da740da8e, 0x0004c3dc09c09c1d, 0x000063bd097b4271, 0x000799d8f18f18fd, 0x0005384222222264, 0x000572b07c1f07fe, 0x00035cd08888889a, 0x00066015555557e3, 0x000725960b60b623, 0x0002fc1fa1d6ce12, }; #else typedef limb_t NTTLimb; #if LIMB_BITS == 64 #define NTT_MOD_LOG2_MIN 61 #define NTT_MOD_LOG2_MAX 62 #define NB_MODS 5 #define NTT_PROOT_2EXP 51 static const int ntt_int_bits[NB_MODS] = { 307, 246, 185, 123, 61, }; static const limb_t ntt_mods[NB_MODS] = { 0x28d8000000000001, 0x2a88000000000001, 0x2ed8000000000001, 0x3508000000000001, 0x3aa8000000000001, }; static const limb_t ntt_proot[2][NB_MODS] = { { 0x1b8ea61034a2bea7, 0x21a9762de58206fb, 0x02ca782f0756a8ea, 0x278384537a3e50a1, 0x106e13fee74ce0ab, }, { 0x233513af133e13b8, 0x1d13140d1c6f75f1, 0x12cde57f97e3eeda, 0x0d6149e23cbe654f, 0x36cd204f522a1379, }, }; static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = { 0x08a9ed097b425eea, 0x18a44aaaaaaaaab3, 0x2493f57f57f57f5d, 0x126b8d0649a7f8d4, 0x09d80ed7303b5ccc, 0x25b8bcf3cf3cf3d5, 0x2ce6ce63398ce638, 0x0e31fad40a57eb59, 0x02a3529fd4a7f52f, 0x3a5493e93e93e94a, }; #elif LIMB_BITS == 32 /* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */ #define NTT_MOD_LOG2_MIN 29 #define NTT_MOD_LOG2_MAX 30 #define NB_MODS 5 #define NTT_PROOT_2EXP 20 static const int ntt_int_bits[NB_MODS] = { 148, 119, 89, 59, 29, }; static const limb_t ntt_mods[NB_MODS] = { 0x0000000032b00001, 0x0000000033700001, 0x0000000036d00001, 0x0000000037300001, 0x000000003e500001, }; static const limb_t ntt_proot[2][NB_MODS] = { { 0x0000000032525f31, 0x0000000005eb3b37, 0x00000000246eda9f, 0x0000000035f25901, 0x00000000022f5768, }, { 0x00000000051eba1a, 0x00000000107be10e, 0x000000001cd574e0, 0x00000000053806e6, 0x000000002cd6bf98, }, }; static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = { 0x000000000449559a, 0x000000001eba6ca9, 0x000000002ec18e46, 0x000000000860160b, 0x000000000d321307, 0x000000000bf51120, 0x000000000f662938, 0x000000000932ab3e, 0x000000002f40eef8, 0x000000002e760905, }; #endif /* LIMB_BITS */ #endif /* !AVX2 */ #if defined(__AVX2__) #define NTT_TRIG_K_MAX 18 #else #define NTT_TRIG_K_MAX 19 #endif typedef struct BFNTTState { bf_context_t *ctx; /* used for mul_mod_fast() */ limb_t ntt_mods_div[NB_MODS]; limb_t ntt_proot_pow[NB_MODS][2][NTT_PROOT_2EXP + 1]; limb_t ntt_proot_pow_inv[NB_MODS][2][NTT_PROOT_2EXP + 1]; NTTLimb *ntt_trig[NB_MODS][2][NTT_TRIG_K_MAX + 1]; /* 1/2^n mod m */ limb_t ntt_len_inv[NB_MODS][NTT_PROOT_2EXP + 1][2]; #if defined(__AVX2__) __m256d ntt_mods_cr_vec[NB_MODS * (NB_MODS - 1) / 2]; __m256d ntt_mods_vec[NB_MODS]; __m256d ntt_mods_inv_vec[NB_MODS]; #else limb_t ntt_mods_cr_inv[NB_MODS * (NB_MODS - 1) / 2]; #endif } BFNTTState; static NTTLimb *get_trig(BFNTTState *s, int k, int inverse, int m_idx); /* add modulo with up to (LIMB_BITS-1) bit modulo */ static inline limb_t add_mod(limb_t a, limb_t b, limb_t m) { limb_t r; r = a + b; if (r >= m) r -= m; return r; } /* sub modulo with up to LIMB_BITS bit modulo */ static inline limb_t sub_mod(limb_t a, limb_t b, limb_t m) { limb_t r; r = a - b; if (r > a) r += m; return r; } /* return (r0+r1*B) mod m precondition: 0 <= r0+r1*B < 2^(64+NTT_MOD_LOG2_MIN) */ static inline limb_t mod_fast(dlimb_t r, limb_t m, limb_t m_inv) { limb_t a1, q, t0, r1, r0; a1 = r >> NTT_MOD_LOG2_MIN; q = ((dlimb_t)a1 * m_inv) >> LIMB_BITS; r = r - (dlimb_t)q * m - m * 2; r1 = r >> LIMB_BITS; t0 = (slimb_t)r1 >> 1; r += m & t0; r0 = r; r1 = r >> LIMB_BITS; r0 += m & r1; return r0; } /* faster version using precomputed modulo inverse. precondition: 0 <= a * b < 2^(64+NTT_MOD_LOG2_MIN) */ static inline limb_t mul_mod_fast(limb_t a, limb_t b, limb_t m, limb_t m_inv) { dlimb_t r; r = (dlimb_t)a * (dlimb_t)b; return mod_fast(r, m, m_inv); } static inline limb_t init_mul_mod_fast(limb_t m) { dlimb_t t; assert(m < (limb_t)1 << NTT_MOD_LOG2_MAX); assert(m >= (limb_t)1 << NTT_MOD_LOG2_MIN); t = (dlimb_t)1 << (LIMB_BITS + NTT_MOD_LOG2_MIN); return t / m; } /* Faster version used when the multiplier is constant. 0 <= a < 2^64, 0 <= b < m. */ static inline limb_t mul_mod_fast2(limb_t a, limb_t b, limb_t m, limb_t b_inv) { limb_t r, q; q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS; r = a * b - q * m; if (r >= m) r -= m; return r; } /* Faster version used when the multiplier is constant. 0 <= a < 2^64, 0 <= b < m. Let r = a * b mod m. The return value is 'r' or 'r + m'. */ static inline limb_t mul_mod_fast3(limb_t a, limb_t b, limb_t m, limb_t b_inv) { limb_t r, q; q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS; r = a * b - q * m; return r; } static inline limb_t init_mul_mod_fast2(limb_t b, limb_t m) { return ((dlimb_t)b << LIMB_BITS) / m; } #ifdef __AVX2__ static inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m) { slimb_t v; v = a; if (v < 0) v += m; if (v >= m) v -= m; return v; } static inline NTTLimb int_to_ntt_limb(limb_t a, limb_t m) { return (slimb_t)a; } static inline NTTLimb int_to_ntt_limb2(limb_t a, limb_t m) { if (a >= (m / 2)) a -= m; return (slimb_t)a; } /* return r + m if r < 0 otherwise r. */ static inline __m256d ntt_mod1(__m256d r, __m256d m) { return _mm256_blendv_pd(r, r + m, r); } /* input: abs(r) < 2 * m. Output: abs(r) < m */ static inline __m256d ntt_mod(__m256d r, __m256d mf, __m256d m2f) { return _mm256_blendv_pd(r, r + m2f, r) - mf; } /* input: abs(a*b) < 2 * m^2, output: abs(r) < m */ static inline __m256d ntt_mul_mod(__m256d a, __m256d b, __m256d mf, __m256d m_inv) { __m256d r, q, ab1, ab0, qm0, qm1; ab1 = a * b; q = _mm256_round_pd(ab1 * m_inv, 0); /* round to nearest */ qm1 = q * mf; qm0 = _mm256_fmsub_pd(q, mf, qm1); /* low part */ ab0 = _mm256_fmsub_pd(a, b, ab1); /* low part */ r = (ab1 - qm1) + (ab0 - qm0); return r; } static void *bf_aligned_malloc(bf_context_t *s, size_t size, size_t align) { void *ptr; void **ptr1; ptr = bf_malloc(s, size + sizeof(void *) + align - 1); if (!ptr) return NULL; ptr1 = (void **)(((uintptr_t)ptr + sizeof(void *) + align - 1) & ~(align - 1)); ptr1[-1] = ptr; return ptr1; } static void bf_aligned_free(bf_context_t *s, void *ptr) { if (!ptr) return; bf_free(s, ((void **)ptr)[-1]); } static void *ntt_malloc(BFNTTState *s, size_t size) { return bf_aligned_malloc(s->ctx, size, 64); } static void ntt_free(BFNTTState *s, void *ptr) { bf_aligned_free(s->ctx, ptr); } static no_inline int ntt_fft(BFNTTState *s, NTTLimb *out_buf, NTTLimb *in_buf, NTTLimb *tmp_buf, int fft_len_log2, int inverse, int m_idx) { limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j; NTTLimb *tab_in, *tab_out, *tmp, *trig; __m256d m_inv, mf, m2f, c, a0, a1, b0, b1; limb_t m; int l; m = ntt_mods[m_idx]; m_inv = _mm256_set1_pd(1.0 / (double)m); mf = _mm256_set1_pd(m); m2f = _mm256_set1_pd(m * 2); n = (limb_t)1 << fft_len_log2; assert(n >= 8); stride_in = n / 2; tab_in = in_buf; tab_out = tmp_buf; trig = get_trig(s, fft_len_log2, inverse, m_idx); if (!trig) return -1; p = 0; for(k = 0; k < stride_in; k += 4) { a0 = _mm256_load_pd(&tab_in[k]); a1 = _mm256_load_pd(&tab_in[k + stride_in]); c = _mm256_load_pd(trig); trig += 4; b0 = ntt_mod(a0 + a1, mf, m2f); b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv); a0 = _mm256_permute2f128_pd(b0, b1, 0x20); a1 = _mm256_permute2f128_pd(b0, b1, 0x31); a0 = _mm256_permute4x64_pd(a0, 0xd8); a1 = _mm256_permute4x64_pd(a1, 0xd8); _mm256_store_pd(&tab_out[p], a0); _mm256_store_pd(&tab_out[p + 4], a1); p += 2 * 4; } tmp = tab_in; tab_in = tab_out; tab_out = tmp; trig = get_trig(s, fft_len_log2 - 1, inverse, m_idx); if (!trig) return -1; p = 0; for(k = 0; k < stride_in; k += 4) { a0 = _mm256_load_pd(&tab_in[k]); a1 = _mm256_load_pd(&tab_in[k + stride_in]); c = _mm256_setr_pd(trig[0], trig[0], trig[1], trig[1]); trig += 2; b0 = ntt_mod(a0 + a1, mf, m2f); b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv); a0 = _mm256_permute2f128_pd(b0, b1, 0x20); a1 = _mm256_permute2f128_pd(b0, b1, 0x31); _mm256_store_pd(&tab_out[p], a0); _mm256_store_pd(&tab_out[p + 4], a1); p += 2 * 4; } tmp = tab_in; tab_in = tab_out; tab_out = tmp; nb_blocks = n / 4; fft_per_block = 4; l = fft_len_log2 - 2; while (nb_blocks != 2) { nb_blocks >>= 1; p = 0; k = 0; trig = get_trig(s, l, inverse, m_idx); if (!trig) return -1; for(i = 0; i < nb_blocks; i++) { c = _mm256_set1_pd(trig[0]); trig++; for(j = 0; j < fft_per_block; j += 4) { a0 = _mm256_load_pd(&tab_in[k + j]); a1 = _mm256_load_pd(&tab_in[k + j + stride_in]); b0 = ntt_mod(a0 + a1, mf, m2f); b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv); _mm256_store_pd(&tab_out[p + j], b0); _mm256_store_pd(&tab_out[p + j + fft_per_block], b1); } k += fft_per_block; p += 2 * fft_per_block; } fft_per_block <<= 1; l--; tmp = tab_in; tab_in = tab_out; tab_out = tmp; } tab_out = out_buf; for(k = 0; k < stride_in; k += 4) { a0 = _mm256_load_pd(&tab_in[k]); a1 = _mm256_load_pd(&tab_in[k + stride_in]); b0 = ntt_mod(a0 + a1, mf, m2f); b1 = ntt_mod(a0 - a1, mf, m2f); _mm256_store_pd(&tab_out[k], b0); _mm256_store_pd(&tab_out[k + stride_in], b1); } return 0; } static void ntt_vec_mul(BFNTTState *s, NTTLimb *tab1, NTTLimb *tab2, limb_t fft_len_log2, int k_tot, int m_idx) { limb_t i, c_inv, n, m; __m256d m_inv, mf, a, b, c; m = ntt_mods[m_idx]; c_inv = s->ntt_len_inv[m_idx][k_tot][0]; m_inv = _mm256_set1_pd(1.0 / (double)m); mf = _mm256_set1_pd(m); c = _mm256_set1_pd(int_to_ntt_limb(c_inv, m)); n = (limb_t)1 << fft_len_log2; for(i = 0; i < n; i += 4) { a = _mm256_load_pd(&tab1[i]); b = _mm256_load_pd(&tab2[i]); a = ntt_mul_mod(a, b, mf, m_inv); a = ntt_mul_mod(a, c, mf, m_inv); _mm256_store_pd(&tab1[i], a); } } static no_inline void mul_trig(NTTLimb *buf, limb_t n, limb_t c1, limb_t m, limb_t m_inv1) { limb_t i, c2, c3, c4; __m256d c, c_mul, a0, mf, m_inv; assert(n >= 2); mf = _mm256_set1_pd(m); m_inv = _mm256_set1_pd(1.0 / (double)m); c2 = mul_mod_fast(c1, c1, m, m_inv1); c3 = mul_mod_fast(c2, c1, m, m_inv1); c4 = mul_mod_fast(c2, c2, m, m_inv1); c = _mm256_setr_pd(1, int_to_ntt_limb(c1, m), int_to_ntt_limb(c2, m), int_to_ntt_limb(c3, m)); c_mul = _mm256_set1_pd(int_to_ntt_limb(c4, m)); for(i = 0; i < n; i += 4) { a0 = _mm256_load_pd(&buf[i]); a0 = ntt_mul_mod(a0, c, mf, m_inv); _mm256_store_pd(&buf[i], a0); c = ntt_mul_mod(c, c_mul, mf, m_inv); } } #else static void *ntt_malloc(BFNTTState *s, size_t size) { return bf_malloc(s->ctx, size); } static void ntt_free(BFNTTState *s, void *ptr) { bf_free(s->ctx, ptr); } static inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m) { if (a >= m) a -= m; return a; } static inline NTTLimb int_to_ntt_limb(slimb_t a, limb_t m) { return a; } static no_inline int ntt_fft(BFNTTState *s, NTTLimb *out_buf, NTTLimb *in_buf, NTTLimb *tmp_buf, int fft_len_log2, int inverse, int m_idx) { limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j, m, m2; NTTLimb *tab_in, *tab_out, *tmp, a0, a1, b0, b1, c, *trig, c_inv; int l; m = ntt_mods[m_idx]; m2 = 2 * m; n = (limb_t)1 << fft_len_log2; nb_blocks = n; fft_per_block = 1; stride_in = n / 2; tab_in = in_buf; tab_out = tmp_buf; l = fft_len_log2; while (nb_blocks != 2) { nb_blocks >>= 1; p = 0; k = 0; trig = get_trig(s, l, inverse, m_idx); if (!trig) return -1; for(i = 0; i < nb_blocks; i++) { c = trig[0]; c_inv = trig[1]; trig += 2; for(j = 0; j < fft_per_block; j++) { a0 = tab_in[k + j]; a1 = tab_in[k + j + stride_in]; b0 = add_mod(a0, a1, m2); b1 = a0 - a1 + m2; b1 = mul_mod_fast3(b1, c, m, c_inv); tab_out[p + j] = b0; tab_out[p + j + fft_per_block] = b1; } k += fft_per_block; p += 2 * fft_per_block; } fft_per_block <<= 1; l--; tmp = tab_in; tab_in = tab_out; tab_out = tmp; } /* no twiddle in last step */ tab_out = out_buf; for(k = 0; k < stride_in; k++) { a0 = tab_in[k]; a1 = tab_in[k + stride_in]; b0 = add_mod(a0, a1, m2); b1 = sub_mod(a0, a1, m2); tab_out[k] = b0; tab_out[k + stride_in] = b1; } return 0; } static void ntt_vec_mul(BFNTTState *s, NTTLimb *tab1, NTTLimb *tab2, int fft_len_log2, int k_tot, int m_idx) { limb_t i, norm, norm_inv, a, n, m, m_inv; m = ntt_mods[m_idx]; m_inv = s->ntt_mods_div[m_idx]; norm = s->ntt_len_inv[m_idx][k_tot][0]; norm_inv = s->ntt_len_inv[m_idx][k_tot][1]; n = (limb_t)1 << fft_len_log2; for(i = 0; i < n; i++) { a = tab1[i]; /* need to reduce the range so that the product is < 2^(LIMB_BITS+NTT_MOD_LOG2_MIN) */ if (a >= m) a -= m; a = mul_mod_fast(a, tab2[i], m, m_inv); a = mul_mod_fast3(a, norm, m, norm_inv); tab1[i] = a; } } static no_inline void mul_trig(NTTLimb *buf, limb_t n, limb_t c_mul, limb_t m, limb_t m_inv) { limb_t i, c0, c_mul_inv; c0 = 1; c_mul_inv = init_mul_mod_fast2(c_mul, m); for(i = 0; i < n; i++) { buf[i] = mul_mod_fast(buf[i], c0, m, m_inv); c0 = mul_mod_fast2(c0, c_mul, m, c_mul_inv); } } #endif /* !AVX2 */ static no_inline NTTLimb *get_trig(BFNTTState *s, int k, int inverse, int m_idx) { NTTLimb *tab; limb_t i, n2, c, c_mul, m, c_mul_inv; if (k > NTT_TRIG_K_MAX) return NULL; tab = s->ntt_trig[m_idx][inverse][k]; if (tab) return tab; n2 = (limb_t)1 << (k - 1); m = ntt_mods[m_idx]; #ifdef __AVX2__ tab = ntt_malloc(s, sizeof(NTTLimb) * n2); #else tab = ntt_malloc(s, sizeof(NTTLimb) * n2 * 2); #endif if (!tab) return NULL; c = 1; c_mul = s->ntt_proot_pow[m_idx][inverse][k]; c_mul_inv = s->ntt_proot_pow_inv[m_idx][inverse][k]; for(i = 0; i < n2; i++) { #ifdef __AVX2__ tab[i] = int_to_ntt_limb2(c, m); #else tab[2 * i] = int_to_ntt_limb(c, m); tab[2 * i + 1] = init_mul_mod_fast2(c, m); #endif c = mul_mod_fast2(c, c_mul, m, c_mul_inv); } s->ntt_trig[m_idx][inverse][k] = tab; return tab; } void fft_clear_cache(bf_context_t *s1) { int m_idx, inverse, k; BFNTTState *s = s1->ntt_state; if (s) { for(m_idx = 0; m_idx < NB_MODS; m_idx++) { for(inverse = 0; inverse < 2; inverse++) { for(k = 0; k < NTT_TRIG_K_MAX + 1; k++) { if (s->ntt_trig[m_idx][inverse][k]) { ntt_free(s, s->ntt_trig[m_idx][inverse][k]); s->ntt_trig[m_idx][inverse][k] = NULL; } } } } #if defined(__AVX2__) bf_aligned_free(s1, s); #else bf_free(s1, s); #endif s1->ntt_state = NULL; } } #define STRIP_LEN 16 /* dst = buf1, src = buf2 */ static int ntt_fft_partial(BFNTTState *s, NTTLimb *buf1, int k1, int k2, limb_t n1, limb_t n2, int inverse, limb_t m_idx) { limb_t i, j, c_mul, c0, m, m_inv, strip_len, l; NTTLimb *buf2, *buf3; buf2 = NULL; buf3 = ntt_malloc(s, sizeof(NTTLimb) * n1); if (!buf3) goto fail; if (k2 == 0) { if (ntt_fft(s, buf1, buf1, buf3, k1, inverse, m_idx)) goto fail; } else { strip_len = STRIP_LEN; buf2 = ntt_malloc(s, sizeof(NTTLimb) * n1 * strip_len); if (!buf2) goto fail; m = ntt_mods[m_idx]; m_inv = s->ntt_mods_div[m_idx]; c0 = s->ntt_proot_pow[m_idx][inverse][k1 + k2]; c_mul = 1; assert((n2 % strip_len) == 0); for(j = 0; j < n2; j += strip_len) { for(i = 0; i < n1; i++) { for(l = 0; l < strip_len; l++) { buf2[i + l * n1] = buf1[i * n2 + (j + l)]; } } for(l = 0; l < strip_len; l++) { if (inverse) mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv); if (ntt_fft(s, buf2 + l * n1, buf2 + l * n1, buf3, k1, inverse, m_idx)) goto fail; if (!inverse) mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv); c_mul = mul_mod_fast(c_mul, c0, m, m_inv); } for(i = 0; i < n1; i++) { for(l = 0; l < strip_len; l++) { buf1[i * n2 + (j + l)] = buf2[i + l *n1]; } } } ntt_free(s, buf2); } ntt_free(s, buf3); return 0; fail: ntt_free(s, buf2); ntt_free(s, buf3); return -1; } /* dst = buf1, src = buf2, tmp = buf3 */ static int ntt_conv(BFNTTState *s, NTTLimb *buf1, NTTLimb *buf2, int k, int k_tot, limb_t m_idx) { limb_t n1, n2, i; int k1, k2; if (k <= NTT_TRIG_K_MAX) { k1 = k; } else { /* recursive split of the FFT */ k1 = bf_min(k / 2, NTT_TRIG_K_MAX); } k2 = k - k1; n1 = (limb_t)1 << k1; n2 = (limb_t)1 << k2; if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 0, m_idx)) return -1; if (ntt_fft_partial(s, buf2, k1, k2, n1, n2, 0, m_idx)) return -1; if (k2 == 0) { ntt_vec_mul(s, buf1, buf2, k, k_tot, m_idx); } else { for(i = 0; i < n1; i++) { ntt_conv(s, buf1 + i * n2, buf2 + i * n2, k2, k_tot, m_idx); } } if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 1, m_idx)) return -1; return 0; } static no_inline void limb_to_ntt(BFNTTState *s, NTTLimb *tabr, limb_t fft_len, const limb_t *taba, limb_t a_len, int dpl, int first_m_idx, int nb_mods) { slimb_t i, n; dlimb_t a, b; int j, shift; limb_t base_mask1, a0, a1, a2, r, m, m_inv; #if 0 for(i = 0; i < a_len; i++) { printf("%" PRId64 ": " FMT_LIMB "\n", (int64_t)i, taba[i]); } #endif memset(tabr, 0, sizeof(NTTLimb) * fft_len * nb_mods); shift = dpl & (LIMB_BITS - 1); if (shift == 0) base_mask1 = -1; else base_mask1 = ((limb_t)1 << shift) - 1; n = bf_min(fft_len, (a_len * LIMB_BITS + dpl - 1) / dpl); for(i = 0; i < n; i++) { a0 = get_bits(taba, a_len, i * dpl); if (dpl <= LIMB_BITS) { a0 &= base_mask1; a = a0; } else { a1 = get_bits(taba, a_len, i * dpl + LIMB_BITS); if (dpl <= (LIMB_BITS + NTT_MOD_LOG2_MIN)) { a = a0 | ((dlimb_t)(a1 & base_mask1) << LIMB_BITS); } else { if (dpl > 2 * LIMB_BITS) { a2 = get_bits(taba, a_len, i * dpl + LIMB_BITS * 2) & base_mask1; } else { a1 &= base_mask1; a2 = 0; } // printf("a=0x%016lx%016lx%016lx\n", a2, a1, a0); a = (a0 >> (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) | ((dlimb_t)a1 << (NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN)) | ((dlimb_t)a2 << (LIMB_BITS + NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN)); a0 &= ((limb_t)1 << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) - 1; } } for(j = 0; j < nb_mods; j++) { m = ntt_mods[first_m_idx + j]; m_inv = s->ntt_mods_div[first_m_idx + j]; r = mod_fast(a, m, m_inv); if (dpl > (LIMB_BITS + NTT_MOD_LOG2_MIN)) { b = ((dlimb_t)r << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) | a0; r = mod_fast(b, m, m_inv); } tabr[i + j * fft_len] = int_to_ntt_limb(r, m); } } } #if defined(__AVX2__) #define VEC_LEN 4 typedef union { __m256d v; double d[4]; } VecUnion; static no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len, const NTTLimb *buf, int fft_len_log2, int dpl, int nb_mods) { const limb_t *mods = ntt_mods + NB_MODS - nb_mods; const __m256d *mods_cr_vec, *mf, *m_inv; VecUnion y[NB_MODS]; limb_t u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r; slimb_t i, len, pos; int j, k, l, shift, n_limb1, p; dlimb_t t; j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2; mods_cr_vec = s->ntt_mods_cr_vec + j; mf = s->ntt_mods_vec + NB_MODS - nb_mods; m_inv = s->ntt_mods_inv_vec + NB_MODS - nb_mods; shift = dpl & (LIMB_BITS - 1); if (shift == 0) base_mask1 = -1; else base_mask1 = ((limb_t)1 << shift) - 1; n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS; for(j = 0; j < NB_MODS; j++) carry[j] = 0; for(j = 0; j < NB_MODS; j++) u[j] = 0; /* avoid warnings */ memset(tabr, 0, sizeof(limb_t) * r_len); fft_len = (limb_t)1 << fft_len_log2; len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl); len = (len + VEC_LEN - 1) & ~(VEC_LEN - 1); i = 0; while (i < len) { for(j = 0; j < nb_mods; j++) y[j].v = *(__m256d *)&buf[i + fft_len * j]; /* Chinese remainder to get mixed radix representation */ l = 0; for(j = 0; j < nb_mods - 1; j++) { y[j].v = ntt_mod1(y[j].v, mf[j]); for(k = j + 1; k < nb_mods; k++) { y[k].v = ntt_mul_mod(y[k].v - y[j].v, mods_cr_vec[l], mf[k], m_inv[k]); l++; } } y[j].v = ntt_mod1(y[j].v, mf[j]); for(p = 0; p < VEC_LEN; p++) { /* back to normal representation */ u[0] = (int64_t)y[nb_mods - 1].d[p]; l = 1; for(j = nb_mods - 2; j >= 1; j--) { r = (int64_t)y[j].d[p]; for(k = 0; k < l; k++) { t = (dlimb_t)u[k] * mods[j] + r; r = t >> LIMB_BITS; u[k] = t; } u[l] = r; l++; } /* XXX: for nb_mods = 5, l should be 4 */ /* last step adds the carry */ r = (int64_t)y[0].d[p]; for(k = 0; k < l; k++) { t = (dlimb_t)u[k] * mods[j] + r + carry[k]; r = t >> LIMB_BITS; u[k] = t; } u[l] = r + carry[l]; #if 0 printf("%" PRId64 ": ", i); for(j = nb_mods - 1; j >= 0; j--) { printf(" %019" PRIu64, u[j]); } printf("\n"); #endif /* write the digits */ pos = i * dpl; for(j = 0; j < n_limb1; j++) { put_bits(tabr, r_len, pos, u[j]); pos += LIMB_BITS; } put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1); /* shift by dpl digits and set the carry */ if (shift == 0) { for(j = n_limb1 + 1; j < nb_mods; j++) carry[j - (n_limb1 + 1)] = u[j]; } else { for(j = n_limb1; j < nb_mods - 1; j++) { carry[j - n_limb1] = (u[j] >> shift) | (u[j + 1] << (LIMB_BITS - shift)); } carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift; } i++; } } } #else static no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len, const NTTLimb *buf, int fft_len_log2, int dpl, int nb_mods) { const limb_t *mods = ntt_mods + NB_MODS - nb_mods; const limb_t *mods_cr, *mods_cr_inv; limb_t y[NB_MODS], u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r; slimb_t i, len, pos; int j, k, l, shift, n_limb1; dlimb_t t; j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2; mods_cr = ntt_mods_cr + j; mods_cr_inv = s->ntt_mods_cr_inv + j; shift = dpl & (LIMB_BITS - 1); if (shift == 0) base_mask1 = -1; else base_mask1 = ((limb_t)1 << shift) - 1; n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS; for(j = 0; j < NB_MODS; j++) carry[j] = 0; for(j = 0; j < NB_MODS; j++) u[j] = 0; /* avoid warnings */ memset(tabr, 0, sizeof(limb_t) * r_len); fft_len = (limb_t)1 << fft_len_log2; len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl); for(i = 0; i < len; i++) { for(j = 0; j < nb_mods; j++) { y[j] = ntt_limb_to_int(buf[i + fft_len * j], mods[j]); } /* Chinese remainder to get mixed radix representation */ l = 0; for(j = 0; j < nb_mods - 1; j++) { for(k = j + 1; k < nb_mods; k++) { limb_t m; m = mods[k]; /* Note: there is no overflow in the sub_mod() because the modulos are sorted by increasing order */ y[k] = mul_mod_fast2(y[k] - y[j] + m, mods_cr[l], m, mods_cr_inv[l]); l++; } } /* back to normal representation */ u[0] = y[nb_mods - 1]; l = 1; for(j = nb_mods - 2; j >= 1; j--) { r = y[j]; for(k = 0; k < l; k++) { t = (dlimb_t)u[k] * mods[j] + r; r = t >> LIMB_BITS; u[k] = t; } u[l] = r; l++; } /* last step adds the carry */ r = y[0]; for(k = 0; k < l; k++) { t = (dlimb_t)u[k] * mods[j] + r + carry[k]; r = t >> LIMB_BITS; u[k] = t; } u[l] = r + carry[l]; #if 0 printf("%" PRId64 ": ", (int64_t)i); for(j = nb_mods - 1; j >= 0; j--) { printf(" " FMT_LIMB, u[j]); } printf("\n"); #endif /* write the digits */ pos = i * dpl; for(j = 0; j < n_limb1; j++) { put_bits(tabr, r_len, pos, u[j]); pos += LIMB_BITS; } put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1); /* shift by dpl digits and set the carry */ if (shift == 0) { for(j = n_limb1 + 1; j < nb_mods; j++) carry[j - (n_limb1 + 1)] = u[j]; } else { for(j = n_limb1; j < nb_mods - 1; j++) { carry[j - n_limb1] = (u[j] >> shift) | (u[j + 1] << (LIMB_BITS - shift)); } carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift; } } } #endif static int ntt_static_init(bf_context_t *s1) { BFNTTState *s; int inverse, i, j, k, l; limb_t c, c_inv, c_inv2, m, m_inv; if (s1->ntt_state) return 0; #if defined(__AVX2__) s = bf_aligned_malloc(s1, sizeof(*s), 64); #else s = bf_malloc(s1, sizeof(*s)); #endif if (!s) return -1; memset(s, 0, sizeof(*s)); s1->ntt_state = s; s->ctx = s1; for(j = 0; j < NB_MODS; j++) { m = ntt_mods[j]; m_inv = init_mul_mod_fast(m); s->ntt_mods_div[j] = m_inv; #if defined(__AVX2__) s->ntt_mods_vec[j] = _mm256_set1_pd(m); s->ntt_mods_inv_vec[j] = _mm256_set1_pd(1.0 / (double)m); #endif c_inv2 = (m + 1) / 2; /* 1/2 */ c_inv = 1; for(i = 0; i <= NTT_PROOT_2EXP; i++) { s->ntt_len_inv[j][i][0] = c_inv; s->ntt_len_inv[j][i][1] = init_mul_mod_fast2(c_inv, m); c_inv = mul_mod_fast(c_inv, c_inv2, m, m_inv); } for(inverse = 0; inverse < 2; inverse++) { c = ntt_proot[inverse][j]; for(i = 0; i < NTT_PROOT_2EXP; i++) { s->ntt_proot_pow[j][inverse][NTT_PROOT_2EXP - i] = c; s->ntt_proot_pow_inv[j][inverse][NTT_PROOT_2EXP - i] = init_mul_mod_fast2(c, m); c = mul_mod_fast(c, c, m, m_inv); } } } l = 0; for(j = 0; j < NB_MODS - 1; j++) { for(k = j + 1; k < NB_MODS; k++) { #if defined(__AVX2__) s->ntt_mods_cr_vec[l] = _mm256_set1_pd(int_to_ntt_limb2(ntt_mods_cr[l], ntt_mods[k])); #else s->ntt_mods_cr_inv[l] = init_mul_mod_fast2(ntt_mods_cr[l], ntt_mods[k]); #endif l++; } } return 0; } int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len) { int dpl, fft_len_log2, n_bits, nb_mods, dpl_found, fft_len_log2_found; int int_bits, nb_mods_found; limb_t cost, min_cost; min_cost = -1; dpl_found = 0; nb_mods_found = 4; fft_len_log2_found = 0; for(nb_mods = 3; nb_mods <= NB_MODS; nb_mods++) { int_bits = ntt_int_bits[NB_MODS - nb_mods]; dpl = bf_min((int_bits - 4) / 2, 2 * LIMB_BITS + 2 * NTT_MOD_LOG2_MIN - NTT_MOD_LOG2_MAX); for(;;) { fft_len_log2 = ceil_log2((len * LIMB_BITS + dpl - 1) / dpl); if (fft_len_log2 > NTT_PROOT_2EXP) goto next; n_bits = fft_len_log2 + 2 * dpl; if (n_bits <= int_bits) { cost = ((limb_t)(fft_len_log2 + 1) << fft_len_log2) * nb_mods; // printf("n=%d dpl=%d: cost=%" PRId64 "\n", nb_mods, dpl, (int64_t)cost); if (cost < min_cost) { min_cost = cost; dpl_found = dpl; nb_mods_found = nb_mods; fft_len_log2_found = fft_len_log2; } break; } dpl--; if (dpl == 0) break; } next: ; } if (!dpl_found) abort(); /* limit dpl if possible to reduce fixed cost of limb/NTT conversion */ if (dpl_found > (LIMB_BITS + NTT_MOD_LOG2_MIN) && ((limb_t)(LIMB_BITS + NTT_MOD_LOG2_MIN) << fft_len_log2_found) >= len * LIMB_BITS) { dpl_found = LIMB_BITS + NTT_MOD_LOG2_MIN; } *pnb_mods = nb_mods_found; *pdpl = dpl_found; return fft_len_log2_found; } /* return 0 if OK, -1 if memory error */ static no_inline int fft_mul(bf_context_t *s1, bf_t *res, limb_t *a_tab, limb_t a_len, limb_t *b_tab, limb_t b_len, int mul_flags) { BFNTTState *s; int dpl, fft_len_log2, j, nb_mods, reduced_mem; slimb_t len, fft_len; NTTLimb *buf1, *buf2, *ptr; #if defined(USE_MUL_CHECK) limb_t ha, hb, hr, h_ref; #endif if (ntt_static_init(s1)) return -1; s = s1->ntt_state; /* find the optimal number of digits per limb (dpl) */ len = a_len + b_len; fft_len_log2 = bf_get_fft_size(&dpl, &nb_mods, len); fft_len = (uint64_t)1 << fft_len_log2; // printf("len=%" PRId64 " fft_len_log2=%d dpl=%d\n", len, fft_len_log2, dpl); #if defined(USE_MUL_CHECK) ha = mp_mod1(a_tab, a_len, BF_CHKSUM_MOD, 0); hb = mp_mod1(b_tab, b_len, BF_CHKSUM_MOD, 0); #endif if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == 0) { if (!(mul_flags & FFT_MUL_R_NORESIZE)) bf_resize(res, 0); } else if (mul_flags & FFT_MUL_R_OVERLAP_B) { limb_t *tmp_tab, tmp_len; /* it is better to free 'b' first */ tmp_tab = a_tab; a_tab = b_tab; b_tab = tmp_tab; tmp_len = a_len; a_len = b_len; b_len = tmp_len; } buf1 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods); if (!buf1) return -1; limb_to_ntt(s, buf1, fft_len, a_tab, a_len, dpl, NB_MODS - nb_mods, nb_mods); if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == FFT_MUL_R_OVERLAP_A) { if (!(mul_flags & FFT_MUL_R_NORESIZE)) bf_resize(res, 0); } reduced_mem = (fft_len_log2 >= 14); if (!reduced_mem) { buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods); if (!buf2) goto fail; limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl, NB_MODS - nb_mods, nb_mods); if (!(mul_flags & FFT_MUL_R_NORESIZE)) bf_resize(res, 0); /* in case res == b */ } else { buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len); if (!buf2) goto fail; } for(j = 0; j < nb_mods; j++) { if (reduced_mem) { limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl, NB_MODS - nb_mods + j, 1); ptr = buf2; } else { ptr = buf2 + fft_len * j; } if (ntt_conv(s, buf1 + fft_len * j, ptr, fft_len_log2, fft_len_log2, j + NB_MODS - nb_mods)) goto fail; } if (!(mul_flags & FFT_MUL_R_NORESIZE)) bf_resize(res, 0); /* in case res == b and reduced mem */ ntt_free(s, buf2); buf2 = NULL; if (!(mul_flags & FFT_MUL_R_NORESIZE)) { if (bf_resize(res, len)) goto fail; } ntt_to_limb(s, res->tab, len, buf1, fft_len_log2, dpl, nb_mods); ntt_free(s, buf1); #if defined(USE_MUL_CHECK) hr = mp_mod1(res->tab, len, BF_CHKSUM_MOD, 0); h_ref = mul_mod(ha, hb, BF_CHKSUM_MOD); if (hr != h_ref) { printf("ntt_mul_error: len=%" PRId_LIMB " fft_len_log2=%d dpl=%d nb_mods=%d\n", len, fft_len_log2, dpl, nb_mods); // printf("ha=0x" FMT_LIMB" hb=0x" FMT_LIMB " hr=0x" FMT_LIMB " expected=0x" FMT_LIMB "\n", ha, hb, hr, h_ref); exit(1); } #endif return 0; fail: ntt_free(s, buf1); ntt_free(s, buf2); return -1; } #else /* USE_FFT_MUL */ int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len) { return 0; } #endif /* !USE_FFT_MUL */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libbf.c
C
apache-2.0
239,756
/* * Tiny arbitrary precision floating point library * * Copyright (c) 2017-2020 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef LIBBF_H #define LIBBF_H #include <stddef.h> #include <stdint.h> #if defined(__x86_64__) #define LIMB_LOG2_BITS 6 #else #define LIMB_LOG2_BITS 5 #endif #define LIMB_BITS (1 << LIMB_LOG2_BITS) #if LIMB_BITS == 64 typedef __int128 int128_t; typedef unsigned __int128 uint128_t; typedef int64_t slimb_t; typedef uint64_t limb_t; typedef uint128_t dlimb_t; #define BF_RAW_EXP_MIN INT64_MIN #define BF_RAW_EXP_MAX INT64_MAX #define LIMB_DIGITS 19 #define BF_DEC_BASE UINT64_C(10000000000000000000) #else typedef int32_t slimb_t; typedef uint32_t limb_t; typedef uint64_t dlimb_t; #define BF_RAW_EXP_MIN INT32_MIN #define BF_RAW_EXP_MAX INT32_MAX #define LIMB_DIGITS 9 #define BF_DEC_BASE 1000000000U #endif /* in bits */ /* minimum number of bits for the exponent */ #define BF_EXP_BITS_MIN 3 /* maximum number of bits for the exponent */ #define BF_EXP_BITS_MAX (LIMB_BITS - 3) /* extended range for exponent, used internally */ #define BF_EXT_EXP_BITS_MAX (BF_EXP_BITS_MAX + 1) /* minimum possible precision */ #define BF_PREC_MIN 2 /* minimum possible precision */ #define BF_PREC_MAX (((limb_t)1 << (LIMB_BITS - 2)) - 2) /* some operations support infinite precision */ #define BF_PREC_INF (BF_PREC_MAX + 1) /* infinite precision */ #if LIMB_BITS == 64 #define BF_CHKSUM_MOD (UINT64_C(975620677) * UINT64_C(9795002197)) #else #define BF_CHKSUM_MOD 975620677U #endif #define BF_EXP_ZERO BF_RAW_EXP_MIN #define BF_EXP_INF (BF_RAW_EXP_MAX - 1) #define BF_EXP_NAN BF_RAW_EXP_MAX /* +/-zero is represented with expn = BF_EXP_ZERO and len = 0, +/-infinity is represented with expn = BF_EXP_INF and len = 0, NaN is represented with expn = BF_EXP_NAN and len = 0 (sign is ignored) */ typedef struct { struct bf_context_t *ctx; int sign; slimb_t expn; limb_t len; limb_t *tab; } bf_t; typedef struct { /* must be kept identical to bf_t */ struct bf_context_t *ctx; int sign; slimb_t expn; limb_t len; limb_t *tab; } bfdec_t; typedef enum { BF_RNDN, /* round to nearest, ties to even */ BF_RNDZ, /* round to zero */ BF_RNDD, /* round to -inf (the code relies on (BF_RNDD xor BF_RNDU) = 1) */ BF_RNDU, /* round to +inf */ BF_RNDNA, /* round to nearest, ties away from zero */ BF_RNDA, /* round away from zero */ BF_RNDF, /* faithful rounding (nondeterministic, either RNDD or RNDU, inexact flag is always set) */ } bf_rnd_t; /* allow subnormal numbers. Only available if the number of exponent bits is <= BF_EXP_BITS_USER_MAX and prec != BF_PREC_INF. */ #define BF_FLAG_SUBNORMAL (1 << 3) /* 'prec' is the precision after the radix point instead of the whole mantissa. Can only be used with bf_round() and bfdec_[add|sub|mul|div|sqrt|round](). */ #define BF_FLAG_RADPNT_PREC (1 << 4) #define BF_RND_MASK 0x7 #define BF_EXP_BITS_SHIFT 5 #define BF_EXP_BITS_MASK 0x3f /* shortcut for bf_set_exp_bits(BF_EXT_EXP_BITS_MAX) */ #define BF_FLAG_EXT_EXP (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT) /* contains the rounding mode and number of exponents bits */ typedef uint32_t bf_flags_t; typedef void *bf_realloc_func_t(void *opaque, void *ptr, size_t size); typedef struct { bf_t val; limb_t prec; } BFConstCache; typedef struct bf_context_t { void *realloc_opaque; bf_realloc_func_t *realloc_func; BFConstCache log2_cache; BFConstCache pi_cache; struct BFNTTState *ntt_state; } bf_context_t; static inline int bf_get_exp_bits(bf_flags_t flags) { int e; e = (flags >> BF_EXP_BITS_SHIFT) & BF_EXP_BITS_MASK; if (e == BF_EXP_BITS_MASK) return BF_EXP_BITS_MAX + 1; else return BF_EXP_BITS_MAX - e; } static inline bf_flags_t bf_set_exp_bits(int n) { return ((BF_EXP_BITS_MAX - n) & BF_EXP_BITS_MASK) << BF_EXP_BITS_SHIFT; } /* returned status */ #define BF_ST_INVALID_OP (1 << 0) #define BF_ST_DIVIDE_ZERO (1 << 1) #define BF_ST_OVERFLOW (1 << 2) #define BF_ST_UNDERFLOW (1 << 3) #define BF_ST_INEXACT (1 << 4) /* indicate that a memory allocation error occured. NaN is returned */ #define BF_ST_MEM_ERROR (1 << 5) #define BF_RADIX_MAX 36 /* maximum radix for bf_atof() and bf_ftoa() */ static inline slimb_t bf_max(slimb_t a, slimb_t b) { if (a > b) return a; else return b; } static inline slimb_t bf_min(slimb_t a, slimb_t b) { if (a < b) return a; else return b; } void bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func, void *realloc_opaque); void bf_context_end(bf_context_t *s); /* free memory allocated for the bf cache data */ void bf_clear_cache(bf_context_t *s); static inline void *bf_realloc(bf_context_t *s, void *ptr, size_t size) { return s->realloc_func(s->realloc_opaque, ptr, size); } /* 'size' must be != 0 */ static inline void *bf_malloc(bf_context_t *s, size_t size) { return bf_realloc(s, NULL, size); } static inline void bf_free(bf_context_t *s, void *ptr) { /* must test ptr otherwise equivalent to malloc(0) */ if (ptr) bf_realloc(s, ptr, 0); } void bf_init(bf_context_t *s, bf_t *r); static inline void bf_delete(bf_t *r) { bf_context_t *s = r->ctx; /* we accept to delete a zeroed bf_t structure */ if (s && r->tab) { bf_realloc(s, r->tab, 0); } } static inline void bf_neg(bf_t *r) { r->sign ^= 1; } static inline int bf_is_finite(const bf_t *a) { return (a->expn < BF_EXP_INF); } static inline int bf_is_nan(const bf_t *a) { return (a->expn == BF_EXP_NAN); } static inline int bf_is_zero(const bf_t *a) { return (a->expn == BF_EXP_ZERO); } static inline void bf_memcpy(bf_t *r, const bf_t *a) { *r = *a; } int bf_set_ui(bf_t *r, uint64_t a); int bf_set_si(bf_t *r, int64_t a); void bf_set_nan(bf_t *r); void bf_set_zero(bf_t *r, int is_neg); void bf_set_inf(bf_t *r, int is_neg); int bf_set(bf_t *r, const bf_t *a); void bf_move(bf_t *r, bf_t *a); int bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode); int bf_set_float64(bf_t *a, double d); int bf_cmpu(const bf_t *a, const bf_t *b); int bf_cmp_full(const bf_t *a, const bf_t *b); int bf_cmp(const bf_t *a, const bf_t *b); static inline int bf_cmp_eq(const bf_t *a, const bf_t *b) { return bf_cmp(a, b) == 0; } static inline int bf_cmp_le(const bf_t *a, const bf_t *b) { return bf_cmp(a, b) <= 0; } static inline int bf_cmp_lt(const bf_t *a, const bf_t *b) { return bf_cmp(a, b) < 0; } int bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags); int bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags); int bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags); int bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags); int bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec, bf_flags_t flags); int bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags); int bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags); int bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags); #define BF_DIVREM_EUCLIDIAN BF_RNDF int bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode); int bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode); int bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags, int rnd_mode); /* round to integer with infinite precision */ int bf_rint(bf_t *r, int rnd_mode); int bf_round(bf_t *r, limb_t prec, bf_flags_t flags); int bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a); int bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); slimb_t bf_get_exp_min(const bf_t *a); int bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b); int bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b); int bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b); /* additional flags for bf_atof */ /* do not accept hex radix prefix (0x or 0X) if radix = 0 or radix = 16 */ #define BF_ATOF_NO_HEX (1 << 16) /* accept binary (0b or 0B) or octal (0o or 0O) radix prefix if radix = 0 */ #define BF_ATOF_BIN_OCT (1 << 17) /* Do not parse NaN or Inf */ #define BF_ATOF_NO_NAN_INF (1 << 18) /* return the exponent separately */ #define BF_ATOF_EXPONENT (1 << 19) int bf_atof(bf_t *a, const char *str, const char **pnext, int radix, limb_t prec, bf_flags_t flags); /* this version accepts prec = BF_PREC_INF and returns the radix exponent */ int bf_atof2(bf_t *r, slimb_t *pexponent, const char *str, const char **pnext, int radix, limb_t prec, bf_flags_t flags); int bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix, slimb_t expn, limb_t prec, bf_flags_t flags); /* Conversion of floating point number to string. Return a null terminated string or NULL if memory error. *plen contains its length if plen != NULL. The exponent letter is "e" for base 10, "p" for bases 2, 8, 16 with a binary exponent and "@" for the other bases. */ #define BF_FTOA_FORMAT_MASK (3 << 16) /* fixed format: prec significant digits rounded with (flags & BF_RND_MASK). Exponential notation is used if too many zeros are needed.*/ #define BF_FTOA_FORMAT_FIXED (0 << 16) /* fractional format: prec digits after the decimal point rounded with (flags & BF_RND_MASK) */ #define BF_FTOA_FORMAT_FRAC (1 << 16) /* free format: For binary radices with bf_ftoa() and for bfdec_ftoa(): use the minimum number of digits to represent 'a'. The precision and the rounding mode are ignored. For the non binary radices with bf_ftoa(): use as many digits as necessary so that bf_atof() return the same number when using precision 'prec', rounding to nearest and the subnormal configuration of 'flags'. The result is meaningful only if 'a' is already rounded to 'prec' bits. If the subnormal flag is set, the exponent in 'flags' must also be set to the desired exponent range. */ #define BF_FTOA_FORMAT_FREE (2 << 16) /* same as BF_FTOA_FORMAT_FREE but uses the minimum number of digits (takes more computation time). Identical to BF_FTOA_FORMAT_FREE for binary radices with bf_ftoa() and for bfdec_ftoa(). */ #define BF_FTOA_FORMAT_FREE_MIN (3 << 16) /* force exponential notation for fixed or free format */ #define BF_FTOA_FORCE_EXP (1 << 20) /* add 0x prefix for base 16, 0o prefix for base 8 or 0b prefix for base 2 if non zero value */ #define BF_FTOA_ADD_PREFIX (1 << 21) /* return "Infinity" instead of "Inf" and add a "+" for positive exponents */ #define BF_FTOA_JS_QUIRKS (1 << 22) char *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec, bf_flags_t flags); /* modulo 2^n instead of saturation. NaN and infinity return 0 */ #define BF_GET_INT_MOD (1 << 0) int bf_get_int32(int *pres, const bf_t *a, int flags); int bf_get_int64(int64_t *pres, const bf_t *a, int flags); int bf_get_uint64(uint64_t *pres, const bf_t *a); /* the following functions are exported for testing only. */ void mp_print_str_a(const char *str, const limb_t *tab, limb_t n); void bf_print_str(const char *str, const bf_t *a); int bf_resize(bf_t *r, limb_t len); int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len); int bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags); int bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k); slimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv, int is_ceil1); int mp_mul(bf_context_t *s, limb_t *result, const limb_t *op1, limb_t op1_size, const limb_t *op2, limb_t op2_size); limb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, limb_t n, limb_t carry); limb_t mp_add_ui(limb_t *tab, limb_t b, size_t n); int mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n); int mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n); limb_t bf_isqrt(limb_t a); /* transcendental functions */ int bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags); int bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags); int bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); #define BF_POW_JS_QUIRKS (1 << 16) /* (+/-1)^(+/-Inf) = NaN, 1^NaN = NaN */ int bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags); int bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_atan2(bf_t *r, const bf_t *y, const bf_t *x, limb_t prec, bf_flags_t flags); int bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); int bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags); /* decimal floating point */ static inline void bfdec_init(bf_context_t *s, bfdec_t *r) { bf_init(s, (bf_t *)r); } static inline void bfdec_delete(bfdec_t *r) { bf_delete((bf_t *)r); } static inline void bfdec_neg(bfdec_t *r) { r->sign ^= 1; } static inline int bfdec_is_finite(const bfdec_t *a) { return (a->expn < BF_EXP_INF); } static inline int bfdec_is_nan(const bfdec_t *a) { return (a->expn == BF_EXP_NAN); } static inline int bfdec_is_zero(const bfdec_t *a) { return (a->expn == BF_EXP_ZERO); } static inline void bfdec_memcpy(bfdec_t *r, const bfdec_t *a) { bf_memcpy((bf_t *)r, (const bf_t *)a); } int bfdec_set_ui(bfdec_t *r, uint64_t a); int bfdec_set_si(bfdec_t *r, int64_t a); static inline void bfdec_set_nan(bfdec_t *r) { bf_set_nan((bf_t *)r); } static inline void bfdec_set_zero(bfdec_t *r, int is_neg) { bf_set_zero((bf_t *)r, is_neg); } static inline void bfdec_set_inf(bfdec_t *r, int is_neg) { bf_set_inf((bf_t *)r, is_neg); } static inline int bfdec_set(bfdec_t *r, const bfdec_t *a) { return bf_set((bf_t *)r, (bf_t *)a); } static inline void bfdec_move(bfdec_t *r, bfdec_t *a) { bf_move((bf_t *)r, (bf_t *)a); } static inline int bfdec_cmpu(const bfdec_t *a, const bfdec_t *b) { return bf_cmpu((const bf_t *)a, (const bf_t *)b); } static inline int bfdec_cmp_full(const bfdec_t *a, const bfdec_t *b) { return bf_cmp_full((const bf_t *)a, (const bf_t *)b); } static inline int bfdec_cmp(const bfdec_t *a, const bfdec_t *b) { return bf_cmp((const bf_t *)a, (const bf_t *)b); } static inline int bfdec_cmp_eq(const bfdec_t *a, const bfdec_t *b) { return bfdec_cmp(a, b) == 0; } static inline int bfdec_cmp_le(const bfdec_t *a, const bfdec_t *b) { return bfdec_cmp(a, b) <= 0; } static inline int bfdec_cmp_lt(const bfdec_t *a, const bfdec_t *b) { return bfdec_cmp(a, b) < 0; } int bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags); int bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags); int bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec, bf_flags_t flags); int bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags); int bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec, bf_flags_t flags); int bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags); int bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int rnd_mode); int bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int rnd_mode); int bfdec_rint(bfdec_t *r, int rnd_mode); int bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags); int bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags); int bfdec_get_int32(int *pres, const bfdec_t *a); int bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b); char *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags); int bfdec_atof(bfdec_t *r, const char *str, const char **pnext, limb_t prec, bf_flags_t flags); /* the following functions are exported for testing only. */ extern const limb_t mp_pow_dec[LIMB_DIGITS + 1]; void bfdec_print_str(const char *str, const bfdec_t *a); static inline int bfdec_resize(bfdec_t *r, limb_t len) { return bf_resize((bf_t *)r, len); } int bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags); #endif /* LIBBF_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libbf.h
C
apache-2.0
17,831
/* * Regular Expression Engine * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifdef DEF DEF(invalid, 1) /* never used */ DEF(char, 3) DEF(char32, 5) DEF(dot, 1) DEF(any, 1) /* same as dot but match any character including line terminator */ DEF(line_start, 1) DEF(line_end, 1) DEF(goto, 5) DEF(split_goto_first, 5) DEF(split_next_first, 5) DEF(match, 1) DEF(save_start, 2) /* save start position */ DEF(save_end, 2) /* save end position, must come after saved_start */ DEF(save_reset, 3) /* reset save positions */ DEF(loop, 5) /* decrement the top the stack and goto if != 0 */ DEF(push_i32, 5) /* push integer on the stack */ DEF(drop, 1) DEF(word_boundary, 1) DEF(not_word_boundary, 1) DEF(back_reference, 2) DEF(backward_back_reference, 2) /* must come after back_reference */ DEF(range, 3) /* variable length */ DEF(range32, 3) /* variable length */ DEF(lookahead, 5) DEF(negative_lookahead, 5) DEF(push_char_pos, 1) /* push the character position on the stack */ DEF(bne_char_pos, 5) /* pop one stack element and jump if equal to the character position */ DEF(prev, 1) /* go to the previous char */ DEF(simple_greedy_quant, 17) #endif /* DEF */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libregexp-opcode.h
C
apache-2.0
2,236
/* * Regular Expression Engine * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include "cutils.h" #include "libregexp.h" #if defined(_WIN32) #include <malloc.h> #endif /* TODO: - Add full unicode canonicalize rules for character ranges (not really useful but needed for exact "ignorecase" compatibility). - Add a lock step execution mode (=linear time execution guaranteed) when the regular expression is "simple" i.e. no backreference nor complicated lookahead. The opcodes are designed for this execution model. */ #if defined(TEST) #define DUMP_REOP #endif typedef enum { #define DEF(id, size) REOP_ ## id, #include "libregexp-opcode.h" #undef DEF REOP_COUNT, } REOPCodeEnum; #define CAPTURE_COUNT_MAX 255 #define STACK_SIZE_MAX 255 /* unicode code points */ #define CP_LS 0x2028 #define CP_PS 0x2029 #define TMP_BUF_SIZE 128 typedef struct { DynBuf byte_code; const uint8_t *buf_ptr; const uint8_t *buf_end; const uint8_t *buf_start; int re_flags; BOOL is_utf16; BOOL ignore_case; BOOL dotall; int capture_count; int total_capture_count; /* -1 = not computed yet */ int has_named_captures; /* -1 = don't know, 0 = no, 1 = yes */ void *mem_opaque; DynBuf group_names; union { char error_msg[TMP_BUF_SIZE]; char tmp_buf[TMP_BUF_SIZE]; } u; } REParseState; typedef struct { #ifdef DUMP_REOP const char *name; #endif uint8_t size; } REOpCode; static const REOpCode reopcode_info[REOP_COUNT] = { #ifdef DUMP_REOP #define DEF(id, size) { #id, size }, #else #define DEF(id, size) { size }, #endif #include "libregexp-opcode.h" #undef DEF }; #define RE_HEADER_FLAGS 0 #define RE_HEADER_CAPTURE_COUNT 1 #define RE_HEADER_STACK_SIZE 2 #define RE_HEADER_LEN 7 static inline int is_digit(int c) { return c >= '0' && c <= '9'; } /* insert 'len' bytes at position 'pos'. Return < 0 if error. */ static int dbuf_insert(DynBuf *s, int pos, int len) { if (dbuf_realloc(s, s->size + len)) return -1; memmove(s->buf + pos + len, s->buf + pos, s->size - pos); s->size += len; return 0; } /* canonicalize with the specific JS regexp rules */ static uint32_t lre_canonicalize(uint32_t c, BOOL is_utf16) { uint32_t res[LRE_CC_RES_LEN_MAX]; int len; if (is_utf16) { if (likely(c < 128)) { if (c >= 'A' && c <= 'Z') c = c - 'A' + 'a'; } else { lre_case_conv(res, c, 2); c = res[0]; } } else { if (likely(c < 128)) { if (c >= 'a' && c <= 'z') c = c - 'a' + 'A'; } else { /* legacy regexp: to upper case if single char >= 128 */ len = lre_case_conv(res, c, FALSE); if (len == 1 && res[0] >= 128) c = res[0]; } } return c; } static const uint16_t char_range_d[] = { 1, 0x0030, 0x0039 + 1, }; /* code point ranges for Zs,Zl or Zp property */ static const uint16_t char_range_s[] = { 10, 0x0009, 0x000D + 1, 0x0020, 0x0020 + 1, 0x00A0, 0x00A0 + 1, 0x1680, 0x1680 + 1, 0x2000, 0x200A + 1, /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */ /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */ 0x2028, 0x2029 + 1, 0x202F, 0x202F + 1, 0x205F, 0x205F + 1, 0x3000, 0x3000 + 1, /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */ 0xFEFF, 0xFEFF + 1, }; BOOL lre_is_space(int c) { int i, n, low, high; n = (countof(char_range_s) - 1) / 2; for(i = 0; i < n; i++) { low = char_range_s[2 * i + 1]; if (c < low) return FALSE; high = char_range_s[2 * i + 2]; if (c < high) return TRUE; } return FALSE; } uint32_t const lre_id_start_table_ascii[4] = { /* $ A-Z _ a-z */ 0x00000000, 0x00000010, 0x87FFFFFE, 0x07FFFFFE }; uint32_t const lre_id_continue_table_ascii[4] = { /* $ 0-9 A-Z _ a-z */ 0x00000000, 0x03FF0010, 0x87FFFFFE, 0x07FFFFFE }; static const uint16_t char_range_w[] = { 4, 0x0030, 0x0039 + 1, 0x0041, 0x005A + 1, 0x005F, 0x005F + 1, 0x0061, 0x007A + 1, }; #define CLASS_RANGE_BASE 0x40000000 typedef enum { CHAR_RANGE_d, CHAR_RANGE_D, CHAR_RANGE_s, CHAR_RANGE_S, CHAR_RANGE_w, CHAR_RANGE_W, } CharRangeEnum; static const uint16_t *char_range_table[] = { char_range_d, char_range_s, char_range_w, }; static int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c) { BOOL invert; const uint16_t *c_pt; int len, i; invert = c & 1; c_pt = char_range_table[c >> 1]; len = *c_pt++; cr_init(cr, s->mem_opaque, lre_realloc); for(i = 0; i < len * 2; i++) { if (cr_add_point(cr, c_pt[i])) goto fail; } if (invert) { if (cr_invert(cr)) goto fail; } return 0; fail: cr_free(cr); return -1; } static int cr_canonicalize(CharRange *cr) { CharRange a; uint32_t pt[2]; int i, ret; cr_init(&a, cr->mem_opaque, lre_realloc); pt[0] = 'a'; pt[1] = 'z' + 1; ret = cr_op(&a, cr->points, cr->len, pt, 2, CR_OP_INTER); if (ret) goto fail; /* convert to upper case */ /* XXX: the generic unicode case would be much more complicated and not really useful */ for(i = 0; i < a.len; i++) { a.points[i] += 'A' - 'a'; } /* Note: for simplicity we keep the lower case ranges */ ret = cr_union1(cr, a.points, a.len); fail: cr_free(&a); return ret; } #ifdef DUMP_REOP static __maybe_unused void lre_dump_bytecode(const uint8_t *buf, int buf_len) { int pos, len, opcode, bc_len, re_flags, i; uint32_t val; assert(buf_len >= RE_HEADER_LEN); re_flags= buf[0]; bc_len = get_u32(buf + 3); assert(bc_len + RE_HEADER_LEN <= buf_len); printf("flags: 0x%x capture_count=%d stack_size=%d\n", re_flags, buf[1], buf[2]); if (re_flags & LRE_FLAG_NAMED_GROUPS) { const char *p; p = (char *)buf + RE_HEADER_LEN + bc_len; printf("named groups: "); for(i = 1; i < buf[1]; i++) { if (i != 1) printf(","); printf("<%s>", p); p += strlen(p) + 1; } printf("\n"); assert(p == (char *)(buf + buf_len)); } printf("bytecode_len=%d\n", bc_len); buf += RE_HEADER_LEN; pos = 0; while (pos < bc_len) { printf("%5u: ", pos); opcode = buf[pos]; len = reopcode_info[opcode].size; if (opcode >= REOP_COUNT) { printf(" invalid opcode=0x%02x\n", opcode); break; } if ((pos + len) > bc_len) { printf(" buffer overflow (opcode=0x%02x)\n", opcode); break; } printf("%s", reopcode_info[opcode].name); switch(opcode) { case REOP_char: val = get_u16(buf + pos + 1); if (val >= ' ' && val <= 126) printf(" '%c'", val); else printf(" 0x%04x", val); break; case REOP_char32: val = get_u32(buf + pos + 1); if (val >= ' ' && val <= 126) printf(" '%c'", val); else printf(" 0x%08x", val); break; case REOP_goto: case REOP_split_goto_first: case REOP_split_next_first: case REOP_loop: case REOP_lookahead: case REOP_negative_lookahead: case REOP_bne_char_pos: val = get_u32(buf + pos + 1); val += (pos + 5); printf(" %u", val); break; case REOP_simple_greedy_quant: printf(" %u %u %u %u", get_u32(buf + pos + 1) + (pos + 17), get_u32(buf + pos + 1 + 4), get_u32(buf + pos + 1 + 8), get_u32(buf + pos + 1 + 12)); break; case REOP_save_start: case REOP_save_end: case REOP_back_reference: case REOP_backward_back_reference: printf(" %u", buf[pos + 1]); break; case REOP_save_reset: printf(" %u %u", buf[pos + 1], buf[pos + 2]); break; case REOP_push_i32: val = get_u32(buf + pos + 1); printf(" %d", val); break; case REOP_range: { int n, i; n = get_u16(buf + pos + 1); len += n * 4; for(i = 0; i < n * 2; i++) { val = get_u16(buf + pos + 3 + i * 2); printf(" 0x%04x", val); } } break; case REOP_range32: { int n, i; n = get_u16(buf + pos + 1); len += n * 8; for(i = 0; i < n * 2; i++) { val = get_u32(buf + pos + 3 + i * 4); printf(" 0x%08x", val); } } break; default: break; } printf("\n"); pos += len; } } #endif static void re_emit_op(REParseState *s, int op) { dbuf_putc(&s->byte_code, op); } /* return the offset of the u32 value */ static int re_emit_op_u32(REParseState *s, int op, uint32_t val) { int pos; dbuf_putc(&s->byte_code, op); pos = s->byte_code.size; dbuf_put_u32(&s->byte_code, val); return pos; } static int re_emit_goto(REParseState *s, int op, uint32_t val) { int pos; dbuf_putc(&s->byte_code, op); pos = s->byte_code.size; dbuf_put_u32(&s->byte_code, val - (pos + 4)); return pos; } static void re_emit_op_u8(REParseState *s, int op, uint32_t val) { dbuf_putc(&s->byte_code, op); dbuf_putc(&s->byte_code, val); } static void re_emit_op_u16(REParseState *s, int op, uint32_t val) { dbuf_putc(&s->byte_code, op); dbuf_put_u16(&s->byte_code, val); } static int __attribute__((format(printf, 2, 3))) re_parse_error(REParseState *s, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(s->u.error_msg, sizeof(s->u.error_msg), fmt, ap); va_end(ap); return -1; } static int re_parse_out_of_memory(REParseState *s) { return re_parse_error(s, "out of memory"); } /* If allow_overflow is false, return -1 in case of overflow. Otherwise return INT32_MAX. */ static int parse_digits(const uint8_t **pp, BOOL allow_overflow) { const uint8_t *p; uint64_t v; int c; p = *pp; v = 0; for(;;) { c = *p; if (c < '0' || c > '9') break; v = v * 10 + c - '0'; if (v >= INT32_MAX) { if (allow_overflow) v = INT32_MAX; else return -1; } p++; } *pp = p; return v; } static int re_parse_expect(REParseState *s, const uint8_t **pp, int c) { const uint8_t *p; p = *pp; if (*p != c) return re_parse_error(s, "expecting '%c'", c); p++; *pp = p; return 0; } /* Parse an escape sequence, *pp points after the '\': allow_utf16 value: 0 : no UTF-16 escapes allowed 1 : UTF-16 escapes allowed 2 : UTF-16 escapes allowed and escapes of surrogate pairs are converted to a unicode character (unicode regexp case). Return the unicode char and update *pp if recognized, return -1 if malformed escape, return -2 otherwise. */ int lre_parse_escape(const uint8_t **pp, int allow_utf16) { const uint8_t *p; uint32_t c; p = *pp; c = *p++; switch(c) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case 'x': case 'u': { int h, n, i; uint32_t c1; if (*p == '{' && allow_utf16) { p++; c = 0; for(;;) { h = from_hex(*p++); if (h < 0) return -1; c = (c << 4) | h; if (c > 0x10FFFF) return -1; if (*p == '}') break; } p++; } else { if (c == 'x') { n = 2; } else { n = 4; } c = 0; for(i = 0; i < n; i++) { h = from_hex(*p++); if (h < 0) { return -1; } c = (c << 4) | h; } if (c >= 0xd800 && c < 0xdc00 && allow_utf16 == 2 && p[0] == '\\' && p[1] == 'u') { /* convert an escaped surrogate pair into a unicode char */ c1 = 0; for(i = 0; i < 4; i++) { h = from_hex(p[2 + i]); if (h < 0) break; c1 = (c1 << 4) | h; } if (i == 4 && c1 >= 0xdc00 && c1 < 0xe000) { p += 6; c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000; } } } } break; case '0' ... '7': c -= '0'; if (allow_utf16 == 2) { /* only accept \0 not followed by digit */ if (c != 0 || is_digit(*p)) return -1; } else { /* parse a legacy octal sequence */ uint32_t v; v = *p - '0'; if (v > 7) break; c = (c << 3) | v; p++; if (c >= 32) break; v = *p - '0'; if (v > 7) break; c = (c << 3) | v; p++; } break; default: return -2; } *pp = p; return c; } #ifdef CONFIG_ALL_UNICODE /* XXX: we use the same chars for name and value */ static BOOL is_unicode_char(int c) { return ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_')); } static int parse_unicode_property(REParseState *s, CharRange *cr, const uint8_t **pp, BOOL is_inv) { const uint8_t *p; char name[64], value[64]; char *q; BOOL script_ext; int ret; p = *pp; if (*p != '{') return re_parse_error(s, "expecting '{' after \\p"); p++; q = name; while (is_unicode_char(*p)) { if ((q - name) > sizeof(name) - 1) goto unknown_property_name; *q++ = *p++; } *q = '\0'; q = value; if (*p == '=') { p++; while (is_unicode_char(*p)) { if ((q - value) > sizeof(value) - 1) return re_parse_error(s, "unknown unicode property value"); *q++ = *p++; } } *q = '\0'; if (*p != '}') return re_parse_error(s, "expecting '}'"); p++; // printf("name=%s value=%s\n", name, value); if (!strcmp(name, "Script") || !strcmp(name, "sc")) { script_ext = FALSE; goto do_script; } else if (!strcmp(name, "Script_Extensions") || !strcmp(name, "scx")) { script_ext = TRUE; do_script: cr_init(cr, s->mem_opaque, lre_realloc); ret = unicode_script(cr, value, script_ext); if (ret) { cr_free(cr); if (ret == -2) return re_parse_error(s, "unknown unicode script"); else goto out_of_memory; } } else if (!strcmp(name, "General_Category") || !strcmp(name, "gc")) { cr_init(cr, s->mem_opaque, lre_realloc); ret = unicode_general_category(cr, value); if (ret) { cr_free(cr); if (ret == -2) return re_parse_error(s, "unknown unicode general category"); else goto out_of_memory; } } else if (value[0] == '\0') { cr_init(cr, s->mem_opaque, lre_realloc); ret = unicode_general_category(cr, name); if (ret == -1) { cr_free(cr); goto out_of_memory; } if (ret < 0) { ret = unicode_prop(cr, name); if (ret) { cr_free(cr); if (ret == -2) goto unknown_property_name; else goto out_of_memory; } } } else { unknown_property_name: return re_parse_error(s, "unknown unicode property name"); } if (is_inv) { if (cr_invert(cr)) { cr_free(cr); return -1; } } *pp = p; return 0; out_of_memory: return re_parse_out_of_memory(s); } #endif /* CONFIG_ALL_UNICODE */ /* return -1 if error otherwise the character or a class range (CLASS_RANGE_BASE). In case of class range, 'cr' is initialized. Otherwise, it is ignored. */ static int get_class_atom(REParseState *s, CharRange *cr, const uint8_t **pp, BOOL inclass) { const uint8_t *p; uint32_t c; int ret; p = *pp; c = *p; switch(c) { case '\\': p++; if (p >= s->buf_end) goto unexpected_end; c = *p++; switch(c) { case 'd': c = CHAR_RANGE_d; goto class_range; case 'D': c = CHAR_RANGE_D; goto class_range; case 's': c = CHAR_RANGE_s; goto class_range; case 'S': c = CHAR_RANGE_S; goto class_range; case 'w': c = CHAR_RANGE_w; goto class_range; case 'W': c = CHAR_RANGE_W; class_range: if (cr_init_char_range(s, cr, c)) return -1; c = CLASS_RANGE_BASE; break; case 'c': c = *p; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (((c >= '0' && c <= '9') || c == '_') && inclass && !s->is_utf16)) { /* Annex B.1.4 */ c &= 0x1f; p++; } else if (s->is_utf16) { goto invalid_escape; } else { /* otherwise return '\' and 'c' */ p--; c = '\\'; } break; #ifdef CONFIG_ALL_UNICODE case 'p': case 'P': if (s->is_utf16) { if (parse_unicode_property(s, cr, &p, (c == 'P'))) return -1; c = CLASS_RANGE_BASE; break; } /* fall thru */ #endif default: p--; ret = lre_parse_escape(&p, s->is_utf16 * 2); if (ret >= 0) { c = ret; } else { if (ret == -2 && *p != '\0' && strchr("^$\\.*+?()[]{}|/", *p)) { /* always valid to escape these characters */ goto normal_char; } else if (s->is_utf16) { invalid_escape: return re_parse_error(s, "invalid escape sequence in regular expression"); } else { /* just ignore the '\' */ goto normal_char; } } break; } break; case '\0': if (p >= s->buf_end) { unexpected_end: return re_parse_error(s, "unexpected end"); } /* fall thru */ default: normal_char: /* normal char */ if (c >= 128) { c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p); if ((unsigned)c > 0xffff && !s->is_utf16) { /* XXX: should handle non BMP-1 code points */ return re_parse_error(s, "malformed unicode char"); } } else { p++; } break; } *pp = p; return c; } static int re_emit_range(REParseState *s, const CharRange *cr) { int len, i; uint32_t high; len = (unsigned)cr->len / 2; if (len >= 65535) return re_parse_error(s, "too many ranges"); if (len == 0) { /* not sure it can really happen. Emit a match that is always false */ re_emit_op_u32(s, REOP_char32, -1); } else { high = cr->points[cr->len - 1]; if (high == UINT32_MAX) high = cr->points[cr->len - 2]; if (high <= 0xffff) { /* can use 16 bit ranges with the conversion that 0xffff = infinity */ re_emit_op_u16(s, REOP_range, len); for(i = 0; i < cr->len; i += 2) { dbuf_put_u16(&s->byte_code, cr->points[i]); high = cr->points[i + 1] - 1; if (high == UINT32_MAX - 1) high = 0xffff; dbuf_put_u16(&s->byte_code, high); } } else { re_emit_op_u16(s, REOP_range32, len); for(i = 0; i < cr->len; i += 2) { dbuf_put_u32(&s->byte_code, cr->points[i]); dbuf_put_u32(&s->byte_code, cr->points[i + 1] - 1); } } } return 0; } static int re_parse_char_class(REParseState *s, const uint8_t **pp) { const uint8_t *p; uint32_t c1, c2; CharRange cr_s, *cr = &cr_s; CharRange cr1_s, *cr1 = &cr1_s; BOOL invert; cr_init(cr, s->mem_opaque, lre_realloc); p = *pp; p++; /* skip '[' */ invert = FALSE; if (*p == '^') { p++; invert = TRUE; } for(;;) { if (*p == ']') break; c1 = get_class_atom(s, cr1, &p, TRUE); if ((int)c1 < 0) goto fail; if (*p == '-' && p[1] != ']') { const uint8_t *p0 = p + 1; if (c1 >= CLASS_RANGE_BASE) { if (s->is_utf16) { cr_free(cr1); goto invalid_class_range; } /* Annex B: match '-' character */ goto class_atom; } c2 = get_class_atom(s, cr1, &p0, TRUE); if ((int)c2 < 0) goto fail; if (c2 >= CLASS_RANGE_BASE) { cr_free(cr1); if (s->is_utf16) { goto invalid_class_range; } /* Annex B: match '-' character */ goto class_atom; } p = p0; if (c2 < c1) { invalid_class_range: re_parse_error(s, "invalid class range"); goto fail; } if (cr_union_interval(cr, c1, c2)) goto memory_error; } else { class_atom: if (c1 >= CLASS_RANGE_BASE) { int ret; ret = cr_union1(cr, cr1->points, cr1->len); cr_free(cr1); if (ret) goto memory_error; } else { if (cr_union_interval(cr, c1, c1)) goto memory_error; } } } if (s->ignore_case) { if (cr_canonicalize(cr)) goto memory_error; } if (invert) { if (cr_invert(cr)) goto memory_error; } if (re_emit_range(s, cr)) goto fail; cr_free(cr); p++; /* skip ']' */ *pp = p; return 0; memory_error: re_parse_out_of_memory(s); fail: cr_free(cr); return -1; } /* Return: 1 if the opcodes in bc_buf[] always advance the character pointer. 0 if the character pointer may not be advanced. -1 if the code may depend on side effects of its previous execution (backreference) */ static int re_check_advance(const uint8_t *bc_buf, int bc_buf_len) { int pos, opcode, ret, len, i; uint32_t val, last; BOOL has_back_reference; uint8_t capture_bitmap[CAPTURE_COUNT_MAX]; ret = -2; /* not known yet */ pos = 0; has_back_reference = FALSE; memset(capture_bitmap, 0, sizeof(capture_bitmap)); while (pos < bc_buf_len) { opcode = bc_buf[pos]; len = reopcode_info[opcode].size; switch(opcode) { case REOP_range: val = get_u16(bc_buf + pos + 1); len += val * 4; goto simple_char; case REOP_range32: val = get_u16(bc_buf + pos + 1); len += val * 8; goto simple_char; case REOP_char: case REOP_char32: case REOP_dot: case REOP_any: simple_char: if (ret == -2) ret = 1; break; case REOP_line_start: case REOP_line_end: case REOP_push_i32: case REOP_push_char_pos: case REOP_drop: case REOP_word_boundary: case REOP_not_word_boundary: case REOP_prev: /* no effect */ break; case REOP_save_start: case REOP_save_end: val = bc_buf[pos + 1]; capture_bitmap[val] |= 1; break; case REOP_save_reset: { val = bc_buf[pos + 1]; last = bc_buf[pos + 2]; while (val < last) capture_bitmap[val++] |= 1; } break; case REOP_back_reference: case REOP_backward_back_reference: val = bc_buf[pos + 1]; capture_bitmap[val] |= 2; has_back_reference = TRUE; break; default: /* safe behvior: we cannot predict the outcome */ if (ret == -2) ret = 0; break; } pos += len; } if (has_back_reference) { /* check if there is back reference which references a capture made in the some code */ for(i = 0; i < CAPTURE_COUNT_MAX; i++) { if (capture_bitmap[i] == 3) return -1; } } if (ret == -2) ret = 0; return ret; } /* return -1 if a simple quantifier cannot be used. Otherwise return the number of characters in the atom. */ static int re_is_simple_quantifier(const uint8_t *bc_buf, int bc_buf_len) { int pos, opcode, len, count; uint32_t val; count = 0; pos = 0; while (pos < bc_buf_len) { opcode = bc_buf[pos]; len = reopcode_info[opcode].size; switch(opcode) { case REOP_range: val = get_u16(bc_buf + pos + 1); len += val * 4; goto simple_char; case REOP_range32: val = get_u16(bc_buf + pos + 1); len += val * 8; goto simple_char; case REOP_char: case REOP_char32: case REOP_dot: case REOP_any: simple_char: count++; break; case REOP_line_start: case REOP_line_end: case REOP_word_boundary: case REOP_not_word_boundary: break; default: return -1; } pos += len; } return count; } /* '*pp' is the first char after '<' */ static int re_parse_group_name(char *buf, int buf_size, const uint8_t **pp, BOOL is_utf16) { const uint8_t *p; uint32_t c; char *q; p = *pp; q = buf; for(;;) { c = *p; if (c == '\\') { p++; if (*p != 'u') return -1; c = lre_parse_escape(&p, is_utf16 * 2); } else if (c == '>') { break; } else if (c >= 128) { c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p); } else { p++; } if (c > 0x10FFFF) return -1; if (q == buf) { if (!lre_js_is_ident_first(c)) return -1; } else { if (!lre_js_is_ident_next(c)) return -1; } if ((q - buf + UTF8_CHAR_LEN_MAX + 1) > buf_size) return -1; if (c < 128) { *q++ = c; } else { q += unicode_to_utf8((uint8_t*)q, c); } } if (q == buf) return -1; *q = '\0'; p++; *pp = p; return 0; } /* if capture_name = NULL: return the number of captures + 1. Otherwise, return the capture index corresponding to capture_name or -1 if none */ static int re_parse_captures(REParseState *s, int *phas_named_captures, const char *capture_name) { const uint8_t *p; int capture_index; char name[TMP_BUF_SIZE]; capture_index = 1; *phas_named_captures = 0; for (p = s->buf_start; p < s->buf_end; p++) { switch (*p) { case '(': if (p[1] == '?') { if (p[2] == '<' && p[3] != '=' && p[3] != '!') { *phas_named_captures = 1; /* potential named capture */ if (capture_name) { p += 3; if (re_parse_group_name(name, sizeof(name), &p, s->is_utf16) == 0) { if (!strcmp(name, capture_name)) return capture_index; } } capture_index++; } } else { capture_index++; } break; case '\\': p++; break; case '[': for (p += 1 + (*p == ']'); p < s->buf_end && *p != ']'; p++) { if (*p == '\\') p++; } break; } } if (capture_name) return -1; else return capture_index; } static int re_count_captures(REParseState *s) { if (s->total_capture_count < 0) { s->total_capture_count = re_parse_captures(s, &s->has_named_captures, NULL); } return s->total_capture_count; } static BOOL re_has_named_captures(REParseState *s) { if (s->has_named_captures < 0) re_count_captures(s); return s->has_named_captures; } static int find_group_name(REParseState *s, const char *name) { const char *p, *buf_end; size_t len, name_len; int capture_index; name_len = strlen(name); p = (char *)s->group_names.buf; buf_end = (char *)s->group_names.buf + s->group_names.size; capture_index = 1; while (p < buf_end) { len = strlen(p); if (len == name_len && memcmp(name, p, name_len) == 0) return capture_index; p += len + 1; capture_index++; } return -1; } static int re_parse_disjunction(REParseState *s, BOOL is_backward_dir); static int re_parse_term(REParseState *s, BOOL is_backward_dir) { const uint8_t *p; int c, last_atom_start, quant_min, quant_max, last_capture_count; BOOL greedy, add_zero_advance_check, is_neg, is_backward_lookahead; CharRange cr_s, *cr = &cr_s; last_atom_start = -1; last_capture_count = 0; p = s->buf_ptr; c = *p; switch(c) { case '^': p++; re_emit_op(s, REOP_line_start); break; case '$': p++; re_emit_op(s, REOP_line_end); break; case '.': p++; last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; if (is_backward_dir) re_emit_op(s, REOP_prev); re_emit_op(s, s->dotall ? REOP_any : REOP_dot); if (is_backward_dir) re_emit_op(s, REOP_prev); break; case '{': if (s->is_utf16) { return re_parse_error(s, "syntax error"); } else if (!is_digit(p[1])) { /* Annex B: we accept '{' not followed by digits as a normal atom */ goto parse_class_atom; } else { const uint8_t *p1 = p + 1; /* Annex B: error if it is like a repetition count */ parse_digits(&p1, TRUE); if (*p1 == ',') { p1++; if (is_digit(*p1)) { parse_digits(&p1, TRUE); } } if (*p1 != '}') { goto parse_class_atom; } } /* fall thru */ case '*': case '+': case '?': return re_parse_error(s, "nothing to repeat"); case '(': if (p[1] == '?') { if (p[2] == ':') { p += 3; last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; s->buf_ptr = p; if (re_parse_disjunction(s, is_backward_dir)) return -1; p = s->buf_ptr; if (re_parse_expect(s, &p, ')')) return -1; } else if ((p[2] == '=' || p[2] == '!')) { is_neg = (p[2] == '!'); is_backward_lookahead = FALSE; p += 3; goto lookahead; } else if (p[2] == '<' && (p[3] == '=' || p[3] == '!')) { int pos; is_neg = (p[3] == '!'); is_backward_lookahead = TRUE; p += 4; /* lookahead */ lookahead: /* Annex B allows lookahead to be used as an atom for the quantifiers */ if (!s->is_utf16 && !is_backward_lookahead) { last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; } pos = re_emit_op_u32(s, REOP_lookahead + is_neg, 0); s->buf_ptr = p; if (re_parse_disjunction(s, is_backward_lookahead)) return -1; p = s->buf_ptr; if (re_parse_expect(s, &p, ')')) return -1; re_emit_op(s, REOP_match); /* jump after the 'match' after the lookahead is successful */ if (dbuf_error(&s->byte_code)) return -1; put_u32(s->byte_code.buf + pos, s->byte_code.size - (pos + 4)); } else if (p[2] == '<') { p += 3; if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf), &p, s->is_utf16)) { return re_parse_error(s, "invalid group name"); } if (find_group_name(s, s->u.tmp_buf) > 0) { return re_parse_error(s, "duplicate group name"); } /* group name with a trailing zero */ dbuf_put(&s->group_names, (uint8_t *)s->u.tmp_buf, strlen(s->u.tmp_buf) + 1); s->has_named_captures = 1; goto parse_capture; } else { return re_parse_error(s, "invalid group"); } } else { int capture_index; p++; /* capture without group name */ dbuf_putc(&s->group_names, 0); parse_capture: if (s->capture_count >= CAPTURE_COUNT_MAX) return re_parse_error(s, "too many captures"); last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; capture_index = s->capture_count++; re_emit_op_u8(s, REOP_save_start + is_backward_dir, capture_index); s->buf_ptr = p; if (re_parse_disjunction(s, is_backward_dir)) return -1; p = s->buf_ptr; re_emit_op_u8(s, REOP_save_start + 1 - is_backward_dir, capture_index); if (re_parse_expect(s, &p, ')')) return -1; } break; case '\\': switch(p[1]) { case 'b': case 'B': re_emit_op(s, REOP_word_boundary + (p[1] != 'b')); p += 2; break; case 'k': { const uint8_t *p1; int dummy_res; p1 = p; if (p1[2] != '<') { /* annex B: we tolerate invalid group names in non unicode mode if there is no named capture definition */ if (s->is_utf16 || re_has_named_captures(s)) return re_parse_error(s, "expecting group name"); else goto parse_class_atom; } p1 += 3; if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf), &p1, s->is_utf16)) { if (s->is_utf16 || re_has_named_captures(s)) return re_parse_error(s, "invalid group name"); else goto parse_class_atom; } c = find_group_name(s, s->u.tmp_buf); if (c < 0) { /* no capture name parsed before, try to look after (inefficient, but hopefully not common */ c = re_parse_captures(s, &dummy_res, s->u.tmp_buf); if (c < 0) { if (s->is_utf16 || re_has_named_captures(s)) return re_parse_error(s, "group name not defined"); else goto parse_class_atom; } } p = p1; } goto emit_back_reference; case '0': p += 2; c = 0; if (s->is_utf16) { if (is_digit(*p)) { return re_parse_error(s, "invalid decimal escape in regular expression"); } } else { /* Annex B.1.4: accept legacy octal */ if (*p >= '0' && *p <= '7') { c = *p++ - '0'; if (*p >= '0' && *p <= '7') { c = (c << 3) + *p++ - '0'; } } } goto normal_char; case '1' ... '9': { const uint8_t *q = ++p; c = parse_digits(&p, FALSE); if (c < 0 || (c >= s->capture_count && c >= re_count_captures(s))) { if (!s->is_utf16) { /* Annex B.1.4: accept legacy octal */ p = q; if (*p <= '7') { c = 0; if (*p <= '3') c = *p++ - '0'; if (*p >= '0' && *p <= '7') { c = (c << 3) + *p++ - '0'; if (*p >= '0' && *p <= '7') { c = (c << 3) + *p++ - '0'; } } } else { c = *p++; } goto normal_char; } return re_parse_error(s, "back reference out of range in reguar expression"); } emit_back_reference: last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; re_emit_op_u8(s, REOP_back_reference + is_backward_dir, c); } break; default: goto parse_class_atom; } break; case '[': last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; if (is_backward_dir) re_emit_op(s, REOP_prev); if (re_parse_char_class(s, &p)) return -1; if (is_backward_dir) re_emit_op(s, REOP_prev); break; case ']': case '}': if (s->is_utf16) return re_parse_error(s, "syntax error"); goto parse_class_atom; default: parse_class_atom: c = get_class_atom(s, cr, &p, FALSE); if ((int)c < 0) return -1; normal_char: last_atom_start = s->byte_code.size; last_capture_count = s->capture_count; if (is_backward_dir) re_emit_op(s, REOP_prev); if (c >= CLASS_RANGE_BASE) { int ret; /* Note: canonicalization is not needed */ ret = re_emit_range(s, cr); cr_free(cr); if (ret) return -1; } else { if (s->ignore_case) c = lre_canonicalize(c, s->is_utf16); if (c <= 0xffff) re_emit_op_u16(s, REOP_char, c); else re_emit_op_u32(s, REOP_char32, c); } if (is_backward_dir) re_emit_op(s, REOP_prev); break; } /* quantifier */ if (last_atom_start >= 0) { c = *p; switch(c) { case '*': p++; quant_min = 0; quant_max = INT32_MAX; goto quantifier; case '+': p++; quant_min = 1; quant_max = INT32_MAX; goto quantifier; case '?': p++; quant_min = 0; quant_max = 1; goto quantifier; case '{': { const uint8_t *p1 = p; /* As an extension (see ES6 annex B), we accept '{' not followed by digits as a normal atom */ if (!is_digit(p[1])) { if (s->is_utf16) goto invalid_quant_count; break; } p++; quant_min = parse_digits(&p, TRUE); quant_max = quant_min; if (*p == ',') { p++; if (is_digit(*p)) { quant_max = parse_digits(&p, TRUE); if (quant_max < quant_min) { invalid_quant_count: return re_parse_error(s, "invalid repetition count"); } } else { quant_max = INT32_MAX; /* infinity */ } } if (*p != '}' && !s->is_utf16) { /* Annex B: normal atom if invalid '{' syntax */ p = p1; break; } if (re_parse_expect(s, &p, '}')) return -1; } quantifier: greedy = TRUE; if (*p == '?') { p++; greedy = FALSE; } if (last_atom_start < 0) { return re_parse_error(s, "nothing to repeat"); } if (greedy) { int len, pos; if (quant_max > 0) { /* specific optimization for simple quantifiers */ if (dbuf_error(&s->byte_code)) goto out_of_memory; len = re_is_simple_quantifier(s->byte_code.buf + last_atom_start, s->byte_code.size - last_atom_start); if (len > 0) { re_emit_op(s, REOP_match); if (dbuf_insert(&s->byte_code, last_atom_start, 17)) goto out_of_memory; pos = last_atom_start; s->byte_code.buf[pos++] = REOP_simple_greedy_quant; put_u32(&s->byte_code.buf[pos], s->byte_code.size - last_atom_start - 17); pos += 4; put_u32(&s->byte_code.buf[pos], quant_min); pos += 4; put_u32(&s->byte_code.buf[pos], quant_max); pos += 4; put_u32(&s->byte_code.buf[pos], len); pos += 4; goto done; } } if (dbuf_error(&s->byte_code)) goto out_of_memory; add_zero_advance_check = (re_check_advance(s->byte_code.buf + last_atom_start, s->byte_code.size - last_atom_start) == 0); } else { add_zero_advance_check = FALSE; } { int len, pos; len = s->byte_code.size - last_atom_start; if (quant_min == 0) { /* need to reset the capture in case the atom is not executed */ if (last_capture_count != s->capture_count) { if (dbuf_insert(&s->byte_code, last_atom_start, 3)) goto out_of_memory; s->byte_code.buf[last_atom_start++] = REOP_save_reset; s->byte_code.buf[last_atom_start++] = last_capture_count; s->byte_code.buf[last_atom_start++] = s->capture_count - 1; } if (quant_max == 0) { s->byte_code.size = last_atom_start; } else if (quant_max == 1) { if (dbuf_insert(&s->byte_code, last_atom_start, 5)) goto out_of_memory; s->byte_code.buf[last_atom_start] = REOP_split_goto_first + greedy; put_u32(s->byte_code.buf + last_atom_start + 1, len); } else if (quant_max == INT32_MAX) { if (dbuf_insert(&s->byte_code, last_atom_start, 5 + add_zero_advance_check)) goto out_of_memory; s->byte_code.buf[last_atom_start] = REOP_split_goto_first + greedy; put_u32(s->byte_code.buf + last_atom_start + 1, len + 5 + add_zero_advance_check); if (add_zero_advance_check) { /* avoid infinite loop by stoping the recursion if no advance was made in the atom (only works if the atom has no side effect) */ s->byte_code.buf[last_atom_start + 1 + 4] = REOP_push_char_pos; re_emit_goto(s, REOP_bne_char_pos, last_atom_start); } else { re_emit_goto(s, REOP_goto, last_atom_start); } } else { if (dbuf_insert(&s->byte_code, last_atom_start, 10)) goto out_of_memory; pos = last_atom_start; s->byte_code.buf[pos++] = REOP_push_i32; put_u32(s->byte_code.buf + pos, quant_max); pos += 4; s->byte_code.buf[pos++] = REOP_split_goto_first + greedy; put_u32(s->byte_code.buf + pos, len + 5); re_emit_goto(s, REOP_loop, last_atom_start + 5); re_emit_op(s, REOP_drop); } } else if (quant_min == 1 && quant_max == INT32_MAX && !add_zero_advance_check) { re_emit_goto(s, REOP_split_next_first - greedy, last_atom_start); } else { if (quant_min == 1) { /* nothing to add */ } else { if (dbuf_insert(&s->byte_code, last_atom_start, 5)) goto out_of_memory; s->byte_code.buf[last_atom_start] = REOP_push_i32; put_u32(s->byte_code.buf + last_atom_start + 1, quant_min); last_atom_start += 5; re_emit_goto(s, REOP_loop, last_atom_start); re_emit_op(s, REOP_drop); } if (quant_max == INT32_MAX) { pos = s->byte_code.size; re_emit_op_u32(s, REOP_split_goto_first + greedy, len + 5 + add_zero_advance_check); if (add_zero_advance_check) re_emit_op(s, REOP_push_char_pos); /* copy the atom */ dbuf_put_self(&s->byte_code, last_atom_start, len); if (add_zero_advance_check) re_emit_goto(s, REOP_bne_char_pos, pos); else re_emit_goto(s, REOP_goto, pos); } else if (quant_max > quant_min) { re_emit_op_u32(s, REOP_push_i32, quant_max - quant_min); pos = s->byte_code.size; re_emit_op_u32(s, REOP_split_goto_first + greedy, len + 5); /* copy the atom */ dbuf_put_self(&s->byte_code, last_atom_start, len); re_emit_goto(s, REOP_loop, pos); re_emit_op(s, REOP_drop); } } last_atom_start = -1; } break; default: break; } } done: s->buf_ptr = p; return 0; out_of_memory: return re_parse_out_of_memory(s); } static int re_parse_alternative(REParseState *s, BOOL is_backward_dir) { const uint8_t *p; int ret; size_t start, term_start, end, term_size; start = s->byte_code.size; for(;;) { p = s->buf_ptr; if (p >= s->buf_end) break; if (*p == '|' || *p == ')') break; term_start = s->byte_code.size; ret = re_parse_term(s, is_backward_dir); if (ret) return ret; if (is_backward_dir) { /* reverse the order of the terms (XXX: inefficient, but speed is not really critical here) */ end = s->byte_code.size; term_size = end - term_start; if (dbuf_realloc(&s->byte_code, end + term_size)) return -1; memmove(s->byte_code.buf + start + term_size, s->byte_code.buf + start, end - start); memcpy(s->byte_code.buf + start, s->byte_code.buf + end, term_size); } } return 0; } static int re_parse_disjunction(REParseState *s, BOOL is_backward_dir) { int start, len, pos; start = s->byte_code.size; if (re_parse_alternative(s, is_backward_dir)) return -1; while (*s->buf_ptr == '|') { s->buf_ptr++; len = s->byte_code.size - start; /* insert a split before the first alternative */ if (dbuf_insert(&s->byte_code, start, 5)) { return re_parse_out_of_memory(s); } s->byte_code.buf[start] = REOP_split_next_first; put_u32(s->byte_code.buf + start + 1, len + 5); pos = re_emit_op_u32(s, REOP_goto, 0); if (re_parse_alternative(s, is_backward_dir)) return -1; /* patch the goto */ len = s->byte_code.size - (pos + 4); put_u32(s->byte_code.buf + pos, len); } return 0; } /* the control flow is recursive so the analysis can be linear */ static int compute_stack_size(const uint8_t *bc_buf, int bc_buf_len) { int stack_size, stack_size_max, pos, opcode, len; uint32_t val; stack_size = 0; stack_size_max = 0; bc_buf += RE_HEADER_LEN; bc_buf_len -= RE_HEADER_LEN; pos = 0; while (pos < bc_buf_len) { opcode = bc_buf[pos]; len = reopcode_info[opcode].size; assert(opcode < REOP_COUNT); assert((pos + len) <= bc_buf_len); switch(opcode) { case REOP_push_i32: case REOP_push_char_pos: stack_size++; if (stack_size > stack_size_max) { if (stack_size > STACK_SIZE_MAX) return -1; stack_size_max = stack_size; } break; case REOP_drop: case REOP_bne_char_pos: assert(stack_size > 0); stack_size--; break; case REOP_range: val = get_u16(bc_buf + pos + 1); len += val * 4; break; case REOP_range32: val = get_u16(bc_buf + pos + 1); len += val * 8; break; } pos += len; } return stack_size_max; } /* 'buf' must be a zero terminated UTF-8 string of length buf_len. Return NULL if error and allocate an error message in *perror_msg, otherwise the compiled bytecode and its length in plen. */ uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size, const char *buf, size_t buf_len, int re_flags, void *opaque) { REParseState s_s, *s = &s_s; int stack_size; BOOL is_sticky; memset(s, 0, sizeof(*s)); s->mem_opaque = opaque; s->buf_ptr = (const uint8_t *)buf; s->buf_end = s->buf_ptr + buf_len; s->buf_start = s->buf_ptr; s->re_flags = re_flags; s->is_utf16 = ((re_flags & LRE_FLAG_UTF16) != 0); is_sticky = ((re_flags & LRE_FLAG_STICKY) != 0); s->ignore_case = ((re_flags & LRE_FLAG_IGNORECASE) != 0); s->dotall = ((re_flags & LRE_FLAG_DOTALL) != 0); s->capture_count = 1; s->total_capture_count = -1; s->has_named_captures = -1; dbuf_init2(&s->byte_code, opaque, lre_realloc); dbuf_init2(&s->group_names, opaque, lre_realloc); dbuf_putc(&s->byte_code, re_flags); /* first element is the flags */ dbuf_putc(&s->byte_code, 0); /* second element is the number of captures */ dbuf_putc(&s->byte_code, 0); /* stack size */ dbuf_put_u32(&s->byte_code, 0); /* bytecode length */ if (!is_sticky) { /* iterate thru all positions (about the same as .*?( ... ) ) . We do it without an explicit loop so that lock step thread execution will be possible in an optimized implementation */ re_emit_op_u32(s, REOP_split_goto_first, 1 + 5); re_emit_op(s, REOP_any); re_emit_op_u32(s, REOP_goto, -(5 + 1 + 5)); } re_emit_op_u8(s, REOP_save_start, 0); if (re_parse_disjunction(s, FALSE)) { error: dbuf_free(&s->byte_code); dbuf_free(&s->group_names); pstrcpy(error_msg, error_msg_size, s->u.error_msg); *plen = 0; return NULL; } re_emit_op_u8(s, REOP_save_end, 0); re_emit_op(s, REOP_match); if (*s->buf_ptr != '\0') { re_parse_error(s, "extraneous characters at the end"); goto error; } if (dbuf_error(&s->byte_code)) { re_parse_out_of_memory(s); goto error; } stack_size = compute_stack_size(s->byte_code.buf, s->byte_code.size); if (stack_size < 0) { re_parse_error(s, "too many imbricated quantifiers"); goto error; } s->byte_code.buf[RE_HEADER_CAPTURE_COUNT] = s->capture_count; s->byte_code.buf[RE_HEADER_STACK_SIZE] = stack_size; put_u32(s->byte_code.buf + 3, s->byte_code.size - RE_HEADER_LEN); /* add the named groups if needed */ if (s->group_names.size > (s->capture_count - 1)) { dbuf_put(&s->byte_code, s->group_names.buf, s->group_names.size); s->byte_code.buf[RE_HEADER_FLAGS] |= LRE_FLAG_NAMED_GROUPS; } dbuf_free(&s->group_names); #ifdef DUMP_REOP lre_dump_bytecode(s->byte_code.buf, s->byte_code.size); #endif error_msg[0] = '\0'; *plen = s->byte_code.size; return s->byte_code.buf; } static BOOL is_line_terminator(uint32_t c) { return (c == '\n' || c == '\r' || c == CP_LS || c == CP_PS); } static BOOL is_word_char(uint32_t c) { return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_')); } #define GET_CHAR(c, cptr, cbuf_end) \ do { \ if (cbuf_type == 0) { \ c = *cptr++; \ } else { \ uint32_t __c1; \ c = *(uint16_t *)cptr; \ cptr += 2; \ if (c >= 0xd800 && c < 0xdc00 && \ cbuf_type == 2 && cptr < cbuf_end) { \ __c1 = *(uint16_t *)cptr; \ if (__c1 >= 0xdc00 && __c1 < 0xe000) { \ c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \ cptr += 2; \ } \ } \ } \ } while (0) #define PEEK_CHAR(c, cptr, cbuf_end) \ do { \ if (cbuf_type == 0) { \ c = cptr[0]; \ } else { \ uint32_t __c1; \ c = ((uint16_t *)cptr)[0]; \ if (c >= 0xd800 && c < 0xdc00 && \ cbuf_type == 2 && (cptr + 2) < cbuf_end) { \ __c1 = ((uint16_t *)cptr)[1]; \ if (__c1 >= 0xdc00 && __c1 < 0xe000) { \ c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \ } \ } \ } \ } while (0) #define PEEK_PREV_CHAR(c, cptr, cbuf_start) \ do { \ if (cbuf_type == 0) { \ c = cptr[-1]; \ } else { \ uint32_t __c1; \ c = ((uint16_t *)cptr)[-1]; \ if (c >= 0xdc00 && c < 0xe000 && \ cbuf_type == 2 && (cptr - 4) >= cbuf_start) { \ __c1 = ((uint16_t *)cptr)[-2]; \ if (__c1 >= 0xd800 && __c1 < 0xdc00 ) { \ c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \ } \ } \ } \ } while (0) #define GET_PREV_CHAR(c, cptr, cbuf_start) \ do { \ if (cbuf_type == 0) { \ cptr--; \ c = cptr[0]; \ } else { \ uint32_t __c1; \ cptr -= 2; \ c = ((uint16_t *)cptr)[0]; \ if (c >= 0xdc00 && c < 0xe000 && \ cbuf_type == 2 && cptr > cbuf_start) { \ __c1 = ((uint16_t *)cptr)[-1]; \ if (__c1 >= 0xd800 && __c1 < 0xdc00 ) { \ cptr -= 2; \ c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \ } \ } \ } \ } while (0) #define PREV_CHAR(cptr, cbuf_start) \ do { \ if (cbuf_type == 0) { \ cptr--; \ } else { \ cptr -= 2; \ if (cbuf_type == 2) { \ c = ((uint16_t *)cptr)[0]; \ if (c >= 0xdc00 && c < 0xe000 && cptr > cbuf_start) { \ c = ((uint16_t *)cptr)[-1]; \ if (c >= 0xd800 && c < 0xdc00) \ cptr -= 2; \ } \ } \ } \ } while (0) typedef uintptr_t StackInt; typedef enum { RE_EXEC_STATE_SPLIT, RE_EXEC_STATE_LOOKAHEAD, RE_EXEC_STATE_NEGATIVE_LOOKAHEAD, RE_EXEC_STATE_GREEDY_QUANT, } REExecStateEnum; typedef struct REExecState { REExecStateEnum type : 8; uint8_t stack_len; size_t count; /* only used for RE_EXEC_STATE_GREEDY_QUANT */ const uint8_t *cptr; const uint8_t *pc; void *buf[0]; } REExecState; typedef struct { const uint8_t *cbuf; const uint8_t *cbuf_end; /* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */ int cbuf_type; int capture_count; int stack_size_max; BOOL multi_line; BOOL ignore_case; BOOL is_utf16; void *opaque; /* used for stack overflow check */ size_t state_size; uint8_t *state_stack; size_t state_stack_size; size_t state_stack_len; } REExecContext; static int push_state(REExecContext *s, uint8_t **capture, StackInt *stack, size_t stack_len, const uint8_t *pc, const uint8_t *cptr, REExecStateEnum type, size_t count) { REExecState *rs; uint8_t *new_stack; size_t new_size, i, n; StackInt *stack_buf; if (unlikely((s->state_stack_len + 1) > s->state_stack_size)) { /* reallocate the stack */ new_size = s->state_stack_size * 3 / 2; if (new_size < 8) new_size = 8; new_stack = lre_realloc(s->opaque, s->state_stack, new_size * s->state_size); if (!new_stack) return -1; s->state_stack_size = new_size; s->state_stack = new_stack; } rs = (REExecState *)(s->state_stack + s->state_stack_len * s->state_size); s->state_stack_len++; rs->type = type; rs->count = count; rs->stack_len = stack_len; rs->cptr = cptr; rs->pc = pc; n = 2 * s->capture_count; for(i = 0; i < n; i++) rs->buf[i] = capture[i]; stack_buf = (StackInt *)(rs->buf + n); for(i = 0; i < stack_len; i++) stack_buf[i] = stack[i]; return 0; } /* return 1 if match, 0 if not match or -1 if error. */ static intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture, StackInt *stack, int stack_len, const uint8_t *pc, const uint8_t *cptr, BOOL no_recurse) { int opcode, ret; int cbuf_type; uint32_t val, c; const uint8_t *cbuf_end; cbuf_type = s->cbuf_type; cbuf_end = s->cbuf_end; for(;;) { // printf("top=%p: pc=%d\n", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN))); opcode = *pc++; switch(opcode) { case REOP_match: { REExecState *rs; if (no_recurse) return (intptr_t)cptr; ret = 1; goto recurse; no_match: if (no_recurse) return 0; ret = 0; recurse: for(;;) { if (s->state_stack_len == 0) return ret; rs = (REExecState *)(s->state_stack + (s->state_stack_len - 1) * s->state_size); if (rs->type == RE_EXEC_STATE_SPLIT) { if (!ret) { pop_state: memcpy(capture, rs->buf, sizeof(capture[0]) * 2 * s->capture_count); pop_state1: pc = rs->pc; cptr = rs->cptr; stack_len = rs->stack_len; memcpy(stack, rs->buf + 2 * s->capture_count, stack_len * sizeof(stack[0])); s->state_stack_len--; break; } } else if (rs->type == RE_EXEC_STATE_GREEDY_QUANT) { if (!ret) { uint32_t char_count, i; memcpy(capture, rs->buf, sizeof(capture[0]) * 2 * s->capture_count); stack_len = rs->stack_len; memcpy(stack, rs->buf + 2 * s->capture_count, stack_len * sizeof(stack[0])); pc = rs->pc; cptr = rs->cptr; /* go backward */ char_count = get_u32(pc + 12); for(i = 0; i < char_count; i++) { PREV_CHAR(cptr, s->cbuf); } pc = (pc + 16) + (int)get_u32(pc); rs->cptr = cptr; rs->count--; if (rs->count == 0) { s->state_stack_len--; } break; } } else { ret = ((rs->type == RE_EXEC_STATE_LOOKAHEAD && ret) || (rs->type == RE_EXEC_STATE_NEGATIVE_LOOKAHEAD && !ret)); if (ret) { /* keep the capture in case of positive lookahead */ if (rs->type == RE_EXEC_STATE_LOOKAHEAD) goto pop_state1; else goto pop_state; } } s->state_stack_len--; } } break; case REOP_char32: val = get_u32(pc); pc += 4; goto test_char; case REOP_char: val = get_u16(pc); pc += 2; test_char: if (cptr >= cbuf_end) goto no_match; GET_CHAR(c, cptr, cbuf_end); if (s->ignore_case) { c = lre_canonicalize(c, s->is_utf16); } if (val != c) goto no_match; break; case REOP_split_goto_first: case REOP_split_next_first: { const uint8_t *pc1; val = get_u32(pc); pc += 4; if (opcode == REOP_split_next_first) { pc1 = pc + (int)val; } else { pc1 = pc; pc = pc + (int)val; } ret = push_state(s, capture, stack, stack_len, pc1, cptr, RE_EXEC_STATE_SPLIT, 0); if (ret < 0) return -1; break; } case REOP_lookahead: case REOP_negative_lookahead: val = get_u32(pc); pc += 4; ret = push_state(s, capture, stack, stack_len, pc + (int)val, cptr, RE_EXEC_STATE_LOOKAHEAD + opcode - REOP_lookahead, 0); if (ret < 0) return -1; break; case REOP_goto: val = get_u32(pc); pc += 4 + (int)val; break; case REOP_line_start: if (cptr == s->cbuf) break; if (!s->multi_line) goto no_match; PEEK_PREV_CHAR(c, cptr, s->cbuf); if (!is_line_terminator(c)) goto no_match; break; case REOP_line_end: if (cptr == cbuf_end) break; if (!s->multi_line) goto no_match; PEEK_CHAR(c, cptr, cbuf_end); if (!is_line_terminator(c)) goto no_match; break; case REOP_dot: if (cptr == cbuf_end) goto no_match; GET_CHAR(c, cptr, cbuf_end); if (is_line_terminator(c)) goto no_match; break; case REOP_any: if (cptr == cbuf_end) goto no_match; GET_CHAR(c, cptr, cbuf_end); break; case REOP_save_start: case REOP_save_end: val = *pc++; assert(val < s->capture_count); capture[2 * val + opcode - REOP_save_start] = (uint8_t *)cptr; break; case REOP_save_reset: { uint32_t val2; val = pc[0]; val2 = pc[1]; pc += 2; assert(val2 < s->capture_count); while (val <= val2) { capture[2 * val] = NULL; capture[2 * val + 1] = NULL; val++; } } break; case REOP_push_i32: val = get_u32(pc); pc += 4; stack[stack_len++] = val; break; case REOP_drop: stack_len--; break; case REOP_loop: val = get_u32(pc); pc += 4; if (--stack[stack_len - 1] != 0) { pc += (int)val; } break; case REOP_push_char_pos: stack[stack_len++] = (uintptr_t)cptr; break; case REOP_bne_char_pos: val = get_u32(pc); pc += 4; if (stack[--stack_len] != (uintptr_t)cptr) pc += (int)val; break; case REOP_word_boundary: case REOP_not_word_boundary: { BOOL v1, v2; /* char before */ if (cptr == s->cbuf) { v1 = FALSE; } else { PEEK_PREV_CHAR(c, cptr, s->cbuf); v1 = is_word_char(c); } /* current char */ if (cptr >= cbuf_end) { v2 = FALSE; } else { PEEK_CHAR(c, cptr, cbuf_end); v2 = is_word_char(c); } if (v1 ^ v2 ^ (REOP_not_word_boundary - opcode)) goto no_match; } break; case REOP_back_reference: case REOP_backward_back_reference: { const uint8_t *cptr1, *cptr1_end, *cptr1_start; uint32_t c1, c2; val = *pc++; if (val >= s->capture_count) goto no_match; cptr1_start = capture[2 * val]; cptr1_end = capture[2 * val + 1]; if (!cptr1_start || !cptr1_end) break; if (opcode == REOP_back_reference) { cptr1 = cptr1_start; while (cptr1 < cptr1_end) { if (cptr >= cbuf_end) goto no_match; GET_CHAR(c1, cptr1, cptr1_end); GET_CHAR(c2, cptr, cbuf_end); if (s->ignore_case) { c1 = lre_canonicalize(c1, s->is_utf16); c2 = lre_canonicalize(c2, s->is_utf16); } if (c1 != c2) goto no_match; } } else { cptr1 = cptr1_end; while (cptr1 > cptr1_start) { if (cptr == s->cbuf) goto no_match; GET_PREV_CHAR(c1, cptr1, cptr1_start); GET_PREV_CHAR(c2, cptr, s->cbuf); if (s->ignore_case) { c1 = lre_canonicalize(c1, s->is_utf16); c2 = lre_canonicalize(c2, s->is_utf16); } if (c1 != c2) goto no_match; } } } break; case REOP_range: { int n; uint32_t low, high, idx_min, idx_max, idx; n = get_u16(pc); /* n must be >= 1 */ pc += 2; if (cptr >= cbuf_end) goto no_match; GET_CHAR(c, cptr, cbuf_end); if (s->ignore_case) { c = lre_canonicalize(c, s->is_utf16); } idx_min = 0; low = get_u16(pc + 0 * 4); if (c < low) goto no_match; idx_max = n - 1; high = get_u16(pc + idx_max * 4 + 2); /* 0xffff in for last value means +infinity */ if (unlikely(c >= 0xffff) && high == 0xffff) goto range_match; if (c > high) goto no_match; while (idx_min <= idx_max) { idx = (idx_min + idx_max) / 2; low = get_u16(pc + idx * 4); high = get_u16(pc + idx * 4 + 2); if (c < low) idx_max = idx - 1; else if (c > high) idx_min = idx + 1; else goto range_match; } goto no_match; range_match: pc += 4 * n; } break; case REOP_range32: { int n; uint32_t low, high, idx_min, idx_max, idx; n = get_u16(pc); /* n must be >= 1 */ pc += 2; if (cptr >= cbuf_end) goto no_match; GET_CHAR(c, cptr, cbuf_end); if (s->ignore_case) { c = lre_canonicalize(c, s->is_utf16); } idx_min = 0; low = get_u32(pc + 0 * 8); if (c < low) goto no_match; idx_max = n - 1; high = get_u32(pc + idx_max * 8 + 4); if (c > high) goto no_match; while (idx_min <= idx_max) { idx = (idx_min + idx_max) / 2; low = get_u32(pc + idx * 8); high = get_u32(pc + idx * 8 + 4); if (c < low) idx_max = idx - 1; else if (c > high) idx_min = idx + 1; else goto range32_match; } goto no_match; range32_match: pc += 8 * n; } break; case REOP_prev: /* go to the previous char */ if (cptr == s->cbuf) goto no_match; PREV_CHAR(cptr, s->cbuf); break; case REOP_simple_greedy_quant: { uint32_t next_pos, quant_min, quant_max; size_t q; intptr_t res; const uint8_t *pc1; next_pos = get_u32(pc); quant_min = get_u32(pc + 4); quant_max = get_u32(pc + 8); pc += 16; pc1 = pc; pc += (int)next_pos; q = 0; for(;;) { res = lre_exec_backtrack(s, capture, stack, stack_len, pc1, cptr, TRUE); if (res == -1) return res; if (!res) break; cptr = (uint8_t *)res; q++; if (q >= quant_max && quant_max != INT32_MAX) break; } if (q < quant_min) goto no_match; if (q > quant_min) { /* will examine all matches down to quant_min */ ret = push_state(s, capture, stack, stack_len, pc1 - 16, cptr, RE_EXEC_STATE_GREEDY_QUANT, q - quant_min); if (ret < 0) return -1; } } break; default: abort(); } } } /* Return 1 if match, 0 if not match or -1 if error. cindex is the starting position of the match and must be such as 0 <= cindex <= clen. */ int lre_exec(uint8_t **capture, const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen, int cbuf_type, void *opaque) { REExecContext s_s, *s = &s_s; int re_flags, i, alloca_size, ret; StackInt *stack_buf; re_flags = bc_buf[RE_HEADER_FLAGS]; s->multi_line = (re_flags & LRE_FLAG_MULTILINE) != 0; s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0; s->is_utf16 = (re_flags & LRE_FLAG_UTF16) != 0; s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT]; s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE]; s->cbuf = cbuf; s->cbuf_end = cbuf + (clen << cbuf_type); s->cbuf_type = cbuf_type; if (s->cbuf_type == 1 && s->is_utf16) s->cbuf_type = 2; s->opaque = opaque; s->state_size = sizeof(REExecState) + s->capture_count * sizeof(capture[0]) * 2 + s->stack_size_max * sizeof(stack_buf[0]); s->state_stack = NULL; s->state_stack_len = 0; s->state_stack_size = 0; for(i = 0; i < s->capture_count * 2; i++) capture[i] = NULL; alloca_size = s->stack_size_max * sizeof(stack_buf[0]); stack_buf = amp_malloc(alloca_size); ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN, cbuf + (cindex << cbuf_type), FALSE); lre_realloc(s->opaque, s->state_stack, 0); amp_free(stack_buf); return ret; } int lre_get_capture_count(const uint8_t *bc_buf) { return bc_buf[RE_HEADER_CAPTURE_COUNT]; } int lre_get_flags(const uint8_t *bc_buf) { return bc_buf[RE_HEADER_FLAGS]; } #ifdef TEST BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size) { return FALSE; } void *lre_realloc(void *opaque, void *ptr, size_t size) { return realloc(ptr, size); } int main(int argc, char **argv) { int len, ret, i; uint8_t *bc; char error_msg[64]; uint8_t *capture[CAPTURE_COUNT_MAX * 2]; const char *input; int input_len, capture_count; if (argc < 3) { printf("usage: %s regexp input\n", argv[0]); exit(1); } bc = lre_compile(&len, error_msg, sizeof(error_msg), argv[1], strlen(argv[1]), 0, NULL); if (!bc) { fprintf(stderr, "error: %s\n", error_msg); exit(1); } input = argv[2]; input_len = strlen(input); ret = lre_exec(capture, bc, (uint8_t *)input, 0, input_len, 0, NULL); printf("ret=%d\n", ret); if (ret == 1) { capture_count = lre_get_capture_count(bc); for(i = 0; i < 2 * capture_count; i++) { uint8_t *ptr; ptr = capture[i]; printf("%d: ", i); if (!ptr) printf("<nil>"); else printf("%u", (int)(ptr - (uint8_t *)input)); printf("\n"); } } return 0; } #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libregexp.c
C
apache-2.0
83,760
/* * Regular Expression Engine * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef LIBREGEXP_H #define LIBREGEXP_H #include <stddef.h> #include "libunicode.h" #define LRE_BOOL int /* for documentation purposes */ #define LRE_FLAG_GLOBAL (1 << 0) #define LRE_FLAG_IGNORECASE (1 << 1) #define LRE_FLAG_MULTILINE (1 << 2) #define LRE_FLAG_DOTALL (1 << 3) #define LRE_FLAG_UTF16 (1 << 4) #define LRE_FLAG_STICKY (1 << 5) #define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */ uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size, const char *buf, size_t buf_len, int re_flags, void *opaque); int lre_get_capture_count(const uint8_t *bc_buf); int lre_get_flags(const uint8_t *bc_buf); int lre_exec(uint8_t **capture, const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen, int cbuf_type, void *opaque); int lre_parse_escape(const uint8_t **pp, int allow_utf16); LRE_BOOL lre_is_space(int c); /* must be provided by the user */ LRE_BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size); void *lre_realloc(void *opaque, void *ptr, size_t size); /* JS identifier test */ extern uint32_t const lre_id_start_table_ascii[4]; extern uint32_t const lre_id_continue_table_ascii[4]; static inline int lre_js_is_ident_first(int c) { if ((uint32_t)c < 128) { return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1; } else { #ifdef CONFIG_ALL_UNICODE return lre_is_id_start(c); #else return !lre_is_space(c); #endif } } static inline int lre_js_is_ident_next(int c) { if ((uint32_t)c < 128) { return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1; } else { /* ZWNJ and ZWJ are accepted in identifiers */ #ifdef CONFIG_ALL_UNICODE return lre_is_id_continue(c) || c == 0x200C || c == 0x200D; #else return !lre_is_space(c) || c == 0x200C || c == 0x200D; #endif } } #undef LRE_BOOL #endif /* LIBREGEXP_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libregexp.h
C
apache-2.0
3,129
/* * Unicode utilities * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <assert.h> #include "cutils.h" #include "libunicode.h" #include "libunicode-table.h" enum { RUN_TYPE_U, RUN_TYPE_L, RUN_TYPE_UF, RUN_TYPE_LF, RUN_TYPE_UL, RUN_TYPE_LSU, RUN_TYPE_U2L_399_EXT2, RUN_TYPE_UF_D20, RUN_TYPE_UF_D1_EXT, RUN_TYPE_U_EXT, RUN_TYPE_LF_EXT, RUN_TYPE_U_EXT2, RUN_TYPE_L_EXT2, RUN_TYPE_U_EXT3, }; /* conv_type: 0 = to upper 1 = to lower 2 = case folding (= to lower with modifications) */ int lre_case_conv(uint32_t *res, uint32_t c, int conv_type) { if (c < 128) { if (conv_type) { if (c >= 'A' && c <= 'Z') { c = c - 'A' + 'a'; } } else { if (c >= 'a' && c <= 'z') { c = c - 'a' + 'A'; } } } else { uint32_t v, code, data, type, len, a, is_lower; int idx, idx_min, idx_max; is_lower = (conv_type != 0); idx_min = 0; idx_max = countof(case_conv_table1) - 1; while (idx_min <= idx_max) { idx = (unsigned)(idx_max + idx_min) / 2; v = case_conv_table1[idx]; code = v >> (32 - 17); len = (v >> (32 - 17 - 7)) & 0x7f; if (c < code) { idx_max = idx - 1; } else if (c >= code + len) { idx_min = idx + 1; } else { type = (v >> (32 - 17 - 7 - 4)) & 0xf; data = ((v & 0xf) << 8) | case_conv_table2[idx]; switch(type) { case RUN_TYPE_U: case RUN_TYPE_L: case RUN_TYPE_UF: case RUN_TYPE_LF: if (conv_type == (type & 1) || (type >= RUN_TYPE_UF && conv_type == 2)) { c = c - code + (case_conv_table1[data] >> (32 - 17)); } break; case RUN_TYPE_UL: a = c - code; if ((a & 1) != (1 - is_lower)) break; c = (a ^ 1) + code; break; case RUN_TYPE_LSU: a = c - code; if (a == 1) { c += 2 * is_lower - 1; } else if (a == (1 - is_lower) * 2) { c += (2 * is_lower - 1) * 2; } break; case RUN_TYPE_U2L_399_EXT2: if (!is_lower) { res[0] = c - code + case_conv_ext[data >> 6]; res[1] = 0x399; return 2; } else { c = c - code + case_conv_ext[data & 0x3f]; } break; case RUN_TYPE_UF_D20: if (conv_type == 1) break; c = data + (conv_type == 2) * 0x20; break; case RUN_TYPE_UF_D1_EXT: if (conv_type == 1) break; c = case_conv_ext[data] + (conv_type == 2); break; case RUN_TYPE_U_EXT: case RUN_TYPE_LF_EXT: if (is_lower != (type - RUN_TYPE_U_EXT)) break; c = case_conv_ext[data]; break; case RUN_TYPE_U_EXT2: case RUN_TYPE_L_EXT2: if (conv_type != (type - RUN_TYPE_U_EXT2)) break; res[0] = c - code + case_conv_ext[data >> 6]; res[1] = case_conv_ext[data & 0x3f]; return 2; default: case RUN_TYPE_U_EXT3: if (conv_type != 0) break; res[0] = case_conv_ext[data >> 8]; res[1] = case_conv_ext[(data >> 4) & 0xf]; res[2] = case_conv_ext[data & 0xf]; return 3; } break; } } } res[0] = c; return 1; } static uint32_t get_le24(const uint8_t *ptr) { #if defined(__x86__) || defined(__x86_64__) return *(uint16_t *)ptr | (ptr[2] << 16); #else return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16); #endif } #define UNICODE_INDEX_BLOCK_LEN 32 /* return -1 if not in table, otherwise the offset in the block */ static int get_index_pos(uint32_t *pcode, uint32_t c, const uint8_t *index_table, int index_table_len) { uint32_t code, v; int idx_min, idx_max, idx; idx_min = 0; v = get_le24(index_table); code = v & ((1 << 21) - 1); if (c < code) { *pcode = 0; return 0; } idx_max = index_table_len - 1; code = get_le24(index_table + idx_max * 3); if (c >= code) return -1; /* invariant: tab[idx_min] <= c < tab2[idx_max] */ while ((idx_max - idx_min) > 1) { idx = (idx_max + idx_min) / 2; v = get_le24(index_table + idx * 3); code = v & ((1 << 21) - 1); if (c < code) { idx_max = idx; } else { idx_min = idx; } } v = get_le24(index_table + idx_min * 3); *pcode = v & ((1 << 21) - 1); return (idx_min + 1) * UNICODE_INDEX_BLOCK_LEN + (v >> 21); } static BOOL lre_is_in_table(uint32_t c, const uint8_t *table, const uint8_t *index_table, int index_table_len) { uint32_t code, b, bit; int pos; const uint8_t *p; pos = get_index_pos(&code, c, index_table, index_table_len); if (pos < 0) return FALSE; /* outside the table */ p = table + pos; bit = 0; for(;;) { b = *p++; if (b < 64) { code += (b >> 3) + 1; if (c < code) return bit; bit ^= 1; code += (b & 7) + 1; } else if (b >= 0x80) { code += b - 0x80 + 1; } else if (b < 0x60) { code += (((b - 0x40) << 8) | p[0]) + 1; p++; } else { code += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1; p += 2; } if (c < code) return bit; bit ^= 1; } } BOOL lre_is_cased(uint32_t c) { uint32_t v, code, len; int idx, idx_min, idx_max; idx_min = 0; idx_max = countof(case_conv_table1) - 1; while (idx_min <= idx_max) { idx = (unsigned)(idx_max + idx_min) / 2; v = case_conv_table1[idx]; code = v >> (32 - 17); len = (v >> (32 - 17 - 7)) & 0x7f; if (c < code) { idx_max = idx - 1; } else if (c >= code + len) { idx_min = idx + 1; } else { return TRUE; } } return lre_is_in_table(c, unicode_prop_Cased1_table, unicode_prop_Cased1_index, sizeof(unicode_prop_Cased1_index) / 3); } BOOL lre_is_case_ignorable(uint32_t c) { return lre_is_in_table(c, unicode_prop_Case_Ignorable_table, unicode_prop_Case_Ignorable_index, sizeof(unicode_prop_Case_Ignorable_index) / 3); } /* character range */ static __maybe_unused void cr_dump(CharRange *cr) { int i; for(i = 0; i < cr->len; i++) printf("%d: 0x%04x\n", i, cr->points[i]); } static void *cr_default_realloc(void *opaque, void *ptr, size_t size) { return realloc(ptr, size); } void cr_init(CharRange *cr, void *mem_opaque, DynBufReallocFunc *realloc_func) { cr->len = cr->size = 0; cr->points = NULL; cr->mem_opaque = mem_opaque; cr->realloc_func = realloc_func ? realloc_func : cr_default_realloc; } void cr_free(CharRange *cr) { cr->realloc_func(cr->mem_opaque, cr->points, 0); } int cr_realloc(CharRange *cr, int size) { int new_size; uint32_t *new_buf; if (size > cr->size) { new_size = max_int(size, cr->size * 3 / 2); new_buf = cr->realloc_func(cr->mem_opaque, cr->points, new_size * sizeof(cr->points[0])); if (!new_buf) return -1; cr->points = new_buf; cr->size = new_size; } return 0; } int cr_copy(CharRange *cr, const CharRange *cr1) { if (cr_realloc(cr, cr1->len)) return -1; memcpy(cr->points, cr1->points, sizeof(cr->points[0]) * cr1->len); cr->len = cr1->len; return 0; } /* merge consecutive intervals and remove empty intervals */ static void cr_compress(CharRange *cr) { int i, j, k, len; uint32_t *pt; pt = cr->points; len = cr->len; i = 0; j = 0; k = 0; while ((i + 1) < len) { if (pt[i] == pt[i + 1]) { /* empty interval */ i += 2; } else { j = i; while ((j + 3) < len && pt[j + 1] == pt[j + 2]) j += 2; /* just copy */ pt[k] = pt[i]; pt[k + 1] = pt[j + 1]; k += 2; i = j + 2; } } cr->len = k; } /* union or intersection */ int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, const uint32_t *b_pt, int b_len, int op) { int a_idx, b_idx, is_in; uint32_t v; a_idx = 0; b_idx = 0; for(;;) { /* get one more point from a or b in increasing order */ if (a_idx < a_len && b_idx < b_len) { if (a_pt[a_idx] < b_pt[b_idx]) { goto a_add; } else if (a_pt[a_idx] == b_pt[b_idx]) { v = a_pt[a_idx]; a_idx++; b_idx++; } else { goto b_add; } } else if (a_idx < a_len) { a_add: v = a_pt[a_idx++]; } else if (b_idx < b_len) { b_add: v = b_pt[b_idx++]; } else { break; } /* add the point if the in/out status changes */ switch(op) { case CR_OP_UNION: is_in = (a_idx & 1) | (b_idx & 1); break; case CR_OP_INTER: is_in = (a_idx & 1) & (b_idx & 1); break; case CR_OP_XOR: is_in = (a_idx & 1) ^ (b_idx & 1); break; default: abort(); } if (is_in != (cr->len & 1)) { if (cr_add_point(cr, v)) return -1; } } cr_compress(cr); return 0; } int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len) { CharRange a = *cr; int ret; cr->len = 0; cr->size = 0; cr->points = NULL; ret = cr_op(cr, a.points, a.len, b_pt, b_len, CR_OP_UNION); cr_free(&a); return ret; } int cr_invert(CharRange *cr) { int len; len = cr->len; if (cr_realloc(cr, len + 2)) return -1; memmove(cr->points + 1, cr->points, len * sizeof(cr->points[0])); cr->points[0] = 0; cr->points[len + 1] = UINT32_MAX; cr->len = len + 2; cr_compress(cr); return 0; } #ifdef CONFIG_ALL_UNICODE BOOL lre_is_id_start(uint32_t c) { return lre_is_in_table(c, unicode_prop_ID_Start_table, unicode_prop_ID_Start_index, sizeof(unicode_prop_ID_Start_index) / 3); } BOOL lre_is_id_continue(uint32_t c) { return lre_is_id_start(c) || lre_is_in_table(c, unicode_prop_ID_Continue1_table, unicode_prop_ID_Continue1_index, sizeof(unicode_prop_ID_Continue1_index) / 3); } #define UNICODE_DECOMP_LEN_MAX 18 typedef enum { DECOMP_TYPE_C1, /* 16 bit char */ DECOMP_TYPE_L1, /* 16 bit char table */ DECOMP_TYPE_L2, DECOMP_TYPE_L3, DECOMP_TYPE_L4, DECOMP_TYPE_L5, /* XXX: not used */ DECOMP_TYPE_L6, /* XXX: could remove */ DECOMP_TYPE_L7, /* XXX: could remove */ DECOMP_TYPE_LL1, /* 18 bit char table */ DECOMP_TYPE_LL2, DECOMP_TYPE_S1, /* 8 bit char table */ DECOMP_TYPE_S2, DECOMP_TYPE_S3, DECOMP_TYPE_S4, DECOMP_TYPE_S5, DECOMP_TYPE_I1, /* increment 16 bit char value */ DECOMP_TYPE_I2_0, DECOMP_TYPE_I2_1, DECOMP_TYPE_I3_1, DECOMP_TYPE_I3_2, DECOMP_TYPE_I4_1, DECOMP_TYPE_I4_2, DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */ DECOMP_TYPE_B2, DECOMP_TYPE_B3, DECOMP_TYPE_B4, DECOMP_TYPE_B5, DECOMP_TYPE_B6, DECOMP_TYPE_B7, DECOMP_TYPE_B8, DECOMP_TYPE_B18, DECOMP_TYPE_LS2, DECOMP_TYPE_PAT3, DECOMP_TYPE_S2_UL, DECOMP_TYPE_LS2_UL, } DecompTypeEnum; static uint32_t unicode_get_short_code(uint32_t c) { static const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 }; if (c < 0x80) return c; else if (c < 0x80 + 0x50) return c - 0x80 + 0x300; else return unicode_short_table[c - 0x80 - 0x50]; } static uint32_t unicode_get_lower_simple(uint32_t c) { if (c < 0x100 || (c >= 0x410 && c <= 0x42f)) c += 0x20; else c++; return c; } static uint16_t unicode_get16(const uint8_t *p) { return p[0] | (p[1] << 8); } static int unicode_decomp_entry(uint32_t *res, uint32_t c, int idx, uint32_t code, uint32_t len, uint32_t type) { uint32_t c1; int l, i, p; const uint8_t *d; if (type == DECOMP_TYPE_C1) { res[0] = unicode_decomp_table2[idx]; return 1; } else { d = unicode_decomp_data + unicode_decomp_table2[idx]; switch(type) { case DECOMP_TYPE_L1 ... DECOMP_TYPE_L7: l = type - DECOMP_TYPE_L1 + 1; d += (c - code) * l * 2; for(i = 0; i < l; i++) { if ((res[i] = unicode_get16(d + 2 * i)) == 0) return 0; } return l; case DECOMP_TYPE_LL1 ... DECOMP_TYPE_LL2: { uint32_t k, p; l = type - DECOMP_TYPE_LL1 + 1; k = (c - code) * l; p = len * l * 2; for(i = 0; i < l; i++) { c1 = unicode_get16(d + 2 * k) | (((d[p + (k / 4)] >> ((k % 4) * 2)) & 3) << 16); if (!c1) return 0; res[i] = c1; k++; } } return l; case DECOMP_TYPE_S1 ... DECOMP_TYPE_S5: l = type - DECOMP_TYPE_S1 + 1; d += (c - code) * l; for(i = 0; i < l; i++) { if ((res[i] = unicode_get_short_code(d[i])) == 0) return 0; } return l; case DECOMP_TYPE_I1: l = 1; p = 0; goto decomp_type_i; case DECOMP_TYPE_I2_0: case DECOMP_TYPE_I2_1: case DECOMP_TYPE_I3_1: case DECOMP_TYPE_I3_2: case DECOMP_TYPE_I4_1: case DECOMP_TYPE_I4_2: l = 2 + ((type - DECOMP_TYPE_I2_0) >> 1); p = ((type - DECOMP_TYPE_I2_0) & 1) + (l > 2); decomp_type_i: for(i = 0; i < l; i++) { c1 = unicode_get16(d + 2 * i); if (i == p) c1 += c - code; res[i] = c1; } return l; case DECOMP_TYPE_B18: l = 18; goto decomp_type_b; case DECOMP_TYPE_B1 ... DECOMP_TYPE_B8: l = type - DECOMP_TYPE_B1 + 1; decomp_type_b: { uint32_t c_min; c_min = unicode_get16(d); d += 2 + (c - code) * l; for(i = 0; i < l; i++) { c1 = d[i]; if (c1 == 0xff) c1 = 0x20; else c1 += c_min; res[i] = c1; } } return l; case DECOMP_TYPE_LS2: d += (c - code) * 3; if (!(res[0] = unicode_get16(d))) return 0; res[1] = unicode_get_short_code(d[2]); return 2; case DECOMP_TYPE_PAT3: res[0] = unicode_get16(d); res[2] = unicode_get16(d + 2); d += 4 + (c - code) * 2; res[1] = unicode_get16(d); return 3; case DECOMP_TYPE_S2_UL: case DECOMP_TYPE_LS2_UL: c1 = c - code; if (type == DECOMP_TYPE_S2_UL) { d += c1 & ~1; c = unicode_get_short_code(*d); d++; } else { d += (c1 >> 1) * 3; c = unicode_get16(d); d += 2; } if (c1 & 1) c = unicode_get_lower_simple(c); res[0] = c; res[1] = unicode_get_short_code(*d); return 2; } } return 0; } /* return the length of the decomposition (length <= UNICODE_DECOMP_LEN_MAX) or 0 if no decomposition */ static int unicode_decomp_char(uint32_t *res, uint32_t c, BOOL is_compat1) { uint32_t v, type, is_compat, code, len; int idx_min, idx_max, idx; idx_min = 0; idx_max = countof(unicode_decomp_table1) - 1; while (idx_min <= idx_max) { idx = (idx_max + idx_min) / 2; v = unicode_decomp_table1[idx]; code = v >> (32 - 18); len = (v >> (32 - 18 - 7)) & 0x7f; // printf("idx=%d code=%05x len=%d\n", idx, code, len); if (c < code) { idx_max = idx - 1; } else if (c >= code + len) { idx_min = idx + 1; } else { is_compat = v & 1; if (is_compat1 < is_compat) break; type = (v >> (32 - 18 - 7 - 6)) & 0x3f; return unicode_decomp_entry(res, c, idx, code, len, type); } } return 0; } /* return 0 if no pair found */ static int unicode_compose_pair(uint32_t c0, uint32_t c1) { uint32_t code, len, type, v, idx1, d_idx, d_offset, ch; int idx_min, idx_max, idx, d; uint32_t pair[2]; idx_min = 0; idx_max = countof(unicode_comp_table) - 1; while (idx_min <= idx_max) { idx = (idx_max + idx_min) / 2; idx1 = unicode_comp_table[idx]; /* idx1 represent an entry of the decomposition table */ d_idx = idx1 >> 6; d_offset = idx1 & 0x3f; v = unicode_decomp_table1[d_idx]; code = v >> (32 - 18); len = (v >> (32 - 18 - 7)) & 0x7f; type = (v >> (32 - 18 - 7 - 6)) & 0x3f; ch = code + d_offset; unicode_decomp_entry(pair, ch, d_idx, code, len, type); d = c0 - pair[0]; if (d == 0) d = c1 - pair[1]; if (d < 0) { idx_max = idx - 1; } else if (d > 0) { idx_min = idx + 1; } else { return ch; } } return 0; } /* return the combining class of character c (between 0 and 255) */ static int unicode_get_cc(uint32_t c) { uint32_t code, n, type, cc, c1, b; int pos; const uint8_t *p; pos = get_index_pos(&code, c, unicode_cc_index, sizeof(unicode_cc_index) / 3); if (pos < 0) return 0; p = unicode_cc_table + pos; for(;;) { b = *p++; type = b >> 6; n = b & 0x3f; if (n < 48) { } else if (n < 56) { n = (n - 48) << 8; n |= *p++; n += 48; } else { n = (n - 56) << 8; n |= *p++ << 8; n |= *p++; n += 48 + (1 << 11); } if (type <= 1) p++; c1 = code + n + 1; if (c < c1) { switch(type) { case 0: cc = p[-1]; break; case 1: cc = p[-1] + c - code; break; case 2: cc = 0; break; default: case 3: cc = 230; break; } return cc; } code = c1; } } static void sort_cc(int *buf, int len) { int i, j, k, cc, cc1, start, ch1; for(i = 0; i < len; i++) { cc = unicode_get_cc(buf[i]); if (cc != 0) { start = i; j = i + 1; while (j < len) { ch1 = buf[j]; cc1 = unicode_get_cc(ch1); if (cc1 == 0) break; k = j - 1; while (k >= start) { if (unicode_get_cc(buf[k]) <= cc1) break; buf[k + 1] = buf[k]; k--; } buf[k + 1] = ch1; j++; } #if 0 printf("cc:"); for(k = start; k < j; k++) { printf(" %3d", unicode_get_cc(buf[k])); } printf("\n"); #endif i = j; } } } static void to_nfd_rec(DynBuf *dbuf, const int *src, int src_len, int is_compat) { uint32_t c, v; int i, l; uint32_t res[UNICODE_DECOMP_LEN_MAX]; for(i = 0; i < src_len; i++) { c = src[i]; if (c >= 0xac00 && c < 0xd7a4) { /* Hangul decomposition */ c -= 0xac00; dbuf_put_u32(dbuf, 0x1100 + c / 588); dbuf_put_u32(dbuf, 0x1161 + (c % 588) / 28); v = c % 28; if (v != 0) dbuf_put_u32(dbuf, 0x11a7 + v); } else { l = unicode_decomp_char(res, c, is_compat); if (l) { to_nfd_rec(dbuf, (int *)res, l, is_compat); } else { dbuf_put_u32(dbuf, c); } } } } /* return 0 if not found */ static int compose_pair(uint32_t c0, uint32_t c1) { /* Hangul composition */ if (c0 >= 0x1100 && c0 < 0x1100 + 19 && c1 >= 0x1161 && c1 < 0x1161 + 21) { return 0xac00 + (c0 - 0x1100) * 588 + (c1 - 0x1161) * 28; } else if (c0 >= 0xac00 && c0 < 0xac00 + 11172 && (c0 - 0xac00) % 28 == 0 && c1 >= 0x11a7 && c1 < 0x11a7 + 28) { return c0 + c1 - 0x11a7; } else { return unicode_compose_pair(c0, c1); } } int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, UnicodeNormalizationEnum n_type, void *opaque, DynBufReallocFunc *realloc_func) { int *buf, buf_len, i, p, starter_pos, cc, last_cc, out_len; BOOL is_compat; DynBuf dbuf_s, *dbuf = &dbuf_s; is_compat = n_type >> 1; dbuf_init2(dbuf, opaque, realloc_func); if (dbuf_realloc(dbuf, sizeof(int) * src_len)) goto fail; /* common case: latin1 is unaffected by NFC */ if (n_type == UNICODE_NFC) { for(i = 0; i < src_len; i++) { if (src[i] >= 0x100) goto not_latin1; } buf = (int *)dbuf->buf; memcpy(buf, src, src_len * sizeof(int)); *pdst = (uint32_t *)buf; return src_len; not_latin1: ; } to_nfd_rec(dbuf, (const int *)src, src_len, is_compat); if (dbuf_error(dbuf)) { fail: *pdst = NULL; return -1; } buf = (int *)dbuf->buf; buf_len = dbuf->size / sizeof(int); sort_cc(buf, buf_len); if (buf_len <= 1 || (n_type & 1) != 0) { /* NFD / NFKD */ *pdst = (uint32_t *)buf; return buf_len; } i = 1; out_len = 1; while (i < buf_len) { /* find the starter character and test if it is blocked from the character at 'i' */ last_cc = unicode_get_cc(buf[i]); starter_pos = out_len - 1; while (starter_pos >= 0) { cc = unicode_get_cc(buf[starter_pos]); if (cc == 0) break; if (cc >= last_cc) goto next; last_cc = 256; starter_pos--; } if (starter_pos >= 0 && (p = compose_pair(buf[starter_pos], buf[i])) != 0) { buf[starter_pos] = p; i++; } else { next: buf[out_len++] = buf[i++]; } } *pdst = (uint32_t *)buf; return out_len; } /* char ranges for various unicode properties */ static int unicode_find_name(const char *name_table, const char *name) { const char *p, *r; int pos; size_t name_len, len; p = name_table; pos = 0; name_len = strlen(name); while (*p) { for(;;) { r = strchr(p, ','); if (!r) len = strlen(p); else len = r - p; if (len == name_len && !memcmp(p, name, name_len)) return pos; p += len + 1; if (!r) break; } pos++; } return -1; } /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2 if not found */ int unicode_script(CharRange *cr, const char *script_name, BOOL is_ext) { int script_idx; const uint8_t *p, *p_end; uint32_t c, c1, b, n, v, v_len, i, type; CharRange cr1_s, *cr1; CharRange cr2_s, *cr2 = &cr2_s; BOOL is_common; script_idx = unicode_find_name(unicode_script_name_table, script_name); if (script_idx < 0) return -2; /* Note: we remove the "Unknown" Script */ script_idx += UNICODE_SCRIPT_Unknown + 1; is_common = (script_idx == UNICODE_SCRIPT_Common || script_idx == UNICODE_SCRIPT_Inherited); if (is_ext) { cr1 = &cr1_s; cr_init(cr1, cr->mem_opaque, cr->realloc_func); cr_init(cr2, cr->mem_opaque, cr->realloc_func); } else { cr1 = cr; } p = unicode_script_table; p_end = unicode_script_table + countof(unicode_script_table); c = 0; while (p < p_end) { b = *p++; type = b >> 7; n = b & 0x7f; if (n < 96) { } else if (n < 112) { n = (n - 96) << 8; n |= *p++; n += 96; } else { n = (n - 112) << 16; n |= *p++ << 8; n |= *p++; n += 96 + (1 << 12); } if (type == 0) v = 0; else v = *p++; c1 = c + n + 1; if (v == script_idx) { if (cr_add_interval(cr1, c, c1)) goto fail; } c = c1; } if (is_ext) { /* add the script extensions */ p = unicode_script_ext_table; p_end = unicode_script_ext_table + countof(unicode_script_ext_table); c = 0; while (p < p_end) { b = *p++; if (b < 128) { n = b; } else if (b < 128 + 64) { n = (b - 128) << 8; n |= *p++; n += 128; } else { n = (b - 128 - 64) << 16; n |= *p++ << 8; n |= *p++; n += 128 + (1 << 14); } c1 = c + n + 1; v_len = *p++; if (is_common) { if (v_len != 0) { if (cr_add_interval(cr2, c, c1)) goto fail; } } else { for(i = 0; i < v_len; i++) { if (p[i] == script_idx) { if (cr_add_interval(cr2, c, c1)) goto fail; break; } } } p += v_len; c = c1; } if (is_common) { /* remove all the characters with script extensions */ if (cr_invert(cr2)) goto fail; if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len, CR_OP_INTER)) goto fail; } else { if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len, CR_OP_UNION)) goto fail; } cr_free(cr1); cr_free(cr2); } return 0; fail: if (is_ext) { cr_free(cr1); cr_free(cr2); } goto fail; } #define M(id) (1U << UNICODE_GC_ ## id) static int unicode_general_category1(CharRange *cr, uint32_t gc_mask) { const uint8_t *p, *p_end; uint32_t c, c0, b, n, v; p = unicode_gc_table; p_end = unicode_gc_table + countof(unicode_gc_table); c = 0; while (p < p_end) { b = *p++; n = b >> 5; v = b & 0x1f; if (n == 7) { n = *p++; if (n < 128) { n += 7; } else if (n < 128 + 64) { n = (n - 128) << 8; n |= *p++; n += 7 + 128; } else { n = (n - 128 - 64) << 16; n |= *p++ << 8; n |= *p++; n += 7 + 128 + (1 << 14); } } c0 = c; c += n + 1; if (v == 31) { /* run of Lu / Ll */ b = gc_mask & (M(Lu) | M(Ll)); if (b != 0) { if (b == (M(Lu) | M(Ll))) { goto add_range; } else { c0 += ((gc_mask & M(Ll)) != 0); for(; c0 < c; c0 += 2) { if (cr_add_interval(cr, c0, c0 + 1)) return -1; } } } } else if ((gc_mask >> v) & 1) { add_range: if (cr_add_interval(cr, c0, c)) return -1; } } return 0; } static int unicode_prop1(CharRange *cr, int prop_idx) { const uint8_t *p, *p_end; uint32_t c, c0, b, bit; p = unicode_prop_table[prop_idx]; p_end = p + unicode_prop_len_table[prop_idx]; c = 0; bit = 0; while (p < p_end) { c0 = c; b = *p++; if (b < 64) { c += (b >> 3) + 1; if (bit) { if (cr_add_interval(cr, c0, c)) return -1; } bit ^= 1; c0 = c; c += (b & 7) + 1; } else if (b >= 0x80) { c += b - 0x80 + 1; } else if (b < 0x60) { c += (((b - 0x40) << 8) | p[0]) + 1; p++; } else { c += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1; p += 2; } if (bit) { if (cr_add_interval(cr, c0, c)) return -1; } bit ^= 1; } return 0; } #define CASE_U (1 << 0) #define CASE_L (1 << 1) #define CASE_F (1 << 2) /* use the case conversion table to generate range of characters. CASE_U: set char if modified by uppercasing, CASE_L: set char if modified by lowercasing, CASE_F: set char if modified by case folding, */ static int unicode_case1(CharRange *cr, int case_mask) { #define MR(x) (1 << RUN_TYPE_ ## x) const uint32_t tab_run_mask[3] = { MR(U) | MR(UF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(UF_D20) | MR(UF_D1_EXT) | MR(U_EXT) | MR(U_EXT2) | MR(U_EXT3), MR(L) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(L_EXT2), MR(UF) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(UF_D20) | MR(UF_D1_EXT) | MR(LF_EXT), }; #undef MR uint32_t mask, v, code, type, len, i, idx; if (case_mask == 0) return 0; mask = 0; for(i = 0; i < 3; i++) { if ((case_mask >> i) & 1) mask |= tab_run_mask[i]; } for(idx = 0; idx < countof(case_conv_table1); idx++) { v = case_conv_table1[idx]; type = (v >> (32 - 17 - 7 - 4)) & 0xf; code = v >> (32 - 17); len = (v >> (32 - 17 - 7)) & 0x7f; if ((mask >> type) & 1) { // printf("%d: type=%d %04x %04x\n", idx, type, code, code + len - 1); switch(type) { case RUN_TYPE_UL: if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F))) goto def_case; code += ((case_mask & CASE_U) != 0); for(i = 0; i < len; i += 2) { if (cr_add_interval(cr, code + i, code + i + 1)) return -1; } break; case RUN_TYPE_LSU: if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F))) goto def_case; if (!(case_mask & CASE_U)) { if (cr_add_interval(cr, code, code + 1)) return -1; } if (cr_add_interval(cr, code + 1, code + 2)) return -1; if (case_mask & CASE_U) { if (cr_add_interval(cr, code + 2, code + 3)) return -1; } break; default: def_case: if (cr_add_interval(cr, code, code + len)) return -1; break; } } } return 0; } typedef enum { POP_GC, POP_PROP, POP_CASE, POP_UNION, POP_INTER, POP_XOR, POP_INVERT, POP_END, } PropOPEnum; #define POP_STACK_LEN_MAX 4 static int unicode_prop_ops(CharRange *cr, ...) { va_list ap; CharRange stack[POP_STACK_LEN_MAX]; int stack_len, op, ret, i; uint32_t a; va_start(ap, cr); stack_len = 0; for(;;) { op = va_arg(ap, int); switch(op) { case POP_GC: assert(stack_len < POP_STACK_LEN_MAX); a = va_arg(ap, int); cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func); if (unicode_general_category1(&stack[stack_len - 1], a)) goto fail; break; case POP_PROP: assert(stack_len < POP_STACK_LEN_MAX); a = va_arg(ap, int); cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func); if (unicode_prop1(&stack[stack_len - 1], a)) goto fail; break; case POP_CASE: assert(stack_len < POP_STACK_LEN_MAX); a = va_arg(ap, int); cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func); if (unicode_case1(&stack[stack_len - 1], a)) goto fail; break; case POP_UNION: case POP_INTER: case POP_XOR: { CharRange *cr1, *cr2, *cr3; assert(stack_len >= 2); assert(stack_len < POP_STACK_LEN_MAX); cr1 = &stack[stack_len - 2]; cr2 = &stack[stack_len - 1]; cr3 = &stack[stack_len++]; cr_init(cr3, cr->mem_opaque, cr->realloc_func); if (cr_op(cr3, cr1->points, cr1->len, cr2->points, cr2->len, op - POP_UNION + CR_OP_UNION)) goto fail; cr_free(cr1); cr_free(cr2); *cr1 = *cr3; stack_len -= 2; } break; case POP_INVERT: assert(stack_len >= 1); if (cr_invert(&stack[stack_len - 1])) goto fail; break; case POP_END: goto done; default: abort(); } } done: assert(stack_len == 1); ret = cr_copy(cr, &stack[0]); cr_free(&stack[0]); return ret; fail: for(i = 0; i < stack_len; i++) cr_free(&stack[i]); return -1; } static const uint32_t unicode_gc_mask_table[] = { M(Lu) | M(Ll) | M(Lt), /* LC */ M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo), /* L */ M(Mn) | M(Mc) | M(Me), /* M */ M(Nd) | M(Nl) | M(No), /* N */ M(Sm) | M(Sc) | M(Sk) | M(So), /* S */ M(Pc) | M(Pd) | M(Ps) | M(Pe) | M(Pi) | M(Pf) | M(Po), /* P */ M(Zs) | M(Zl) | M(Zp), /* Z */ M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn), /* C */ }; /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2 if not found */ int unicode_general_category(CharRange *cr, const char *gc_name) { int gc_idx; uint32_t gc_mask; gc_idx = unicode_find_name(unicode_gc_name_table, gc_name); if (gc_idx < 0) return -2; if (gc_idx <= UNICODE_GC_Co) { gc_mask = (uint64_t)1 << gc_idx; } else { gc_mask = unicode_gc_mask_table[gc_idx - UNICODE_GC_LC]; } return unicode_general_category1(cr, gc_mask); } /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2 if not found */ int unicode_prop(CharRange *cr, const char *prop_name) { int prop_idx, ret; prop_idx = unicode_find_name(unicode_prop_name_table, prop_name); if (prop_idx < 0) return -2; prop_idx += UNICODE_PROP_ASCII_Hex_Digit; ret = 0; switch(prop_idx) { case UNICODE_PROP_ASCII: if (cr_add_interval(cr, 0x00, 0x7f + 1)) return -1; break; case UNICODE_PROP_Any: if (cr_add_interval(cr, 0x00000, 0x10ffff + 1)) return -1; break; case UNICODE_PROP_Assigned: ret = unicode_prop_ops(cr, POP_GC, M(Cn), POP_INVERT, POP_END); break; case UNICODE_PROP_Math: ret = unicode_prop_ops(cr, POP_GC, M(Sm), POP_PROP, UNICODE_PROP_Other_Math, POP_UNION, POP_END); break; case UNICODE_PROP_Lowercase: ret = unicode_prop_ops(cr, POP_GC, M(Ll), POP_PROP, UNICODE_PROP_Other_Lowercase, POP_UNION, POP_END); break; case UNICODE_PROP_Uppercase: ret = unicode_prop_ops(cr, POP_GC, M(Lu), POP_PROP, UNICODE_PROP_Other_Uppercase, POP_UNION, POP_END); break; case UNICODE_PROP_Cased: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt), POP_PROP, UNICODE_PROP_Other_Uppercase, POP_UNION, POP_PROP, UNICODE_PROP_Other_Lowercase, POP_UNION, POP_END); break; case UNICODE_PROP_Alphabetic: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl), POP_PROP, UNICODE_PROP_Other_Uppercase, POP_UNION, POP_PROP, UNICODE_PROP_Other_Lowercase, POP_UNION, POP_PROP, UNICODE_PROP_Other_Alphabetic, POP_UNION, POP_END); break; case UNICODE_PROP_Grapheme_Base: ret = unicode_prop_ops(cr, POP_GC, M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn) | M(Zl) | M(Zp) | M(Me) | M(Mn), POP_PROP, UNICODE_PROP_Other_Grapheme_Extend, POP_UNION, POP_INVERT, POP_END); break; case UNICODE_PROP_Grapheme_Extend: ret = unicode_prop_ops(cr, POP_GC, M(Me) | M(Mn), POP_PROP, UNICODE_PROP_Other_Grapheme_Extend, POP_UNION, POP_END); break; case UNICODE_PROP_XID_Start: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl), POP_PROP, UNICODE_PROP_Other_ID_Start, POP_UNION, POP_PROP, UNICODE_PROP_Pattern_Syntax, POP_PROP, UNICODE_PROP_Pattern_White_Space, POP_UNION, POP_PROP, UNICODE_PROP_XID_Start1, POP_UNION, POP_INVERT, POP_INTER, POP_END); break; case UNICODE_PROP_XID_Continue: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) | M(Mn) | M(Mc) | M(Nd) | M(Pc), POP_PROP, UNICODE_PROP_Other_ID_Start, POP_UNION, POP_PROP, UNICODE_PROP_Other_ID_Continue, POP_UNION, POP_PROP, UNICODE_PROP_Pattern_Syntax, POP_PROP, UNICODE_PROP_Pattern_White_Space, POP_UNION, POP_PROP, UNICODE_PROP_XID_Continue1, POP_UNION, POP_INVERT, POP_INTER, POP_END); break; case UNICODE_PROP_Changes_When_Uppercased: ret = unicode_case1(cr, CASE_U); break; case UNICODE_PROP_Changes_When_Lowercased: ret = unicode_case1(cr, CASE_L); break; case UNICODE_PROP_Changes_When_Casemapped: ret = unicode_case1(cr, CASE_U | CASE_L | CASE_F); break; case UNICODE_PROP_Changes_When_Titlecased: ret = unicode_prop_ops(cr, POP_CASE, CASE_U, POP_PROP, UNICODE_PROP_Changes_When_Titlecased1, POP_XOR, POP_END); break; case UNICODE_PROP_Changes_When_Casefolded: ret = unicode_prop_ops(cr, POP_CASE, CASE_F, POP_PROP, UNICODE_PROP_Changes_When_Casefolded1, POP_XOR, POP_END); break; case UNICODE_PROP_Changes_When_NFKC_Casefolded: ret = unicode_prop_ops(cr, POP_CASE, CASE_F, POP_PROP, UNICODE_PROP_Changes_When_NFKC_Casefolded1, POP_XOR, POP_END); break; #if 0 case UNICODE_PROP_ID_Start: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl), POP_PROP, UNICODE_PROP_Other_ID_Start, POP_UNION, POP_PROP, UNICODE_PROP_Pattern_Syntax, POP_PROP, UNICODE_PROP_Pattern_White_Space, POP_UNION, POP_INVERT, POP_INTER, POP_END); break; case UNICODE_PROP_ID_Continue: ret = unicode_prop_ops(cr, POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) | M(Mn) | M(Mc) | M(Nd) | M(Pc), POP_PROP, UNICODE_PROP_Other_ID_Start, POP_UNION, POP_PROP, UNICODE_PROP_Other_ID_Continue, POP_UNION, POP_PROP, UNICODE_PROP_Pattern_Syntax, POP_PROP, UNICODE_PROP_Pattern_White_Space, POP_UNION, POP_INVERT, POP_INTER, POP_END); break; case UNICODE_PROP_Case_Ignorable: ret = unicode_prop_ops(cr, POP_GC, M(Mn) | M(Cf) | M(Lm) | M(Sk), POP_PROP, UNICODE_PROP_Case_Ignorable1, POP_XOR, POP_END); break; #else /* we use the existing tables */ case UNICODE_PROP_ID_Continue: ret = unicode_prop_ops(cr, POP_PROP, UNICODE_PROP_ID_Start, POP_PROP, UNICODE_PROP_ID_Continue1, POP_XOR, POP_END); break; #endif default: if (prop_idx >= countof(unicode_prop_table)) return -2; ret = unicode_prop1(cr, prop_idx); break; } return ret; } #endif /* CONFIG_ALL_UNICODE */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libunicode.c
C
apache-2.0
46,403
/* * Unicode utilities * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef LIBUNICODE_H #define LIBUNICODE_H #include <inttypes.h> #define LRE_BOOL int /* for documentation purposes */ /* define it to include all the unicode tables (40KB larger) */ #define CONFIG_ALL_UNICODE #define LRE_CC_RES_LEN_MAX 3 typedef enum { UNICODE_NFC, UNICODE_NFD, UNICODE_NFKC, UNICODE_NFKD, } UnicodeNormalizationEnum; int lre_case_conv(uint32_t *res, uint32_t c, int conv_type); LRE_BOOL lre_is_cased(uint32_t c); LRE_BOOL lre_is_case_ignorable(uint32_t c); /* char ranges */ typedef struct { int len; /* in points, always even */ int size; uint32_t *points; /* points sorted by increasing value */ void *mem_opaque; void *(*realloc_func)(void *opaque, void *ptr, size_t size); } CharRange; typedef enum { CR_OP_UNION, CR_OP_INTER, CR_OP_XOR, } CharRangeOpEnum; void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); void cr_free(CharRange *cr); int cr_realloc(CharRange *cr, int size); int cr_copy(CharRange *cr, const CharRange *cr1); static inline int cr_add_point(CharRange *cr, uint32_t v) { if (cr->len >= cr->size) { if (cr_realloc(cr, cr->len + 1)) return -1; } cr->points[cr->len++] = v; return 0; } static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2) { if ((cr->len + 2) > cr->size) { if (cr_realloc(cr, cr->len + 2)) return -1; } cr->points[cr->len++] = c1; cr->points[cr->len++] = c2; return 0; } int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len); static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2) { uint32_t b_pt[2]; b_pt[0] = c1; b_pt[1] = c2 + 1; return cr_union1(cr, b_pt, 2); } int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, const uint32_t *b_pt, int b_len, int op); int cr_invert(CharRange *cr); #ifdef CONFIG_ALL_UNICODE LRE_BOOL lre_is_id_start(uint32_t c); LRE_BOOL lre_is_id_continue(uint32_t c); int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, UnicodeNormalizationEnum n_type, void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); /* Unicode character range functions */ int unicode_script(CharRange *cr, const char *script_name, LRE_BOOL is_ext); int unicode_general_category(CharRange *cr, const char *gc_name); int unicode_prop(CharRange *cr, const char *prop_name); #endif /* CONFIG_ALL_UNICODE */ #undef LRE_BOOL #endif /* LIBUNICODE_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/libunicode.h
C
apache-2.0
3,751
// // jquick_mutex.c // // Copyright (C) 2015-2021 Alibaba Group Holding Limited. // #include "linux_jquick_mutex.h" #include <stdio.h> #include <pthread.h> #include <stdlib.h> JQuick_Mutex jquick_mutex_create() { JQuick_Mutex mutex = (JQuick_Mutex)malloc(sizeof(pthread_mutex_t)); if (!mutex) { printf("JQuick_Mutex: out of memory\n"); return NULL; } int v = pthread_mutex_init((pthread_mutex_t*)mutex, NULL); if (0 == v) { return mutex; } printf("JQuick_Mutex: Init JQuick_Mutex failed\n"); free(mutex); return NULL; } int jquick_mutex_lock(JQuick_Mutex mutex) { if (!mutex) { printf("JQuick_Mutex: Mutex is NULL\n"); return -1; } return pthread_mutex_lock((pthread_mutex_t*)mutex); } int jquick_mutex_unlock(JQuick_Mutex mutex) { if (!mutex) { printf("JQuick_Mutex: Mutex is NULL\n"); return -1; } return pthread_mutex_unlock((pthread_mutex_t*)mutex); } int jquick_mutex_destroy(JQuick_Mutex mutex) { if (!mutex) { printf("JQuick_Mutex: Mutex is NULL\n"); return -1; } int v = pthread_mutex_destroy((pthread_mutex_t*)mutex); if (v == 0) { free(mutex); } return v; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/linux_jquick_mutex.c
C
apache-2.0
1,247
#ifndef __AOS_AMP_JQUICK_MUTEX_H__ #define __AOS_AMP_JQUICK_MUTEX_H__ #ifdef __cplusplus extern "C" { #endif typedef void* JQuick_Mutex; JQuick_Mutex jquick_mutex_create(); int jquick_mutex_lock( JQuick_Mutex m); int jquick_mutex_unlock( JQuick_Mutex m); int jquick_mutex_destroy( JQuick_Mutex m); #ifdef __cplusplus } #endif #endif // __QEMU_FREERTOS_JQUICK_MUTEX_H__
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/linux_jquick_mutex.h
C
apache-2.0
403
/* * Linux klist like system * * Copyright (c) 2016-2017 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef LIST_H #define LIST_H #ifndef NULL #include <stddef.h> #endif struct list_head { struct list_head *prev; struct list_head *next; }; #define LIST_HEAD_INIT(el) { &(el), &(el) } /* return the pointer of type 'type *' containing 'el' as field 'member' */ #define list_entry(el, type, member) \ ((type *)((uint8_t *)(el) - offsetof(type, member))) static inline void init_list_head(struct list_head *head) { head->prev = head; head->next = head; } /* insert 'el' between 'prev' and 'next' */ static inline void __list_add(struct list_head *el, struct list_head *prev, struct list_head *next) { prev->next = el; el->prev = prev; el->next = next; next->prev = el; } /* add 'el' at the head of the list 'head' (= after element head) */ static inline void list_add(struct list_head *el, struct list_head *head) { __list_add(el, head, head->next); } /* add 'el' at the end of the list 'head' (= before element head) */ static inline void list_add_tail(struct list_head *el, struct list_head *head) { __list_add(el, head->prev, head); } static inline void list_del(struct list_head *el) { struct list_head *prev, *next; if(el == NULL) { return; } prev = el->prev; next = el->next; if (prev != NULL) { prev->next = next; } if (next != NULL) { next->prev = prev; } el->prev = NULL; /* fail safe */ el->next = NULL; /* fail safe */ } static inline int list_empty(struct list_head *el) { return el->next == el; } #define list_for_each(el, head) \ for(el = (head)->next; el != (head); el = el->next) #define list_for_each_safe(el, el1, head) \ for(el = (head)->next, el1 = el->next; el != (head); \ el = el1, el1 = el->next) #define list_for_each_prev(el, head) \ for(el = (head)->prev; el != (head); el = el->prev) #define list_for_each_prev_safe(el, el1, head) \ for(el = (head)->prev, el1 = el->prev; el != (head); \ el = el1, el1 = el->prev) #endif /* LIST_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/list.h
C
apache-2.0
3,228
/* * QuickJS stand alone interpreter * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <time.h> #if defined(__APPLE__) #include <malloc/malloc.h> #elif defined(__linux__) #include <malloc.h> #endif #include "cutils.h" #include "quickjs-libc.h" extern const uint8_t qjsc_repl[]; extern const uint32_t qjsc_repl_size; #ifdef CONFIG_BIGNUM extern const uint8_t qjsc_qjscalc[]; extern const uint32_t qjsc_qjscalc_size; #endif static int eval_buf(JSContext *ctx, const void *buf, int buf_len, const char *filename, int eval_flags) { JSValue val; int ret; if ((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE) { /* for the modules, we compile then run to be able to set import.meta */ val = JS_Eval(ctx, buf, buf_len, filename, eval_flags | JS_EVAL_FLAG_COMPILE_ONLY); if (!JS_IsException(val)) { js_module_set_import_meta(ctx, val, TRUE, TRUE); val = JS_EvalFunction(ctx, val); } } else { val = JS_Eval(ctx, buf, buf_len, filename, eval_flags); } if (JS_IsException(val)) { js_std_dump_error(ctx); ret = -1; } else { ret = 0; } JS_FreeValue(ctx, val); return ret; } static int eval_file(JSContext *ctx, const char *filename, int module) { uint8_t *buf; int ret, eval_flags; size_t buf_len; buf = js_load_file(ctx, &buf_len, filename); if (!buf) { perror(filename); exit(1); } if (module < 0) { module = (has_suffix(filename, ".mjs") || JS_DetectModule((const char *)buf, buf_len)); } if (module) eval_flags = JS_EVAL_TYPE_MODULE; else eval_flags = JS_EVAL_TYPE_GLOBAL; ret = eval_buf(ctx, buf, buf_len, filename, eval_flags); js_free(ctx, buf); return ret; } #if defined(__APPLE__) #define MALLOC_OVERHEAD 0 #else #define MALLOC_OVERHEAD 8 #endif struct trace_malloc_data { uint8_t *base; }; static inline unsigned long long js_trace_malloc_ptr_offset(uint8_t *ptr, struct trace_malloc_data *dp) { return ptr - dp->base; } /* default memory allocation functions with memory limitation */ static inline size_t js_trace_malloc_usable_size(void *ptr) { #if defined(__APPLE__) return malloc_size(ptr); #elif defined(_WIN32) return _msize(ptr); #elif defined(EMSCRIPTEN) return 0; #elif defined(__linux__) return malloc_usable_size(ptr); #elif defined(__AOS_AMP__) return 0; #else /* change this to `return 0;` if compilation fails */ return malloc_usable_size(ptr); #endif } static void __attribute__((format(printf, 2, 3))) js_trace_malloc_printf(JSMallocState *s, const char *fmt, ...) { va_list ap; int c; va_start(ap, fmt); while ((c = *fmt++) != '\0') { if (c == '%') { /* only handle %p and %zd */ if (*fmt == 'p') { uint8_t *ptr = va_arg(ap, void *); if (ptr == NULL) { printf("NULL"); } else { printf("H%+06lld.%zd", js_trace_malloc_ptr_offset(ptr, s->opaque), js_trace_malloc_usable_size(ptr)); } fmt++; continue; } if (fmt[0] == 'z' && fmt[1] == 'd') { size_t sz = va_arg(ap, size_t); printf("%zd", sz); fmt += 2; continue; } } putc(c, stdout); } va_end(ap); } static void js_trace_malloc_init(struct trace_malloc_data *s) { free(s->base = malloc(8)); } static void *js_trace_malloc(JSMallocState *s, size_t size) { void *ptr; /* Do not allocate zero bytes: behavior is platform dependent */ assert(size != 0); if (unlikely(s->malloc_size + size > s->malloc_limit)) return NULL; ptr = malloc(size); js_trace_malloc_printf(s, "A %zd -> %p\n", size, ptr); if (ptr) { s->malloc_count++; s->malloc_size += js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD; } return ptr; } static void js_trace_free(JSMallocState *s, void *ptr) { if (!ptr) return; js_trace_malloc_printf(s, "F %p\n", ptr); s->malloc_count--; s->malloc_size -= js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD; free(ptr); } static void *js_trace_realloc(JSMallocState *s, void *ptr, size_t size) { size_t old_size; if (!ptr) { if (size == 0) return NULL; return js_trace_malloc(s, size); } old_size = js_trace_malloc_usable_size(ptr); if (size == 0) { js_trace_malloc_printf(s, "R %zd %p\n", size, ptr); s->malloc_count--; s->malloc_size -= old_size + MALLOC_OVERHEAD; free(ptr); return NULL; } if (s->malloc_size + size - old_size > s->malloc_limit) return NULL; js_trace_malloc_printf(s, "R %zd %p", size, ptr); ptr = realloc(ptr, size); js_trace_malloc_printf(s, " -> %p\n", ptr); if (ptr) { s->malloc_size += js_trace_malloc_usable_size(ptr) - old_size; } return ptr; } static const JSMallocFunctions trace_mf = { js_trace_malloc, js_trace_free, js_trace_realloc, #if defined(__APPLE__) malloc_size, #elif defined(_WIN32) (size_t (*)(const void *))_msize, #elif defined(EMSCRIPTEN) NULL, #elif defined(__linux__) (size_t (*)(const void *))malloc_usable_size, #elif defined(__ALIOS__) NULL, #else /* change this to `NULL,` if compilation fails */ malloc_usable_size, #endif }; #define PROG_NAME "qjs" void help(void) { printf("QuickJS version " CONFIG_VERSION "\n" "usage: " PROG_NAME " [options] [file [args]]\n" "-h --help list options\n" "-e --eval EXPR evaluate EXPR\n" "-i --interactive go to interactive mode\n" "-m --module load as ES6 module (default=autodetect)\n" " --script load as ES6 script (default=autodetect)\n" "-I --include file include an additional file\n" " --std make 'std' and 'os' available to the loaded script\n" #ifdef CONFIG_BIGNUM " --bignum enable the bignum extensions (BigFloat, BigDecimal)\n" " --qjscalc load the QJSCalc runtime (default if invoked as qjscalc)\n" #endif "-T --trace trace memory allocation\n" "-d --dump dump the memory usage stats\n" " --memory-limit n limit the memory usage to 'n' bytes\n" " --stack-size n limit the stack size to 'n' bytes\n" " --unhandled-rejection dump unhandled promise rejections\n" "-q --quit just instantiate the interpreter and quit\n"); exit(1); } int main(int argc, char **argv) { JSRuntime *rt; JSContext *ctx; struct trace_malloc_data trace_data = { NULL }; int optind; char *expr = NULL; int interactive = 0; int dump_memory = 0; int trace_memory = 0; int empty_run = 0; int module = -1; int load_std = 0; int dump_unhandled_promise_rejection = 0; size_t memory_limit = 0; char *include_list[32]; int i, include_count = 0; #ifdef CONFIG_BIGNUM int load_jscalc, bignum_ext = 0; #endif size_t stack_size = 0; #ifdef CONFIG_BIGNUM /* load jscalc runtime if invoked as 'qjscalc' */ { const char *p, *exename; exename = argv[0]; p = strrchr(exename, '/'); if (p) exename = p + 1; load_jscalc = !strcmp(exename, "qjscalc"); } #endif /* cannot use getopt because we want to pass the command line to the script */ optind = 1; while (optind < argc && *argv[optind] == '-') { char *arg = argv[optind] + 1; const char *longopt = ""; /* a single - is not an option, it also stops argument scanning */ if (!*arg) break; optind++; if (*arg == '-') { longopt = arg + 1; arg += strlen(arg); /* -- stops argument scanning */ if (!*longopt) break; } for (; *arg || *longopt; longopt = "") { char opt = *arg; if (opt) arg++; if (opt == 'h' || opt == '?' || !strcmp(longopt, "help")) { help(); continue; } if (opt == 'e' || !strcmp(longopt, "eval")) { if (*arg) { expr = arg; break; } if (optind < argc) { expr = argv[optind++]; break; } fprintf(stderr, "qjs: missing expression for -e\n"); exit(2); } if (opt == 'I' || !strcmp(longopt, "include")) { if (optind >= argc) { fprintf(stderr, "expecting filename"); exit(1); } if (include_count >= countof(include_list)) { fprintf(stderr, "too many included files"); exit(1); } include_list[include_count++] = argv[optind++]; continue; } if (opt == 'i' || !strcmp(longopt, "interactive")) { interactive++; continue; } if (opt == 'm' || !strcmp(longopt, "module")) { module = 1; continue; } if (!strcmp(longopt, "script")) { module = 0; continue; } if (opt == 'd' || !strcmp(longopt, "dump")) { dump_memory++; continue; } if (opt == 'T' || !strcmp(longopt, "trace")) { trace_memory++; continue; } if (!strcmp(longopt, "std")) { load_std = 1; continue; } if (!strcmp(longopt, "unhandled-rejection")) { dump_unhandled_promise_rejection = 1; continue; } #ifdef CONFIG_BIGNUM if (!strcmp(longopt, "bignum")) { bignum_ext = 1; continue; } if (!strcmp(longopt, "qjscalc")) { load_jscalc = 1; continue; } #endif if (opt == 'q' || !strcmp(longopt, "quit")) { empty_run++; continue; } if (!strcmp(longopt, "memory-limit")) { if (optind >= argc) { fprintf(stderr, "expecting memory limit"); exit(1); } memory_limit = (size_t)strtod(argv[optind++], NULL); continue; } if (!strcmp(longopt, "stack-size")) { if (optind >= argc) { fprintf(stderr, "expecting stack size"); exit(1); } stack_size = (size_t)strtod(argv[optind++], NULL); continue; } if (opt) { fprintf(stderr, "qjs: unknown option '-%c'\n", opt); } else { fprintf(stderr, "qjs: unknown option '--%s'\n", longopt); } help(); } } if (trace_memory) { js_trace_malloc_init(&trace_data); rt = JS_NewRuntime2(&trace_mf, &trace_data); } else { rt = JS_NewRuntime(); } if (!rt) { fprintf(stderr, "qjs: cannot allocate JS runtime\n"); exit(2); } if (memory_limit != 0) JS_SetMemoryLimit(rt, memory_limit); if (stack_size != 0) JS_SetMaxStackSize(rt, stack_size); js_std_init_handlers(rt); ctx = JS_NewContext(rt); if (!ctx) { fprintf(stderr, "qjs: cannot allocate JS context\n"); exit(2); } #ifdef CONFIG_BIGNUM if (bignum_ext || load_jscalc) { JS_AddIntrinsicBigFloat(ctx); JS_AddIntrinsicBigDecimal(ctx); JS_AddIntrinsicOperators(ctx); JS_EnableBignumExt(ctx, TRUE); } #endif /* loader for ES6 modules */ JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL); if (dump_unhandled_promise_rejection) { JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker, NULL); } if (!empty_run) { #ifdef CONFIG_BIGNUM if (load_jscalc) { js_std_eval_binary(ctx, qjsc_qjscalc, qjsc_qjscalc_size, 0); } #endif js_std_add_helpers(ctx, argc - optind, argv + optind); /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); /* make 'std' and 'os' visible to non module code */ if (load_std) { const char *str = "import * as std from 'std';\n" "import * as os from 'os';\n" "globalThis.std = std;\n" "globalThis.os = os;\n"; eval_buf(ctx, str, strlen(str), "<input>", JS_EVAL_TYPE_MODULE); } for(i = 0; i < include_count; i++) { if (eval_file(ctx, include_list[i], module)) goto fail; } if (expr) { if (eval_buf(ctx, expr, strlen(expr), "<cmdline>", 0)) goto fail; } else if (optind >= argc) { /* interactive mode */ interactive = 1; } else { const char *filename; filename = argv[optind]; if (eval_file(ctx, filename, module)) goto fail; } if (interactive) { js_std_eval_binary(ctx, qjsc_repl, qjsc_repl_size, 0); } js_std_loop(ctx); } if (dump_memory) { JSMemoryUsage stats; JS_ComputeMemoryUsage(rt, &stats); JS_DumpMemoryUsage(stdout, &stats, rt); } js_std_free_handlers(rt); JS_FreeContext(ctx); JS_FreeRuntime(rt); if (empty_run && dump_memory) { clock_t t[5]; double best[5]; int i, j; for (i = 0; i < 100; i++) { t[0] = clock(); rt = JS_NewRuntime(); t[1] = clock(); ctx = JS_NewContext(rt); t[2] = clock(); JS_FreeContext(ctx); t[3] = clock(); JS_FreeRuntime(rt); t[4] = clock(); for (j = 4; j > 0; j--) { double ms = 1000.0 * (t[j] - t[j - 1]) / CLOCKS_PER_SEC; if (i == 0 || best[j] > ms) best[j] = ms; } } printf("\nInstantiation times (ms): %.3f = %.3f+%.3f+%.3f+%.3f\n", best[1] + best[2] + best[3] + best[4], best[1], best[2], best[3], best[4]); } return 0; fail: js_std_free_handlers(rt); JS_FreeContext(ctx); JS_FreeRuntime(rt); return 1; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/qjs.c
C
apache-2.0
16,502
/* * QuickJS command line compiler * * Copyright (c) 2018-2020 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <errno.h> #if !defined(_WIN32) #include <sys/wait.h> #endif #include "cutils.h" #include "quickjs-libc.h" typedef struct { char *name; char *short_name; int flags; } namelist_entry_t; typedef struct namelist_t { namelist_entry_t *array; int count; int size; } namelist_t; typedef struct { const char *option_name; const char *init_name; } FeatureEntry; static namelist_t cname_list; static namelist_t cmodule_list; static namelist_t init_module_list; static uint64_t feature_bitmap; static FILE *outfile; static BOOL byte_swap; static BOOL dynamic_export; static const char *c_ident_prefix = "qjsc_"; #define FE_ALL (-1) static const FeatureEntry feature_list[] = { { "date", "Date" }, { "eval", "Eval" }, { "string-normalize", "StringNormalize" }, { "regexp", "RegExp" }, { "json", "JSON" }, { "proxy", "Proxy" }, { "map", "MapSet" }, { "typedarray", "TypedArrays" }, { "promise", "Promise" }, #define FE_MODULE_LOADER 9 { "module-loader", NULL }, #ifdef CONFIG_BIGNUM { "bigint", "BigInt" }, #endif }; void namelist_add(namelist_t *lp, const char *name, const char *short_name, int flags) { namelist_entry_t *e; if (lp->count == lp->size) { size_t newsize = lp->size + (lp->size >> 1) + 4; namelist_entry_t *a = realloc(lp->array, sizeof(lp->array[0]) * newsize); /* XXX: check for realloc failure */ lp->array = a; lp->size = newsize; } e = &lp->array[lp->count++]; e->name = strdup(name); if (short_name) e->short_name = strdup(short_name); else e->short_name = NULL; e->flags = flags; } void namelist_free(namelist_t *lp) { while (lp->count > 0) { namelist_entry_t *e = &lp->array[--lp->count]; free(e->name); free(e->short_name); } free(lp->array); lp->array = NULL; lp->size = 0; } namelist_entry_t *namelist_find(namelist_t *lp, const char *name) { int i; for(i = 0; i < lp->count; i++) { namelist_entry_t *e = &lp->array[i]; if (!strcmp(e->name, name)) return e; } return NULL; } static void get_c_name(char *buf, size_t buf_size, const char *file) { const char *p, *r; size_t len, i; int c; char *q; p = strrchr(file, '/'); if (!p) p = file; else p++; r = strrchr(p, '.'); if (!r) len = strlen(p); else len = r - p; pstrcpy(buf, buf_size, c_ident_prefix); q = buf + strlen(buf); for(i = 0; i < len; i++) { c = p[i]; if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) { c = '_'; } if ((q - buf) < buf_size - 1) *q++ = c; } *q = '\0'; } static void dump_hex(FILE *f, const uint8_t *buf, size_t len) { size_t i, col; col = 0; for(i = 0; i < len; i++) { fprintf(f, " 0x%02x,", buf[i]); if (++col == 8) { fprintf(f, "\n"); col = 0; } } if (col != 0) fprintf(f, "\n"); } static void output_object_code(JSContext *ctx, FILE *fo, JSValueConst obj, const char *c_name, BOOL load_only) { uint8_t *out_buf; size_t out_buf_len; int flags; flags = JS_WRITE_OBJ_BYTECODE; if (byte_swap) flags |= JS_WRITE_OBJ_BSWAP; out_buf = JS_WriteObject(ctx, &out_buf_len, obj, flags); if (!out_buf) { js_std_dump_error(ctx); exit(1); } namelist_add(&cname_list, c_name, NULL, load_only); fprintf(fo, "const uint32_t %s_size = %u;\n\n", c_name, (unsigned int)out_buf_len); fprintf(fo, "const uint8_t %s[%u] = {\n", c_name, (unsigned int)out_buf_len); dump_hex(fo, out_buf, out_buf_len); fprintf(fo, "};\n\n"); js_free(ctx, out_buf); } static int js_module_dummy_init(JSContext *ctx, JSModuleDef *m) { /* should never be called when compiling JS code */ abort(); } static void find_unique_cname(char *cname, size_t cname_size) { char cname1[1024]; int suffix_num; size_t len, max_len; assert(cname_size >= 32); /* find a C name not matching an existing module C name by adding a numeric suffix */ len = strlen(cname); max_len = cname_size - 16; if (len > max_len) cname[max_len] = '\0'; suffix_num = 1; for(;;) { snprintf(cname1, sizeof(cname1), "%s_%d", cname, suffix_num); if (!namelist_find(&cname_list, cname1)) break; suffix_num++; } pstrcpy(cname, cname_size, cname1); } JSModuleDef *jsc_module_loader(JSContext *ctx, const char *module_name, void *opaque) { JSModuleDef *m; namelist_entry_t *e; /* check if it is a declared C or system module */ e = namelist_find(&cmodule_list, module_name); if (e) { /* add in the static init module list */ namelist_add(&init_module_list, e->name, e->short_name, 0); /* create a dummy module */ m = JS_NewCModule(ctx, module_name, js_module_dummy_init); } else if (has_suffix(module_name, ".so")) { fprintf(stderr, "Warning: binary module '%s' will be dynamically loaded\n", module_name); /* create a dummy module */ m = JS_NewCModule(ctx, module_name, js_module_dummy_init); /* the resulting executable will export its symbols for the dynamic library */ dynamic_export = TRUE; } else { size_t buf_len; uint8_t *buf; JSValue func_val; char cname[1024]; buf = js_load_file(ctx, &buf_len, module_name); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (JS_IsException(func_val)) return NULL; get_c_name(cname, sizeof(cname), module_name); if (namelist_find(&cname_list, cname)) { find_unique_cname(cname, sizeof(cname)); } output_object_code(ctx, outfile, func_val, cname, TRUE); /* the module is already referenced, so we must free it */ m = JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); } return m; } static void compile_file(JSContext *ctx, FILE *fo, const char *filename, const char *c_name1, int module) { uint8_t *buf; char c_name[1024]; int eval_flags; JSValue obj; size_t buf_len; buf = js_load_file(ctx, &buf_len, filename); if (!buf) { fprintf(stderr, "Could not load '%s'\n", filename); exit(1); } eval_flags = JS_EVAL_FLAG_COMPILE_ONLY; if (module < 0) { module = (has_suffix(filename, ".mjs") || JS_DetectModule((const char *)buf, buf_len)); } if (module) eval_flags |= JS_EVAL_TYPE_MODULE; else eval_flags |= JS_EVAL_TYPE_GLOBAL; obj = JS_Eval(ctx, (const char *)buf, buf_len, filename, eval_flags); if (JS_IsException(obj)) { js_std_dump_error(ctx); exit(1); } js_free(ctx, buf); if (c_name1) { pstrcpy(c_name, sizeof(c_name), c_name1); } else { get_c_name(c_name, sizeof(c_name), filename); } output_object_code(ctx, fo, obj, c_name, FALSE); JS_FreeValue(ctx, obj); } static const char main_c_template1[] = "int main(int argc, char **argv)\n" "{\n" " JSRuntime *rt;\n" " JSContext *ctx;\n" " rt = JS_NewRuntime();\n" " js_std_init_handlers(rt);\n" ; static const char main_c_template2[] = " js_std_loop(ctx);\n" " JS_FreeContext(ctx);\n" " JS_FreeRuntime(rt);\n" " return 0;\n" "}\n"; #define PROG_NAME "qjsc" void help(void) { printf("QuickJS Compiler version " CONFIG_VERSION "\n" "usage: " PROG_NAME " [options] [files]\n" "\n" "options are:\n" "-c only output bytecode in a C file\n" "-e output main() and bytecode in a C file (default = executable output)\n" "-o output set the output filename\n" "-N cname set the C name of the generated data\n" "-m compile as Javascript module (default=autodetect)\n" "-M module_name[,cname] add initialization code for an external C module\n" "-x byte swapped output\n" "-p prefix set the prefix of the generated C names\n" "-S n set the maximum stack size to 'n' bytes (default=%d)\n", JS_DEFAULT_STACK_SIZE); #ifdef CONFIG_LTO { int i; printf("-flto use link time optimization\n"); printf("-fbignum enable bignum extensions\n"); printf("-fno-["); for(i = 0; i < countof(feature_list); i++) { if (i != 0) printf("|"); printf("%s", feature_list[i].option_name); } printf("]\n" " disable selected language features (smaller code size)\n"); } #endif exit(1); } #if defined(CONFIG_CC) && !defined(_WIN32) int exec_cmd(char **argv) { int pid, status, ret; pid = fork(); if (pid == 0) { execvp(argv[0], argv); exit(1); } for(;;) { ret = waitpid(pid, &status, 0); if (ret == pid && WIFEXITED(status)) break; } return WEXITSTATUS(status); } static int output_executable(const char *out_filename, const char *cfilename, BOOL use_lto, BOOL verbose, const char *exename) { const char *argv[64]; const char **arg, *bn_suffix, *lto_suffix; char libjsname[1024]; char exe_dir[1024], inc_dir[1024], lib_dir[1024], buf[1024], *p; int ret; /* get the directory of the executable */ pstrcpy(exe_dir, sizeof(exe_dir), exename); p = strrchr(exe_dir, '/'); if (p) { *p = '\0'; } else { pstrcpy(exe_dir, sizeof(exe_dir), "."); } /* if 'quickjs.h' is present at the same path as the executable, we use it as include and lib directory */ snprintf(buf, sizeof(buf), "%s/quickjs.h", exe_dir); if (access(buf, R_OK) == 0) { pstrcpy(inc_dir, sizeof(inc_dir), exe_dir); pstrcpy(lib_dir, sizeof(lib_dir), exe_dir); } else { snprintf(inc_dir, sizeof(inc_dir), "%s/include/quickjs", CONFIG_PREFIX); snprintf(lib_dir, sizeof(lib_dir), "%s/lib/quickjs", CONFIG_PREFIX); } lto_suffix = ""; bn_suffix = ""; arg = argv; *arg++ = CONFIG_CC; *arg++ = "-O2"; #ifdef CONFIG_LTO if (use_lto) { *arg++ = "-flto"; lto_suffix = ".lto"; } #endif /* XXX: use the executable path to find the includes files and libraries */ *arg++ = "-D"; *arg++ = "_GNU_SOURCE"; *arg++ = "-I"; *arg++ = inc_dir; *arg++ = "-o"; *arg++ = out_filename; if (dynamic_export) *arg++ = "-rdynamic"; *arg++ = cfilename; snprintf(libjsname, sizeof(libjsname), "%s/libquickjs%s%s.a", lib_dir, bn_suffix, lto_suffix); *arg++ = libjsname; *arg++ = "-lm"; *arg++ = "-ldl"; *arg++ = "-lpthread"; *arg = NULL; if (verbose) { for(arg = argv; *arg != NULL; arg++) printf("%s ", *arg); printf("\n"); } ret = exec_cmd((char **)argv); unlink(cfilename); return ret; } #else static int output_executable(const char *out_filename, const char *cfilename, BOOL use_lto, BOOL verbose, const char *exename) { fprintf(stderr, "Executable output is not supported for this target\n"); exit(1); return 0; } #endif typedef enum { OUTPUT_C, OUTPUT_C_MAIN, OUTPUT_EXECUTABLE, } OutputTypeEnum; int main(int argc, char **argv) { int c, i, verbose; const char *out_filename, *cname; char cfilename[1024]; FILE *fo; JSRuntime *rt; JSContext *ctx; BOOL use_lto; int module; OutputTypeEnum output_type; size_t stack_size; #ifdef CONFIG_BIGNUM BOOL bignum_ext = FALSE; #endif out_filename = NULL; output_type = OUTPUT_EXECUTABLE; cname = NULL; feature_bitmap = FE_ALL; module = -1; byte_swap = FALSE; verbose = 0; use_lto = FALSE; stack_size = 0; /* add system modules */ namelist_add(&cmodule_list, "std", "std", 0); namelist_add(&cmodule_list, "os", "os", 0); for(;;) { c = getopt(argc, argv, "ho:cN:f:mxevM:p:S:"); if (c == -1) break; switch(c) { case 'h': help(); case 'o': out_filename = optarg; break; case 'c': output_type = OUTPUT_C; break; case 'e': output_type = OUTPUT_C_MAIN; break; case 'N': cname = optarg; break; case 'f': { const char *p; p = optarg; if (!strcmp(optarg, "lto")) { use_lto = TRUE; } else if (strstart(p, "no-", &p)) { use_lto = TRUE; for(i = 0; i < countof(feature_list); i++) { if (!strcmp(p, feature_list[i].option_name)) { feature_bitmap &= ~((uint64_t)1 << i); break; } } if (i == countof(feature_list)) goto bad_feature; } else #ifdef CONFIG_BIGNUM if (!strcmp(optarg, "bignum")) { bignum_ext = TRUE; } else #endif { bad_feature: fprintf(stderr, "unsupported feature: %s\n", optarg); exit(1); } } break; case 'm': module = 1; break; case 'M': { char *p; char path[1024]; char cname[1024]; pstrcpy(path, sizeof(path), optarg); p = strchr(path, ','); if (p) { *p = '\0'; pstrcpy(cname, sizeof(cname), p + 1); } else { get_c_name(cname, sizeof(cname), path); } namelist_add(&cmodule_list, path, cname, 0); } break; case 'x': byte_swap = TRUE; break; case 'v': verbose++; break; case 'p': c_ident_prefix = optarg; break; case 'S': stack_size = (size_t)strtod(optarg, NULL); break; default: break; } } if (optind >= argc) help(); if (!out_filename) { if (output_type == OUTPUT_EXECUTABLE) { out_filename = "a.out"; } else { out_filename = "out.c"; } } if (output_type == OUTPUT_EXECUTABLE) { #if defined(_WIN32) || defined(__ANDROID__) /* XXX: find a /tmp directory ? */ snprintf(cfilename, sizeof(cfilename), "out%d.c", getpid()); #else snprintf(cfilename, sizeof(cfilename), "/tmp/out%d.c", getpid()); #endif } else { pstrcpy(cfilename, sizeof(cfilename), out_filename); } fo = fopen(cfilename, "w"); if (!fo) { perror(cfilename); exit(1); } outfile = fo; rt = JS_NewRuntime(); ctx = JS_NewContext(rt); #ifdef CONFIG_BIGNUM if (bignum_ext) { JS_AddIntrinsicBigFloat(ctx); JS_AddIntrinsicBigDecimal(ctx); JS_AddIntrinsicOperators(ctx); JS_EnableBignumExt(ctx, TRUE); } #endif /* loader for ES6 modules */ JS_SetModuleLoaderFunc(rt, NULL, jsc_module_loader, NULL); fprintf(fo, "/* File generated automatically by the QuickJS compiler. */\n" "\n" ); if (output_type != OUTPUT_C) { fprintf(fo, "#include \"quickjs-libc.h\"\n" "\n" ); } else { fprintf(fo, "#include <inttypes.h>\n" "\n" ); } for(i = optind; i < argc; i++) { const char *filename = argv[i]; compile_file(ctx, fo, filename, cname, module); cname = NULL; } if (output_type != OUTPUT_C) { fputs(main_c_template1, fo); fprintf(fo, " ctx = JS_NewContextRaw(rt);\n"); if (stack_size != 0) { fprintf(fo, " JS_SetMaxStackSize(rt, %u);\n", (unsigned int)stack_size); } /* add the module loader if necessary */ if (feature_bitmap & (1 << FE_MODULE_LOADER)) { fprintf(fo, " JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\n"); } /* add the basic objects */ fprintf(fo, " JS_AddIntrinsicBaseObjects(ctx);\n"); for(i = 0; i < countof(feature_list); i++) { if ((feature_bitmap & ((uint64_t)1 << i)) && feature_list[i].init_name) { fprintf(fo, " JS_AddIntrinsic%s(ctx);\n", feature_list[i].init_name); } } #ifdef CONFIG_BIGNUM if (bignum_ext) { fprintf(fo, " JS_AddIntrinsicBigFloat(ctx);\n" " JS_AddIntrinsicBigDecimal(ctx);\n" " JS_AddIntrinsicOperators(ctx);\n" " JS_EnableBignumExt(ctx, 1);\n"); } #endif fprintf(fo, " js_std_add_helpers(ctx, argc, argv);\n"); for(i = 0; i < init_module_list.count; i++) { namelist_entry_t *e = &init_module_list.array[i]; /* initialize the static C modules */ fprintf(fo, " {\n" " extern JSModuleDef *js_init_module_%s(JSContext *ctx, const char *name);\n" " js_init_module_%s(ctx, \"%s\");\n" " }\n", e->short_name, e->short_name, e->name); } for(i = 0; i < cname_list.count; i++) { namelist_entry_t *e = &cname_list.array[i]; fprintf(fo, " js_std_eval_binary(ctx, %s, %s_size, %s);\n", e->name, e->name, e->flags ? "1" : "0"); } fputs(main_c_template2, fo); } JS_FreeContext(ctx); JS_FreeRuntime(rt); fclose(fo); if (output_type == OUTPUT_EXECUTABLE) { return output_executable(out_filename, cfilename, use_lto, verbose, argv[0]); } namelist_free(&cname_list); namelist_free(&cmodule_list); namelist_free(&init_module_list); return 0; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/qjsc.c
C
apache-2.0
20,655
/* * QuickJS Javascript Calculator * * Copyright (c) 2017-2020 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ "use strict"; "use math"; var Integer, Float, Fraction, Complex, Mod, Polynomial, PolyMod, RationalFunction, Series, Matrix; (function(global) { global.Integer = global.BigInt; global.Float = global.BigFloat; global.algebraicMode = true; /* add non enumerable properties */ function add_props(obj, props) { var i, val, prop, tab, desc; tab = Reflect.ownKeys(props); for(i = 0; i < tab.length; i++) { prop = tab[i]; desc = Object.getOwnPropertyDescriptor(props, prop); desc.enumerable = false; if ("value" in desc) { if (typeof desc.value !== "function") { desc.writable = false; desc.configurable = false; } } else { /* getter/setter */ desc.configurable = false; } Object.defineProperty(obj, prop, desc); } } /* same as proto[Symbol.operatorSet] = Operators.create(..op_list) but allow shortcuts: left: [], right: [] or both */ function operators_set(proto, ...op_list) { var new_op_list, i, a, j, b, k, obj, tab; var fields = [ "left", "right" ]; new_op_list = []; for(i = 0; i < op_list.length; i++) { a = op_list[i]; if (a.left || a.right) { tab = [ a.left, a.right ]; delete a.left; delete a.right; for(k = 0; k < 2; k++) { obj = tab[k]; if (obj) { if (!Array.isArray(obj)) { obj = [ obj ]; } for(j = 0; j < obj.length; j++) { b = {}; Object.assign(b, a); b[fields[k]] = obj[j]; new_op_list.push(b); } } } } else { new_op_list.push(a); } } proto[Symbol.operatorSet] = Operators.create.call(null, ...new_op_list); } /* Integer */ function generic_pow(a, b) { var r, is_neg, i; if (!Integer.isInteger(b)) { return exp(log(a) * b); } if (Array.isArray(a) && !(a instanceof Polynomial || a instanceof Series)) { r = idn(Matrix.check_square(a)); } else { r = 1; } if (b == 0) return r; is_neg = false; if (b < 0) { is_neg = true; b = -b; } r = a; for(i = Integer.floorLog2(b) - 1; i >= 0; i--) { r *= r; if ((b >> i) & 1) r *= a; } if (is_neg) { if (typeof r.inverse != "function") throw "negative powers are not supported for this type"; r = r.inverse(); } return r; } var small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499 ]; function miller_rabin_test(n, t) { var d, r, s, i, j, a; d = n - 1; s = 0; while ((d & 1) == 0) { d >>= 1; s++; } if (small_primes.length < t) t = small_primes.length; loop: for(j = 0; j < t; j++) { a = small_primes[j]; r = Integer.pmod(a, d, n); if (r == 1 || r == (n - 1)) continue; for(i = 1; i < s; i++) { r = (r * r) % n; if (r == 1) return false; if (r == (n - 1)) continue loop; } return false; /* n is composite */ } return true; /* n is probably prime with probability (1-0.5^t) */ } function fact_rec(a, b) { /* assumes a <= b */ var i, r; if ((b - a) <= 5) { r = a; for(i = a + 1; i <= b; i++) r *= i; return r; } else { /* to avoid a quadratic running time it is better to multiply numbers of similar size */ i = (a + b) >> 1; return fact_rec(a, i) * fact_rec(i + 1, b); } } /* math mode specific quirk to overload the integer division and power */ Operators.updateBigIntOperators( { "/"(a, b) { if (algebraicMode) { return Fraction.toFraction(a, b); } else { return Float(a) / Float(b); } }, "**"(a, b) { if (algebraicMode) { return generic_pow(a, b); } else { return Float(a) ** Float(b); } } }); add_props(Integer, { isInteger(a) { /* integers are represented either as bigint or as number */ return typeof a === "bigint" || (typeof a === "number" && Number.isSafeInteger(a)); }, gcd(a, b) { var r; while (b != 0) { r = a % b; a = b; b = r; } return a; }, fact(n) { return n <= 0 ? 1 : fact_rec(1, n); }, /* binomial coefficient */ comb(n, k) { if (k < 0 || k > n) return 0; if (k > n - k) k = n - k; if (k == 0) return 1; return Integer.tdiv(fact_rec(n - k + 1, n), fact_rec(1, k)); }, /* inverse of x modulo y */ invmod(x, y) { var q, u, v, a, c, t; u = x; v = y; c = 1; a = 0; while (u != 0) { t = Integer.fdivrem(v, u); q = t[0]; v = u; u = t[1]; t = c; c = a - q * c; a = t; } /* v = gcd(x, y) */ if (v != 1) throw RangeError("not invertible"); return a % y; }, /* return a ^ b modulo m */ pmod(a, b, m) { var r; if (b == 0) return 1; if (b < 0) { a = Integer.invmod(a, m); b = -b; } r = 1; for(;;) { if (b & 1) { r = (r * a) % m; } b >>= 1; if (b == 0) break; a = (a * a) % m; } return r; }, /* return true if n is prime (or probably prime with probability 1-0.5^t) */ isPrime(n, t) { var i, d, n1; if (!Integer.isInteger(n)) throw TypeError("invalid type"); if (n <= 1) return false; n1 = small_primes.length; /* XXX: need Integer.sqrt() */ for(i = 0; i < n1; i++) { d = small_primes[i]; if (d == n) return true; if (d > n) return false; if ((n % d) == 0) return false; } if (n < d * d) return true; if (typeof t == "undefined") t = 64; return miller_rabin_test(n, t); }, nextPrime(n) { if (!Integer.isInteger(n)) throw TypeError("invalid type"); if (n < 1) n = 1; for(;;) { n++; if (Integer.isPrime(n)) return n; } }, factor(n) { var r, d; if (!Integer.isInteger(n)) throw TypeError("invalid type"); r = []; if (abs(n) <= 1) { r.push(n); return r; } if (n < 0) { r.push(-1); n = -n; } while ((n % 2) == 0) { n >>= 1; r.push(2); } d = 3; while (n != 1) { if (Integer.isPrime(n)) { r.push(n); break; } /* we are sure there is at least one divisor, so one test */ for(;;) { if ((n % d) == 0) break; d += 2; } for(;;) { r.push(d); n = Integer.tdiv(n, d); if ((n % d) != 0) break; } } return r; }, }); add_props(Integer.prototype, { inverse() { return 1 / this; }, norm2() { return this * this; }, abs() { var v = this; if (v < 0) v = -v; return v; }, conj() { return this; }, arg() { if (this >= 0) return 0; else return Float.PI; }, exp() { if (this == 0) return 1; else return Float.exp(this); }, log() { if (this == 1) return 0; else return Float(this).log(); }, }); /* Fraction */ Fraction = function Fraction(a, b) { var d, r, obj; if (new.target) throw TypeError("not a constructor"); if (a instanceof Fraction) return a; if (!Integer.isInteger(a)) throw TypeError("integer expected"); if (typeof b === "undefined") { b = 1; } else { if (!Integer.isInteger(b)) throw TypeError("integer expected"); if (b == 0) throw RangeError("division by zero"); d = Integer.gcd(a, b); if (d != 1) { a = Integer.tdiv(a, d); b = Integer.tdiv(b, d); } /* the fractions are normalized with den > 0 */ if (b < 0) { a = -a; b = -b; } } obj = Object.create(Fraction.prototype); obj.num = a; obj.den = b; return obj; } function fraction_add(a, b) { a = Fraction(a); b = Fraction(b); return Fraction.toFraction(a.num * b.den + a.den * b.num, a.den * b.den); } function fraction_sub(a, b) { a = Fraction(a); b = Fraction(b); return Fraction.toFraction(a.num * b.den - a.den * b.num, a.den * b.den); } function fraction_mul(a, b) { a = Fraction(a); b = Fraction(b); return Fraction.toFraction(a.num * b.num, a.den * b.den); } function fraction_div(a, b) { a = Fraction(a); b = Fraction(b); return Fraction.toFraction(a.num * b.den, a.den * b.num); } function fraction_mod(a, b) { var a1 = Fraction(a); var b1 = Fraction(b); return a - Integer.ediv(a1.num * b1.den, a1.den * b1.num) * b; } function fraction_eq(a, b) { a = Fraction(a); b = Fraction(b); /* we assume the fractions are normalized */ return (a.num == b.num && a.den == b.den); } function fraction_lt(a, b) { a = Fraction(a); b = Fraction(b); return (a.num * b.den < b.num * a.den); } /* operators are needed for fractions */ function float_add(a, b) { return Float(a) + Float(b); } function float_sub(a, b) { return Float(a) - Float(b); } function float_mul(a, b) { return Float(a) * Float(b); } function float_div(a, b) { return Float(a) / Float(b); } function float_mod(a, b) { return Float(a) % Float(b); } function float_pow(a, b) { return Float(a) ** Float(b); } function float_eq(a, b) { /* XXX: may be better to use infinite precision for the comparison */ return Float(a) === Float(b); } function float_lt(a, b) { a = Float(a); b = Float(b); /* XXX: may be better to use infinite precision for the comparison */ if (Float.isNaN(a) || Float.isNaN(b)) return undefined; else return a < b; } operators_set(Fraction.prototype, { "+": fraction_add, "-": fraction_sub, "*": fraction_mul, "/": fraction_div, "%": fraction_mod, "**": generic_pow, "==": fraction_eq, "<": fraction_lt, "pos"(a) { return a; }, "neg"(a) { return Fraction(-a.num, a.den); }, }, { left: [Number, BigInt], right: [Number, BigInt], "+": fraction_add, "-": fraction_sub, "*": fraction_mul, "/": fraction_div, "%": fraction_mod, "**": generic_pow, "==": fraction_eq, "<": fraction_lt, }, { left: Float, right: Float, "+": float_add, "-": float_sub, "*": float_mul, "/": float_div, "%": float_mod, "**": float_pow, "==": float_eq, "<": float_lt, }); add_props(Fraction, { /* (internal use) simplify 'a' to an integer when possible */ toFraction(a, b) { var r = Fraction(a, b); if (algebraicMode && r.den == 1) return r.num; else return r; }, }); add_props(Fraction.prototype, { [Symbol.toPrimitive](hint) { if (hint === "string") { return this.toString(); } else { return Float(this.num) / this.den; } }, inverse() { return Fraction(this.den, this.num); }, toString() { return this.num + "/" + this.den; }, norm2() { return this * this; }, abs() { if (this.num < 0) return -this; else return this; }, conj() { return this; }, arg() { if (this.num >= 0) return 0; else return Float.PI; }, exp() { return Float.exp(Float(this)); }, log() { return Float(this).log(); }, }); /* Number (Float64) */ add_props(Number.prototype, { inverse() { return 1 / this; }, norm2() { return this * this; }, abs() { return Math.abs(this); }, conj() { return this; }, arg() { if (this >= 0) return 0; else return Float.PI; }, exp() { return Float.exp(this); }, log() { if (this < 0) { return Complex(this).log(); } else { return Float.log(this); } }, }); /* Float */ var const_tab = []; /* we cache the constants for small precisions */ function get_const(n) { var t, c, p; t = const_tab[n]; p = BigFloatEnv.prec; if (t && t.prec == p) { return t.val; } else { switch(n) { case 0: c = Float.exp(1); break; case 1: c = Float.log(10); break; // case 2: c = Float.log(2); break; case 3: c = 1/Float.log(2); break; case 4: c = 1/Float.log(10); break; // case 5: c = Float.atan(1) * 4; break; case 6: c = Float.sqrt(0.5); break; case 7: c = Float.sqrt(2); break; } if (p <= 1024) { const_tab[n] = { prec: p, val: c }; } return c; } } add_props(Float, { isFloat(a) { return typeof a === "number" || typeof a === "bigfloat"; }, bestappr(u, b) { var num1, num0, den1, den0, u, num, den, n; if (typeof b === "undefined") throw TypeError("second argument expected"); num1 = 1; num0 = 0; den1 = 0; den0 = 1; for(;;) { n = Integer(Float.floor(u)); num = n * num1 + num0; den = n * den1 + den0; if (den > b) break; u = 1.0 / (u - n); num0 = num1; num1 = num; den0 = den1; den1 = den; } return Fraction(num1, den1); }, /* similar constants as Math.x */ get E() { return get_const(0); }, get LN10() { return get_const(1); }, // get LN2() { return get_const(2); }, get LOG2E() { return get_const(3); }, get LOG10E() { return get_const(4); }, // get PI() { return get_const(5); }, get SQRT1_2() { return get_const(6); }, get SQRT2() { return get_const(7); }, }); add_props(Float.prototype, { inverse() { return 1.0 / this; }, norm2() { return this * this; }, abs() { return Float.abs(this); }, conj() { return this; }, arg() { if (this >= 0) return 0; else return Float.PI; }, exp() { return Float.exp(this); }, log() { if (this < 0) { return Complex(this).log(); } else { return Float.log(this); } }, }); /* Complex */ Complex = function Complex(re, im) { var obj; if (new.target) throw TypeError("not a constructor"); if (re instanceof Complex) return re; if (typeof im === "undefined") { im = 0; } obj = Object.create(Complex.prototype); obj.re = re; obj.im = im; return obj; } function complex_add(a, b) { a = Complex(a); b = Complex(b); return Complex.toComplex(a.re + b.re, a.im + b.im); } function complex_sub(a, b) { a = Complex(a); b = Complex(b); return Complex.toComplex(a.re - b.re, a.im - b.im); } function complex_mul(a, b) { a = Complex(a); b = Complex(b); return Complex.toComplex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re); } function complex_div(a, b) { a = Complex(a); b = Complex(b); return a * b.inverse(); } function complex_eq(a, b) { a = Complex(a); b = Complex(b); return a.re == b.re && a.im == b.im; } operators_set(Complex.prototype, { "+": complex_add, "-": complex_sub, "*": complex_mul, "/": complex_div, "**": generic_pow, "==": complex_eq, "pos"(a) { return a; }, "neg"(a) { return Complex(-a.re, -a.im); } }, { left: [Number, BigInt, Float, Fraction], right: [Number, BigInt, Float, Fraction], "+": complex_add, "-": complex_sub, "*": complex_mul, "/": complex_div, "**": generic_pow, "==": complex_eq, }); add_props(Complex, { /* simplify to real number when possible */ toComplex(re, im) { if (algebraicMode && im == 0) return re; else return Complex(re, im); }, }); add_props(Complex.prototype, { inverse() { var c = this.norm2(); return Complex(this.re / c, -this.im / c); }, toString() { var v, s = "", a = this; if (a.re != 0) s += a.re.toString(); if (a.im == 1) { if (s != "") s += "+"; s += "I"; } else if (a.im == -1) { s += "-I"; } else { v = a.im.toString(); if (v[0] != "-" && s != "") s += "+"; s += v + "*I"; } return s; }, norm2() { return this.re * this.re + this.im * this.im; }, abs() { return Float.sqrt(norm2(this)); }, conj() { return Complex(this.re, -this.im); }, arg() { return Float.atan2(this.im, this.re); }, exp() { var arg = this.im, r = this.re.exp(); return Complex(r * cos(arg), r * sin(arg)); }, log() { return Complex(abs(this).log(), atan2(this.im, this.re)); }, }); /* Mod */ Mod = function Mod(a, m) { var obj, t; if (new.target) throw TypeError("not a constructor"); obj = Object.create(Mod.prototype); if (Integer.isInteger(m)) { if (m <= 0) throw RangeError("the modulo cannot be <= 0"); if (Integer.isInteger(a)) { a %= m; } else if (a instanceof Fraction) { return Mod(a.num, m) / a.den; } else { throw TypeError("invalid types"); } } else { throw TypeError("invalid types"); } obj.res = a; obj.mod = m; return obj; }; function mod_add(a, b) { if (!(a instanceof Mod)) { return Mod(a + b.res, b.mod); } else if (!(b instanceof Mod)) { return Mod(a.res + b, a.mod); } else { if (a.mod != b.mod) throw TypeError("different modulo for binary operator"); return Mod(a.res + b.res, a.mod); } } function mod_sub(a, b) { if (!(a instanceof Mod)) { return Mod(a - b.res, b.mod); } else if (!(b instanceof Mod)) { return Mod(a.res - b, a.mod); } else { if (a.mod != b.mod) throw TypeError("different modulo for binary operator"); return Mod(a.res - b.res, a.mod); } } function mod_mul(a, b) { if (!(a instanceof Mod)) { return Mod(a * b.res, b.mod); } else if (!(b instanceof Mod)) { return Mod(a.res * b, a.mod); } else { if (a.mod != b.mod) throw TypeError("different modulo for binary operator"); return Mod(a.res * b.res, a.mod); } } function mod_div(a, b) { if (!(b instanceof Mod)) b = Mod(b, a.mod); return mod_mul(a, b.inverse()); } function mod_eq(a, b) { return (a.mod == b.mod && a.res == b.res); } operators_set(Mod.prototype, { "+": mod_add, "-": mod_sub, "*": mod_mul, "/": mod_div, "**": generic_pow, "==": mod_eq, "pos"(a) { return a; }, "neg"(a) { return Mod(-a.res, a.mod); } }, { left: [Number, BigInt, Float, Fraction], right: [Number, BigInt, Float, Fraction], "+": mod_add, "-": mod_sub, "*": mod_mul, "/": mod_div, "**": generic_pow, }); add_props(Mod.prototype, { inverse() { var a = this, m = a.mod; if (Integer.isInteger(m)) { return Mod(Integer.invmod(a.res, m), m); } else { throw TypeError("unsupported type"); } }, toString() { return "Mod(" + this.res + "," + this.mod + ")"; }, }); /* Polynomial */ function polynomial_is_scalar(a) { if (typeof a === "number" || typeof a === "bigint" || typeof a === "bigfloat") return true; if (a instanceof Fraction || a instanceof Complex || a instanceof Mod) return true; return false; } Polynomial = function Polynomial(a) { if (new.target) throw TypeError("not a constructor"); if (a instanceof Polynomial) { return a; } else if (Array.isArray(a)) { if (a.length == 0) a = [ 0 ]; Object.setPrototypeOf(a, Polynomial.prototype); return a.trim(); } else if (polynomial_is_scalar(a)) { a = [a]; Object.setPrototypeOf(a, Polynomial.prototype); return a; } else { throw TypeError("invalid type"); } } function number_need_paren(c) { return !(Integer.isInteger(c) || Float.isFloat(c) || c instanceof Fraction || (c instanceof Complex && c.re == 0)); } /* string for c*X^i */ function monomial_toString(c, i) { var str1; if (i == 0) { str1 = c.toString(); } else { if (c == 1) { str1 = ""; } else if (c == -1) { str1 = "-"; } else { if (number_need_paren(c)) { str1 = "(" + c + ")"; } else { str1 = String(c); } str1 += "*"; } str1 += "X"; if (i != 1) { str1 += "^" + i; } } return str1; } /* find one complex root of 'p' starting from z at precision eps using at most max_it iterations. Return null if could not find root. */ function poly_root_laguerre1(p, z, max_it) { var p1, p2, i, z0, z1, z2, d, t0, t1, d1, d2, e, el, zl; d = p.deg(); if (d == 1) { /* monomial case */ return -p[0] / p[1]; } /* trivial zero */ if (p[0] == 0) return 0.0; p1 = p.deriv(); p2 = p1.deriv(); el = 0.0; zl = 0.0; for(i = 0; i < max_it; i++) { z0 = p.apply(z); if (z0 == 0) return z; /* simple exit case */ /* Ward stopping criteria */ e = abs(z - zl); // print("e", i, e); if (i >= 2 && e >= el) { if (abs(zl) < 1e-4) { if (e < 1e-7) return zl; } else { if (e < abs(zl) * 1e-3) return zl; } } el = e; zl = z; z1 = p1.apply(z); z2 = p2.apply(z); t0 = (d - 1) * z1; t0 = t0 * t0; t1 = d * (d - 1) * z0 * z2; t0 = sqrt(t0 - t1); d1 = z1 + t0; d2 = z1 - t0; if (norm2(d2) > norm2(d1)) d1 = d2; if (d1 == 0) return null; z = z - d * z0 / d1; } return null; } function poly_roots(p) { var d, i, roots, j, z, eps; var start_points = [ 0.1, -1.4, 1.7 ]; if (!(p instanceof Polynomial)) throw TypeError("polynomial expected"); d = p.deg(); if (d <= 0) return []; eps = 2.0 ^ (-BigFloatEnv.prec); roots = []; for(i = 0; i < d; i++) { /* XXX: should select another start point if error */ for(j = 0; j < 3; j++) { z = poly_root_laguerre1(p, start_points[j], 100); if (z !== null) break; } if (j == 3) throw RangeError("error in root finding algorithm"); roots[i] = z; p = Polynomial.divrem(p, X - z)[0]; } return roots; } add_props(Polynomial.prototype, { trim() { var a = this, i; i = a.length; while (i > 1 && a[i - 1] == 0) i--; a.length = i; return a; }, conj() { var r, i, n, a; a = this; n = a.length; r = []; for(i = 0; i < n; i++) r[i] = a[i].conj(); return Polynomial(r); }, inverse() { return RationalFunction(Polynomial([1]), this); }, toString() { var i, str, str1, c, a = this; if (a.length == 1) { return a[0].toString(); } str=""; for(i = a.length - 1; i >= 0; i--) { c = a[i]; if (c == 0 || (c instanceof Mod) && c.res == 0) continue; str1 = monomial_toString(c, i); if (str1[0] != "-") { if (str != "") str += "+"; } str += str1; } return str; }, deg() { if (this.length == 1 && this[0] == 0) return -Infinity; else return this.length - 1; }, apply(b) { var i, n, r, a = this; n = a.length - 1; r = a[n]; while (n > 0) { n--; r = r * b + a[n]; } return r; }, deriv() { var a = this, n, r, i; n = a.length; if (n == 1) { return Polynomial(0); } else { r = []; for(i = 1; i < n; i++) { r[i - 1] = i * a[i]; } return Polynomial(r); } }, integ() { var a = this, n, r, i; n = a.length; r = [0]; for(i = 0; i < n; i++) { r[i + 1] = a[i] / (i + 1); } return Polynomial(r); }, norm2() { var a = this, n, r, i; n = a.length; r = 0; for(i = 0; i < n; i++) { r += a[i].norm2(); } return r; }, }); function polynomial_add(a, b) { var tmp, r, i, n1, n2; a = Polynomial(a); b = Polynomial(b); if (a.length < b.length) { tmp = a; a = b; b = tmp; } n1 = b.length; n2 = a.length; r = []; for(i = 0; i < n1; i++) r[i] = a[i] + b[i]; for(i = n1; i < n2; i++) r[i] = a[i]; return Polynomial(r); } function polynomial_sub(a, b) { return polynomial_add(a, -b); } function polynomial_mul(a, b) { var i, j, n1, n2, n, r; a = Polynomial(a); b = Polynomial(b); n1 = a.length; n2 = b.length; n = n1 + n2 - 1; r = []; for(i = 0; i < n; i++) r[i] = 0; for(i = 0; i < n1; i++) { for(j = 0; j < n2; j++) { r[i + j] += a[i] * b[j]; } } return Polynomial(r); } function polynomial_div_scalar(a, b) { return a * (1 / b); } function polynomial_div(a, b) { return RationalFunction(Polynomial(a), Polynomial(b)); } function polynomial_mod(a, b) { return Polynomial.divrem(a, b)[1]; } function polynomial_eq(a, b) { var n, i; n = a.length; if (n != b.length) return false; for(i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } operators_set(Polynomial.prototype, { "+": polynomial_add, "-": polynomial_sub, "*": polynomial_mul, "/": polynomial_div, "**": generic_pow, "==": polynomial_eq, "pos"(a) { return a; }, "neg"(a) { var r, i, n, a; n = a.length; r = []; for(i = 0; i < n; i++) r[i] = -a[i]; return Polynomial(r); }, }, { left: [Number, BigInt, Float, Fraction, Complex, Mod], "+": polynomial_add, "-": polynomial_sub, "*": polynomial_mul, "/": polynomial_div, "**": generic_pow, /* XXX: only for integer */ }, { right: [Number, BigInt, Float, Fraction, Complex, Mod], "+": polynomial_add, "-": polynomial_sub, "*": polynomial_mul, "/": polynomial_div_scalar, "**": generic_pow, /* XXX: only for integer */ }); add_props(Polynomial, { divrem(a, b) { var n1, n2, i, j, q, r, n, c; if (b.deg() < 0) throw RangeError("division by zero"); n1 = a.length; n2 = b.length; if (n1 < n2) return [Polynomial([0]), a]; r = Array.prototype.dup.call(a); q = []; n2--; n = n1 - n2; for(i = 0; i < n; i++) q[i] = 0; for(i = n - 1; i >= 0; i--) { c = r[i + n2]; if (c != 0) { c = c / b[n2]; r[i + n2] = 0; for(j = 0; j < n2; j++) { r[i + j] -= b[j] * c; } q[i] = c; } } return [Polynomial(q), Polynomial(r)]; }, gcd(a, b) { var t; while (b.deg() >= 0) { t = Polynomial.divrem(a, b); a = b; b = t[1]; } /* convert to monic form */ return a / a[a.length - 1]; }, invmod(x, y) { var q, u, v, a, c, t; u = x; v = y; c = Polynomial([1]); a = Polynomial([0]); while (u.deg() >= 0) { t = Polynomial.divrem(v, u); q = t[0]; v = u; u = t[1]; t = c; c = a - q * c; a = t; } /* v = gcd(x, y) */ if (v.deg() > 0) throw RangeError("not invertible"); return Polynomial.divrem(a, y)[1]; }, roots(p) { return poly_roots(p); } }); /* Polynomial Modulo Q */ PolyMod = function PolyMod(a, m) { var obj, t; if (new.target) throw TypeError("not a constructor"); obj = Object.create(PolyMod.prototype); if (m instanceof Polynomial) { if (m.deg() <= 0) throw RangeError("the modulo cannot have a degree <= 0"); if (a instanceof RationalFunction) { return PolyMod(a.num, m) / a.den; } else { a = Polynomial(a); t = Polynomial.divrem(a, m); a = t[1]; } } else { throw TypeError("invalid types"); } obj.res = a; obj.mod = m; return obj; }; function polymod_add(a, b) { if (!(a instanceof PolyMod)) { return PolyMod(a + b.res, b.mod); } else if (!(b instanceof PolyMod)) { return PolyMod(a.res + b, a.mod); } else { if (a.mod != b.mod) throw TypeError("different modulo for binary operator"); return PolyMod(a.res + b.res, a.mod); } } function polymod_sub(a, b) { return polymod_add(a, -b); } function polymod_mul(a, b) { if (!(a instanceof PolyMod)) { return PolyMod(a * b.res, b.mod); } else if (!(b instanceof PolyMod)) { return PolyMod(a.res * b, a.mod); } else { if (a.mod != b.mod) throw TypeError("different modulo for binary operator"); return PolyMod(a.res * b.res, a.mod); } } function polymod_div(a, b) { if (!(b instanceof PolyMod)) b = PolyMod(b, a.mod); return polymod_mul(a, b.inverse()); } function polymod_eq(a, b) { return (a.mod == b.mod && a.res == b.res); } operators_set(PolyMod.prototype, { "+": polymod_add, "-": polymod_sub, "*": polymod_mul, "/": polymod_div, "**": generic_pow, "==": polymod_eq, "pos"(a) { return a; }, "neg"(a) { return PolyMod(-a.res, a.mod); }, }, { left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], "+": polymod_add, "-": polymod_sub, "*": polymod_mul, "/": polymod_div, "**": generic_pow, /* XXX: only for integer */ }); add_props(PolyMod.prototype, { inverse() { var a = this, m = a.mod; if (m instanceof Polynomial) { return PolyMod(Polynomial.invmod(a.res, m), m); } else { throw TypeError("unsupported type"); } }, toString() { return "PolyMod(" + this.res + "," + this.mod + ")"; }, }); /* Rational function */ RationalFunction = function RationalFunction(a, b) { var t, r, d, obj; if (new.target) throw TypeError("not a constructor"); if (!(a instanceof Polynomial) || !(b instanceof Polynomial)) throw TypeError("polynomial expected"); t = Polynomial.divrem(a, b); r = t[1]; if (r.deg() < 0) return t[0]; /* no need for a fraction */ d = Polynomial.gcd(b, r); if (d.deg() > 0) { a = Polynomial.divrem(a, d)[0]; b = Polynomial.divrem(b, d)[0]; } obj = Object.create(RationalFunction.prototype); obj.num = a; obj.den = b; return obj; } add_props(RationalFunction.prototype, { inverse() { return RationalFunction(this.den, this.num); }, conj() { return RationalFunction(this.num.conj(), this.den.conj()); }, toString() { var str; if (this.num.deg() <= 0 && !number_need_paren(this.num[0])) str = this.num.toString(); else str = "(" + this.num.toString() + ")"; str += "/(" + this.den.toString() + ")" return str; }, apply(b) { return this.num.apply(b) / this.den.apply(b); }, deriv() { var n = this.num, d = this.den; return RationalFunction(n.deriv() * d - n * d.deriv(), d * d); }, }); function ratfunc_add(a, b) { a = RationalFunction.toRationalFunction(a); b = RationalFunction.toRationalFunction(b); return RationalFunction(a.num * b.den + a.den * b.num, a.den * b.den); } function ratfunc_sub(a, b) { a = RationalFunction.toRationalFunction(a); b = RationalFunction.toRationalFunction(b); return RationalFunction(a.num * b.den - a.den * b.num, a.den * b.den); } function ratfunc_mul(a, b) { a = RationalFunction.toRationalFunction(a); b = RationalFunction.toRationalFunction(b); return RationalFunction(a.num * b.num, a.den * b.den); } function ratfunc_div(a, b) { a = RationalFunction.toRationalFunction(a); b = RationalFunction.toRationalFunction(b); return RationalFunction(a.num * b.den, a.den * b.num); } function ratfunc_eq(a, b) { a = RationalFunction.toRationalFunction(a); b = RationalFunction.toRationalFunction(b); /* we assume the fractions are normalized */ return (a.num == b.num && a.den == b.den); } operators_set(RationalFunction.prototype, { "+": ratfunc_add, "-": ratfunc_sub, "*": ratfunc_mul, "/": ratfunc_div, "**": generic_pow, "==": ratfunc_eq, "pos"(a) { return a; }, "neg"(a) { return RationalFunction(-this.num, this.den); }, }, { left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], "+": ratfunc_add, "-": ratfunc_sub, "*": ratfunc_mul, "/": ratfunc_div, "**": generic_pow, /* should only be used with integers */ }); add_props(RationalFunction, { /* This function always return a RationalFunction object even if it could simplified to a polynomial, so it is not equivalent to RationalFunction(a) */ toRationalFunction(a) { var obj; if (a instanceof RationalFunction) { return a; } else { obj = Object.create(RationalFunction.prototype); obj.num = Polynomial(a); obj.den = Polynomial(1); return obj; } }, }); /* Power series */ /* 'a' is an array */ function get_emin(a) { var i, n; n = a.length; for(i = 0; i < n; i++) { if (a[i] != 0) return i; } return n; }; function series_is_scalar_or_polynomial(a) { return polynomial_is_scalar(a) || (a instanceof Polynomial); } /* n is the maximum number of terms if 'a' is not a serie */ Series = function Series(a, n) { var emin, r, i; if (a instanceof Series) { return a; } else if (series_is_scalar_or_polynomial(a)) { if (n <= 0) { /* XXX: should still use the polynomial degree */ return Series.zero(0, 0); } else { a = Polynomial(a); emin = get_emin(a); r = Series.zero(n, emin); n = Math.min(a.length - emin, n); for(i = 0; i < n; i++) r[i] = a[i + emin]; return r; } } else if (a instanceof RationalFunction) { return Series(a.num, n) / a.den; } else { throw TypeError("invalid type"); } }; function series_add(v1, v2) { var tmp, d, emin, n, r, i, j, v2_emin, c1, c2; if (!(v1 instanceof Series)) { tmp = v1; v1 = v2; v2 = tmp; } d = v1.emin + v1.length; if (series_is_scalar_or_polynomial(v2)) { v2 = Polynomial(v2); if (d <= 0) return v1; v2_emin = 0; } else if (v2 instanceof RationalFunction) { /* compute the emin of the rational fonction */ i = get_emin(v2.num) - get_emin(v2.den); if (d <= i) return v1; /* compute the serie with the required terms */ v2 = Series(v2, d - i); v2_emin = v2.emin; } else { v2_emin = v2.emin; d = Math.min(d, v2_emin + v2.length); } emin = Math.min(v1.emin, v2_emin); n = d - emin; r = Series.zero(n, emin); /* XXX: slow */ for(i = emin; i < d; i++) { j = i - v1.emin; if (j >= 0 && j < v1.length) c1 = v1[j]; else c1 = 0; j = i - v2_emin; if (j >= 0 && j < v2.length) c2 = v2[j]; else c2 = 0; r[i - emin] = c1 + c2; } return r.trim(); } function series_sub(a, b) { return series_add(a, -b); } function series_mul(v1, v2) { var n, i, j, r, n, emin, n1, n2, k; if (!(v1 instanceof Series)) v1 = Series(v1, v2.length); else if (!(v2 instanceof Series)) v2 = Series(v2, v1.length); emin = v1.emin + v2.emin; n = Math.min(v1.length, v2.length); n1 = v1.length; n2 = v2.length; r = Series.zero(n, emin); for(i = 0; i < n1; i++) { k = Math.min(n2, n - i); for(j = 0; j < k; j++) { r[i + j] += v1[i] * v2[j]; } } return r.trim(); } function series_div(v1, v2) { if (!(v2 instanceof Series)) v2 = Series(v2, v1.length); return series_mul(v1, v2.inverse()); } function series_pow(a, b) { if (Integer.isInteger(b)) { return generic_pow(a, b); } else { if (!(a instanceof Series)) a = Series(a, b.length); return exp(log(a) * b); } } function series_eq(a, b) { var n, i; if (a.emin != b.emin) return false; n = a.length; if (n != b.length) return false; for(i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } operators_set(Series.prototype, { "+": series_add, "-": series_sub, "*": series_mul, "/": series_div, "**": series_pow, "==": series_eq, "pos"(a) { return a; }, "neg"(a) { var obj, n, i; n = a.length; obj = Series.zero(a.length, a.emin); for(i = 0; i < n; i++) { obj[i] = -a[i]; } return obj; }, }, { left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial], "+": series_add, "-": series_sub, "*": series_mul, "/": series_div, "**": series_pow, }); add_props(Series.prototype, { conj() { var obj, n, i; n = this.length; obj = Series.zero(this.length, this.emin); for(i = 0; i < n; i++) { obj[i] = this[i].conj(); } return obj; }, inverse() { var r, n, i, j, sum, v1 = this; n = v1.length; if (n == 0) throw RangeError("division by zero"); r = Series.zero(n, -v1.emin); r[0] = 1 / v1[0]; for(i = 1; i < n; i++) { sum = 0; for(j = 1; j <= i; j++) { sum += v1[j] * r[i - j]; } r[i] = -sum * r[0]; } return r; }, /* remove leading zero terms */ trim() { var i, j, n, r, v1 = this; n = v1.length; i = 0; while (i < n && v1[i] == 0) i++; if (i == 0) return v1; for(j = i; j < n; j++) v1[j - i] = v1[j]; v1.length = n - i; v1.__proto__.emin += i; return v1; }, toString() { var i, j, str, str1, c, a = this, emin, n; str=""; emin = this.emin; n = this.length; for(j = 0; j < n; j++) { i = j + emin; c = a[j]; if (c != 0) { str1 = monomial_toString(c, i); if (str1[0] != "-") { if (str != "") str += "+"; } str += str1; } } if (str != "") str += "+"; str += "O(" + monomial_toString(1, n + emin) + ")"; return str; }, apply(b) { var i, n, r, a = this; n = a.length; if (n == 0) return 0; r = a[--n]; while (n > 0) { n--; r = r * b + a[n]; } if (a.emin != 0) r *= b ^ a.emin; return r; }, deriv() { var a = this, n = a.length, emin = a.emin, r, i, j; if (n == 0 && emin == 0) { return Series.zero(0, 0); } else { r = Series.zero(n, emin - 1); for(i = 0; i < n; i++) { j = emin + i; if (j == 0) r[i] = 0; else r[i] = j * a[i]; } return r.trim(); } }, integ() { var a = this, n = a.length, emin = a.emin, i, j, r; r = Series.zero(n, emin + 1); for(i = 0; i < n; i++) { j = emin + i; if (j == -1) { if (a[i] != 0) throw RangError("cannot represent integ(1/X)"); } else { r[i] = a[i] / (j + 1); } } return r.trim(); }, exp() { var c, i, r, n, a = this; if (a.emin < 0) throw RangeError("negative exponent in exp"); n = a.emin + a.length; if (a.emin > 0 || a[0] == 0) { c = 1; } else { c = global.exp(a[0]); a -= a[0]; } r = Series.zero(n, 0); for(i = 0; i < n; i++) { r[i] = c / fact(i); } return r.apply(a); }, log() { var a = this, r; if (a.emin != 0) throw Range("log argument must have a non zero constant term"); r = integ(deriv(a) / a); /* add the constant term */ r += global.log(a[0]); return r; }, }); add_props(Series, { /* new series of length n and first exponent emin */ zero(n, emin) { var r, i, obj; r = []; for(i = 0; i < n; i++) r[i] = 0; /* we return an array and store emin in its prototype */ obj = Object.create(Series.prototype); obj.emin = emin; Object.setPrototypeOf(r, obj); return r; }, O(a) { function ErrorO() { return TypeError("invalid O() argument"); } var n; if (series_is_scalar_or_polynomial(a)) { a = Polynomial(a); n = a.deg(); if (n < 0) throw ErrorO(); } else if (a instanceof RationalFunction) { if (a.num.deg() != 0) throw ErrorO(); n = a.den.deg(); if (n < 0) throw ErrorO(); n = -n; } else throw ErrorO(); return Series.zero(0, n); }, }); /* Array (Matrix) */ Matrix = function Matrix(h, w) { var i, j, r, rl; if (typeof w === "undefined") w = h; r = []; for(i = 0; i < h; i++) { rl = []; for(j = 0; j < w; j++) rl[j] = 0; r[i] = rl; } return r; }; add_props(Matrix, { idn(n) { var r, i; r = Matrix(n, n); for(i = 0; i < n; i++) r[i][i] = 1; return r; }, diag(a) { var r, i, n; n = a.length; r = Matrix(n, n); for(i = 0; i < n; i++) r[i][i] = a[i]; return r; }, hilbert(n) { var i, j, r; r = Matrix(n); for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { r[i][j] = 1 / (1 + i + j); } } return r; }, trans(a) { var h, w, r, i, j; if (!Array.isArray(a)) throw TypeError("matrix expected"); h = a.length; if (!Array.isArray(a[0])) { w = 1; r = Matrix(w, h); for(i = 0; i < h; i++) { r[0][i] = a[i]; } } else { w = a[0].length; r = Matrix(w, h); for(i = 0; i < h; i++) { for(j = 0; j < w; j++) { r[j][i] = a[i][j]; } } } return r; }, check_square(a) { var a, n; if (!Array.isArray(a)) throw TypeError("array expected"); n = a.length; if (!Array.isArray(a[0]) || n != a[0].length) throw TypeError("square matrix expected"); return n; }, trace(a) { var n, r, i; n = Matrix.check_square(a); r = a[0][0]; for(i = 1; i < n; i++) { r += a[i][i]; } return r; }, charpoly(a) { var n, p, c, i, j, coef; n = Matrix.check_square(a); p = []; for(i = 0; i < n + 1; i++) p[i] = 0; p[n] = 1; c = Matrix.idn(n); for(i = 0; i < n; i++) { c = c * a; coef = -trace(c) / (i + 1); p[n - i - 1] = coef; for(j = 0; j < n; j++) c[j][j] += coef; } return Polynomial(p); }, eigenvals(a) { return Polynomial.roots(Matrix.charpoly(a)); }, det(a) { var n, i, j, k, s, src, v, c; n = Matrix.check_square(a); s = 1; src = a.dup(); for(i=0;i<n;i++) { for(j = i; j < n; j++) { if (src[j][i] != 0) break; } if (j == n) return 0; if (j != i) { for(k = 0;k < n; k++) { v = src[j][k]; src[j][k] = src[i][k]; src[i][k] = v; } s = -s; } c = src[i][i].inverse(); for(j = i + 1; j < n; j++) { v = c * src[j][i]; for(k = 0;k < n; k++) { src[j][k] -= src[i][k] * v; } } } c = s; for(i=0;i<n;i++) c *= src[i][i]; return c; }, inverse(a) { var n, dst, src, i, j, k, n2, r, c, v; n = Matrix.check_square(a); src = a.dup(); dst = Matrix.idn(n); for(i=0;i<n;i++) { for(j = i; j < n; j++) { if (src[j][i] != 0) break; } if (j == n) throw RangeError("matrix is not invertible"); if (j != i) { /* swap lines in src and dst */ v = src[j]; src[j] = src[i]; src[i] = v; v = dst[j]; dst[j] = dst[i]; dst[i] = v; } c = src[i][i].inverse(); for(k = 0; k < n; k++) { src[i][k] *= c; dst[i][k] *= c; } for(j = 0; j < n; j++) { if (j != i) { c = src[j][i]; for(k = i; k < n; k++) { src[j][k] -= src[i][k] * c; } for(k = 0; k < n; k++) { dst[j][k] -= dst[i][k] * c; } } } } return dst; }, rank(a) { var src, i, j, k, w, h, l, c; if (!Array.isArray(a) || !Array.isArray(a[0])) throw TypeError("matrix expected"); h = a.length; w = a[0].length; src = a.dup(); l = 0; for(i=0;i<w;i++) { for(j = l; j < h; j++) { if (src[j][i] != 0) break; } if (j == h) continue; if (j != l) { /* swap lines */ for(k = 0; k < w; k++) { v = src[j][k]; src[j][k] = src[l][k]; src[l][k] = v; } } c = src[l][i].inverse(); for(k = 0; k < w; k++) { src[l][k] *= c; } for(j = l + 1; j < h; j++) { c = src[j][i]; for(k = i; k < w; k++) { src[j][k] -= src[l][k] * c; } } l++; } return l; }, ker(a) { var src, i, j, k, w, h, l, m, r, im_cols, ker_dim, c; if (!Array.isArray(a) || !Array.isArray(a[0])) throw TypeError("matrix expected"); h = a.length; w = a[0].length; src = a.dup(); im_cols = []; l = 0; for(i=0;i<w;i++) { im_cols[i] = false; for(j = l; j < h; j++) { if (src[j][i] != 0) break; } if (j == h) continue; im_cols[i] = true; if (j != l) { /* swap lines */ for(k = 0; k < w; k++) { v = src[j][k]; src[j][k] = src[l][k]; src[l][k] = v; } } c = src[l][i].inverse(); for(k = 0; k < w; k++) { src[l][k] *= c; } for(j = 0; j < h; j++) { if (j != l) { c = src[j][i]; for(k = i; k < w; k++) { src[j][k] -= src[l][k] * c; } } } l++; // log_str("m=" + cval_toString(v1) + "\n"); } // log_str("im cols="+im_cols+"\n"); /* build the kernel vectors */ ker_dim = w - l; r = Matrix(w, ker_dim); k = 0; for(i = 0; i < w; i++) { if (!im_cols[i]) { /* select this column from the matrix */ l = 0; m = 0; for(j = 0; j < w; j++) { if (im_cols[j]) { r[j][k] = -src[m][i]; m++; } else { if (l == k) { r[j][k] = 1; } else { r[j][k] = 0; } l++; } } k++; } } return r; }, dp(a, b) { var i, n, r; n = a.length; if (n != b.length) throw TypeError("incompatible array length"); /* XXX: could do complex product */ r = 0; for(i = 0; i < n; i++) { r += a[i] * b[i]; } return r; }, /* cross product */ cp(v1, v2) { var r; if (v1.length != 3 || v2.length != 3) throw TypeError("vectors must have 3 elements"); r = []; r[0] = v1[1] * v2[2] - v1[2] * v2[1]; r[1] = v1[2] * v2[0] - v1[0] * v2[2]; r[2] = v1[0] * v2[1] - v1[1] * v2[0]; return r; }, }); function array_add(a, b) { var r, i, n; n = a.length; if (n != b.length) throw TypeError("incompatible array size"); r = []; for(i = 0; i < n; i++) r[i] = a[i] + b[i]; return r; } function array_sub(a, b) { var r, i, n; n = a.length; if (n != b.length) throw TypeError("incompatible array size"); r = []; for(i = 0; i < n; i++) r[i] = a[i] - b[i]; return r; } function array_scalar_mul(a, b) { var r, i, n; n = a.length; r = []; for(i = 0; i < n; i++) r[i] = a[i] * b; return r; } function array_mul(a, b) { var h, w, l, i, j, k, r, rl, sum, a_mat, b_mat; h = a.length; a_mat = Array.isArray(a[0]); if (a_mat) { l = a[0].length; } else { l = 1; } if (l != b.length) throw RangeError("incompatible matrix size"); b_mat = Array.isArray(b[0]); if (b_mat) w = b[0].length; else w = 1; r = []; if (a_mat && b_mat) { for(i = 0; i < h; i++) { rl = []; for(j = 0; j < w; j++) { sum = 0; for(k = 0; k < l; k++) { sum += a[i][k] * b[k][j]; } rl[j] = sum; } r[i] = rl; } } else if (a_mat && !b_mat) { for(i = 0; i < h; i++) { sum = 0; for(k = 0; k < l; k++) { sum += a[i][k] * b[k]; } r[i] = sum; } } else if (!a_mat && b_mat) { for(i = 0; i < h; i++) { rl = []; for(j = 0; j < w; j++) { rl[j] = a[i] * b[0][j]; } r[i] = rl; } } else { for(i = 0; i < h; i++) { r[i] = a[i] * b[0]; } } return r; } function array_div(a, b) { return array_mul(a, b.inverse()); } function array_scalar_div(a, b) { return a * b.inverse(); } function array_eq(a, b) { var n, i; n = a.length; if (n != b.length) return false; for(i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } operators_set(Array.prototype, { "+": array_add, "-": array_sub, "*": array_mul, "/": array_div, "==": array_eq, "pos"(a) { return a; }, "neg"(a) { var i, n, r; n = a.length; r = []; for(i = 0; i < n; i++) r[i] = -a[i]; return r; } }, { right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial, PolyMod, RationalFunction, Series], "*": array_scalar_mul, "/": array_scalar_div, "**": generic_pow, /* XXX: only for integer */ }, { left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial, PolyMod, RationalFunction, Series], "*"(a, b) { return array_scalar_mul(b, a); }, "/"(a, b) { return array_scalar_div(b, a); }, }); add_props(Array.prototype, { conj() { var i, n, r; n = this.length; r = []; for(i = 0; i < n; i++) r[i] = this[i].conj(); return r; }, dup() { var r, i, n, el, a = this; r = []; n = a.length; for(i = 0; i < n; i++) { el = a[i]; if (Array.isArray(el)) el = el.dup(); r[i] = el; } return r; }, inverse() { return Matrix.inverse(this); }, norm2: Polynomial.prototype.norm2, }); })(this); /* global definitions */ var I = Complex(0, 1); var X = Polynomial([0, 1]); var O = Series.O; Object.defineProperty(this, "PI", { get: function () { return Float.PI } }); /* put frequently used functions in the global context */ var gcd = Integer.gcd; var fact = Integer.fact; var comb = Integer.comb; var pmod = Integer.pmod; var invmod = Integer.invmod; var factor = Integer.factor; var isprime = Integer.isPrime; var nextprime = Integer.nextPrime; function deriv(a) { return a.deriv(); } function integ(a) { return a.integ(); } function norm2(a) { return a.norm2(); } function abs(a) { return a.abs(); } function conj(a) { return a.conj(); } function arg(a) { return a.arg(); } function inverse(a) { return a.inverse(); } function trunc(a) { if (Integer.isInteger(a)) { return a; } else if (a instanceof Fraction) { return Integer.tdiv(a.num, a.den); } else if (a instanceof Polynomial) { return a; } else if (a instanceof RationalFunction) { return Polynomial.divrem(a.num, a.den)[0]; } else { return Float.ceil(a); } } function floor(a) { if (Integer.isInteger(a)) { return a; } else if (a instanceof Fraction) { return Integer.fdiv(a.num, a.den); } else { return Float.floor(a); } } function ceil(a) { if (Integer.isInteger(a)) { return a; } else if (a instanceof Fraction) { return Integer.cdiv(a.num, a.den); } else { return Float.ceil(a); } } function sqrt(a) { var t, u, re, im; if (a instanceof Series) { return a ^ (1/2); } else if (a instanceof Complex) { t = abs(a); u = a.re; re = sqrt((t + u) / 2); im = sqrt((t - u) / 2); if (a.im < 0) im = -im; return Complex.toComplex(re, im); } else { a = Float(a); if (a < 0) { return Complex(0, Float.sqrt(-a)); } else { return Float.sqrt(a); } } } function exp(a) { return a.exp(); } function log(a) { return a.log(); } function log2(a) { return log(a) * Float.LOG2E; } function log10(a) { return log(a) * Float.LOG10E; } function todb(a) { return log10(a) * 10; } function fromdb(a) { return 10 ^ (a / 10); } function sin(a) { var t; if (a instanceof Complex || a instanceof Series) { t = exp(a * I); return (t - 1/t) / (2 * I); } else { return Float.sin(Float(a)); } } function cos(a) { var t; if (a instanceof Complex || a instanceof Series) { t = exp(a * I); return (t + 1/t) / 2; } else { return Float.cos(Float(a)); } } function tan(a) { if (a instanceof Complex || a instanceof Series) { return sin(a) / cos(a); } else { return Float.tan(Float(a)); } } function asin(a) { return Float.asin(Float(a)); } function acos(a) { return Float.acos(Float(a)); } function atan(a) { return Float.atan(Float(a)); } function atan2(a, b) { return Float.atan2(Float(a), Float(b)); } function sinc(a) { if (a == 0) { return 1; } else { a *= Float.PI; return sin(a) / a; } } function todeg(a) { return a * 180 / Float.PI; } function fromdeg(a) { return a * Float.PI / 180; } function sinh(a) { var e = Float.exp(Float(a)); return (e - 1/e) * 0.5; } function cosh(a) { var e = Float.exp(Float(a)); return (e + 1/e) * 0.5; } function tanh(a) { var e = Float.exp(Float(a) * 2); return (e - 1) / (e + 1); } function asinh(a) { var x = Float(a); return log(sqrt(x * x + 1) + x); } function acosh(a) { var x = Float(a); return log(sqrt(x * x - 1) + x); } function atanh(a) { var x = Float(a); return 0.5 * log((1 + x) / (1 - x)); } var idn = Matrix.idn; var diag = Matrix.diag; var trans = Matrix.trans; var trace = Matrix.trace; var charpoly = Matrix.charpoly; var eigenvals = Matrix.eigenvals; var det = Matrix.det; var rank = Matrix.rank; var ker = Matrix.ker; var cp = Matrix.cp; var dp = Matrix.dp; var polroots = Polynomial.roots; var bestappr = Float.bestappr;
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/qjscalc.js
JavaScript
apache-2.0
72,796
/* * QuickJS atom definitions * * Copyright (c) 2017-2018 Fabrice Bellard * Copyright (c) 2017-2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifdef DEF /* Note: first atoms are considered as keywords in the parser */ DEF(null, "null") /* must be first */ DEF(false, "false") DEF(true, "true") DEF(if, "if") DEF(else, "else") DEF(return, "return") DEF(var, "var") DEF(this, "this") DEF(delete, "delete") DEF(void, "void") DEF(typeof, "typeof") DEF(new, "new") DEF(in, "in") DEF(instanceof, "instanceof") DEF(do, "do") DEF(while, "while") DEF(for, "for") DEF(break, "break") DEF(continue, "continue") DEF(switch, "switch") DEF(case, "case") DEF(default, "default") DEF(throw, "throw") DEF(try, "try") DEF(catch, "catch") DEF(finally, "finally") DEF(function, "function") DEF(debugger, "debugger") DEF(with, "with") /* FutureReservedWord */ DEF(class, "class") DEF(const, "const") DEF(enum, "enum") DEF(export, "export") DEF(extends, "extends") DEF(import, "import") DEF(super, "super") /* FutureReservedWords when parsing strict mode code */ DEF(implements, "implements") DEF(interface, "interface") DEF(let, "let") DEF(package, "package") DEF(private, "private") DEF(protected, "protected") DEF(public, "public") DEF(static, "static") DEF(yield, "yield") DEF(await, "await") /* empty string */ DEF(empty_string, "") /* identifiers */ DEF(length, "length") DEF(fileName, "fileName") DEF(lineNumber, "lineNumber") DEF(message, "message") DEF(errors, "errors") DEF(stack, "stack") DEF(name, "name") DEF(toString, "toString") DEF(toLocaleString, "toLocaleString") DEF(valueOf, "valueOf") DEF(eval, "eval") DEF(prototype, "prototype") DEF(constructor, "constructor") DEF(configurable, "configurable") DEF(writable, "writable") DEF(enumerable, "enumerable") DEF(value, "value") DEF(get, "get") DEF(set, "set") DEF(of, "of") DEF(__proto__, "__proto__") DEF(undefined, "undefined") DEF(number, "number") DEF(boolean, "boolean") DEF(string, "string") DEF(object, "object") DEF(symbol, "symbol") DEF(integer, "integer") DEF(unknown, "unknown") DEF(arguments, "arguments") DEF(callee, "callee") DEF(caller, "caller") DEF(_eval_, "<eval>") DEF(_ret_, "<ret>") DEF(_var_, "<var>") DEF(_with_, "<with>") DEF(lastIndex, "lastIndex") DEF(target, "target") DEF(index, "index") DEF(input, "input") DEF(defineProperties, "defineProperties") DEF(apply, "apply") DEF(join, "join") DEF(concat, "concat") DEF(split, "split") DEF(construct, "construct") DEF(getPrototypeOf, "getPrototypeOf") DEF(setPrototypeOf, "setPrototypeOf") DEF(isExtensible, "isExtensible") DEF(preventExtensions, "preventExtensions") DEF(has, "has") DEF(deleteProperty, "deleteProperty") DEF(defineProperty, "defineProperty") DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor") DEF(ownKeys, "ownKeys") DEF(add, "add") DEF(done, "done") DEF(next, "next") DEF(values, "values") DEF(source, "source") DEF(flags, "flags") DEF(global, "global") DEF(unicode, "unicode") DEF(raw, "raw") DEF(new_target, "new.target") DEF(this_active_func, "this.active_func") DEF(home_object, "<home_object>") DEF(computed_field, "<computed_field>") DEF(static_computed_field, "<static_computed_field>") /* must come after computed_fields */ DEF(class_fields_init, "<class_fields_init>") DEF(brand, "<brand>") DEF(hash_constructor, "#constructor") DEF(as, "as") DEF(from, "from") DEF(meta, "meta") DEF(_default_, "*default*") DEF(_star_, "*") DEF(Module, "Module") DEF(then, "then") DEF(resolve, "resolve") DEF(reject, "reject") DEF(promise, "promise") DEF(proxy, "proxy") DEF(revoke, "revoke") DEF(async, "async") DEF(exec, "exec") DEF(groups, "groups") DEF(status, "status") DEF(reason, "reason") DEF(globalThis, "globalThis") #ifdef CONFIG_BIGNUM DEF(bigint, "bigint") DEF(bigfloat, "bigfloat") DEF(bigdecimal, "bigdecimal") DEF(roundingMode, "roundingMode") DEF(maximumSignificantDigits, "maximumSignificantDigits") DEF(maximumFractionDigits, "maximumFractionDigits") #endif #ifdef CONFIG_ATOMICS DEF(not_equal, "not-equal") DEF(timed_out, "timed-out") DEF(ok, "ok") #endif DEF(toJSON, "toJSON") /* class names */ DEF(Object, "Object") DEF(Array, "Array") DEF(Error, "Error") DEF(Number, "Number") DEF(String, "String") DEF(Boolean, "Boolean") DEF(Symbol, "Symbol") DEF(Arguments, "Arguments") DEF(Math, "Math") DEF(JSON, "JSON") DEF(Date, "Date") DEF(Function, "Function") DEF(GeneratorFunction, "GeneratorFunction") DEF(ForInIterator, "ForInIterator") DEF(RegExp, "RegExp") DEF(ArrayBuffer, "ArrayBuffer") DEF(SharedArrayBuffer, "SharedArrayBuffer") /* must keep same order as class IDs for typed arrays */ DEF(Uint8ClampedArray, "Uint8ClampedArray") DEF(Int8Array, "Int8Array") DEF(Uint8Array, "Uint8Array") DEF(Int16Array, "Int16Array") DEF(Uint16Array, "Uint16Array") DEF(Int32Array, "Int32Array") DEF(Uint32Array, "Uint32Array") #ifdef CONFIG_BIGNUM DEF(BigInt64Array, "BigInt64Array") DEF(BigUint64Array, "BigUint64Array") #endif DEF(Float32Array, "Float32Array") DEF(Float64Array, "Float64Array") DEF(DataView, "DataView") #ifdef CONFIG_BIGNUM DEF(BigInt, "BigInt") DEF(BigFloat, "BigFloat") DEF(BigFloatEnv, "BigFloatEnv") DEF(BigDecimal, "BigDecimal") DEF(OperatorSet, "OperatorSet") DEF(Operators, "Operators") #endif DEF(Map, "Map") DEF(Set, "Set") /* Map + 1 */ DEF(WeakMap, "WeakMap") /* Map + 2 */ DEF(WeakSet, "WeakSet") /* Map + 3 */ DEF(Map_Iterator, "Map Iterator") DEF(Set_Iterator, "Set Iterator") DEF(Array_Iterator, "Array Iterator") DEF(String_Iterator, "String Iterator") DEF(RegExp_String_Iterator, "RegExp String Iterator") DEF(Generator, "Generator") DEF(Proxy, "Proxy") DEF(Promise, "Promise") DEF(PromiseResolveFunction, "PromiseResolveFunction") DEF(PromiseRejectFunction, "PromiseRejectFunction") DEF(AsyncFunction, "AsyncFunction") DEF(AsyncFunctionResolve, "AsyncFunctionResolve") DEF(AsyncFunctionReject, "AsyncFunctionReject") DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction") DEF(AsyncGenerator, "AsyncGenerator") DEF(EvalError, "EvalError") DEF(RangeError, "RangeError") DEF(ReferenceError, "ReferenceError") DEF(SyntaxError, "SyntaxError") DEF(TypeError, "TypeError") DEF(URIError, "URIError") DEF(InternalError, "InternalError") /* private symbols */ DEF(Private_brand, "<brand>") /* symbols */ DEF(Symbol_toPrimitive, "Symbol.toPrimitive") DEF(Symbol_iterator, "Symbol.iterator") DEF(Symbol_match, "Symbol.match") DEF(Symbol_matchAll, "Symbol.matchAll") DEF(Symbol_replace, "Symbol.replace") DEF(Symbol_search, "Symbol.search") DEF(Symbol_split, "Symbol.split") DEF(Symbol_toStringTag, "Symbol.toStringTag") DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable") DEF(Symbol_hasInstance, "Symbol.hasInstance") DEF(Symbol_species, "Symbol.species") DEF(Symbol_unscopables, "Symbol.unscopables") DEF(Symbol_asyncIterator, "Symbol.asyncIterator") #ifdef CONFIG_BIGNUM DEF(Symbol_operatorSet, "Symbol.operatorSet") #endif #endif /* DEF */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/quickjs-atom.h
C
apache-2.0
7,886
/* * QuickJS C library * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <time.h> #include <signal.h> #include <limits.h> #include <sys/stat.h> #include <dirent.h> #if defined(_WIN32) #include <windows.h> #include <conio.h> #include <utime.h> #elif defined(__AOS_AMP__) #include <sys/signal.h> #include <sys/wait.h> #else #include <dlfcn.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/wait.h> #if defined(__APPLE__) typedef sig_t sighandler_t; #if !defined(environ) #include <crt_externs.h> #define environ (*_NSGetEnviron()) #endif #endif /* __APPLE__ */ #endif #if !defined(_WIN32) /* enable the os.Worker API. IT relies on POSIX threads */ #define USE_WORKER #endif #ifdef USE_WORKER #include <pthread.h> #include <stdatomic.h> #endif #include "cutils.h" #include "list.h" #include "quickjs-libc.h" /* TODO: - add socket calls */ typedef struct { struct list_head link; int fd; JSValue rw_func[2]; } JSOSRWHandler; typedef struct { struct list_head link; int sig_num; JSValue func; } JSOSSignalHandler; typedef struct { struct list_head link; BOOL has_object; int64_t timeout; JSValue func; } JSOSTimer; typedef struct { struct list_head link; uint8_t *data; size_t data_len; /* list of SharedArrayBuffers, necessary to free the message */ uint8_t **sab_tab; size_t sab_tab_len; } JSWorkerMessage; typedef struct { int ref_count; #ifdef USE_WORKER pthread_mutex_t mutex; #endif struct list_head msg_queue; /* list of JSWorkerMessage.link */ int read_fd; int write_fd; } JSWorkerMessagePipe; typedef struct { struct list_head link; JSWorkerMessagePipe *recv_pipe; JSValue on_message_func; } JSWorkerMessageHandler; typedef struct JSThreadState { struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */ struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */ struct list_head os_timers; /* list of JSOSTimer.link */ struct list_head port_list; /* list of JSWorkerMessageHandler.link */ int eval_script_recurse; /* only used in the main thread */ /* not used in the main thread */ JSWorkerMessagePipe *recv_pipe, *send_pipe; } JSThreadState; static uint64_t os_pending_signals; static int (*os_poll_func)(JSContext *ctx); static void js_std_dbuf_init(JSContext *ctx, DynBuf *s) { dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt); } static BOOL my_isdigit(int c) { return (c >= '0' && c <= '9'); } static JSValue js_printf_internal(JSContext *ctx, int argc, JSValueConst *argv, FILE *fp) { char fmtbuf[32]; uint8_t cbuf[UTF8_CHAR_LEN_MAX+1]; JSValue res; DynBuf dbuf; const char *fmt_str; const uint8_t *fmt, *fmt_end; const uint8_t *p; char *q; int i, c, len, mod; size_t fmt_len; int32_t int32_arg; int64_t int64_arg; double double_arg; const char *string_arg; /* Use indirect call to dbuf_printf to prevent gcc warning */ int (*dbuf_printf_fun)(DynBuf *s, const char *fmt, ...) = (void*)dbuf_printf; js_std_dbuf_init(ctx, &dbuf); if (argc > 0) { fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]); if (!fmt_str) goto fail; i = 1; fmt = (const uint8_t *)fmt_str; fmt_end = fmt + fmt_len; while (fmt < fmt_end) { for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++) continue; dbuf_put(&dbuf, p, fmt - p); if (fmt >= fmt_end) break; q = fmtbuf; *q++ = *fmt++; /* copy '%' */ /* flags */ for(;;) { c = *fmt; if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' || c == '\'') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = c; fmt++; } else { break; } } /* width */ if (*fmt == '*') { if (i >= argc) goto missing; if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; } } if (*fmt == '.') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; if (*fmt == '*') { if (i >= argc) goto missing; if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; } } } /* we only support the "l" modifier for 64 bit numbers */ mod = ' '; if (*fmt == 'l') { mod = *fmt++; } /* type */ c = *fmt++; if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = c; *q = '\0'; switch (c) { case 'c': if (i >= argc) goto missing; if (JS_IsString(argv[i])) { string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) goto fail; int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p); JS_FreeCString(ctx, string_arg); } else { if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; } /* handle utf-8 encoding explicitly */ if ((unsigned)int32_arg > 0x10FFFF) int32_arg = 0xFFFD; /* ignore conversion flags, width and precision */ len = unicode_to_utf8(cbuf, int32_arg); dbuf_put(&dbuf, cbuf, len); break; case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': if (i >= argc) goto missing; if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++])) goto fail; if (mod == 'l') { /* 64 bit number */ #if defined(_WIN32) if (q >= fmtbuf + sizeof(fmtbuf) - 3) goto invalid; q[2] = q[-1]; q[-1] = 'I'; q[0] = '6'; q[1] = '4'; q[3] = '\0'; dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg); #else if (q >= fmtbuf + sizeof(fmtbuf) - 2) goto invalid; q[1] = q[-1]; q[-1] = q[0] = 'l'; q[2] = '\0'; dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg); #endif } else { dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg); } break; case 's': if (i >= argc) goto missing; /* XXX: handle strings containing null characters */ string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) goto fail; dbuf_printf_fun(&dbuf, fmtbuf, string_arg); JS_FreeCString(ctx, string_arg); break; case 'e': case 'f': case 'g': case 'a': case 'E': case 'F': case 'G': case 'A': if (i >= argc) goto missing; if (JS_ToFloat64(ctx, &double_arg, argv[i++])) goto fail; dbuf_printf_fun(&dbuf, fmtbuf, double_arg); break; case '%': dbuf_putc(&dbuf, '%'); break; default: /* XXX: should support an extension mechanism */ invalid: JS_ThrowTypeError(ctx, "invalid conversion specifier in format string"); goto fail; missing: JS_ThrowReferenceError(ctx, "missing argument for conversion specifier"); goto fail; } } JS_FreeCString(ctx, fmt_str); } if (dbuf.error) { res = JS_ThrowOutOfMemory(ctx); } else { if (fp) { len = fwrite(dbuf.buf, 1, dbuf.size, fp); res = JS_NewInt32(ctx, len); } else { res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size); } } dbuf_free(&dbuf); return res; fail: dbuf_free(&dbuf); return JS_EXCEPTION; } uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename) { FILE *f; uint8_t *buf; size_t buf_len; long lret; f = fopen(filename, "rb"); if (!f) return NULL; if (fseek(f, 0, SEEK_END) < 0) goto fail; lret = ftell(f); if (lret < 0) goto fail; /* XXX: on Linux, ftell() return LONG_MAX for directories */ if (lret == LONG_MAX) { errno = EISDIR; goto fail; } buf_len = lret; if (fseek(f, 0, SEEK_SET) < 0) goto fail; if (ctx) buf = js_malloc(ctx, buf_len + 1); else buf = malloc(buf_len + 1); if (!buf) goto fail; if (fread(buf, 1, buf_len, f) != buf_len) { errno = EIO; if (ctx) js_free(ctx, buf); else free(buf); fail: fclose(f); return NULL; } buf[buf_len] = '\0'; fclose(f); *pbuf_len = buf_len; return buf; } /* load and evaluate a file */ static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValue ret; size_t buf_len; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; buf = js_load_file(ctx, &buf_len, filename); if (!buf) { JS_ThrowReferenceError(ctx, "could not load '%s'", filename); JS_FreeCString(ctx, filename); return JS_EXCEPTION; } ret = JS_Eval(ctx, (char *)buf, buf_len, filename, JS_EVAL_TYPE_GLOBAL); js_free(ctx, buf); JS_FreeCString(ctx, filename); return ret; } /* load a file as a UTF-8 encoded string */ static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValue ret; size_t buf_len; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; buf = js_load_file(ctx, &buf_len, filename); JS_FreeCString(ctx, filename); if (!buf) return JS_NULL; ret = JS_NewStringLen(ctx, (char *)buf, buf_len); js_free(ctx, buf); return ret; } typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx, const char *module_name); #if defined(_WIN32) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JS_ThrowReferenceError(ctx, "shared library modules are not supported yet"); return NULL; } #elif defined(__AOS_AMP__) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JS_ThrowReferenceError(ctx, "shared library modules are not supported yet"); printf("%s: func:%s not supported yet\n", __FILE__, __func__); return NULL; } #else static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JSModuleDef *m; void *hd; JSInitModuleFunc *init; char *filename; if (!strchr(module_name, '/')) { /* must add a '/' so that the DLL is not searched in the system library paths */ filename = js_malloc(ctx, strlen(module_name) + 2 + 1); if (!filename) return NULL; strcpy(filename, "./"); strcpy(filename + 2, module_name); } else { filename = (char *)module_name; } /* C module */ hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL); if (filename != module_name) js_free(ctx, filename); if (!hd) { JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library", module_name); goto fail; } init = dlsym(hd, "js_init_module"); if (!init) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found", module_name); goto fail; } m = init(ctx, module_name); if (!m) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error", module_name); fail: if (hd) dlclose(hd); return NULL; } return m; } #endif /* !_WIN32 */ int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, JS_BOOL use_realpath, JS_BOOL is_main) { JSModuleDef *m; char buf[PATH_MAX + 16]; JSValue meta_obj; JSAtom module_name_atom; const char *module_name; assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE); m = JS_VALUE_GET_PTR(func_val); module_name_atom = JS_GetModuleName(ctx, m); module_name = JS_AtomToCString(ctx, module_name_atom); JS_FreeAtom(ctx, module_name_atom); if (!module_name) return -1; if (!strchr(module_name, ':')) { strcpy(buf, "file://"); #if !defined(_WIN32) && !defined(__AOS_AMP__) /* realpath() cannot be used with modules compiled with qjsc because the corresponding module source code is not necessarily present */ if (use_realpath) { char *res = realpath(module_name, buf + strlen(buf)); if (!res) { JS_ThrowTypeError(ctx, "realpath failure"); JS_FreeCString(ctx, module_name); return -1; } } else #endif { pstrcat(buf, sizeof(buf), module_name); } } else { pstrcpy(buf, sizeof(buf), module_name); } JS_FreeCString(ctx, module_name); meta_obj = JS_GetImportMeta(ctx, m); if (JS_IsException(meta_obj)) return -1; JS_DefinePropertyValueStr(ctx, meta_obj, "url", JS_NewString(ctx, buf), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, meta_obj, "main", JS_NewBool(ctx, is_main), JS_PROP_C_W_E); JS_FreeValue(ctx, meta_obj); return 0; } JSModuleDef *js_module_loader(JSContext *ctx, const char *module_name, void *opaque) { JSModuleDef *m; if (has_suffix(module_name, ".so")) { m = js_module_loader_so(ctx, module_name); } else { size_t buf_len; uint8_t *buf; JSValue func_val; buf = js_load_file(ctx, &buf_len, module_name); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (JS_IsException(func_val)) return NULL; /* XXX: could propagate the exception */ js_module_set_import_meta(ctx, func_val, TRUE, FALSE); /* the module is already referenced, so we must free it */ m = JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); } return m; } static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int status; if (JS_ToInt32(ctx, &status, argv[0])) status = -1; exit(status); return JS_UNDEFINED; } static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *name, *str; name = JS_ToCString(ctx, argv[0]); if (!name) return JS_EXCEPTION; str = getenv(name); JS_FreeCString(ctx, name); if (!str) return JS_UNDEFINED; else return JS_NewString(ctx, str); } static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_RunGC(JS_GetRuntime(ctx)); return JS_UNDEFINED; } static int interrupt_handler(JSRuntime *rt, void *opaque) { return (os_pending_signals >> SIGINT) & 1; } static int get_bool_option(JSContext *ctx, BOOL *pbool, JSValueConst obj, const char *option) { JSValue val; val = JS_GetPropertyStr(ctx, obj, option); if (JS_IsException(val)) return -1; if (!JS_IsUndefined(val)) { *pbool = JS_ToBool(ctx, val); } JS_FreeValue(ctx, val); return 0; } static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); const char *str; size_t len; JSValue ret; JSValueConst options_obj; BOOL backtrace_barrier = FALSE; int flags; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &backtrace_barrier, options_obj, "backtrace_barrier")) return JS_EXCEPTION; } str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) return JS_EXCEPTION; if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) { /* install the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); } flags = JS_EVAL_TYPE_GLOBAL; if (backtrace_barrier) flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER; ret = JS_Eval(ctx, str, len, "<evalScript>", flags); JS_FreeCString(ctx, str); if (!ts->recv_pipe && --ts->eval_script_recurse == 0) { /* remove the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL); os_pending_signals &= ~((uint64_t)1 << SIGINT); /* convert the uncatchable "interrupted" error into a normal error so that it can be caught by the REPL */ if (JS_IsException(ret)) JS_ResetUncatchableError(ctx); } return ret; } static JSClassID js_std_file_class_id; typedef struct { FILE *f; BOOL close_in_finalizer; BOOL is_popen; } JSSTDFile; static void js_std_file_finalizer(JSRuntime *rt, JSValue val) { JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id); if (s) { if (s->f && s->close_in_finalizer) { if (s->is_popen) pclose(s->f); else fclose(s->f); } js_free_rt(rt, s); } } static ssize_t js_get_errno(ssize_t ret) { if (ret == -1) ret = -errno; return ret; } static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int err; if (JS_ToInt32(ctx, &err, argv[0])) return JS_EXCEPTION; return JS_NewString(ctx, strerror(err)); } static JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValue obj; const char *str; size_t len; str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) return JS_EXCEPTION; obj = JS_ParseJSON2(ctx, str, len, "<input>", JS_PARSE_JSON_EXT); JS_FreeCString(ctx, str); return obj; } static JSValue js_new_std_file(JSContext *ctx, FILE *f, BOOL close_in_finalizer, BOOL is_popen) { JSSTDFile *s; JSValue obj; obj = JS_NewObjectClass(ctx, js_std_file_class_id); if (JS_IsException(obj)) return obj; s = js_mallocz(ctx, sizeof(*s)); if (!s) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } s->close_in_finalizer = close_in_finalizer; s->is_popen = is_popen; s->f = f; JS_SetOpaque(obj, s); return obj; } static void js_set_error_object(JSContext *ctx, JSValue obj, int err) { if (!JS_IsUndefined(obj)) { JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err)); } } static JSValue js_std_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) goto fail; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (mode[strspn(mode, "rwa+b")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fopen(filename, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, TRUE, FALSE); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) goto fail; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (mode[strspn(mode, "rw")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = popen(filename, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, TRUE, TRUE); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *mode; FILE *f; int fd, err; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (mode[strspn(mode, "rwa+")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fdopen(fd, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, TRUE, FALSE); fail: JS_FreeCString(ctx, mode); return JS_EXCEPTION; } static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f; f = tmpfile(); if (argc >= 1) js_set_error_object(ctx, argv[0], f ? 0 : errno); if (!f) return JS_NULL; return js_new_std_file(ctx, f, TRUE, FALSE); } static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, NULL); } static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, stdout); } static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj) { JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id); if (!s) return NULL; if (!s->f) { JS_ThrowTypeError(ctx, "invalid file handle"); return NULL; } return s->f; } static JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f; int i; const char *str; size_t len; if (magic == 0) { f = stdout; } else { f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; } for(i = 0; i < argc; i++) { str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) return JS_EXCEPTION; fwrite(str, 1, len, f); JS_FreeCString(ctx, str); } return JS_UNDEFINED; } static JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSSTDFile *s = JS_GetOpaque2(ctx, this_val, js_std_file_class_id); int err; if (!s) return JS_EXCEPTION; if (!s->f) return JS_ThrowTypeError(ctx, "invalid file handle"); if (s->is_popen) err = js_get_errno(pclose(s->f)); else err = js_get_errno(fclose(s->f)); s->f = NULL; return JS_NewInt32(ctx, err); } static JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return js_printf_internal(ctx, argc, argv, f); } static JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; fflush(f); return JS_UNDEFINED; } static JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_bigint) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; if (!f) return JS_EXCEPTION; #if defined(__linux__) pos = ftello(f); #else pos = ftell(f); #endif if (is_bigint) return JS_NewBigInt64(ctx, pos); else return JS_NewInt64(ctx, pos); } static JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; int whence, ret; if (!f) return JS_EXCEPTION; if (JS_ToInt64Ext(ctx, &pos, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &whence, argv[1])) return JS_EXCEPTION; #if defined(__linux__) ret = fseeko(f, pos, whence); #else ret = fseek(f, pos, whence); #endif if (ret < 0) ret = -errno; return JS_NewInt32(ctx, ret); } static JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewBool(ctx, feof(f)); } static JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewBool(ctx, ferror(f)); } static JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; clearerr(f); return JS_UNDEFINED; } static JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewInt32(ctx, fileno(f)); } static JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f = js_std_file_get(ctx, this_val); uint64_t pos, len; size_t size, ret; uint8_t *buf; if (!f) return JS_EXCEPTION; if (JS_ToIndex(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[2])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); if (magic) ret = fwrite(buf + pos, 1, len, f); else ret = fread(buf + pos, 1, len, f); return JS_NewInt64(ctx, ret); } /* XXX: could use less memory and go faster */ static JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; if (!f) return JS_EXCEPTION; js_std_dbuf_init(ctx, &dbuf); for(;;) { c = fgetc(f); if (c == EOF) { if (dbuf.size == 0) { /* EOF */ dbuf_free(&dbuf); return JS_NULL; } else { break; } } if (c == '\n') break; if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_ThrowOutOfMemory(ctx); } } obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); return obj; } /* XXX: could use less memory and go faster */ static JSValue js_std_file_readAsString(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; uint64_t max_size64; size_t max_size; JSValueConst max_size_val; if (!f) return JS_EXCEPTION; if (argc >= 1) max_size_val = argv[0]; else max_size_val = JS_UNDEFINED; max_size = (size_t)-1; if (!JS_IsUndefined(max_size_val)) { if (JS_ToIndex(ctx, &max_size64, max_size_val)) return JS_EXCEPTION; if (max_size64 < max_size) max_size = max_size64; } js_std_dbuf_init(ctx, &dbuf); while (max_size != 0) { c = fgetc(f); if (c == EOF) break; if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_EXCEPTION; } max_size--; } obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); return obj; } static JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewInt32(ctx, fgetc(f)); } static JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; if (!f) return JS_EXCEPTION; if (JS_ToInt32(ctx, &c, argv[0])) return JS_EXCEPTION; c = fputc(c, f); return JS_NewInt32(ctx, c); } /* urlGet */ #define URL_GET_PROGRAM "curl -s -i" #define URL_GET_BUF_SIZE 4096 static int http_get_header_line(FILE *f, char *buf, size_t buf_size, DynBuf *dbuf) { int c; char *p; p = buf; for(;;) { c = fgetc(f); if (c < 0) return -1; if ((p - buf) < buf_size - 1) *p++ = c; if (dbuf) dbuf_putc(dbuf, c); if (c == '\n') break; } *p = '\0'; return 0; } static int http_get_status(const char *buf) { const char *p = buf; while (*p != ' ' && *p != '\0') p++; if (*p != ' ') return 0; while (*p == ' ') p++; return atoi(p); } static JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *url; DynBuf cmd_buf; DynBuf data_buf_s, *data_buf = &data_buf_s; DynBuf header_buf_s, *header_buf = &header_buf_s; char *buf; size_t i, len; int c, status; JSValue response = JS_UNDEFINED, ret_obj; JSValueConst options_obj; FILE *f; BOOL binary_flag, full_flag; url = JS_ToCString(ctx, argv[0]); if (!url) return JS_EXCEPTION; binary_flag = FALSE; full_flag = FALSE; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &binary_flag, options_obj, "binary")) goto fail_obj; if (get_bool_option(ctx, &full_flag, options_obj, "full")) { fail_obj: JS_FreeCString(ctx, url); return JS_EXCEPTION; } } js_std_dbuf_init(ctx, &cmd_buf); dbuf_printf(&cmd_buf, "%s ''", URL_GET_PROGRAM); len = strlen(url); for(i = 0; i < len; i++) { c = url[i]; if (c == '\'' || c == '\\') dbuf_putc(&cmd_buf, '\\'); dbuf_putc(&cmd_buf, c); } JS_FreeCString(ctx, url); dbuf_putstr(&cmd_buf, "''"); dbuf_putc(&cmd_buf, '\0'); if (dbuf_error(&cmd_buf)) { dbuf_free(&cmd_buf); return JS_EXCEPTION; } // printf("%s\n", (char *)cmd_buf.buf); f = popen((char *)cmd_buf.buf, "r"); dbuf_free(&cmd_buf); if (!f) { return JS_ThrowTypeError(ctx, "could not start curl"); } js_std_dbuf_init(ctx, data_buf); js_std_dbuf_init(ctx, header_buf); buf = js_malloc(ctx, URL_GET_BUF_SIZE); if (!buf) goto fail; /* get the HTTP status */ if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) { status = 0; goto bad_header; } status = http_get_status(buf); if (!full_flag && !(status >= 200 && status <= 299)) { goto bad_header; } /* wait until there is an empty line */ for(;;) { if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) { bad_header: response = JS_NULL; goto done; } if (!strcmp(buf, "\r\n")) break; } if (dbuf_error(header_buf)) goto fail; header_buf->size -= 2; /* remove the trailing CRLF */ /* download the data */ for(;;) { len = fread(buf, 1, URL_GET_BUF_SIZE, f); if (len == 0) break; dbuf_put(data_buf, (uint8_t *)buf, len); } if (dbuf_error(data_buf)) goto fail; if (binary_flag) { response = JS_NewArrayBufferCopy(ctx, data_buf->buf, data_buf->size); } else { response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size); } if (JS_IsException(response)) goto fail; done: js_free(ctx, buf); buf = NULL; pclose(f); f = NULL; dbuf_free(data_buf); data_buf = NULL; if (full_flag) { ret_obj = JS_NewObject(ctx); if (JS_IsException(ret_obj)) goto fail; JS_DefinePropertyValueStr(ctx, ret_obj, "response", response, JS_PROP_C_W_E); if (!JS_IsNull(response)) { JS_DefinePropertyValueStr(ctx, ret_obj, "responseHeaders", JS_NewStringLen(ctx, (char *)header_buf->buf, header_buf->size), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, ret_obj, "status", JS_NewInt32(ctx, status), JS_PROP_C_W_E); } } else { ret_obj = response; } dbuf_free(header_buf); return ret_obj; fail: if (f) pclose(f); js_free(ctx, buf); if (data_buf) dbuf_free(data_buf); if (header_buf) dbuf_free(header_buf); JS_FreeValue(ctx, response); return JS_EXCEPTION; } static JSClassDef js_std_file_class = { "FILE", .finalizer = js_std_file_finalizer, }; static const JSCFunctionListEntry js_std_error_props[] = { /* various errno values */ #define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) DEF(EINVAL), DEF(EIO), DEF(EACCES), DEF(EEXIST), DEF(ENOSPC), DEF(ENOSYS), DEF(EBUSY), DEF(ENOENT), DEF(EPERM), DEF(EPIPE), DEF(EBADF), #undef DEF }; static const JSCFunctionListEntry js_std_funcs[] = { JS_CFUNC_DEF("exit", 1, js_std_exit ), JS_CFUNC_DEF("gc", 0, js_std_gc ), JS_CFUNC_DEF("evalScript", 1, js_evalScript ), JS_CFUNC_DEF("loadScript", 1, js_loadScript ), JS_CFUNC_DEF("getenv", 1, js_std_getenv ), JS_CFUNC_DEF("urlGet", 1, js_std_urlGet ), JS_CFUNC_DEF("loadFile", 1, js_std_loadFile ), JS_CFUNC_DEF("strerror", 1, js_std_strerror ), JS_CFUNC_DEF("parseExtJSON", 1, js_std_parseExtJSON ), /* FILE I/O */ JS_CFUNC_DEF("open", 2, js_std_open ), JS_CFUNC_DEF("popen", 2, js_std_popen ), JS_CFUNC_DEF("fdopen", 2, js_std_fdopen ), JS_CFUNC_DEF("tmpfile", 0, js_std_tmpfile ), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 0 ), JS_CFUNC_DEF("printf", 1, js_std_printf ), JS_CFUNC_DEF("sprintf", 1, js_std_sprintf ), JS_PROP_INT32_DEF("SEEK_SET", SEEK_SET, JS_PROP_CONFIGURABLE ), JS_PROP_INT32_DEF("SEEK_CUR", SEEK_CUR, JS_PROP_CONFIGURABLE ), JS_PROP_INT32_DEF("SEEK_END", SEEK_END, JS_PROP_CONFIGURABLE ), JS_OBJECT_DEF("Error", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE), /* setenv, ... */ }; static const JSCFunctionListEntry js_std_file_proto_funcs[] = { JS_CFUNC_DEF("close", 0, js_std_file_close ), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 1 ), JS_CFUNC_DEF("printf", 1, js_std_file_printf ), JS_CFUNC_DEF("flush", 0, js_std_file_flush ), JS_CFUNC_MAGIC_DEF("tell", 0, js_std_file_tell, 0 ), JS_CFUNC_MAGIC_DEF("tello", 0, js_std_file_tell, 1 ), JS_CFUNC_DEF("seek", 2, js_std_file_seek ), JS_CFUNC_DEF("eof", 0, js_std_file_eof ), JS_CFUNC_DEF("fileno", 0, js_std_file_fileno ), JS_CFUNC_DEF("error", 0, js_std_file_error ), JS_CFUNC_DEF("clearerr", 0, js_std_file_clearerr ), JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0 ), JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1 ), JS_CFUNC_DEF("getline", 0, js_std_file_getline ), JS_CFUNC_DEF("readAsString", 0, js_std_file_readAsString ), JS_CFUNC_DEF("getByte", 0, js_std_file_getByte ), JS_CFUNC_DEF("putByte", 1, js_std_file_putByte ), /* setvbuf, ... */ }; static int js_std_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; /* FILE class */ /* the class ID is created once */ JS_NewClassID(&js_std_file_class_id); /* the class is created once per runtime */ JS_NewClass(JS_GetRuntime(ctx), js_std_file_class_id, &js_std_file_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs, countof(js_std_file_proto_funcs)); JS_SetClassProto(ctx, js_std_file_class_id, proto); JS_SetModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_SetModuleExport(ctx, m, "in", js_new_std_file(ctx, stdin, FALSE, FALSE)); JS_SetModuleExport(ctx, m, "out", js_new_std_file(ctx, stdout, FALSE, FALSE)); JS_SetModuleExport(ctx, m, "err", js_new_std_file(ctx, stderr, FALSE, FALSE)); return 0; } JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_std_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_AddModuleExport(ctx, m, "in"); JS_AddModuleExport(ctx, m, "out"); JS_AddModuleExport(ctx, m, "err"); return m; } /**********************************************************/ /* 'os' object */ static JSValue js_os_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int flags, mode, ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; if (JS_ToInt32(ctx, &flags, argv[1])) goto fail; if (argc >= 3 && !JS_IsUndefined(argv[2])) { if (JS_ToInt32(ctx, &mode, argv[2])) { fail: JS_FreeCString(ctx, filename); return JS_EXCEPTION; } } else { mode = 0666; } #if defined(_WIN32) /* force binary mode by default */ if (!(flags & O_TEXT)) flags |= O_BINARY; #endif ret = js_get_errno(open(filename, flags, mode)); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; ret = js_get_errno(close(fd)); return JS_NewInt32(ctx, ret); } static JSValue js_os_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, whence; int64_t pos, ret; BOOL is_bigint; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; is_bigint = JS_IsBigInt(ctx, argv[1]); if (JS_ToInt64Ext(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &whence, argv[2])) return JS_EXCEPTION; ret = lseek(fd, pos, whence); if (ret == -1) ret = -errno; if (is_bigint) return JS_NewBigInt64(ctx, ret); else return JS_NewInt64(ctx, ret); } static JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { int fd; uint64_t pos, len; size_t size; ssize_t ret; uint8_t *buf; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &pos, argv[2])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[3])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[1]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); if (magic) ret = js_get_errno(write(fd, buf + pos, len)); else ret = js_get_errno(read(fd, buf + pos, len)); return JS_NewInt64(ctx, ret); } static JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; return JS_NewBool(ctx, isatty(fd) == 1); } #if defined(_WIN32) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; CONSOLE_SCREEN_BUFFER_INFO info; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; handle = (HANDLE)_get_osfhandle(fd); if (!GetConsoleScreenBufferInfo(handle, &info)) return JS_NULL; obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E); return obj; } static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; handle = (HANDLE)_get_osfhandle(fd); SetConsoleMode(handle, ENABLE_WINDOW_INPUT); return JS_UNDEFINED; } #elif defined(__AOS_AMP__) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_ThrowReferenceError(ctx, "func:%s not supported yet", __func__); printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_EXCEPTION; } static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_ThrowReferenceError(ctx, "func:%s not supported yet", __func__); printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_EXCEPTION; } #else static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; struct winsize ws; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (ioctl(fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 4 && ws.ws_row >= 4) { obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E); return obj; } else { return JS_NULL; } } static struct termios oldtty; static void term_exit(void) { tcsetattr(0, TCSANOW, &oldtty); } /* XXX: should add a way to go back to normal mode */ static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { struct termios tty; int fd; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; memset(&tty, 0, sizeof(tty)); tcgetattr(fd, &tty); oldtty = tty; tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP |INLCR|IGNCR|ICRNL|IXON); tty.c_oflag |= OPOST; tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN); tty.c_cflag &= ~(CSIZE|PARENB); tty.c_cflag |= CS8; tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &tty); atexit(term_exit); return JS_UNDEFINED; } #endif /* !_WIN32 */ static JSValue js_os_remove(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; ret = js_get_errno(remove(filename)); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_rename(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *oldpath, *newpath; int ret; oldpath = JS_ToCString(ctx, argv[0]); if (!oldpath) return JS_EXCEPTION; newpath = JS_ToCString(ctx, argv[1]); if (!newpath) { JS_FreeCString(ctx, oldpath); return JS_EXCEPTION; } ret = js_get_errno(rename(oldpath, newpath)); JS_FreeCString(ctx, oldpath); JS_FreeCString(ctx, newpath); return JS_NewInt32(ctx, ret); } static BOOL is_main_thread(JSRuntime *rt) { JSThreadState *ts = JS_GetRuntimeOpaque(rt); return !ts->recv_pipe; } static JSOSRWHandler *find_rh(JSThreadState *ts, int fd) { JSOSRWHandler *rh; struct list_head *el; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == fd) return rh; } return NULL; } static void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh) { int i; list_del(&rh->link); for(i = 0; i < 2; i++) { JS_FreeValueRT(rt, rh->rw_func[i]); } js_free_rt(rt, rh); } static JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSOSRWHandler *rh; int fd; JSValueConst func; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; func = argv[1]; if (JS_IsNull(func)) { rh = find_rh(ts, fd); if (rh) { JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_NULL; if (JS_IsNull(rh->rw_func[0]) && JS_IsNull(rh->rw_func[1])) { /* remove the entry */ free_rw_handler(JS_GetRuntime(ctx), rh); } } } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); rh = find_rh(ts, fd); if (!rh) { rh = js_mallocz(ctx, sizeof(*rh)); if (!rh) return JS_EXCEPTION; rh->fd = fd; rh->rw_func[0] = JS_NULL; rh->rw_func[1] = JS_NULL; list_add_tail(&rh->link, &ts->os_rw_handlers); } JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num) { JSOSSignalHandler *sh; struct list_head *el; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); if (sh->sig_num == sig_num) return sh; } return NULL; } static void free_sh(JSRuntime *rt, JSOSSignalHandler *sh) { list_del(&sh->link); JS_FreeValueRT(rt, sh->func); js_free_rt(rt, sh); } static void os_signal_handler(int sig_num) { os_pending_signals |= ((uint64_t)1 << sig_num); } #if defined(_WIN32) typedef void (*sighandler_t)(int sig_num); #endif #if defined(__AOS_AMP__) static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { printf("%s: func:%s not supported yet\n", __FILE__, __func__); return JS_UNDEFINED; } #else static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSOSSignalHandler *sh; uint32_t sig_num; JSValueConst func; sighandler_t handler; if (!is_main_thread(rt)) return JS_ThrowTypeError(ctx, "signal handler can only be set in the main thread"); if (JS_ToUint32(ctx, &sig_num, argv[0])) return JS_EXCEPTION; if (sig_num >= 64) return JS_ThrowRangeError(ctx, "invalid signal number"); func = argv[1]; /* func = null: SIG_DFL, func = undefined, SIG_IGN */ if (JS_IsNull(func) || JS_IsUndefined(func)) { sh = find_sh(ts, sig_num); if (sh) { free_sh(JS_GetRuntime(ctx), sh); } if (JS_IsNull(func)) handler = SIG_DFL; else handler = SIG_IGN; signal(sig_num, handler); } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); sh = find_sh(ts, sig_num); if (!sh) { sh = js_mallocz(ctx, sizeof(*sh)); if (!sh) return JS_EXCEPTION; sh->sig_num = sig_num; list_add_tail(&sh->link, &ts->os_signal_handlers); } JS_FreeValue(ctx, sh->func); sh->func = JS_DupValue(ctx, func); signal(sig_num, os_signal_handler); } return JS_UNDEFINED; } #endif /* __AOS_AMP__ */ #if defined(__linux__) || defined(__APPLE__) static int64_t get_time_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000); } #else /* more portable, but does not work if the date is updated */ static int64_t get_time_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000); } #endif static void unlink_timer(JSRuntime *rt, JSOSTimer *th) { if (th->link.prev) { list_del(&th->link); th->link.prev = th->link.next = NULL; } } static void free_timer(JSRuntime *rt, JSOSTimer *th) { JS_FreeValueRT(rt, th->func); js_free_rt(rt, th); } static JSClassID js_os_timer_class_id; static void js_os_timer_finalizer(JSRuntime *rt, JSValue val) { JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id); if (th) { th->has_object = FALSE; if (!th->link.prev) free_timer(rt, th); } } static void js_os_timer_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id); if (th) { JS_MarkValue(rt, th->func, mark_func); } } static JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int64_t delay; JSValueConst func; JSOSTimer *th; JSValue obj; func = argv[0]; if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); if (JS_ToInt64(ctx, &delay, argv[1])) return JS_EXCEPTION; obj = JS_NewObjectClass(ctx, js_os_timer_class_id); if (JS_IsException(obj)) return obj; th = js_mallocz(ctx, sizeof(*th)); if (!th) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } th->has_object = TRUE; th->timeout = get_time_ms() + delay; th->func = JS_DupValue(ctx, func); list_add_tail(&th->link, &ts->os_timers); JS_SetOpaque(obj, th); return obj; } static JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSOSTimer *th = JS_GetOpaque2(ctx, argv[0], js_os_timer_class_id); if (!th) return JS_EXCEPTION; unlink_timer(JS_GetRuntime(ctx), th); return JS_UNDEFINED; } static JSClassDef js_os_timer_class = { "OSTimer", .finalizer = js_os_timer_finalizer, .gc_mark = js_os_timer_mark, }; static void call_handler(JSContext *ctx, JSValueConst func) { JSValue ret, func1; /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func1 = JS_DupValue(ctx, func); ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL); JS_FreeValue(ctx, func1); if (JS_IsException(ret)) js_std_dump_error(ctx); JS_FreeValue(ctx, ret); } #if defined(_WIN32) static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int min_delay, console_fd; int64_t cur_time, delay; JSOSRWHandler *rh; struct list_head *el; /* XXX: handle signals if useful */ if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers)) return -1; /* no more events */ /* XXX: only timers and basic console input are supported */ if (!list_empty(&ts->os_timers)) { cur_time = get_time_ms(); min_delay = 10000; list_for_each(el, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); delay = th->timeout - cur_time; if (delay <= 0) { JSValue func; /* the timer expired */ func = th->func; th->func = JS_UNDEFINED; unlink_timer(rt, th); if (!th->has_object) free_timer(rt, th); call_handler(ctx, func); JS_FreeValue(ctx, func); return 0; } else if (delay < min_delay) { min_delay = delay; } } } else { min_delay = -1; } console_fd = -1; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) { console_fd = rh->fd; break; } } if (console_fd >= 0) { DWORD ti, ret; HANDLE handle; if (min_delay == -1) ti = INFINITE; else ti = min_delay; handle = (HANDLE)_get_osfhandle(console_fd); ret = WaitForSingleObject(handle, ti); if (ret == WAIT_OBJECT_0) { list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) { call_handler(ctx, rh->rw_func[0]); /* must stop because the list may have been modified */ break; } } } } else { Sleep(min_delay); } return 0; } #else #ifdef USE_WORKER static void js_free_message(JSWorkerMessage *msg); /* return 1 if a message was handled, 0 if no message */ static int handle_posted_message(JSRuntime *rt, JSContext *ctx, JSWorkerMessageHandler *port) { JSWorkerMessagePipe *ps = port->recv_pipe; int ret; struct list_head *el; JSWorkerMessage *msg; JSValue obj, data_obj, func, retval; pthread_mutex_lock(&ps->mutex); if (!list_empty(&ps->msg_queue)) { el = ps->msg_queue.next; msg = list_entry(el, JSWorkerMessage, link); /* remove the message from the queue */ list_del(&msg->link); if (list_empty(&ps->msg_queue)) { uint8_t buf[16]; int ret; for(;;) { ret = read(ps->read_fd, buf, sizeof(buf)); if (ret >= 0) break; if (errno != EAGAIN && errno != EINTR) break; } } pthread_mutex_unlock(&ps->mutex); data_obj = JS_ReadObject(ctx, msg->data, msg->data_len, JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE); js_free_message(msg); if (JS_IsException(data_obj)) goto fail; obj = JS_NewObject(ctx); if (JS_IsException(obj)) { JS_FreeValue(ctx, data_obj); goto fail; } JS_DefinePropertyValueStr(ctx, obj, "data", data_obj, JS_PROP_C_W_E); /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func = JS_DupValue(ctx, port->on_message_func); retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj); JS_FreeValue(ctx, obj); JS_FreeValue(ctx, func); if (JS_IsException(retval)) { fail: js_std_dump_error(ctx); } else { JS_FreeValue(ctx, retval); } ret = 1; } else { pthread_mutex_unlock(&ps->mutex); ret = 0; } return ret; } #else static int handle_posted_message(JSRuntime *rt, JSContext *ctx, JSWorkerMessageHandler *port) { return 0; } #endif static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); int ret, fd_max, min_delay; int64_t cur_time, delay; fd_set rfds, wfds; JSOSRWHandler *rh; struct list_head *el; struct timeval tv, *tvp; /* only check signals in the main thread */ if (!ts->recv_pipe && unlikely(os_pending_signals != 0)) { JSOSSignalHandler *sh; uint64_t mask; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); mask = (uint64_t)1 << sh->sig_num; if (os_pending_signals & mask) { os_pending_signals &= ~mask; call_handler(ctx, sh->func); return 0; } } } if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers) && list_empty(&ts->port_list)) return -1; /* no more events */ if (!list_empty(&ts->os_timers)) { cur_time = get_time_ms(); min_delay = 10000; list_for_each(el, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); delay = th->timeout - cur_time; if (delay <= 0) { JSValue func; /* the timer expired */ func = th->func; th->func = JS_UNDEFINED; unlink_timer(rt, th); if (!th->has_object) free_timer(rt, th); call_handler(ctx, func); JS_FreeValue(ctx, func); return 0; } else if (delay < min_delay) { min_delay = delay; } } tv.tv_sec = min_delay / 1000; tv.tv_usec = (min_delay % 1000) * 1000; tvp = &tv; } else { tvp = NULL; } FD_ZERO(&rfds); FD_ZERO(&wfds); fd_max = -1; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); fd_max = max_int(fd_max, rh->fd); if (!JS_IsNull(rh->rw_func[0])) FD_SET(rh->fd, &rfds); if (!JS_IsNull(rh->rw_func[1])) FD_SET(rh->fd, &wfds); } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; fd_max = max_int(fd_max, ps->read_fd); FD_SET(ps->read_fd, &rfds); } } ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp); if (ret > 0) { list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (!JS_IsNull(rh->rw_func[0]) && FD_ISSET(rh->fd, &rfds)) { call_handler(ctx, rh->rw_func[0]); /* must stop because the list may have been modified */ goto done; } if (!JS_IsNull(rh->rw_func[1]) && FD_ISSET(rh->fd, &wfds)) { call_handler(ctx, rh->rw_func[1]); /* must stop because the list may have been modified */ goto done; } } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; if (FD_ISSET(ps->read_fd, &rfds)) { if (handle_posted_message(rt, ctx, port)) goto done; } } } } done: return 0; } #endif /* !_WIN32 */ static JSValue make_obj_error(JSContext *ctx, JSValue obj, int err) { JSValue arr; if (JS_IsException(obj)) return obj; arr = JS_NewArray(ctx); if (JS_IsException(arr)) return JS_EXCEPTION; JS_DefinePropertyValueUint32(ctx, arr, 0, obj, JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err), JS_PROP_C_W_E); return arr; } static JSValue make_string_error(JSContext *ctx, const char *buf, int err) { return make_obj_error(ctx, JS_NewString(ctx, buf), err); } /* return [cwd, errorcode] */ static JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char buf[PATH_MAX]; int err; if (!getcwd(buf, sizeof(buf))) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } static JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target; int err; target = JS_ToCString(ctx, argv[0]); if (!target) return JS_EXCEPTION; err = js_get_errno(chdir(target)); JS_FreeCString(ctx, target); return JS_NewInt32(ctx, err); } static JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int mode, ret; const char *path; if (argc >= 2) { if (JS_ToInt32(ctx, &mode, argv[1])) return JS_EXCEPTION; } else { mode = 0777; } path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) (void)mode; ret = js_get_errno(mkdir(path)); #else ret = js_get_errno(mkdir(path, mode)); #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } /* return [array, errorcode] */ static JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; DIR *f; struct dirent *d; JSValue obj; int err; uint32_t len; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; obj = JS_NewArray(ctx); if (JS_IsException(obj)) { JS_FreeCString(ctx, path); return JS_EXCEPTION; } f = opendir(path); if (!f) err = errno; else err = 0; JS_FreeCString(ctx, path); if (!f) goto done; len = 0; for(;;) { errno = 0; d = readdir(f); if (!d) { err = errno; break; } JS_DefinePropertyValueUint32(ctx, obj, len++, JS_NewString(ctx, d->d_name), JS_PROP_C_W_E); } closedir(f); done: return make_obj_error(ctx, obj, err); } #if !defined(_WIN32) static int64_t timespec_to_ms(const struct timespec *tv) { return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000); } #endif /* return [obj, errcode] */ static JSValue js_os_stat(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_lstat) { const char *path; int err, res; struct stat st; JSValue obj; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) res = stat(path, &st); #else if (is_lstat) res = lstat(path, &st); else res = stat(path, &st); #endif JS_FreeCString(ctx, path); if (res < 0) { err = errno; obj = JS_NULL; } else { err = 0; obj = JS_NewObject(ctx); if (JS_IsException(obj)) return JS_EXCEPTION; JS_DefinePropertyValueStr(ctx, obj, "dev", JS_NewInt64(ctx, st.st_dev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ino", JS_NewInt64(ctx, st.st_ino), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mode", JS_NewInt32(ctx, st.st_mode), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "nlink", JS_NewInt64(ctx, st.st_nlink), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "uid", JS_NewInt64(ctx, st.st_uid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "gid", JS_NewInt64(ctx, st.st_gid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "rdev", JS_NewInt64(ctx, st.st_rdev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "size", JS_NewInt64(ctx, st.st_size), JS_PROP_C_W_E); #if !defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "blocks", JS_NewInt64(ctx, st.st_blocks), JS_PROP_C_W_E); #endif #if defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, (int64_t)st.st_atime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000), JS_PROP_C_W_E); #elif defined(__APPLE__) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)), JS_PROP_C_W_E); #else JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)), JS_PROP_C_W_E); #endif } return make_obj_error(ctx, obj, err); } #if !defined(_WIN32) static void ms_to_timeval(struct timeval *tv, uint64_t v) { tv->tv_sec = v / 1000; tv->tv_usec = (v % 1000) * 1000; } #endif static JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; int64_t atime, mtime; int ret; if (JS_ToInt64(ctx, &atime, argv[1])) return JS_EXCEPTION; if (JS_ToInt64(ctx, &mtime, argv[2])) return JS_EXCEPTION; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) { struct _utimbuf times; times.actime = atime / 1000; times.modtime = mtime / 1000; ret = js_get_errno(_utime(path, &times)); } #else { struct timeval times[2]; ms_to_timeval(&times[0], atime); ms_to_timeval(&times[1], mtime); ret = js_get_errno(utimes(path, times)); } #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } #if !defined(_WIN32) /* return [path, errorcode] */ static JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[PATH_MAX], *res; int err; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; res = realpath(path, buf); JS_FreeCString(ctx, path); if (!res) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } static JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target, *linkpath; int err; target = JS_ToCString(ctx, argv[0]); if (!target) return JS_EXCEPTION; linkpath = JS_ToCString(ctx, argv[1]); if (!linkpath) { JS_FreeCString(ctx, target); return JS_EXCEPTION; } err = js_get_errno(symlink(target, linkpath)); JS_FreeCString(ctx, target); JS_FreeCString(ctx, linkpath); return JS_NewInt32(ctx, err); } /* return [path, errorcode] */ static JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[PATH_MAX]; int err; ssize_t res; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; res = readlink(path, buf, sizeof(buf) - 1); if (res < 0) { buf[0] = '\0'; err = errno; } else { buf[res] = '\0'; err = 0; } JS_FreeCString(ctx, path); return make_string_error(ctx, buf, err); } static char **build_envp(JSContext *ctx, JSValueConst obj) { uint32_t len, i; JSPropertyEnum *tab; char **envp, *pair; const char *key, *str; JSValue val; size_t key_len, str_len; if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0) return NULL; envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1)); if (!envp) goto fail; for(i = 0; i < len; i++) { val = JS_GetProperty(ctx, obj, tab[i].atom); if (JS_IsException(val)) goto fail; str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) goto fail; key = JS_AtomToCString(ctx, tab[i].atom); if (!key) { JS_FreeCString(ctx, str); goto fail; } key_len = strlen(key); str_len = strlen(str); pair = js_malloc(ctx, key_len + str_len + 2); if (!pair) { JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); goto fail; } memcpy(pair, key, key_len); pair[key_len] = '='; memcpy(pair + key_len + 1, str, str_len); pair[key_len + 1 + str_len] = '\0'; envp[i] = pair; JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); } done: for(i = 0; i < len; i++) JS_FreeAtom(ctx, tab[i].atom); js_free(ctx, tab); return envp; fail: if (envp) { for(i = 0; i < len; i++) js_free(ctx, envp[i]); js_free(ctx, envp); envp = NULL; } goto done; } /* execvpe is not available on non GNU systems */ static int my_execvpe(const char *filename, char **argv, char **envp) { char *path, *p, *p_next, *p1; char buf[PATH_MAX]; size_t filename_len, path_len; BOOL eacces_error; filename_len = strlen(filename); if (filename_len == 0) { errno = ENOENT; return -1; } if (strchr(filename, '/')) return execve(filename, argv, envp); path = getenv("PATH"); if (!path) path = (char *)"/bin:/usr/bin"; eacces_error = FALSE; p = path; for(p = path; p != NULL; p = p_next) { p1 = strchr(p, ':'); if (!p1) { p_next = NULL; path_len = strlen(p); } else { p_next = p1 + 1; path_len = p1 - p; } /* path too long */ if ((path_len + 1 + filename_len + 1) > PATH_MAX) continue; memcpy(buf, p, path_len); buf[path_len] = '/'; memcpy(buf + path_len + 1, filename, filename_len); buf[path_len + 1 + filename_len] = '\0'; execve(buf, argv, envp); switch(errno) { case EACCES: eacces_error = TRUE; break; case ENOENT: case ENOTDIR: break; default: return -1; } } if (eacces_error) errno = EACCES; return -1; } /* exec(args[, options]) -> exitcode */ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValueConst options, args = argv[0]; JSValue val, ret_val; const char **exec_argv, *file = NULL, *str, *cwd = NULL; char **envp = environ; uint32_t exec_argc, i; int ret, pid, status; BOOL block_flag = TRUE, use_path = TRUE; static const char *std_name[3] = { "stdin", "stdout", "stderr" }; int std_fds[3]; uint32_t uid = -1, gid = -1; val = JS_GetPropertyStr(ctx, args, "length"); if (JS_IsException(val)) return JS_EXCEPTION; ret = JS_ToUint32(ctx, &exec_argc, val); JS_FreeValue(ctx, val); if (ret) return JS_EXCEPTION; /* arbitrary limit to avoid overflow */ if (exec_argc < 1 || exec_argc > 65535) { return JS_ThrowTypeError(ctx, "invalid number of arguments"); } exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1)); if (!exec_argv) return JS_EXCEPTION; for(i = 0; i < exec_argc; i++) { val = JS_GetPropertyUint32(ctx, args, i); if (JS_IsException(val)) goto exception; str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) goto exception; exec_argv[i] = str; } exec_argv[exec_argc] = NULL; for(i = 0; i < 3; i++) std_fds[i] = i; /* get the options, if any */ if (argc >= 2) { options = argv[1]; if (get_bool_option(ctx, &block_flag, options, "block")) goto exception; if (get_bool_option(ctx, &use_path, options, "usePath")) goto exception; val = JS_GetPropertyStr(ctx, options, "file"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { file = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!file) goto exception; } val = JS_GetPropertyStr(ctx, options, "cwd"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { cwd = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!cwd) goto exception; } /* stdin/stdout/stderr handles */ for(i = 0; i < 3; i++) { val = JS_GetPropertyStr(ctx, options, std_name[i]); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { int fd; ret = JS_ToInt32(ctx, &fd, val); JS_FreeValue(ctx, val); if (ret) goto exception; std_fds[i] = fd; } } val = JS_GetPropertyStr(ctx, options, "env"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { envp = build_envp(ctx, val); JS_FreeValue(ctx, val); if (!envp) goto exception; } val = JS_GetPropertyStr(ctx, options, "uid"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &uid, val); JS_FreeValue(ctx, val); if (ret) goto exception; } val = JS_GetPropertyStr(ctx, options, "gid"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &gid, val); JS_FreeValue(ctx, val); if (ret) goto exception; } } pid = fork(); if (pid < 0) { JS_ThrowTypeError(ctx, "fork error"); goto exception; } if (pid == 0) { /* child */ int fd_max = sysconf(_SC_OPEN_MAX); /* remap the stdin/stdout/stderr handles if necessary */ for(i = 0; i < 3; i++) { if (std_fds[i] != i) { if (dup2(std_fds[i], i) < 0) _exit(127); } } for(i = 3; i < fd_max; i++) close(i); if (cwd) { if (chdir(cwd) < 0) _exit(127); } if (uid != -1) { if (setuid(uid) < 0) _exit(127); } if (gid != -1) { if (setgid(gid) < 0) _exit(127); } if (!file) file = exec_argv[0]; if (use_path) ret = my_execvpe(file, (char **)exec_argv, envp); else ret = execve(file, (char **)exec_argv, envp); _exit(127); } /* parent */ if (block_flag) { for(;;) { ret = waitpid(pid, &status, 0); if (ret == pid) { if (WIFEXITED(status)) { ret = WEXITSTATUS(status); break; } else if (WIFSIGNALED(status)) { ret = -WTERMSIG(status); break; } } } } else { ret = pid; } ret_val = JS_NewInt32(ctx, ret); done: JS_FreeCString(ctx, file); JS_FreeCString(ctx, cwd); for(i = 0; i < exec_argc; i++) JS_FreeCString(ctx, exec_argv[i]); js_free(ctx, exec_argv); if (envp != environ) { char **p; p = envp; while (*p != NULL) { js_free(ctx, *p); p++; } js_free(ctx, envp); } return ret_val; exception: ret_val = JS_EXCEPTION; goto done; } /* waitpid(pid, block) -> [pid, status] */ static JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, status, options, ret; JSValue obj; if (JS_ToInt32(ctx, &pid, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &options, argv[1])) return JS_EXCEPTION; ret = waitpid(pid, &status, options); if (ret < 0) { ret = -errno; status = 0; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status), JS_PROP_C_W_E); return obj; } /* pipe() -> [read_fd, write_fd] or null if error */ static JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pipe_fds[2], ret; JSValue obj; ret = pipe(pipe_fds); if (ret < 0) return JS_NULL; obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]), JS_PROP_C_W_E); return obj; } /* kill(pid, sig) */ static JSValue js_os_kill(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, sig, ret; if (JS_ToInt32(ctx, &pid, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &sig, argv[1])) return JS_EXCEPTION; ret = js_get_errno(kill(pid, sig)); return JS_NewInt32(ctx, ret); } /* sleep(delay_ms) */ static JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int64_t delay; struct timespec ts; int ret; if (JS_ToInt64(ctx, &delay, argv[0])) return JS_EXCEPTION; ts.tv_sec = delay / 1000; ts.tv_nsec = (delay % 1000) * 1000000; ret = js_get_errno(nanosleep(&ts, NULL)); return JS_NewInt32(ctx, ret); } /* dup(fd) */ static JSValue js_os_dup(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; ret = js_get_errno(dup(fd)); return JS_NewInt32(ctx, ret); } /* dup2(fd) */ static JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, fd2, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &fd2, argv[1])) return JS_EXCEPTION; ret = js_get_errno(dup2(fd, fd2)); return JS_NewInt32(ctx, ret); } #endif /* !_WIN32 */ #ifdef USE_WORKER /* Worker */ typedef struct { JSWorkerMessagePipe *recv_pipe; JSWorkerMessagePipe *send_pipe; JSWorkerMessageHandler *msg_handler; } JSWorkerData; typedef struct { /* source code of the worker */ char *eval_buf; size_t eval_buf_len; JSWorkerMessagePipe *recv_pipe, *send_pipe; } WorkerFuncArgs; typedef struct { int ref_count; uint64_t buf[0]; } JSSABHeader; static JSClassID js_worker_class_id; static int atomic_add_int(int *ptr, int v) { return atomic_fetch_add((_Atomic(uint32_t) *)ptr, v) + v; } /* shared array buffer allocator */ static void *js_sab_alloc(void *opaque, size_t size) { JSSABHeader *sab; sab = malloc(sizeof(JSSABHeader) + size); if (!sab) return NULL; sab->ref_count = 1; return sab->buf; } static void js_sab_free(void *opaque, void *ptr) { JSSABHeader *sab; int ref_count; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); ref_count = atomic_add_int(&sab->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { free(sab); } } static void js_sab_dup(void *opaque, void *ptr) { JSSABHeader *sab; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); atomic_add_int(&sab->ref_count, 1); } static JSWorkerMessagePipe *js_new_message_pipe(void) { JSWorkerMessagePipe *ps; int pipe_fds[2]; if (pipe(pipe_fds) < 0) return NULL; ps = malloc(sizeof(*ps)); if (!ps) { close(pipe_fds[0]); close(pipe_fds[1]); return NULL; } ps->ref_count = 1; init_list_head(&ps->msg_queue); pthread_mutex_init(&ps->mutex, NULL); ps->read_fd = pipe_fds[0]; ps->write_fd = pipe_fds[1]; return ps; } static JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps) { atomic_add_int(&ps->ref_count, 1); return ps; } static void js_free_message(JSWorkerMessage *msg) { size_t i; /* free the SAB */ for(i = 0; i < msg->sab_tab_len; i++) { js_sab_free(NULL, msg->sab_tab[i]); } free(msg->sab_tab); free(msg->data); free(msg); } static void js_free_message_pipe(JSWorkerMessagePipe *ps) { struct list_head *el, *el1; JSWorkerMessage *msg; int ref_count; if (!ps) return; ref_count = atomic_add_int(&ps->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { list_for_each_safe(el, el1, &ps->msg_queue) { msg = list_entry(el, JSWorkerMessage, link); js_free_message(msg); } pthread_mutex_destroy(&ps->mutex); close(ps->read_fd); close(ps->write_fd); free(ps); } } static void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port) { if (port) { js_free_message_pipe(port->recv_pipe); JS_FreeValueRT(rt, port->on_message_func); list_del(&port->link); js_free_rt(rt, port); } } static void js_worker_finalizer(JSRuntime *rt, JSValue val) { JSWorkerData *worker = JS_GetOpaque(val, js_worker_class_id); if (worker) { js_free_message_pipe(worker->recv_pipe); js_free_message_pipe(worker->send_pipe); js_free_port(rt, worker->msg_handler); js_free_rt(rt, worker); } } static JSClassDef js_worker_class = { "Worker", .finalizer = js_worker_finalizer, }; static void *worker_func(void *opaque) { WorkerFuncArgs *args = opaque; JSRuntime *rt; JSThreadState *ts; JSContext *ctx; JSValue retval; rt = JS_NewRuntime(); if (rt == NULL) { fprintf(stderr, "JS_NewRuntime failure"); exit(1); } js_std_init_handlers(rt); /* set the pipe to communicate with the parent */ ts = JS_GetRuntimeOpaque(rt); ts->recv_pipe = args->recv_pipe; ts->send_pipe = args->send_pipe; ctx = JS_NewContext(rt); if (ctx == NULL) { fprintf(stderr, "JS_NewContext failure"); } JS_SetCanBlock(rt, TRUE); js_std_add_helpers(ctx, -1, NULL); /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); retval = JS_Eval(ctx, args->eval_buf, args->eval_buf_len, "<worker>", JS_EVAL_TYPE_MODULE); free(args->eval_buf); free(args); if (JS_IsException(retval)) js_std_dump_error(ctx); JS_FreeValue(ctx, retval); js_std_loop(ctx); JS_FreeContext(ctx); js_std_free_handlers(rt); JS_FreeRuntime(rt); return NULL; } static JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target, JSWorkerMessagePipe *recv_pipe, JSWorkerMessagePipe *send_pipe) { JSValue obj = JS_UNDEFINED, proto; JSWorkerData *s; /* create the object */ if (JS_IsUndefined(new_target)) { proto = JS_GetClassProto(ctx, js_worker_class_id); } else { proto = JS_GetPropertyStr(ctx, new_target, "prototype"); if (JS_IsException(proto)) goto fail; } obj = JS_NewObjectProtoClass(ctx, proto, js_worker_class_id); JS_FreeValue(ctx, proto); if (JS_IsException(obj)) goto fail; s = js_mallocz(ctx, sizeof(*s)); if (!s) goto fail; s->recv_pipe = js_dup_message_pipe(recv_pipe); s->send_pipe = js_dup_message_pipe(send_pipe); JS_SetOpaque(obj, s); return obj; fail: JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); WorkerFuncArgs *args; const char *str; size_t str_len; pthread_t tid; pthread_attr_t attr; JSValue obj = JS_UNDEFINED; int ret; /* XXX: in order to avoid problems with resource liberation, we don't support creating workers inside workers */ if (!is_main_thread(rt)) return JS_ThrowTypeError(ctx, "cannot create a worker inside a worker"); /* script source */ str = JS_ToCStringLen(ctx, &str_len, argv[0]); if (!str) return JS_EXCEPTION; args = malloc(sizeof(*args)); if (!args) { JS_ThrowOutOfMemory(ctx); goto fail; } memset(args, 0, sizeof(*args)); args->eval_buf = malloc(str_len + 1); if (!args->eval_buf) { JS_ThrowOutOfMemory(ctx); goto fail; } memcpy(args->eval_buf, str, str_len + 1); args->eval_buf_len = str_len; JS_FreeCString(ctx, str); str = NULL; /* ports */ args->recv_pipe = js_new_message_pipe(); if (!args->recv_pipe) goto fail; args->send_pipe = js_new_message_pipe(); if (!args->send_pipe) goto fail; obj = js_worker_ctor_internal(ctx, new_target, args->send_pipe, args->recv_pipe); if (JS_IsUndefined(obj)) goto fail; pthread_attr_init(&attr); /* no join at the end */ pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); ret = pthread_create(&tid, &attr, worker_func, args); pthread_attr_destroy(&attr); if (ret != 0) { JS_ThrowTypeError(ctx, "could not create worker"); goto fail; } return obj; fail: JS_FreeCString(ctx, str); if (args) { free(args->eval_buf); js_free_message_pipe(args->recv_pipe); js_free_message_pipe(args->send_pipe); free(args); } JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessagePipe *ps; size_t data_len, sab_tab_len, i; uint8_t *data; JSWorkerMessage *msg; uint8_t **sab_tab; if (!worker) return JS_EXCEPTION; data = JS_WriteObject2(ctx, &data_len, argv[0], JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE, &sab_tab, &sab_tab_len); if (!data) return JS_EXCEPTION; msg = malloc(sizeof(*msg)); if (!msg) goto fail; msg->data = NULL; msg->sab_tab = NULL; /* must reallocate because the allocator may be different */ msg->data = malloc(data_len); if (!msg->data) goto fail; memcpy(msg->data, data, data_len); msg->data_len = data_len; msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab_len); if (!msg->sab_tab) goto fail; memcpy(msg->sab_tab, sab_tab, sizeof(msg->sab_tab[0]) * sab_tab_len); msg->sab_tab_len = sab_tab_len; js_free(ctx, data); js_free(ctx, sab_tab); /* increment the SAB reference counts */ for(i = 0; i < msg->sab_tab_len; i++) { js_sab_dup(NULL, msg->sab_tab[i]); } ps = worker->send_pipe; pthread_mutex_lock(&ps->mutex); /* indicate that data is present */ if (list_empty(&ps->msg_queue)) { uint8_t ch = '\0'; int ret; for(;;) { ret = write(ps->write_fd, &ch, 1); if (ret == 1) break; if (ret < 0 && (errno != EAGAIN || errno != EINTR)) break; } } list_add_tail(&msg->link, &ps->msg_queue); pthread_mutex_unlock(&ps->mutex); return JS_UNDEFINED; fail: if (msg) { free(msg->data); free(msg->sab_tab); free(msg); } js_free(ctx, data); js_free(ctx, sab_tab); return JS_EXCEPTION; } static JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val, JSValueConst func) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessageHandler *port; if (!worker) return JS_EXCEPTION; port = worker->msg_handler; if (JS_IsNull(func)) { if (port) { js_free_port(rt, port); worker->msg_handler = NULL; } } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); if (!port) { port = js_mallocz(ctx, sizeof(*port)); if (!port) return JS_EXCEPTION; port->recv_pipe = js_dup_message_pipe(worker->recv_pipe); port->on_message_func = JS_NULL; list_add_tail(&port->link, &ts->port_list); worker->msg_handler = port; } JS_FreeValue(ctx, port->on_message_func); port->on_message_func = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val) { JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id); JSWorkerMessageHandler *port; if (!worker) return JS_EXCEPTION; port = worker->msg_handler; if (port) { return JS_DupValue(ctx, port->on_message_func); } else { return JS_NULL; } } static const JSCFunctionListEntry js_worker_proto_funcs[] = { JS_CFUNC_DEF("postMessage", 1, js_worker_postMessage ), JS_CGETSET_DEF("onmessage", js_worker_get_onmessage, js_worker_set_onmessage ), }; #endif /* USE_WORKER */ #if defined(_WIN32) #define OS_PLATFORM "win32" #elif defined(__APPLE__) #define OS_PLATFORM "darwin" #elif defined(EMSCRIPTEN) #define OS_PLATFORM "js" #else #define OS_PLATFORM "linux" #endif #define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) static const JSCFunctionListEntry js_os_funcs[] = { JS_CFUNC_DEF("open", 2, js_os_open ), OS_FLAG(O_RDONLY), OS_FLAG(O_WRONLY), OS_FLAG(O_RDWR), OS_FLAG(O_APPEND), OS_FLAG(O_CREAT), OS_FLAG(O_EXCL), OS_FLAG(O_TRUNC), #if defined(_WIN32) OS_FLAG(O_BINARY), OS_FLAG(O_TEXT), #endif JS_CFUNC_DEF("close", 1, js_os_close ), JS_CFUNC_DEF("seek", 3, js_os_seek ), JS_CFUNC_MAGIC_DEF("read", 4, js_os_read_write, 0 ), JS_CFUNC_MAGIC_DEF("write", 4, js_os_read_write, 1 ), JS_CFUNC_DEF("isatty", 1, js_os_isatty ), JS_CFUNC_DEF("ttyGetWinSize", 1, js_os_ttyGetWinSize ), JS_CFUNC_DEF("ttySetRaw", 1, js_os_ttySetRaw ), JS_CFUNC_DEF("remove", 1, js_os_remove ), JS_CFUNC_DEF("rename", 2, js_os_rename ), JS_CFUNC_MAGIC_DEF("setReadHandler", 2, js_os_setReadHandler, 0 ), JS_CFUNC_MAGIC_DEF("setWriteHandler", 2, js_os_setReadHandler, 1 ), JS_CFUNC_DEF("signal", 2, js_os_signal ), OS_FLAG(SIGINT), OS_FLAG(SIGABRT), OS_FLAG(SIGFPE), OS_FLAG(SIGILL), OS_FLAG(SIGSEGV), OS_FLAG(SIGTERM), #if !defined(_WIN32) OS_FLAG(SIGQUIT), OS_FLAG(SIGPIPE), OS_FLAG(SIGALRM), OS_FLAG(SIGUSR1), OS_FLAG(SIGUSR2), #if !defined(__AOS_AMP__) OS_FLAG(SIGCHLD), OS_FLAG(SIGCONT), #endif /* __AOS_AMP__ */ OS_FLAG(SIGSTOP), OS_FLAG(SIGTSTP), #if !defined(__AOS_AMP__) OS_FLAG(SIGTTIN), OS_FLAG(SIGTTOU), #endif /* __AOS_AMP__ */ #endif JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ), JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ), JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ), JS_CFUNC_DEF("getcwd", 0, js_os_getcwd ), JS_CFUNC_DEF("chdir", 0, js_os_chdir ), JS_CFUNC_DEF("mkdir", 1, js_os_mkdir ), JS_CFUNC_DEF("readdir", 1, js_os_readdir ), /* st_mode constants */ OS_FLAG(S_IFMT), OS_FLAG(S_IFIFO), OS_FLAG(S_IFCHR), OS_FLAG(S_IFDIR), OS_FLAG(S_IFBLK), OS_FLAG(S_IFREG), #if !defined(_WIN32) OS_FLAG(S_IFSOCK), OS_FLAG(S_IFLNK), OS_FLAG(S_ISGID), OS_FLAG(S_ISUID), #endif JS_CFUNC_MAGIC_DEF("stat", 1, js_os_stat, 0 ), JS_CFUNC_DEF("utimes", 3, js_os_utimes ), #if !defined(_WIN32) JS_CFUNC_MAGIC_DEF("lstat", 1, js_os_stat, 1 ), JS_CFUNC_DEF("realpath", 1, js_os_realpath ), JS_CFUNC_DEF("symlink", 2, js_os_symlink ), JS_CFUNC_DEF("readlink", 1, js_os_readlink ), JS_CFUNC_DEF("exec", 1, js_os_exec ), JS_CFUNC_DEF("waitpid", 2, js_os_waitpid ), OS_FLAG(WNOHANG), JS_CFUNC_DEF("pipe", 0, js_os_pipe ), JS_CFUNC_DEF("kill", 2, js_os_kill ), JS_CFUNC_DEF("sleep", 1, js_os_sleep ), JS_CFUNC_DEF("dup", 1, js_os_dup ), JS_CFUNC_DEF("dup2", 2, js_os_dup2 ), #endif }; static int js_os_init(JSContext *ctx, JSModuleDef *m) { os_poll_func = js_os_poll; /* OSTimer class */ JS_NewClassID(&js_os_timer_class_id); JS_NewClass(JS_GetRuntime(ctx), js_os_timer_class_id, &js_os_timer_class); #ifdef USE_WORKER { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = JS_GetRuntimeOpaque(rt); JSValue proto, obj; /* Worker class */ JS_NewClassID(&js_worker_class_id); JS_NewClass(JS_GetRuntime(ctx), js_worker_class_id, &js_worker_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs)); obj = JS_NewCFunction2(ctx, js_worker_ctor, "Worker", 1, JS_CFUNC_constructor, 0); JS_SetConstructor(ctx, obj, proto); JS_SetClassProto(ctx, js_worker_class_id, proto); /* set 'Worker.parent' if necessary */ if (ts->recv_pipe && ts->send_pipe) { JS_DefinePropertyValueStr(ctx, obj, "parent", js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe), JS_PROP_C_W_E); } JS_SetModuleExport(ctx, m, "Worker", obj); } #endif /* USE_WORKER */ return JS_SetModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); } JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_os_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); #ifdef USE_WORKER JS_AddModuleExport(ctx, m, "Worker"); #endif return m; } /**********************************************************/ static JSValue js_print(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; const char *str; size_t len; for(i = 0; i < argc; i++) { if (i != 0) putchar(' '); str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) return JS_EXCEPTION; fwrite(str, 1, len, stdout); JS_FreeCString(ctx, str); } putchar('\n'); return JS_UNDEFINED; } void js_std_add_helpers(JSContext *ctx, int argc, char **argv) { JSValue global_obj, console, args; int i; /* XXX: should these global definitions be enumerable? */ global_obj = JS_GetGlobalObject(ctx); console = JS_NewObject(ctx); JS_SetPropertyStr(ctx, console, "log", JS_NewCFunction(ctx, js_print, "log", 1)); JS_SetPropertyStr(ctx, global_obj, "console", console); /* same methods as the mozilla JS shell */ if (argc >= 0) { args = JS_NewArray(ctx); for(i = 0; i < argc; i++) { JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i])); } JS_SetPropertyStr(ctx, global_obj, "scriptArgs", args); } JS_SetPropertyStr(ctx, global_obj, "print", JS_NewCFunction(ctx, js_print, "print", 1)); JS_SetPropertyStr(ctx, global_obj, "__loadScript", JS_NewCFunction(ctx, js_loadScript, "__loadScript", 1)); JS_FreeValue(ctx, global_obj); } void js_std_init_handlers(JSRuntime *rt) { JSThreadState *ts; ts = malloc(sizeof(*ts)); if (!ts) { fprintf(stderr, "Could not allocate memory for the worker"); exit(1); } memset(ts, 0, sizeof(*ts)); init_list_head(&ts->os_rw_handlers); init_list_head(&ts->os_signal_handlers); init_list_head(&ts->os_timers); init_list_head(&ts->port_list); JS_SetRuntimeOpaque(rt, ts); #ifdef USE_WORKER /* set the SharedArrayBuffer memory handlers */ { JSSharedArrayBufferFunctions sf; memset(&sf, 0, sizeof(sf)); sf.sab_alloc = js_sab_alloc; sf.sab_free = js_sab_free; sf.sab_dup = js_sab_dup; JS_SetSharedArrayBufferFunctions(rt, &sf); } #endif } void js_std_free_handlers(JSRuntime *rt) { JSThreadState *ts = JS_GetRuntimeOpaque(rt); struct list_head *el, *el1; list_for_each_safe(el, el1, &ts->os_rw_handlers) { JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link); free_rw_handler(rt, rh); } list_for_each_safe(el, el1, &ts->os_signal_handlers) { JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link); free_sh(rt, sh); } list_for_each_safe(el, el1, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); unlink_timer(rt, th); if (!th->has_object) free_timer(rt, th); } free(ts); JS_SetRuntimeOpaque(rt, NULL); /* fail safe */ } static void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val) { const char *str; str = JS_ToCString(ctx, val); if (str) { fprintf(f, "%s\n", str); JS_FreeCString(ctx, str); } else { fprintf(f, "[exception]\n"); } } static void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val) { JSValue val; BOOL is_error; is_error = JS_IsError(ctx, exception_val); js_dump_obj(ctx, stderr, exception_val); if (is_error) { val = JS_GetPropertyStr(ctx, exception_val, "stack"); if (!JS_IsUndefined(val)) { js_dump_obj(ctx, stderr, val); } JS_FreeValue(ctx, val); } } void js_std_dump_error(JSContext *ctx) { JSValue exception_val; exception_val = JS_GetException(ctx); js_std_dump_error1(ctx, exception_val); JS_FreeValue(ctx, exception_val); } void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, BOOL is_handled, void *opaque) { if (!is_handled) { fprintf(stderr, "Possibly unhandled promise rejection: "); js_std_dump_error1(ctx, reason); } } /* main loop which calls the user JS callbacks */ void js_std_loop(JSContext *ctx) { JSContext *ctx1; int err; for(;;) { /* execute the pending jobs */ for(;;) { err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (err <= 0) { if (err < 0) { js_std_dump_error(ctx1); } break; } } if (!os_poll_func || os_poll_func(ctx)) break; } } void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len, int load_only) { JSValue obj, val; obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE); if (JS_IsException(obj)) goto exception; if (load_only) { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { js_module_set_import_meta(ctx, obj, FALSE, FALSE); } } else { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (JS_ResolveModule(ctx, obj) < 0) { JS_FreeValue(ctx, obj); goto exception; } js_module_set_import_meta(ctx, obj, FALSE, TRUE); } val = JS_EvalFunction(ctx, obj); if (JS_IsException(val)) { exception: js_std_dump_error(ctx); exit(1); } JS_FreeValue(ctx, val); } }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/quickjs-libc.c
C
apache-2.0
108,121
/* * QuickJS C library * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef QUICKJS_LIBC_H #define QUICKJS_LIBC_H #include <stdio.h> #include <stdlib.h> #include "quickjs.h" #ifdef __cplusplus extern "C" { #endif JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name); JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name); void js_std_add_helpers(JSContext *ctx, int argc, char **argv); void js_std_loop(JSContext *ctx); void js_std_init_handlers(JSRuntime *rt); void js_std_free_handlers(JSRuntime *rt); void js_std_dump_error(JSContext *ctx); uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename); int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, JS_BOOL use_realpath, JS_BOOL is_main); JSModuleDef *js_module_loader(JSContext *ctx, const char *module_name, void *opaque); void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len, int flags); void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, void *opaque); #ifdef __cplusplus } /* extern "C" { */ #endif #endif /* QUICKJS_LIBC_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/quickjs-libc.h
C
apache-2.0
2,399
/* * QuickJS opcode definitions * * Copyright (c) 2017-2018 Fabrice Bellard * Copyright (c) 2017-2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifdef FMT FMT(none) FMT(none_int) FMT(none_loc) FMT(none_arg) FMT(none_var_ref) FMT(u8) FMT(i8) FMT(loc8) FMT(const8) FMT(label8) FMT(u16) FMT(i16) FMT(label16) FMT(npop) FMT(npopx) FMT(npop_u16) FMT(loc) FMT(arg) FMT(var_ref) FMT(u32) FMT(i32) FMT(const) FMT(label) FMT(atom) FMT(atom_u8) FMT(atom_u16) FMT(atom_label_u8) FMT(atom_label_u16) FMT(label_u16) #undef FMT #endif /* FMT */ #ifdef DEF #ifndef def #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) #endif DEF(invalid, 1, 0, 0, none) /* never emitted */ /* push values */ DEF( push_i32, 5, 0, 1, i32) DEF( push_const, 5, 0, 1, const) DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ DEF(push_atom_value, 5, 0, 1, atom) DEF( private_symbol, 5, 0, 1, atom) DEF( undefined, 1, 0, 1, none) DEF( null, 1, 0, 1, none) DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ DEF( push_false, 1, 0, 1, none) DEF( push_true, 1, 0, 1, none) DEF( object, 1, 0, 1, none) DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ DEF( drop, 1, 1, 0, none) /* a -> */ DEF( nip, 1, 2, 1, none) /* a b -> b */ DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ DEF( dup, 1, 1, 2, none) /* a -> a a */ DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ DEF( swap, 1, 2, 2, none) /* a b -> b a */ DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ DEF( apply, 3, 3, 1, u16) DEF( return, 1, 1, 0, none) DEF( return_undef, 1, 0, 0, none) DEF(check_ctor_return, 1, 1, 2, none) DEF( check_ctor, 1, 0, 0, none) DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ DEF( return_async, 1, 1, 0, none) DEF( throw, 1, 1, 0, none) DEF( throw_var, 6, 0, 0, atom_u8) DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a bytecode string */ DEF( get_super, 1, 1, 1, none) DEF( import, 1, 1, 1, none) /* dynamic module import */ DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */ DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */ DEF( get_ref_value, 1, 2, 3, none) DEF( put_ref_value, 1, 3, 0, none) DEF( define_var, 6, 0, 0, atom_u8) DEF(check_define_var, 6, 0, 0, atom_u8) DEF( define_func, 6, 1, 0, atom_u8) DEF( get_field, 5, 1, 1, atom) DEF( get_field2, 5, 1, 2, atom) DEF( put_field, 5, 2, 0, atom) DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ DEF( get_array_el, 1, 2, 1, none) DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ DEF( put_array_el, 1, 3, 0, none) DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ DEF( define_field, 5, 2, 1, atom) DEF( set_name, 5, 1, 1, atom) DEF(set_name_computed, 1, 2, 2, none) DEF( set_proto, 1, 2, 1, none) DEF(set_home_object, 1, 2, 2, none) DEF(define_array_el, 1, 3, 2, none) DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ DEF(copy_data_properties, 2, 3, 3, u8) DEF( define_method, 6, 2, 1, atom_u8) DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ DEF( get_loc, 3, 0, 1, loc) DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ DEF( get_arg, 3, 0, 1, arg) DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ DEF( get_var_ref, 3, 0, 1, var_ref) DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ DEF(set_loc_uninitialized, 3, 0, 0, loc) DEF( get_loc_check, 3, 0, 1, loc) DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ DEF( put_loc_check_init, 3, 1, 0, loc) DEF(get_var_ref_check, 3, 0, 1, var_ref) DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ DEF(put_var_ref_check_init, 3, 1, 0, var_ref) DEF( close_loc, 3, 0, 0, loc) DEF( if_false, 5, 1, 0, label) DEF( if_true, 5, 1, 0, label) /* must come after if_false */ DEF( goto, 5, 0, 0, label) /* must come after if_true */ DEF( catch, 5, 0, 1, label) DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ DEF( to_object, 1, 1, 1, none) //DEF( to_string, 1, 1, 1, none) DEF( to_propkey, 1, 1, 1, none) DEF( to_propkey2, 1, 2, 2, none) DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) DEF( make_loc_ref, 7, 0, 2, atom_u16) DEF( make_arg_ref, 7, 0, 2, atom_u16) DEF(make_var_ref_ref, 7, 0, 2, atom_u16) DEF( make_var_ref, 5, 0, 2, atom) DEF( for_in_start, 1, 1, 1, none) DEF( for_of_start, 1, 1, 3, none) DEF(for_await_of_start, 1, 1, 3, none) DEF( for_in_next, 1, 1, 3, none) DEF( for_of_next, 2, 3, 5, u8) DEF(for_await_of_next, 1, 3, 4, none) DEF(iterator_get_value_done, 1, 1, 2, none) DEF( iterator_close, 1, 3, 0, none) DEF(iterator_close_return, 1, 4, 4, none) DEF(async_iterator_close, 1, 3, 2, none) DEF(async_iterator_next, 1, 4, 4, none) DEF(async_iterator_get, 2, 4, 5, u8) DEF( initial_yield, 1, 0, 0, none) DEF( yield, 1, 1, 2, none) DEF( yield_star, 1, 2, 2, none) DEF(async_yield_star, 1, 1, 2, none) DEF( await, 1, 1, 1, none) /* arithmetic/logic operations */ DEF( neg, 1, 1, 1, none) DEF( plus, 1, 1, 1, none) DEF( dec, 1, 1, 1, none) DEF( inc, 1, 1, 1, none) DEF( post_dec, 1, 1, 2, none) DEF( post_inc, 1, 1, 2, none) DEF( dec_loc, 2, 0, 0, loc8) DEF( inc_loc, 2, 0, 0, loc8) DEF( add_loc, 2, 1, 0, loc8) DEF( not, 1, 1, 1, none) DEF( lnot, 1, 1, 1, none) DEF( typeof, 1, 1, 1, none) DEF( delete, 1, 2, 1, none) DEF( delete_var, 5, 0, 1, atom) DEF( mul, 1, 2, 1, none) DEF( div, 1, 2, 1, none) DEF( mod, 1, 2, 1, none) DEF( add, 1, 2, 1, none) DEF( sub, 1, 2, 1, none) DEF( pow, 1, 2, 1, none) DEF( shl, 1, 2, 1, none) DEF( sar, 1, 2, 1, none) DEF( shr, 1, 2, 1, none) DEF( lt, 1, 2, 1, none) DEF( lte, 1, 2, 1, none) DEF( gt, 1, 2, 1, none) DEF( gte, 1, 2, 1, none) DEF( instanceof, 1, 2, 1, none) DEF( in, 1, 2, 1, none) DEF( eq, 1, 2, 1, none) DEF( neq, 1, 2, 1, none) DEF( strict_eq, 1, 2, 1, none) DEF( strict_neq, 1, 2, 1, none) DEF( and, 1, 2, 1, none) DEF( xor, 1, 2, 1, none) DEF( or, 1, 2, 1, none) DEF(is_undefined_or_null, 1, 1, 1, none) #ifdef CONFIG_BIGNUM DEF( mul_pow10, 1, 2, 1, none) DEF( math_mod, 1, 2, 1, none) #endif /* must be the last non short and non temporary opcode */ DEF( nop, 1, 0, 0, none) /* temporary opcodes: never emitted in the final bytecode */ def(set_arg_valid_upto, 3, 0, 0, arg) /* emitted in phase 1, removed in phase 2 */ def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ def(scope_put_private_field, 7, 1, 1, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ def( line_num, 5, 0, 0, u32) /* emitted in phase 1, removed in phase 3 */ #if SHORT_OPCODES DEF( push_minus1, 1, 0, 1, none_int) DEF( push_0, 1, 0, 1, none_int) DEF( push_1, 1, 0, 1, none_int) DEF( push_2, 1, 0, 1, none_int) DEF( push_3, 1, 0, 1, none_int) DEF( push_4, 1, 0, 1, none_int) DEF( push_5, 1, 0, 1, none_int) DEF( push_6, 1, 0, 1, none_int) DEF( push_7, 1, 0, 1, none_int) DEF( push_i8, 2, 0, 1, i8) DEF( push_i16, 3, 0, 1, i16) DEF( push_const8, 2, 0, 1, const8) DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ DEF(push_empty_string, 1, 0, 1, none) DEF( get_loc8, 2, 0, 1, loc8) DEF( put_loc8, 2, 1, 0, loc8) DEF( set_loc8, 2, 1, 1, loc8) DEF( get_loc0, 1, 0, 1, none_loc) DEF( get_loc1, 1, 0, 1, none_loc) DEF( get_loc2, 1, 0, 1, none_loc) DEF( get_loc3, 1, 0, 1, none_loc) DEF( put_loc0, 1, 1, 0, none_loc) DEF( put_loc1, 1, 1, 0, none_loc) DEF( put_loc2, 1, 1, 0, none_loc) DEF( put_loc3, 1, 1, 0, none_loc) DEF( set_loc0, 1, 1, 1, none_loc) DEF( set_loc1, 1, 1, 1, none_loc) DEF( set_loc2, 1, 1, 1, none_loc) DEF( set_loc3, 1, 1, 1, none_loc) DEF( get_arg0, 1, 0, 1, none_arg) DEF( get_arg1, 1, 0, 1, none_arg) DEF( get_arg2, 1, 0, 1, none_arg) DEF( get_arg3, 1, 0, 1, none_arg) DEF( put_arg0, 1, 1, 0, none_arg) DEF( put_arg1, 1, 1, 0, none_arg) DEF( put_arg2, 1, 1, 0, none_arg) DEF( put_arg3, 1, 1, 0, none_arg) DEF( set_arg0, 1, 1, 1, none_arg) DEF( set_arg1, 1, 1, 1, none_arg) DEF( set_arg2, 1, 1, 1, none_arg) DEF( set_arg3, 1, 1, 1, none_arg) DEF( get_var_ref0, 1, 0, 1, none_var_ref) DEF( get_var_ref1, 1, 0, 1, none_var_ref) DEF( get_var_ref2, 1, 0, 1, none_var_ref) DEF( get_var_ref3, 1, 0, 1, none_var_ref) DEF( put_var_ref0, 1, 1, 0, none_var_ref) DEF( put_var_ref1, 1, 1, 0, none_var_ref) DEF( put_var_ref2, 1, 1, 0, none_var_ref) DEF( put_var_ref3, 1, 1, 0, none_var_ref) DEF( set_var_ref0, 1, 1, 1, none_var_ref) DEF( set_var_ref1, 1, 1, 1, none_var_ref) DEF( set_var_ref2, 1, 1, 1, none_var_ref) DEF( set_var_ref3, 1, 1, 1, none_var_ref) DEF( get_length, 1, 1, 1, none) DEF( if_false8, 2, 1, 0, label8) DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ DEF( goto16, 3, 0, 0, label16) DEF( call0, 1, 1, 1, npopx) DEF( call1, 1, 1, 1, npopx) DEF( call2, 1, 1, 1, npopx) DEF( call3, 1, 1, 1, npopx) DEF( is_undefined, 1, 1, 1, none) DEF( is_null, 1, 1, 1, none) DEF( is_function, 1, 1, 1, none) #endif #undef DEF #undef def #endif /* DEF */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/quickjs-opcode.h
C
apache-2.0
15,331
/* * QuickJS Javascript Engine * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef QUICKJS_H #define QUICKJS_H #include <stdio.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #if defined(__GNUC__) || defined(__clang__) #define js_likely(x) __builtin_expect(!!(x), 1) #define js_unlikely(x) __builtin_expect(!!(x), 0) #define js_force_inline inline __attribute__((always_inline)) #define __js_printf_like(f, a) __attribute__((format(printf, f, a))) #else #define js_likely(x) (x) #define js_unlikely(x) (x) #define js_force_inline inline #define __js_printf_like(a, b) #endif #define JS_BOOL int typedef struct JSRuntime JSRuntime; typedef struct JSContext JSContext; typedef struct JSObject JSObject; typedef struct JSClass JSClass; typedef uint32_t JSClassID; typedef uint32_t JSAtom; #if INTPTR_MAX >= INT64_MAX #define JS_PTR64 #define JS_PTR64_DEF(a) a #else #define JS_PTR64_DEF(a) #endif #ifndef JS_PTR64 #define JS_NAN_BOXING #endif enum { /* all tags with a reference count are negative */ JS_TAG_FIRST = -11, /* first negative tag */ JS_TAG_BIG_DECIMAL = -11, JS_TAG_BIG_INT = -10, JS_TAG_BIG_FLOAT = -9, JS_TAG_SYMBOL = -8, JS_TAG_STRING = -7, JS_TAG_MODULE = -3, /* used internally */ JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */ JS_TAG_OBJECT = -1, JS_TAG_INT = 0, JS_TAG_BOOL = 1, JS_TAG_NULL = 2, JS_TAG_UNDEFINED = 3, JS_TAG_UNINITIALIZED = 4, JS_TAG_CATCH_OFFSET = 5, JS_TAG_EXCEPTION = 6, JS_TAG_FLOAT64 = 7, /* any larger tag is FLOAT64 if JS_NAN_BOXING */ }; typedef struct JSRefCountHeader { int ref_count; } JSRefCountHeader; #define JS_FLOAT64_NAN NAN #ifdef CONFIG_CHECK_JSVALUE /* JSValue consistency : it is not possible to run the code in this mode, but it is useful to detect simple reference counting errors. It would be interesting to modify a static C analyzer to handle specific annotations (clang has such annotations but only for objective C) */ typedef struct __JSValue *JSValue; typedef const struct __JSValue *JSValueConst; #define JS_VALUE_GET_TAG(v) (int)((uintptr_t)(v) & 0xf) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ #define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) #define JS_VALUE_GET_INT(v) (int)((intptr_t)(v) >> 4) #define JS_VALUE_GET_BOOL(v) JS_VALUE_GET_INT(v) #define JS_VALUE_GET_FLOAT64(v) (double)JS_VALUE_GET_INT(v) #define JS_VALUE_GET_PTR(v) (void *)((intptr_t)(v) & ~0xf) #define JS_MKVAL(tag, val) (JSValue)(intptr_t)(((val) << 4) | (tag)) #define JS_MKPTR(tag, p) (JSValue)((intptr_t)(p) | (tag)) #define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) #define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 1) static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { return JS_MKVAL(JS_TAG_FLOAT64, (int)d); } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { return 0; } #elif defined(JS_NAN_BOXING) typedef uint64_t JSValue; #define JSValueConst JSValue #define JS_VALUE_GET_TAG(v) (int)((v) >> 32) #define JS_VALUE_GET_INT(v) (int)(v) #define JS_VALUE_GET_BOOL(v) (int)(v) #define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v) #define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val)) #define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr)) #define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */ static inline double JS_VALUE_GET_FLOAT64(JSValue v) { union { JSValue v; double d; } u; u.v = v; u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32; return u.d; } #define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32)) static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { union { double d; uint64_t u64; } u; JSValue v; u.d = d; /* normalize NaN */ if (js_unlikely((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000)) v = JS_NAN; else v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32); return v; } #define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST)) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ static inline int JS_VALUE_GET_NORM_TAG(JSValue v) { uint32_t tag; tag = JS_VALUE_GET_TAG(v); if (JS_TAG_IS_FLOAT64(tag)) return JS_TAG_FLOAT64; else return tag; } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { uint32_t tag; tag = JS_VALUE_GET_TAG(v); return tag == (JS_NAN >> 32); } #else /* !JS_NAN_BOXING */ typedef union JSValueUnion { int32_t int32; double float64; void *ptr; } JSValueUnion; typedef struct JSValue { JSValueUnion u; int64_t tag; } JSValue; #define JSValueConst JSValue #define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ #define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) #define JS_VALUE_GET_INT(v) ((v).u.int32) #define JS_VALUE_GET_BOOL(v) ((v).u.int32) #define JS_VALUE_GET_FLOAT64(v) ((v).u.float64) #define JS_VALUE_GET_PTR(v) ((v).u.ptr) #define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag } #define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag } #define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) #define JS_NAN (JSValue){ .u.float64 = JS_FLOAT64_NAN, JS_TAG_FLOAT64 } static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { JSValue v; v.tag = JS_TAG_FLOAT64; v.u.float64 = d; return v; } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { union { double d; uint64_t u64; } u; if (v.tag != JS_TAG_FLOAT64) return 0; u.d = v.u.float64; return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000; } #endif /* !JS_NAN_BOXING */ #define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0) #define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2))) #define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v)) #define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v)) #define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST) /* special values */ #define JS_NULL JS_MKVAL(JS_TAG_NULL, 0) #define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0) #define JS_FALSE JS_MKVAL(JS_TAG_BOOL, 0) #define JS_TRUE JS_MKVAL(JS_TAG_BOOL, 1) #define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0) #define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0) /* flags for object properties */ #define JS_PROP_CONFIGURABLE (1 << 0) #define JS_PROP_WRITABLE (1 << 1) #define JS_PROP_ENUMERABLE (1 << 2) #define JS_PROP_C_W_E (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE) #define JS_PROP_LENGTH (1 << 3) /* used internally in Arrays */ #define JS_PROP_TMASK (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */ #define JS_PROP_NORMAL (0 << 4) #define JS_PROP_GETSET (1 << 4) #define JS_PROP_VARREF (2 << 4) /* used internally */ #define JS_PROP_AUTOINIT (3 << 4) /* used internally */ /* flags for JS_DefineProperty */ #define JS_PROP_HAS_SHIFT 8 #define JS_PROP_HAS_CONFIGURABLE (1 << 8) #define JS_PROP_HAS_WRITABLE (1 << 9) #define JS_PROP_HAS_ENUMERABLE (1 << 10) #define JS_PROP_HAS_GET (1 << 11) #define JS_PROP_HAS_SET (1 << 12) #define JS_PROP_HAS_VALUE (1 << 13) /* throw an exception if false would be returned (JS_DefineProperty/JS_SetProperty) */ #define JS_PROP_THROW (1 << 14) /* throw an exception if false would be returned in strict mode (JS_SetProperty) */ #define JS_PROP_THROW_STRICT (1 << 15) #define JS_PROP_NO_ADD (1 << 16) /* internal use */ #define JS_PROP_NO_EXOTIC (1 << 17) /* internal use */ #define JS_DEFAULT_STACK_SIZE (256 * 1024) /* JS_Eval() flags */ #define JS_EVAL_TYPE_GLOBAL (0 << 0) /* global code (default) */ #define JS_EVAL_TYPE_MODULE (1 << 0) /* module code */ #define JS_EVAL_TYPE_DIRECT (2 << 0) /* direct call (internal use) */ #define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */ #define JS_EVAL_TYPE_MASK (3 << 0) #define JS_EVAL_FLAG_STRICT (1 << 3) /* force 'strict' mode */ #define JS_EVAL_FLAG_STRIP (1 << 4) /* force 'strip' mode */ /* compile but do not run. The result is an object with a JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed with JS_EvalFunction(). */ #define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5) /* don't include the stack frames before this eval in the Error() backtraces */ #define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6) typedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); typedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); typedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data); typedef struct JSMallocState { size_t malloc_count; size_t malloc_size; size_t malloc_limit; void *opaque; /* user opaque */ } JSMallocState; typedef struct JSMallocFunctions { void *(*js_malloc)(JSMallocState *s, size_t size); void (*js_free)(JSMallocState *s, void *ptr); void *(*js_realloc)(JSMallocState *s, void *ptr, size_t size); size_t (*js_malloc_usable_size)(const void *ptr); } JSMallocFunctions; typedef struct JSGCObjectHeader JSGCObjectHeader; JSRuntime *JS_NewRuntime(void); /* info lifetime must exceed that of rt */ void JS_SetRuntimeInfo(JSRuntime *rt, const char *info); void JS_SetMemoryLimit(JSRuntime *rt, size_t limit); void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold); void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size); JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque); void JS_FreeRuntime(JSRuntime *rt); void *JS_GetRuntimeOpaque(JSRuntime *rt); void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque); typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp); void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); void JS_RunGC(JSRuntime *rt); JS_BOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj); JSContext *JS_NewContext(JSRuntime *rt); void JS_FreeContext(JSContext *s); JSContext *JS_DupContext(JSContext *ctx); void *JS_GetContextOpaque(JSContext *ctx); void JS_SetContextOpaque(JSContext *ctx, void *opaque); JSRuntime *JS_GetRuntime(JSContext *ctx); void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj); JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id); /* the following functions are used to select the intrinsic object to save memory */ JSContext *JS_NewContextRaw(JSRuntime *rt); void JS_AddIntrinsicBaseObjects(JSContext *ctx); void JS_AddIntrinsicDate(JSContext *ctx); void JS_AddIntrinsicEval(JSContext *ctx); void JS_AddIntrinsicStringNormalize(JSContext *ctx); void JS_AddIntrinsicRegExpCompiler(JSContext *ctx); void JS_AddIntrinsicRegExp(JSContext *ctx); void JS_AddIntrinsicJSON(JSContext *ctx); void JS_AddIntrinsicProxy(JSContext *ctx); void JS_AddIntrinsicMapSet(JSContext *ctx); void JS_AddIntrinsicTypedArrays(JSContext *ctx); void JS_AddIntrinsicPromise(JSContext *ctx); void JS_AddIntrinsicBigInt(JSContext *ctx); void JS_AddIntrinsicBigFloat(JSContext *ctx); void JS_AddIntrinsicBigDecimal(JSContext *ctx); /* enable operator overloading */ void JS_AddIntrinsicOperators(JSContext *ctx); /* enable "use math" */ void JS_EnableBignumExt(JSContext *ctx, JS_BOOL enable); JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); void *js_malloc_rt(JSRuntime *rt, size_t size); void js_free_rt(JSRuntime *rt, void *ptr); void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size); size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr); void *js_mallocz_rt(JSRuntime *rt, size_t size); void *js_malloc(JSContext *ctx, size_t size); void js_free(JSContext *ctx, void *ptr); void *js_realloc(JSContext *ctx, void *ptr, size_t size); size_t js_malloc_usable_size(JSContext *ctx, const void *ptr); void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack); void *js_mallocz(JSContext *ctx, size_t size); char *js_strdup(JSContext *ctx, const char *str); char *js_strndup(JSContext *ctx, const char *s, size_t n); typedef struct JSMemoryUsage { int64_t malloc_size, malloc_limit, memory_used_size; int64_t malloc_count; int64_t memory_used_count; int64_t atom_count, atom_size; int64_t str_count, str_size; int64_t obj_count, obj_size; int64_t prop_count, prop_size; int64_t shape_count, shape_size; int64_t js_func_count, js_func_size, js_func_code_size; int64_t js_func_pc2line_count, js_func_pc2line_size; int64_t c_func_count, array_count; int64_t fast_array_count, fast_array_elements; int64_t binary_object_count, binary_object_size; } JSMemoryUsage; void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s); void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt); /* atom support */ JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len); JSAtom JS_NewAtom(JSContext *ctx, const char *str); JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n); JSAtom JS_DupAtom(JSContext *ctx, JSAtom v); void JS_FreeAtom(JSContext *ctx, JSAtom v); void JS_FreeAtomRT(JSRuntime *rt, JSAtom v); JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom); JSValue JS_AtomToString(JSContext *ctx, JSAtom atom); const char *JS_AtomToCString(JSContext *ctx, JSAtom atom); JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val); /* object class support */ typedef struct JSPropertyEnum { JS_BOOL is_enumerable; JSAtom atom; } JSPropertyEnum; typedef struct JSPropertyDescriptor { int flags; JSValue value; JSValue getter; JSValue setter; } JSPropertyDescriptor; typedef struct JSClassExoticMethods { /* Return -1 if exception (can only happen in case of Proxy object), FALSE if the property does not exists, TRUE if it exists. If 1 is returned, the property descriptor 'desc' is filled if != NULL. */ int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop); /* '*ptab' should hold the '*plen' property keys. Return 0 if OK, -1 if exception. The 'is_enumerable' field is ignored. */ int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj); /* return < 0 if exception, or TRUE/FALSE */ int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop); /* return < 0 if exception or TRUE/FALSE */ int (*define_own_property)(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); /* The following methods can be emulated with the previous ones, so they are usually not needed */ /* return < 0 if exception or TRUE/FALSE */ int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom); JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst receiver); /* return < 0 if exception or TRUE/FALSE */ int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst value, JSValueConst receiver, int flags); } JSClassExoticMethods; typedef void JSClassFinalizer(JSRuntime *rt, JSValue val); typedef void JSClassGCMark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); #define JS_CALL_FLAG_CONSTRUCTOR (1 << 0) typedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj, JSValueConst this_val, int argc, JSValueConst *argv, int flags); typedef struct JSClassDef { const char *class_name; JSClassFinalizer *finalizer; JSClassGCMark *gc_mark; /* if call != NULL, the object is a function. If (flags & JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a constructor. In this case, 'this_val' is new.target. A constructor call only happens if the object constructor bit is set (see JS_SetConstructorBit()). */ JSClassCall *call; /* XXX: suppress this indirection ? It is here only to save memory because only a few classes need these methods */ JSClassExoticMethods *exotic; } JSClassDef; JSClassID JS_NewClassID(JSClassID *pclass_id); int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def); int JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id); /* value handling */ static js_force_inline JSValue JS_NewBool(JSContext *ctx, JS_BOOL val) { return JS_MKVAL(JS_TAG_BOOL, (val != 0)); } static js_force_inline JSValue JS_NewInt32(JSContext *ctx, int32_t val) { return JS_MKVAL(JS_TAG_INT, val); } static js_force_inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val) { return JS_MKVAL(JS_TAG_CATCH_OFFSET, val); } static js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val) { JSValue v; if (val == (int32_t)val) { v = JS_NewInt32(ctx, val); } else { v = __JS_NewFloat64(ctx, val); } return v; } static js_force_inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val) { JSValue v; if (val <= 0x7fffffff) { v = JS_NewInt32(ctx, val); } else { v = __JS_NewFloat64(ctx, val); } return v; } JSValue JS_NewBigInt64(JSContext *ctx, int64_t v); JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v); static js_force_inline JSValue JS_NewFloat64(JSContext *ctx, double d) { JSValue v; int32_t val; union { double d; uint64_t u; } u, t; u.d = d; val = (int32_t)d; t.d = val; /* -0 cannot be represented as integer, so we compare the bit representation */ if (u.u == t.u) { v = JS_MKVAL(JS_TAG_INT, val); } else { v = __JS_NewFloat64(ctx, d); } return v; } static inline JS_BOOL JS_IsNumber(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag); } static inline JS_BOOL JS_IsBigInt(JSContext *ctx, JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_INT; } static inline JS_BOOL JS_IsBigFloat(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_FLOAT; } static inline JS_BOOL JS_IsBigDecimal(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_DECIMAL; } static inline JS_BOOL JS_IsBool(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL; } static inline JS_BOOL JS_IsNull(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_NULL; } static inline JS_BOOL JS_IsUndefined(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED; } static inline JS_BOOL JS_IsException(JSValueConst v) { return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION); } static inline JS_BOOL JS_IsUninitialized(JSValueConst v) { return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED); } static inline JS_BOOL JS_IsString(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_STRING; } static inline JS_BOOL JS_IsSymbol(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL; } static inline JS_BOOL JS_IsObject(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT; } JSValue JS_Throw(JSContext *ctx, JSValue obj); JSValue JS_GetException(JSContext *ctx); JS_BOOL JS_IsError(JSContext *ctx, JSValueConst val); void JS_ResetUncatchableError(JSContext *ctx); JSValue JS_NewError(JSContext *ctx); JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...); JSValue JS_ThrowOutOfMemory(JSContext *ctx); void __JS_FreeValue(JSContext *ctx, JSValue v); static inline void JS_FreeValue(JSContext *ctx, JSValue v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); if (--p->ref_count <= 0) { __JS_FreeValue(ctx, v); } } } void __JS_FreeValueRT(JSRuntime *rt, JSValue v); static inline void JS_FreeValueRT(JSRuntime *rt, JSValue v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); if (--p->ref_count <= 0) { __JS_FreeValueRT(rt, v); } } } static inline JSValue JS_DupValue(JSContext *ctx, JSValueConst v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); p->ref_count++; } return (JSValue)v; } static inline JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); p->ref_count++; } return (JSValue)v; } int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */ int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val); static inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val) { return JS_ToInt32(ctx, (int32_t*)pres, val); } int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val); int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val); int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val); /* return an exception if 'val' is a Number */ int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val); /* same as JS_ToInt64() but allow BigInt */ int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val); JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1); JSValue JS_NewString(JSContext *ctx, const char *str); JSValue JS_NewAtomString(JSContext *ctx, const char *str); JSValue JS_ToString(JSContext *ctx, JSValueConst val); JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val); const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, JS_BOOL cesu8); static inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1) { return JS_ToCStringLen2(ctx, plen, val1, 0); } static inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1) { return JS_ToCStringLen2(ctx, NULL, val1, 0); } void JS_FreeCString(JSContext *ctx, const char *ptr); JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, JSClassID class_id); JSValue JS_NewObjectClass(JSContext *ctx, int class_id); JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto); JSValue JS_NewObject(JSContext *ctx); JS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val); JS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val); JS_BOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, JS_BOOL val); JSValue JS_NewArray(JSContext *ctx); int JS_IsArray(JSContext *ctx, JSValueConst val); JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error); static js_force_inline JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop) { return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0); } JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop); JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx); int JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags); static inline int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val) { return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW); } int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val); int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, int64_t idx, JSValue val); int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val); int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop); int JS_IsExtensible(JSContext *ctx, JSValueConst obj); int JS_PreventExtensions(JSContext *ctx, JSValueConst obj); int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags); int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val); JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val); #define JS_GPN_STRING_MASK (1 << 0) #define JS_GPN_SYMBOL_MASK (1 << 1) #define JS_GPN_PRIVATE_MASK (1 << 2) /* only include the enumerable properties */ #define JS_GPN_ENUM_ONLY (1 << 4) /* set theJSPropertyEnum.is_enumerable field */ #define JS_GPN_SET_ENUM (1 << 5) int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj, int flags); int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop); JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv); JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst *argv); JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, int argc, JSValueConst *argv); JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, JSValueConst new_target, int argc, JSValueConst *argv); JS_BOOL JS_DetectModule(const char *input, size_t input_len); /* 'input' must be zero terminated i.e. input[input_len] = '\0'. */ JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len, const char *filename, int eval_flags); // export JS_EvalObject api by falcon JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj, JSValueConst val, int flags, int scope_idx); JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj); JSValue JS_GetGlobalObject(JSContext *ctx); int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj); int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags); int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val, int flags); int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val, int flags); int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue getter, JSValue setter, int flags); void JS_SetOpaque(JSValue obj, void *opaque); void *JS_GetOpaque(JSValueConst obj, JSClassID class_id); void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id); /* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */ JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len, const char *filename); #define JS_PARSE_JSON_EXT (1 << 0) /* allow extended JSON */ JSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len, const char *filename, int flags); JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj, JSValueConst replacer, JSValueConst space0); typedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr); JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len, JSFreeArrayBufferDataFunc *free_func, void *opaque, JS_BOOL is_shared); JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len); void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj); uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj); JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj, size_t *pbyte_offset, size_t *pbyte_length, size_t *pbytes_per_element); typedef struct { void *(*sab_alloc)(void *opaque, size_t size); void (*sab_free)(void *opaque, void *ptr); void (*sab_dup)(void *opaque, void *ptr); void *sab_opaque; } JSSharedArrayBufferFunctions; void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArrayBufferFunctions *sf); JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs); /* is_handled = TRUE means that the rejection is handled */ typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, void *opaque); void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque); /* return != 0 if the JS code needs to be interrupted */ typedef int JSInterruptHandler(JSRuntime *rt, void *opaque); void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque); /* if can_block is TRUE, Atomics.wait() can be used */ void JS_SetCanBlock(JSRuntime *rt, JS_BOOL can_block); typedef struct JSModuleDef JSModuleDef; /* return the module specifier (allocated with js_malloc()) or NULL if exception */ typedef char *JSModuleNormalizeFunc(JSContext *ctx, const char *module_base_name, const char *module_name, void *opaque); typedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx, const char *module_name, void *opaque); /* module_normalize = NULL is allowed and invokes the default module filename normalizer */ void JS_SetModuleLoaderFunc(JSRuntime *rt, JSModuleNormalizeFunc *module_normalize, JSModuleLoaderFunc *module_loader, void *opaque); /* return the import.meta object of a module */ JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m); JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m); /* JS Job support */ typedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv); int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv); JS_BOOL JS_IsJobPending(JSRuntime *rt); int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx); /* Object Writer/Reader (currently only used to handle precompiled code) */ #define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */ #define JS_WRITE_OBJ_BSWAP (1 << 1) /* byte swapped output */ #define JS_WRITE_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ #define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to encode arbitrary object graph */ uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj, int flags); uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj, int flags, uint8_t ***psab_tab, size_t *psab_tab_len); #define JS_READ_OBJ_BYTECODE (1 << 0) /* allow function/module */ #define JS_READ_OBJ_ROM_DATA (1 << 1) /* avoid duplicating 'buf' data */ #define JS_READ_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ #define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */ JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len, int flags); /* load the dependencies of the module 'obj'. Useful when JS_ReadObject() returns a module. */ int JS_ResolveModule(JSContext *ctx, JSValueConst obj); /* C function definition */ typedef enum JSCFunctionEnum { /* XXX: should rename for namespace isolation */ JS_CFUNC_generic, JS_CFUNC_generic_magic, JS_CFUNC_constructor, JS_CFUNC_constructor_magic, JS_CFUNC_constructor_or_func, JS_CFUNC_constructor_or_func_magic, JS_CFUNC_f_f, JS_CFUNC_f_f_f, JS_CFUNC_getter, JS_CFUNC_setter, JS_CFUNC_getter_magic, JS_CFUNC_setter_magic, JS_CFUNC_iterator_next, } JSCFunctionEnum; typedef union JSCFunctionType { JSCFunction *generic; JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); JSCFunction *constructor; JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic); JSCFunction *constructor_or_func; double (*f_f)(double); double (*f_f_f)(double, double); JSValue (*getter)(JSContext *ctx, JSValueConst this_val); JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val); JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic); JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic); JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int *pdone, int magic); } JSCFunctionType; JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, const char *name, int length, JSCFunctionEnum cproto, int magic); JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, int length, int magic, int data_len, JSValueConst *data); static inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, const char *name, int length) { return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0); } static inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func, const char *name, int length, JSCFunctionEnum cproto, int magic) { return JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic); } void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, JSValueConst proto); /* C property definition */ typedef struct JSCFunctionListEntry { const char *name; uint8_t prop_flags; uint8_t def_type; int16_t magic; union { struct { uint8_t length; /* XXX: should move outside union */ uint8_t cproto; /* XXX: should move outside union */ JSCFunctionType cfunc; } func; struct { JSCFunctionType get; JSCFunctionType set; } getset; struct { const char *name; int base; } alias; struct { const struct JSCFunctionListEntry *tab; int len; } prop_list; const char *str; int32_t i32; int64_t i64; double f64; } u; } JSCFunctionListEntry; #define JS_DEF_CFUNC 0 #define JS_DEF_CGETSET 1 #define JS_DEF_CGETSET_MAGIC 2 #define JS_DEF_PROP_STRING 3 #define JS_DEF_PROP_INT32 4 #define JS_DEF_PROP_INT64 5 #define JS_DEF_PROP_DOUBLE 6 #define JS_DEF_PROP_UNDEFINED 7 #define JS_DEF_OBJECT 8 #define JS_DEF_ALIAS 9 /* Note: c++ does not like nested designators */ #define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } } #define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } } #define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } } #define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } } #define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, .u = { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } } #define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, .u = { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } } #define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, .u = { .str = cstr } } #define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, .u = { .i32 = val } } #define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, .u = { .i64 = val } } #define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, .u = { .f64 = val } } #define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, .u = { .i32 = 0 } } #define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, .u = { .prop_list = { tab, len } } } #define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, -1 } } } #define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, base } } } void JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj, const JSCFunctionListEntry *tab, int len); /* C module definition */ typedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m); JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str, JSModuleInitFunc *func); /* can only be called before the module is instantiated */ int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str); int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m, const JSCFunctionListEntry *tab, int len); /* can only be called after the module is instantiated */ int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name, JSValue val); int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m, const JSCFunctionListEntry *tab, int len); #undef js_unlikely #undef js_force_inline #ifdef __cplusplus } /* extern "C" { */ #endif #endif /* QUICKJS_H */
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/quickjs.h
C
apache-2.0
40,726
#!/bin/sh # Release the QuickJS source code set -e version=`cat VERSION` if [ "$1" = "-h" ] ; then echo "release.sh [all]" echo "" echo "all: build all the archives. Otherwise only build the quickjs source archive." exit 1 fi extras="no" binary="no" quickjs="no" if [ "$1" = "all" ] ; then extras="yes" binary="yes" quickjs="yes" elif [ "$1" = "binary" ] ; then binary="yes" else quickjs="yes" fi #################################################" # extras if [ "$extras" = "yes" ] ; then d="quickjs-${version}" name="quickjs-extras-${version}" outdir="/tmp/${d}" rm -rf $outdir mkdir -p $outdir $outdir/unicode $outdir/tests cp unicode/* $outdir/unicode cp -a tests/bench-v8 $outdir/tests ( cd /tmp && tar Jcvf /tmp/${name}.tar.xz ${d} ) fi #################################################" # binary release if [ "$binary" = "yes" ] ; then make -j4 qjs run-test262 make -j4 CONFIG_M32=y qjs32 run-test262-32 strip qjs run-test262 qjs32 run-test262-32 d="quickjs-linux-x86_64-${version}" outdir="/tmp/${d}" rm -rf $outdir mkdir -p $outdir cp qjs run-test262 $outdir ( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . ) d="quickjs-linux-i686-${version}" outdir="/tmp/${d}" rm -rf $outdir mkdir -p $outdir cp qjs32 $outdir/qjs cp run-test262-32 $outdir/run-test262 ( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . ) fi #################################################" # quickjs if [ "$quickjs" = "yes" ] ; then make build_doc d="quickjs-${version}" outdir="/tmp/${d}" rm -rf $outdir mkdir -p $outdir $outdir/doc $outdir/tests $outdir/examples cp Makefile VERSION TODO Changelog readme.txt release.sh unicode_download.sh \ qjs.c qjsc.c qjscalc.js repl.js \ quickjs.c quickjs.h quickjs-atom.h \ quickjs-libc.c quickjs-libc.h quickjs-opcode.h \ cutils.c cutils.h list.h \ libregexp.c libregexp.h libregexp-opcode.h \ libunicode.c libunicode.h libunicode-table.h \ libbf.c libbf.h \ jscompress.c unicode_gen.c unicode_gen_def.h \ run-test262.c test262o.conf test262.conf \ test262o_errors.txt test262_errors.txt \ $outdir cp tests/*.js tests/*.patch tests/bjson.c $outdir/tests cp examples/*.js examples/*.c $outdir/examples cp doc/quickjs.texi doc/quickjs.pdf doc/quickjs.html \ doc/jsbignum.texi doc/jsbignum.html doc/jsbignum.pdf \ $outdir/doc ( cd /tmp && tar Jcvf /tmp/${d}.tar.xz ${d} ) fi
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/release.sh
Shell
apache-2.0
2,421
/* * QuickJS Read Eval Print Loop * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ "use strip"; import * as std from "std"; import * as os from "os"; (function(g) { /* add 'os' and 'std' bindings */ g.os = os; g.std = std; /* close global objects */ var Object = g.Object; var String = g.String; var Array = g.Array; var Date = g.Date; var Math = g.Math; var isFinite = g.isFinite; var parseFloat = g.parseFloat; /* XXX: use preprocessor ? */ var config_numcalc = (typeof os.open === "undefined"); var has_jscalc = (typeof Fraction === "function"); var has_bignum = (typeof BigFloat === "function"); var colors = { none: "\x1b[0m", black: "\x1b[30m", red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m", blue: "\x1b[34m", magenta: "\x1b[35m", cyan: "\x1b[36m", white: "\x1b[37m", gray: "\x1b[30;1m", grey: "\x1b[30;1m", bright_red: "\x1b[31;1m", bright_green: "\x1b[32;1m", bright_yellow: "\x1b[33;1m", bright_blue: "\x1b[34;1m", bright_magenta: "\x1b[35;1m", bright_cyan: "\x1b[36;1m", bright_white: "\x1b[37;1m", }; var styles; if (config_numcalc) { styles = { 'default': 'black', 'comment': 'white', 'string': 'green', 'regex': 'cyan', 'number': 'green', 'keyword': 'blue', 'function': 'gray', 'type': 'bright_magenta', 'identifier': 'yellow', 'error': 'bright_red', 'result': 'black', 'error_msg': 'bright_red', }; } else { styles = { 'default': 'bright_green', 'comment': 'white', 'string': 'bright_cyan', 'regex': 'cyan', 'number': 'green', 'keyword': 'bright_white', 'function': 'bright_yellow', 'type': 'bright_magenta', 'identifier': 'bright_green', 'error': 'red', 'result': 'bright_white', 'error_msg': 'bright_red', }; } var history = []; var clip_board = ""; var prec; var expBits; var log2_10; var pstate = ""; var prompt = ""; var plen = 0; var ps1; if (config_numcalc) ps1 = "> "; else ps1 = "qjs > "; var ps2 = " ... "; var utf8 = true; var show_time = false; var show_colors = true; var eval_time = 0; var mexpr = ""; var level = 0; var cmd = ""; var cursor_pos = 0; var last_cmd = ""; var last_cursor_pos = 0; var history_index; var this_fun, last_fun; var quote_flag = false; var utf8_state = 0; var utf8_val = 0; var term_fd; var term_read_buf; var term_width; /* current X position of the cursor in the terminal */ var term_cursor_x = 0; function termInit() { var tab; term_fd = std.in.fileno(); /* get the terminal size */ term_width = 80; if (os.isatty(term_fd)) { if (os.ttyGetWinSize) { tab = os.ttyGetWinSize(term_fd); if (tab) term_width = tab[0]; } if (os.ttySetRaw) { /* set the TTY to raw mode */ os.ttySetRaw(term_fd); } } /* install a Ctrl-C signal handler */ os.signal(os.SIGINT, sigint_handler); /* install a handler to read stdin */ term_read_buf = new Uint8Array(64); os.setReadHandler(term_fd, term_read_handler); } function sigint_handler() { /* send Ctrl-C to readline */ handle_byte(3); } function term_read_handler() { var l, i; l = os.read(term_fd, term_read_buf.buffer, 0, term_read_buf.length); for(i = 0; i < l; i++) handle_byte(term_read_buf[i]); } function handle_byte(c) { if (!utf8) { handle_char(c); } else if (utf8_state !== 0 && (c >= 0x80 && c < 0xc0)) { utf8_val = (utf8_val << 6) | (c & 0x3F); utf8_state--; if (utf8_state === 0) { handle_char(utf8_val); } } else if (c >= 0xc0 && c < 0xf8) { utf8_state = 1 + (c >= 0xe0) + (c >= 0xf0); utf8_val = c & ((1 << (6 - utf8_state)) - 1); } else { utf8_state = 0; handle_char(c); } } function is_alpha(c) { return typeof c === "string" && ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')); } function is_digit(c) { return typeof c === "string" && (c >= '0' && c <= '9'); } function is_word(c) { return typeof c === "string" && (is_alpha(c) || is_digit(c) || c == '_' || c == '$'); } function ucs_length(str) { var len, c, i, str_len = str.length; len = 0; /* we never count the trailing surrogate to have the following property: ucs_length(str) = ucs_length(str.substring(0, a)) + ucs_length(str.substring(a, str.length)) for 0 <= a <= str.length */ for(i = 0; i < str_len; i++) { c = str.charCodeAt(i); if (c < 0xdc00 || c >= 0xe000) len++; } return len; } function is_trailing_surrogate(c) { var d; if (typeof c !== "string") return false; d = c.codePointAt(0); /* can be NaN if empty string */ return d >= 0xdc00 && d < 0xe000; } function is_balanced(a, b) { switch (a + b) { case "()": case "[]": case "{}": return true; } return false; } function print_color_text(str, start, style_names) { var i, j; for (j = start; j < str.length;) { var style = style_names[i = j]; while (++j < str.length && style_names[j] == style) continue; std.puts(colors[styles[style] || 'default']); std.puts(str.substring(i, j)); std.puts(colors['none']); } } function print_csi(n, code) { std.puts("\x1b[" + ((n != 1) ? n : "") + code); } /* XXX: handle double-width characters */ function move_cursor(delta) { var i, l; if (delta > 0) { while (delta != 0) { if (term_cursor_x == (term_width - 1)) { std.puts("\n"); /* translated to CRLF */ term_cursor_x = 0; delta--; } else { l = Math.min(term_width - 1 - term_cursor_x, delta); print_csi(l, "C"); /* right */ delta -= l; term_cursor_x += l; } } } else { delta = -delta; while (delta != 0) { if (term_cursor_x == 0) { print_csi(1, "A"); /* up */ print_csi(term_width - 1, "C"); /* right */ delta--; term_cursor_x = term_width - 1; } else { l = Math.min(delta, term_cursor_x); print_csi(l, "D"); /* left */ delta -= l; term_cursor_x -= l; } } } } function update() { var i, cmd_len; /* cursor_pos is the position in 16 bit characters inside the UTF-16 string 'cmd' */ if (cmd != last_cmd) { if (!show_colors && last_cmd.substring(0, last_cursor_pos) == cmd.substring(0, last_cursor_pos)) { /* optimize common case */ std.puts(cmd.substring(last_cursor_pos)); } else { /* goto the start of the line */ move_cursor(-ucs_length(last_cmd.substring(0, last_cursor_pos))); if (show_colors) { var str = mexpr ? mexpr + '\n' + cmd : cmd; var start = str.length - cmd.length; var colorstate = colorize_js(str); print_color_text(str, start, colorstate[2]); } else { std.puts(cmd); } } term_cursor_x = (term_cursor_x + ucs_length(cmd)) % term_width; if (term_cursor_x == 0) { /* show the cursor on the next line */ std.puts(" \x08"); } /* remove the trailing characters */ std.puts("\x1b[J"); last_cmd = cmd; last_cursor_pos = cmd.length; } if (cursor_pos > last_cursor_pos) { move_cursor(ucs_length(cmd.substring(last_cursor_pos, cursor_pos))); } else if (cursor_pos < last_cursor_pos) { move_cursor(-ucs_length(cmd.substring(cursor_pos, last_cursor_pos))); } last_cursor_pos = cursor_pos; std.out.flush(); } /* editing commands */ function insert(str) { if (str) { cmd = cmd.substring(0, cursor_pos) + str + cmd.substring(cursor_pos); cursor_pos += str.length; } } function quoted_insert() { quote_flag = true; } function abort() { cmd = ""; cursor_pos = 0; return -2; } function alert() { } function beginning_of_line() { cursor_pos = 0; } function end_of_line() { cursor_pos = cmd.length; } function forward_char() { if (cursor_pos < cmd.length) { cursor_pos++; while (is_trailing_surrogate(cmd.charAt(cursor_pos))) cursor_pos++; } } function backward_char() { if (cursor_pos > 0) { cursor_pos--; while (is_trailing_surrogate(cmd.charAt(cursor_pos))) cursor_pos--; } } function skip_word_forward(pos) { while (pos < cmd.length && !is_word(cmd.charAt(pos))) pos++; while (pos < cmd.length && is_word(cmd.charAt(pos))) pos++; return pos; } function skip_word_backward(pos) { while (pos > 0 && !is_word(cmd.charAt(pos - 1))) pos--; while (pos > 0 && is_word(cmd.charAt(pos - 1))) pos--; return pos; } function forward_word() { cursor_pos = skip_word_forward(cursor_pos); } function backward_word() { cursor_pos = skip_word_backward(cursor_pos); } function accept_line() { std.puts("\n"); history_add(cmd); return -1; } function history_add(str) { if (str) { history.push(str); } history_index = history.length; } function previous_history() { if (history_index > 0) { if (history_index == history.length) { history.push(cmd); } history_index--; cmd = history[history_index]; cursor_pos = cmd.length; } } function next_history() { if (history_index < history.length - 1) { history_index++; cmd = history[history_index]; cursor_pos = cmd.length; } } function history_search(dir) { var pos = cursor_pos; for (var i = 1; i <= history.length; i++) { var index = (history.length + i * dir + history_index) % history.length; if (history[index].substring(0, pos) == cmd.substring(0, pos)) { history_index = index; cmd = history[index]; return; } } } function history_search_backward() { return history_search(-1); } function history_search_forward() { return history_search(1); } function delete_char_dir(dir) { var start, end; start = cursor_pos; if (dir < 0) { start--; while (is_trailing_surrogate(cmd.charAt(start))) start--; } end = start + 1; while (is_trailing_surrogate(cmd.charAt(end))) end++; if (start >= 0 && start < cmd.length) { if (last_fun === kill_region) { kill_region(start, end, dir); } else { cmd = cmd.substring(0, start) + cmd.substring(end); cursor_pos = start; } } } function delete_char() { delete_char_dir(1); } function control_d() { if (cmd.length == 0) { std.puts("\n"); return -3; /* exit read eval print loop */ } else { delete_char_dir(1); } } function backward_delete_char() { delete_char_dir(-1); } function transpose_chars() { var pos = cursor_pos; if (cmd.length > 1 && pos > 0) { if (pos == cmd.length) pos--; cmd = cmd.substring(0, pos - 1) + cmd.substring(pos, pos + 1) + cmd.substring(pos - 1, pos) + cmd.substring(pos + 1); cursor_pos = pos + 1; } } function transpose_words() { var p1 = skip_word_backward(cursor_pos); var p2 = skip_word_forward(p1); var p4 = skip_word_forward(cursor_pos); var p3 = skip_word_backward(p4); if (p1 < p2 && p2 <= cursor_pos && cursor_pos <= p3 && p3 < p4) { cmd = cmd.substring(0, p1) + cmd.substring(p3, p4) + cmd.substring(p2, p3) + cmd.substring(p1, p2); cursor_pos = p4; } } function upcase_word() { var end = skip_word_forward(cursor_pos); cmd = cmd.substring(0, cursor_pos) + cmd.substring(cursor_pos, end).toUpperCase() + cmd.substring(end); } function downcase_word() { var end = skip_word_forward(cursor_pos); cmd = cmd.substring(0, cursor_pos) + cmd.substring(cursor_pos, end).toLowerCase() + cmd.substring(end); } function kill_region(start, end, dir) { var s = cmd.substring(start, end); if (last_fun !== kill_region) clip_board = s; else if (dir < 0) clip_board = s + clip_board; else clip_board = clip_board + s; cmd = cmd.substring(0, start) + cmd.substring(end); if (cursor_pos > end) cursor_pos -= end - start; else if (cursor_pos > start) cursor_pos = start; this_fun = kill_region; } function kill_line() { kill_region(cursor_pos, cmd.length, 1); } function backward_kill_line() { kill_region(0, cursor_pos, -1); } function kill_word() { kill_region(cursor_pos, skip_word_forward(cursor_pos), 1); } function backward_kill_word() { kill_region(skip_word_backward(cursor_pos), cursor_pos, -1); } function yank() { insert(clip_board); } function control_c() { if (last_fun === control_c) { std.puts("\n"); std.exit(0); } else { std.puts("\n(Press Ctrl-C again to quit)\n"); readline_print_prompt(); } } function reset() { cmd = ""; cursor_pos = 0; } function get_context_word(line, pos) { var s = ""; while (pos > 0 && is_word(line[pos - 1])) { pos--; s = line[pos] + s; } return s; } function get_context_object(line, pos) { var obj, base, c; if (pos <= 0 || " ~!%^&*(-+={[|:;,<>?/".indexOf(line[pos - 1]) >= 0) return g; if (pos >= 2 && line[pos - 1] === ".") { pos--; obj = {}; switch (c = line[pos - 1]) { case '\'': case '\"': return "a"; case ']': return []; case '}': return {}; case '/': return / /; default: if (is_word(c)) { base = get_context_word(line, pos); if (["true", "false", "null", "this"].includes(base) || !isNaN(+base)) return eval(base); obj = get_context_object(line, pos - base.length); if (obj === null || obj === void 0) return obj; if (obj === g && obj[base] === void 0) return eval(base); else return obj[base]; } return {}; } } return void 0; } function get_completions(line, pos) { var s, obj, ctx_obj, r, i, j, paren; s = get_context_word(line, pos); ctx_obj = get_context_object(line, pos - s.length); r = []; /* enumerate properties from object and its prototype chain, add non-numeric regular properties with s as e prefix */ for (i = 0, obj = ctx_obj; i < 10 && obj !== null && obj !== void 0; i++) { var props = Object.getOwnPropertyNames(obj); /* add non-numeric regular properties */ for (j = 0; j < props.length; j++) { var prop = props[j]; if (typeof prop == "string" && ""+(+prop) != prop && prop.startsWith(s)) r.push(prop); } obj = Object.getPrototypeOf(obj); } if (r.length > 1) { /* sort list with internal names last and remove duplicates */ function symcmp(a, b) { if (a[0] != b[0]) { if (a[0] == '_') return 1; if (b[0] == '_') return -1; } if (a < b) return -1; if (a > b) return +1; return 0; } r.sort(symcmp); for(i = j = 1; i < r.length; i++) { if (r[i] != r[i - 1]) r[j++] = r[i]; } r.length = j; } /* 'tab' = list of completions, 'pos' = cursor position inside the completions */ return { tab: r, pos: s.length, ctx: ctx_obj }; } function completion() { var tab, res, s, i, j, len, t, max_width, col, n_cols, row, n_rows; res = get_completions(cmd, cursor_pos); tab = res.tab; if (tab.length === 0) return; s = tab[0]; len = s.length; /* add the chars which are identical in all the completions */ for(i = 1; i < tab.length; i++) { t = tab[i]; for(j = 0; j < len; j++) { if (t[j] !== s[j]) { len = j; break; } } } for(i = res.pos; i < len; i++) { insert(s[i]); } if (last_fun === completion && tab.length == 1) { /* append parentheses to function names */ var m = res.ctx[tab[0]]; if (typeof m == "function") { insert('('); if (m.length == 0) insert(')'); } else if (typeof m == "object") { insert('.'); } } /* show the possible completions */ if (last_fun === completion && tab.length >= 2) { max_width = 0; for(i = 0; i < tab.length; i++) max_width = Math.max(max_width, tab[i].length); max_width += 2; n_cols = Math.max(1, Math.floor((term_width + 1) / max_width)); n_rows = Math.ceil(tab.length / n_cols); std.puts("\n"); /* display the sorted list column-wise */ for (row = 0; row < n_rows; row++) { for (col = 0; col < n_cols; col++) { i = col * n_rows + row; if (i >= tab.length) break; s = tab[i]; if (col != n_cols - 1) s = s.padEnd(max_width); std.puts(s); } std.puts("\n"); } /* show a new prompt */ readline_print_prompt(); } } var commands = { /* command table */ "\x01": beginning_of_line, /* ^A - bol */ "\x02": backward_char, /* ^B - backward-char */ "\x03": control_c, /* ^C - abort */ "\x04": control_d, /* ^D - delete-char or exit */ "\x05": end_of_line, /* ^E - eol */ "\x06": forward_char, /* ^F - forward-char */ "\x07": abort, /* ^G - bell */ "\x08": backward_delete_char, /* ^H - backspace */ "\x09": completion, /* ^I - history-search-backward */ "\x0a": accept_line, /* ^J - newline */ "\x0b": kill_line, /* ^K - delete to end of line */ "\x0d": accept_line, /* ^M - enter */ "\x0e": next_history, /* ^N - down */ "\x10": previous_history, /* ^P - up */ "\x11": quoted_insert, /* ^Q - quoted-insert */ "\x12": alert, /* ^R - reverse-search */ "\x13": alert, /* ^S - search */ "\x14": transpose_chars, /* ^T - transpose */ "\x18": reset, /* ^X - cancel */ "\x19": yank, /* ^Y - yank */ "\x1bOA": previous_history, /* ^[OA - up */ "\x1bOB": next_history, /* ^[OB - down */ "\x1bOC": forward_char, /* ^[OC - right */ "\x1bOD": backward_char, /* ^[OD - left */ "\x1bOF": forward_word, /* ^[OF - ctrl-right */ "\x1bOH": backward_word, /* ^[OH - ctrl-left */ "\x1b[1;5C": forward_word, /* ^[[1;5C - ctrl-right */ "\x1b[1;5D": backward_word, /* ^[[1;5D - ctrl-left */ "\x1b[1~": beginning_of_line, /* ^[[1~ - bol */ "\x1b[3~": delete_char, /* ^[[3~ - delete */ "\x1b[4~": end_of_line, /* ^[[4~ - eol */ "\x1b[5~": history_search_backward,/* ^[[5~ - page up */ "\x1b[6~": history_search_forward, /* ^[[5~ - page down */ "\x1b[A": previous_history, /* ^[[A - up */ "\x1b[B": next_history, /* ^[[B - down */ "\x1b[C": forward_char, /* ^[[C - right */ "\x1b[D": backward_char, /* ^[[D - left */ "\x1b[F": end_of_line, /* ^[[F - end */ "\x1b[H": beginning_of_line, /* ^[[H - home */ "\x1b\x7f": backward_kill_word, /* M-C-? - backward_kill_word */ "\x1bb": backward_word, /* M-b - backward_word */ "\x1bd": kill_word, /* M-d - kill_word */ "\x1bf": forward_word, /* M-f - backward_word */ "\x1bk": backward_kill_line, /* M-k - backward_kill_line */ "\x1bl": downcase_word, /* M-l - downcase_word */ "\x1bt": transpose_words, /* M-t - transpose_words */ "\x1bu": upcase_word, /* M-u - upcase_word */ "\x7f": backward_delete_char, /* ^? - delete */ }; function dupstr(str, count) { var res = ""; while (count-- > 0) res += str; return res; } var readline_keys; var readline_state; var readline_cb; function readline_print_prompt() { std.puts(prompt); term_cursor_x = ucs_length(prompt) % term_width; last_cmd = ""; last_cursor_pos = 0; } function readline_start(defstr, cb) { cmd = defstr || ""; cursor_pos = cmd.length; history_index = history.length; readline_cb = cb; prompt = pstate; if (mexpr) { prompt += dupstr(" ", plen - prompt.length); prompt += ps2; } else { if (show_time) { var t = Math.round(eval_time) + " "; eval_time = 0; t = dupstr("0", 5 - t.length) + t; prompt += t.substring(0, t.length - 4) + "." + t.substring(t.length - 4); } plen = prompt.length; prompt += ps1; } readline_print_prompt(); update(); readline_state = 0; } function handle_char(c1) { var c; c = String.fromCodePoint(c1); switch(readline_state) { case 0: if (c == '\x1b') { /* '^[' - ESC */ readline_keys = c; readline_state = 1; } else { handle_key(c); } break; case 1: /* '^[ */ readline_keys += c; if (c == '[') { readline_state = 2; } else if (c == 'O') { readline_state = 3; } else { handle_key(readline_keys); readline_state = 0; } break; case 2: /* '^[[' - CSI */ readline_keys += c; if (!(c == ';' || (c >= '0' && c <= '9'))) { handle_key(readline_keys); readline_state = 0; } break; case 3: /* '^[O' - ESC2 */ readline_keys += c; handle_key(readline_keys); readline_state = 0; break; } } function handle_key(keys) { var fun; if (quote_flag) { if (ucs_length(keys) === 1) insert(keys); quote_flag = false; } else if (fun = commands[keys]) { this_fun = fun; switch (fun(keys)) { case -1: readline_cb(cmd); return; case -2: readline_cb(null); return; case -3: /* uninstall a Ctrl-C signal handler */ os.signal(os.SIGINT, null); /* uninstall the stdin read handler */ os.setReadHandler(term_fd, null); return; } last_fun = this_fun; } else if (ucs_length(keys) === 1 && keys >= ' ') { insert(keys); last_fun = insert; } else { alert(); /* beep! */ } cursor_pos = (cursor_pos < 0) ? 0 : (cursor_pos > cmd.length) ? cmd.length : cursor_pos; update(); } var hex_mode = false; var eval_mode = "std"; function number_to_string(a, radix) { var s; if (!isFinite(a)) { /* NaN, Infinite */ return a.toString(); } else { if (a == 0) { if (1 / a < 0) s = "-0"; else s = "0"; } else { if (radix == 16 && a === Math.floor(a)) { var s; if (a < 0) { a = -a; s = "-"; } else { s = ""; } s += "0x" + a.toString(16); } else { s = a.toString(); } } return s; } } function bigfloat_to_string(a, radix) { var s; if (!BigFloat.isFinite(a)) { /* NaN, Infinite */ if (eval_mode !== "math") { return "BigFloat(" + a.toString() + ")"; } else { return a.toString(); } } else { if (a == 0) { if (1 / a < 0) s = "-0"; else s = "0"; } else { if (radix == 16) { var s; if (a < 0) { a = -a; s = "-"; } else { s = ""; } s += "0x" + a.toString(16); } else { s = a.toString(); } } if (typeof a === "bigfloat" && eval_mode !== "math") { s += "l"; } else if (eval_mode !== "std" && s.indexOf(".") < 0 && ((radix == 16 && s.indexOf("p") < 0) || (radix == 10 && s.indexOf("e") < 0))) { /* add a decimal point so that the floating point type is visible */ s += ".0"; } return s; } } function bigint_to_string(a, radix) { var s; if (radix == 16) { var s; if (a < 0) { a = -a; s = "-"; } else { s = ""; } s += "0x" + a.toString(16); } else { s = a.toString(); } if (eval_mode === "std") s += "n"; return s; } function print(a) { var stack = []; function print_rec(a) { var n, i, keys, key, type, s; type = typeof(a); if (type === "object") { if (a === null) { std.puts(a); } else if (stack.indexOf(a) >= 0) { std.puts("[circular]"); } else if (has_jscalc && (a instanceof Fraction || a instanceof Complex || a instanceof Mod || a instanceof Polynomial || a instanceof PolyMod || a instanceof RationalFunction || a instanceof Series)) { std.puts(a.toString()); } else { stack.push(a); if (Array.isArray(a)) { n = a.length; std.puts("[ "); for(i = 0; i < n; i++) { if (i !== 0) std.puts(", "); if (i in a) { print_rec(a[i]); } else { std.puts("<empty>"); } if (i > 20) { std.puts("..."); break; } } std.puts(" ]"); } else if (Object.__getClass(a) === "RegExp") { std.puts(a.toString()); } else { keys = Object.keys(a); n = keys.length; std.puts("{ "); for(i = 0; i < n; i++) { if (i !== 0) std.puts(", "); key = keys[i]; std.puts(key, ": "); print_rec(a[key]); } std.puts(" }"); } stack.pop(a); } } else if (type === "string") { s = a.__quote(); if (s.length > 79) s = s.substring(0, 75) + "...\""; std.puts(s); } else if (type === "number") { std.puts(number_to_string(a, hex_mode ? 16 : 10)); } else if (type === "bigint") { std.puts(bigint_to_string(a, hex_mode ? 16 : 10)); } else if (type === "bigfloat") { std.puts(bigfloat_to_string(a, hex_mode ? 16 : 10)); } else if (type === "bigdecimal") { std.puts(a.toString() + "m"); } else if (type === "symbol") { std.puts(String(a)); } else if (type === "function") { std.puts("function " + a.name + "()"); } else { std.puts(a); } } print_rec(a); } function extract_directive(a) { var pos; if (a[0] !== '\\') return ""; for (pos = 1; pos < a.length; pos++) { if (!is_alpha(a[pos])) break; } return a.substring(1, pos); } /* return true if the string after cmd can be evaluted as JS */ function handle_directive(cmd, expr) { var param, prec1, expBits1; if (cmd === "h" || cmd === "?" || cmd == "help") { help(); } else if (cmd === "load") { var filename = expr.substring(cmd.length + 1).trim(); if (filename.lastIndexOf(".") <= filename.lastIndexOf("/")) filename += ".js"; std.loadScript(filename); return false; } else if (cmd === "x") { hex_mode = true; } else if (cmd === "d") { hex_mode = false; } else if (cmd === "t") { show_time = !show_time; } else if (has_bignum && cmd === "p") { param = expr.substring(cmd.length + 1).trim().split(" "); if (param.length === 1 && param[0] === "") { std.puts("BigFloat precision=" + prec + " bits (~" + Math.floor(prec / log2_10) + " digits), exponent size=" + expBits + " bits\n"); } else if (param[0] === "f16") { prec = 11; expBits = 5; } else if (param[0] === "f32") { prec = 24; expBits = 8; } else if (param[0] === "f64") { prec = 53; expBits = 11; } else if (param[0] === "f128") { prec = 113; expBits = 15; } else { prec1 = parseInt(param[0]); if (param.length >= 2) expBits1 = parseInt(param[1]); else expBits1 = BigFloatEnv.expBitsMax; if (Number.isNaN(prec1) || prec1 < BigFloatEnv.precMin || prec1 > BigFloatEnv.precMax) { std.puts("Invalid precision\n"); return false; } if (Number.isNaN(expBits1) || expBits1 < BigFloatEnv.expBitsMin || expBits1 > BigFloatEnv.expBitsMax) { std.puts("Invalid exponent bits\n"); return false; } prec = prec1; expBits = expBits1; } return false; } else if (has_bignum && cmd === "digits") { param = expr.substring(cmd.length + 1).trim(); prec1 = Math.ceil(parseFloat(param) * log2_10); if (prec1 < BigFloatEnv.precMin || prec1 > BigFloatEnv.precMax) { std.puts("Invalid precision\n"); return false; } prec = prec1; expBits = BigFloatEnv.expBitsMax; return false; } else if (has_bignum && cmd === "mode") { param = expr.substring(cmd.length + 1).trim(); if (param === "") { std.puts("Running mode=" + eval_mode + "\n"); } else if (param === "std" || param === "math") { eval_mode = param; } else { std.puts("Invalid mode\n"); } return false; } else if (cmd === "clear") { std.puts("\x1b[H\x1b[J"); } else if (cmd === "q") { std.exit(0); } else if (has_jscalc && cmd === "a") { algebraicMode = true; } else if (has_jscalc && cmd === "n") { algebraicMode = false; } else { std.puts("Unknown directive: " + cmd + "\n"); return false; } return true; } if (config_numcalc) { /* called by the GUI */ g.execCmd = function (cmd) { switch(cmd) { case "dec": hex_mode = false; break; case "hex": hex_mode = true; break; case "num": algebraicMode = false; break; case "alg": algebraicMode = true; break; } } } function help() { function sel(n) { return n ? "*": " "; } std.puts("\\h this help\n" + "\\x " + sel(hex_mode) + "hexadecimal number display\n" + "\\d " + sel(!hex_mode) + "decimal number display\n" + "\\t " + sel(show_time) + "toggle timing display\n" + "\\clear clear the terminal\n"); if (has_jscalc) { std.puts("\\a " + sel(algebraicMode) + "algebraic mode\n" + "\\n " + sel(!algebraicMode) + "numeric mode\n"); } if (has_bignum) { std.puts("\\p [m [e]] set the BigFloat precision to 'm' bits\n" + "\\digits n set the BigFloat precision to 'ceil(n*log2(10))' bits\n"); if (!has_jscalc) { std.puts("\\mode [std|math] change the running mode (current = " + eval_mode + ")\n"); } } if (!config_numcalc) { std.puts("\\q exit\n"); } } function eval_and_print(expr) { var result; try { if (eval_mode === "math") expr = '"use math"; void 0;' + expr; var now = (new Date).getTime(); /* eval as a script */ result = std.evalScript(expr, { backtrace_barrier: true }); eval_time = (new Date).getTime() - now; std.puts(colors[styles.result]); print(result); std.puts("\n"); std.puts(colors.none); /* set the last result */ g._ = result; } catch (error) { std.puts(colors[styles.error_msg]); if (error instanceof Error) { console.log(error); if (error.stack) { std.puts(error.stack); } } else { std.puts("Throw: "); console.log(error); } std.puts(colors.none); } } function cmd_start() { if (!config_numcalc) { if (has_jscalc) std.puts('QJSCalc - Type "\\h" for help\n'); else std.puts('QuickJS - Type "\\h" for help\n'); } if (has_bignum) { log2_10 = Math.log(10) / Math.log(2); prec = 113; expBits = 15; if (has_jscalc) { eval_mode = "math"; /* XXX: numeric mode should always be the default ? */ g.algebraicMode = config_numcalc; } } cmd_readline_start(); } function cmd_readline_start() { readline_start(dupstr(" ", level), readline_handle_cmd); } function readline_handle_cmd(expr) { handle_cmd(expr); cmd_readline_start(); } function handle_cmd(expr) { var colorstate, cmd; if (expr === null) { expr = ""; return; } if (expr === "?") { help(); return; } cmd = extract_directive(expr); if (cmd.length > 0) { if (!handle_directive(cmd, expr)) return; expr = expr.substring(cmd.length + 1); } if (expr === "") return; if (mexpr) expr = mexpr + '\n' + expr; colorstate = colorize_js(expr); pstate = colorstate[0]; level = colorstate[1]; if (pstate) { mexpr = expr; return; } mexpr = ""; if (has_bignum) { BigFloatEnv.setPrec(eval_and_print.bind(null, expr), prec, expBits); } else { eval_and_print(expr); } level = 0; /* run the garbage collector after each command */ std.gc(); } function colorize_js(str) { var i, c, start, n = str.length; var style, state = "", level = 0; var primary, can_regex = 1; var r = []; function push_state(c) { state += c; } function last_state(c) { return state.substring(state.length - 1); } function pop_state(c) { var c = last_state(); state = state.substring(0, state.length - 1); return c; } function parse_block_comment() { style = 'comment'; push_state('/'); for (i++; i < n - 1; i++) { if (str[i] == '*' && str[i + 1] == '/') { i += 2; pop_state('/'); break; } } } function parse_line_comment() { style = 'comment'; for (i++; i < n; i++) { if (str[i] == '\n') { break; } } } function parse_string(delim) { style = 'string'; push_state(delim); while (i < n) { c = str[i++]; if (c == '\n') { style = 'error'; continue; } if (c == '\\') { if (i >= n) break; i++; } else if (c == delim) { pop_state(); break; } } } function parse_regex() { style = 'regex'; push_state('/'); while (i < n) { c = str[i++]; if (c == '\n') { style = 'error'; continue; } if (c == '\\') { if (i < n) { i++; } continue; } if (last_state() == '[') { if (c == ']') { pop_state() } // ECMA 5: ignore '/' inside char classes continue; } if (c == '[') { push_state('['); if (str[i] == '[' || str[i] == ']') i++; continue; } if (c == '/') { pop_state(); while (i < n && is_word(str[i])) i++; break; } } } function parse_number() { style = 'number'; while (i < n && (is_word(str[i]) || (str[i] == '.' && (i == n - 1 || str[i + 1] != '.')))) { i++; } } var js_keywords = "|" + "break|case|catch|continue|debugger|default|delete|do|" + "else|finally|for|function|if|in|instanceof|new|" + "return|switch|this|throw|try|typeof|while|with|" + "class|const|enum|import|export|extends|super|" + "implements|interface|let|package|private|protected|" + "public|static|yield|" + "undefined|null|true|false|Infinity|NaN|" + "eval|arguments|" + "await|"; var js_no_regex = "|this|super|undefined|null|true|false|Infinity|NaN|arguments|"; var js_types = "|void|var|"; function parse_identifier() { can_regex = 1; while (i < n && is_word(str[i])) i++; var w = '|' + str.substring(start, i) + '|'; if (js_keywords.indexOf(w) >= 0) { style = 'keyword'; if (js_no_regex.indexOf(w) >= 0) can_regex = 0; return; } var i1 = i; while (i1 < n && str[i1] == ' ') i1++; if (i1 < n && str[i1] == '(') { style = 'function'; return; } if (js_types.indexOf(w) >= 0) { style = 'type'; return; } style = 'identifier'; can_regex = 0; } function set_style(from, to) { while (r.length < from) r.push('default'); while (r.length < to) r.push(style); } for (i = 0; i < n;) { style = null; start = i; switch (c = str[i++]) { case ' ': case '\t': case '\r': case '\n': continue; case '+': case '-': if (i < n && str[i] == c) { i++; continue; } can_regex = 1; continue; case '/': if (i < n && str[i] == '*') { // block comment parse_block_comment(); break; } if (i < n && str[i] == '/') { // line comment parse_line_comment(); break; } if (can_regex) { parse_regex(); can_regex = 0; break; } can_regex = 1; continue; case '\'': case '\"': case '`': parse_string(c); can_regex = 0; break; case '(': case '[': case '{': can_regex = 1; level++; push_state(c); continue; case ')': case ']': case '}': can_regex = 0; if (level > 0 && is_balanced(last_state(), c)) { level--; pop_state(); continue; } style = 'error'; break; default: if (is_digit(c)) { parse_number(); can_regex = 0; break; } if (is_word(c) || c == '$') { parse_identifier(); break; } can_regex = 1; continue; } if (style) set_style(start, i); } set_style(n, n); return [ state, level, r ]; } termInit(); cmd_start(); })(globalThis);
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/repl.js
JavaScript
apache-2.0
49,267
/* * ECMA Test 262 Runner for QuickJS * * Copyright (c) 2017-2020 Fabrice Bellard * Copyright (c) 2017-2020 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <ctype.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <dirent.h> #include <ftw.h> #include "cutils.h" #include "list.h" #include "quickjs-libc.h" /* enable test262 thread support to test SharedArrayBuffer and Atomics */ #define CONFIG_AGENT #define CMD_NAME "run-test262" typedef struct namelist_t { char **array; int count; int size; unsigned int sorted : 1; } namelist_t; namelist_t test_list; namelist_t exclude_list; namelist_t exclude_dir_list; FILE *outfile; enum test_mode_t { TEST_DEFAULT_NOSTRICT, /* run tests as nostrict unless test is flagged as strictonly */ TEST_DEFAULT_STRICT, /* run tests as strict unless test is flagged as nostrict */ TEST_NOSTRICT, /* run tests as nostrict, skip strictonly tests */ TEST_STRICT, /* run tests as strict, skip nostrict tests */ TEST_ALL, /* run tests in both strict and nostrict, unless restricted by spec */ } test_mode = TEST_DEFAULT_NOSTRICT; int skip_async; int skip_module; int new_style; int dump_memory; int stats_count; JSMemoryUsage stats_all, stats_avg, stats_min, stats_max; char *stats_min_filename; char *stats_max_filename; int verbose; char *harness_dir; char *harness_exclude; char *harness_features; char *harness_skip_features; char *error_filename; char *error_file; FILE *error_out; char *report_filename; int update_errors; int test_count, test_failed, test_index, test_skipped, test_excluded; int new_errors, changed_errors, fixed_errors; int async_done; void warning(const char *, ...) __attribute__((__format__(__printf__, 1, 2))); void fatal(int, const char *, ...) __attribute__((__format__(__printf__, 2, 3))); void warning(const char *fmt, ...) { va_list ap; fflush(stdout); fprintf(stderr, "%s: ", CMD_NAME); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } void fatal(int errcode, const char *fmt, ...) { va_list ap; fflush(stdout); fprintf(stderr, "%s: ", CMD_NAME); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); exit(errcode); } void perror_exit(int errcode, const char *s) { fflush(stdout); fprintf(stderr, "%s: ", CMD_NAME); perror(s); exit(errcode); } char *strdup_len(const char *str, int len) { char *p = malloc(len + 1); memcpy(p, str, len); p[len] = '\0'; return p; } static inline int str_equal(const char *a, const char *b) { return !strcmp(a, b); } char *str_append(char **pp, const char *sep, const char *str) { char *res, *p; size_t len = 0; p = *pp; if (p) { len = strlen(p) + strlen(sep); } res = malloc(len + strlen(str) + 1); if (p) { strcpy(res, p); strcat(res, sep); } strcpy(res + len, str); free(p); return *pp = res; } char *str_strip(char *p) { size_t len = strlen(p); while (len > 0 && isspace((unsigned char)p[len - 1])) p[--len] = '\0'; while (isspace((unsigned char)*p)) p++; return p; } int has_prefix(const char *str, const char *prefix) { return !strncmp(str, prefix, strlen(prefix)); } char *skip_prefix(const char *str, const char *prefix) { int i; for (i = 0;; i++) { if (prefix[i] == '\0') { /* skip the prefix */ str += i; break; } if (str[i] != prefix[i]) break; } return (char *)str; } char *get_basename(const char *filename) { char *p; p = strrchr(filename, '/'); if (!p) return NULL; return strdup_len(filename, p - filename); } char *compose_path(const char *path, const char *name) { int path_len, name_len; char *d, *q; if (!path || path[0] == '\0' || *name == '/') { d = strdup(name); } else { path_len = strlen(path); name_len = strlen(name); d = malloc(path_len + 1 + name_len + 1); if (d) { q = d; memcpy(q, path, path_len); q += path_len; if (path[path_len - 1] != '/') *q++ = '/'; memcpy(q, name, name_len + 1); } } return d; } int namelist_cmp(const char *a, const char *b) { /* compare strings in modified lexicographical order */ for (;;) { int ca = (unsigned char)*a++; int cb = (unsigned char)*b++; if (isdigit(ca) && isdigit(cb)) { int na = ca - '0'; int nb = cb - '0'; while (isdigit(ca = (unsigned char)*a++)) na = na * 10 + ca - '0'; while (isdigit(cb = (unsigned char)*b++)) nb = nb * 10 + cb - '0'; if (na < nb) return -1; if (na > nb) return +1; } if (ca < cb) return -1; if (ca > cb) return +1; if (ca == '\0') return 0; } } int namelist_cmp_indirect(const void *a, const void *b) { return namelist_cmp(*(const char **)a, *(const char **)b); } void namelist_sort(namelist_t *lp) { int i, count; if (lp->count > 1) { qsort(lp->array, lp->count, sizeof(*lp->array), namelist_cmp_indirect); /* remove duplicates */ for (count = i = 1; i < lp->count; i++) { if (namelist_cmp(lp->array[count - 1], lp->array[i]) == 0) { free(lp->array[i]); } else { lp->array[count++] = lp->array[i]; } } lp->count = count; } lp->sorted = 1; } int namelist_find(namelist_t *lp, const char *name) { int a, b, m, cmp; if (!lp->sorted) { namelist_sort(lp); } for (a = 0, b = lp->count; a < b;) { m = a + (b - a) / 2; cmp = namelist_cmp(lp->array[m], name); if (cmp < 0) a = m + 1; else if (cmp > 0) b = m; else return m; } return -1; } void namelist_add(namelist_t *lp, const char *base, const char *name) { char *s; s = compose_path(base, name); if (!s) goto fail; if (lp->count == lp->size) { size_t newsize = lp->size + (lp->size >> 1) + 4; char **a = realloc(lp->array, sizeof(lp->array[0]) * newsize); if (!a) goto fail; lp->array = a; lp->size = newsize; } lp->array[lp->count] = s; lp->count++; return; fail: fatal(1, "allocation failure\n"); } void namelist_load(namelist_t *lp, const char *filename) { char buf[1024]; char *base_name; FILE *f; f = fopen(filename, "rb"); if (!f) { perror_exit(1, filename); } base_name = get_basename(filename); while (fgets(buf, sizeof(buf), f) != NULL) { char *p = str_strip(buf); if (*p == '#' || *p == ';' || *p == '\0') continue; /* line comment */ namelist_add(lp, base_name, p); } free(base_name); fclose(f); } void namelist_add_from_error_file(namelist_t *lp, const char *file) { const char *p, *p0; char *pp; for (p = file; (p = strstr(p, ".js:")) != NULL; p++) { for (p0 = p; p0 > file && p0[-1] != '\n'; p0--) continue; pp = strdup_len(p0, p + 3 - p0); namelist_add(lp, NULL, pp); free(pp); } } void namelist_free(namelist_t *lp) { while (lp->count > 0) { free(lp->array[--lp->count]); } free(lp->array); lp->array = NULL; lp->size = 0; } static int add_test_file(const char *filename, const struct stat *ptr, int flag) { namelist_t *lp = &test_list; if (has_suffix(filename, ".js") && !has_suffix(filename, "_FIXTURE.js")) namelist_add(lp, NULL, filename); return 0; } /* find js files from the directory tree and sort the list */ static void enumerate_tests(const char *path) { namelist_t *lp = &test_list; int start = lp->count; ftw(path, add_test_file, 100); qsort(lp->array + start, lp->count - start, sizeof(*lp->array), namelist_cmp_indirect); } static JSValue js_print(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; const char *str; if (outfile) { for (i = 0; i < argc; i++) { if (i != 0) fputc(' ', outfile); str = JS_ToCString(ctx, argv[i]); if (!str) return JS_EXCEPTION; if (!strcmp(str, "Test262:AsyncTestComplete")) { async_done++; } else if (strstart(str, "Test262:AsyncTestFailure", NULL)) { async_done = 2; /* force an error */ } fputs(str, outfile); JS_FreeCString(ctx, str); } fputc('\n', outfile); } return JS_UNDEFINED; } static JSValue js_detachArrayBuffer(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { JS_DetachArrayBuffer(ctx, argv[0]); return JS_UNDEFINED; } static JSValue js_evalScript(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { const char *str; size_t len; JSValue ret; str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) return JS_EXCEPTION; ret = JS_Eval(ctx, str, len, "<evalScript>", JS_EVAL_TYPE_GLOBAL); JS_FreeCString(ctx, str); return ret; } #ifdef CONFIG_AGENT #include <pthread.h> typedef struct { struct list_head link; pthread_t tid; char *script; JSValue broadcast_func; BOOL broadcast_pending; JSValue broadcast_sab; /* in the main context */ uint8_t *broadcast_sab_buf; size_t broadcast_sab_size; int32_t broadcast_val; } Test262Agent; typedef struct { struct list_head link; char *str; } AgentReport; static JSValue add_helpers1(JSContext *ctx); static void add_helpers(JSContext *ctx); static pthread_mutex_t agent_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t agent_cond = PTHREAD_COND_INITIALIZER; /* list of Test262Agent.link */ static struct list_head agent_list = LIST_HEAD_INIT(agent_list); static pthread_mutex_t report_mutex = PTHREAD_MUTEX_INITIALIZER; /* list of AgentReport.link */ static struct list_head report_list = LIST_HEAD_INIT(report_list); static void *agent_start(void *arg) { Test262Agent *agent = arg; JSRuntime *rt; JSContext *ctx; JSValue ret_val; int ret; rt = JS_NewRuntime(); if (rt == NULL) { fatal(1, "JS_NewRuntime failure"); } ctx = JS_NewContext(rt); if (ctx == NULL) { JS_FreeRuntime(rt); fatal(1, "JS_NewContext failure"); } JS_SetContextOpaque(ctx, agent); JS_SetRuntimeInfo(rt, "agent"); JS_SetCanBlock(rt, TRUE); add_helpers(ctx); ret_val = JS_Eval(ctx, agent->script, strlen(agent->script), "<evalScript>", JS_EVAL_TYPE_GLOBAL); free(agent->script); agent->script = NULL; if (JS_IsException(ret_val)) js_std_dump_error(ctx); JS_FreeValue(ctx, ret_val); for(;;) { JSContext *ctx1; ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (ret < 0) { js_std_dump_error(ctx); break; } else if (ret == 0) { if (JS_IsUndefined(agent->broadcast_func)) { break; } else { JSValue args[2]; pthread_mutex_lock(&agent_mutex); while (!agent->broadcast_pending) { pthread_cond_wait(&agent_cond, &agent_mutex); } agent->broadcast_pending = FALSE; pthread_cond_signal(&agent_cond); pthread_mutex_unlock(&agent_mutex); args[0] = JS_NewArrayBuffer(ctx, agent->broadcast_sab_buf, agent->broadcast_sab_size, NULL, NULL, TRUE); args[1] = JS_NewInt32(ctx, agent->broadcast_val); ret_val = JS_Call(ctx, agent->broadcast_func, JS_UNDEFINED, 2, (JSValueConst *)args); JS_FreeValue(ctx, args[0]); JS_FreeValue(ctx, args[1]); if (JS_IsException(ret_val)) js_std_dump_error(ctx); JS_FreeValue(ctx, ret_val); JS_FreeValue(ctx, agent->broadcast_func); agent->broadcast_func = JS_UNDEFINED; } } } JS_FreeValue(ctx, agent->broadcast_func); JS_FreeContext(ctx); JS_FreeRuntime(rt); return NULL; } static JSValue js_agent_start(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { const char *script; Test262Agent *agent; if (JS_GetContextOpaque(ctx) != NULL) return JS_ThrowTypeError(ctx, "cannot be called inside an agent"); script = JS_ToCString(ctx, argv[0]); if (!script) return JS_EXCEPTION; agent = malloc(sizeof(*agent)); memset(agent, 0, sizeof(*agent)); agent->broadcast_func = JS_UNDEFINED; agent->broadcast_sab = JS_UNDEFINED; agent->script = strdup(script); JS_FreeCString(ctx, script); list_add_tail(&agent->link, &agent_list); pthread_create(&agent->tid, NULL, agent_start, agent); return JS_UNDEFINED; } static void js_agent_free(JSContext *ctx) { struct list_head *el, *el1; Test262Agent *agent; list_for_each_safe(el, el1, &agent_list) { agent = list_entry(el, Test262Agent, link); pthread_join(agent->tid, NULL); JS_FreeValue(ctx, agent->broadcast_sab); list_del(&agent->link); free(agent); } } static JSValue js_agent_leaving(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { Test262Agent *agent = JS_GetContextOpaque(ctx); if (!agent) return JS_ThrowTypeError(ctx, "must be called inside an agent"); /* nothing to do */ return JS_UNDEFINED; } static BOOL is_broadcast_pending(void) { struct list_head *el; Test262Agent *agent; list_for_each(el, &agent_list) { agent = list_entry(el, Test262Agent, link); if (agent->broadcast_pending) return TRUE; } return FALSE; } static JSValue js_agent_broadcast(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { JSValueConst sab = argv[0]; struct list_head *el; Test262Agent *agent; uint8_t *buf; size_t buf_size; int32_t val; if (JS_GetContextOpaque(ctx) != NULL) return JS_ThrowTypeError(ctx, "cannot be called inside an agent"); buf = JS_GetArrayBuffer(ctx, &buf_size, sab); if (!buf) return JS_EXCEPTION; if (JS_ToInt32(ctx, &val, argv[1])) return JS_EXCEPTION; /* broadcast the values and wait until all agents have started calling their callbacks */ pthread_mutex_lock(&agent_mutex); list_for_each(el, &agent_list) { agent = list_entry(el, Test262Agent, link); agent->broadcast_pending = TRUE; /* the shared array buffer is used by the thread, so increment its refcount */ agent->broadcast_sab = JS_DupValue(ctx, sab); agent->broadcast_sab_buf = buf; agent->broadcast_sab_size = buf_size; agent->broadcast_val = val; } pthread_cond_broadcast(&agent_cond); while (is_broadcast_pending()) { pthread_cond_wait(&agent_cond, &agent_mutex); } pthread_mutex_unlock(&agent_mutex); return JS_UNDEFINED; } static JSValue js_agent_receiveBroadcast(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { Test262Agent *agent = JS_GetContextOpaque(ctx); if (!agent) return JS_ThrowTypeError(ctx, "must be called inside an agent"); if (!JS_IsFunction(ctx, argv[0])) return JS_ThrowTypeError(ctx, "expecting function"); JS_FreeValue(ctx, agent->broadcast_func); agent->broadcast_func = JS_DupValue(ctx, argv[0]); return JS_UNDEFINED; } static JSValue js_agent_sleep(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { uint32_t duration; if (JS_ToUint32(ctx, &duration, argv[0])) return JS_EXCEPTION; usleep(duration * 1000); return JS_UNDEFINED; } static int64_t get_clock_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000); } static JSValue js_agent_monotonicNow(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { return JS_NewInt64(ctx, get_clock_ms()); } static JSValue js_agent_getReport(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { AgentReport *rep; JSValue ret; pthread_mutex_lock(&report_mutex); if (list_empty(&report_list)) { rep = NULL; } else { rep = list_entry(report_list.next, AgentReport, link); list_del(&rep->link); } pthread_mutex_unlock(&report_mutex); if (rep) { ret = JS_NewString(ctx, rep->str); free(rep->str); free(rep); } else { ret = JS_NULL; } return ret; } static JSValue js_agent_report(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { const char *str; AgentReport *rep; str = JS_ToCString(ctx, argv[0]); if (!str) return JS_EXCEPTION; rep = malloc(sizeof(*rep)); rep->str = strdup(str); JS_FreeCString(ctx, str); pthread_mutex_lock(&report_mutex); list_add_tail(&rep->link, &report_list); pthread_mutex_unlock(&report_mutex); return JS_UNDEFINED; } static const JSCFunctionListEntry js_agent_funcs[] = { /* only in main */ JS_CFUNC_DEF("start", 1, js_agent_start ), JS_CFUNC_DEF("getReport", 0, js_agent_getReport ), JS_CFUNC_DEF("broadcast", 2, js_agent_broadcast ), /* only in agent */ JS_CFUNC_DEF("report", 1, js_agent_report ), JS_CFUNC_DEF("leaving", 0, js_agent_leaving ), JS_CFUNC_DEF("receiveBroadcast", 1, js_agent_receiveBroadcast ), /* in both */ JS_CFUNC_DEF("sleep", 1, js_agent_sleep ), JS_CFUNC_DEF("monotonicNow", 0, js_agent_monotonicNow ), }; static JSValue js_new_agent(JSContext *ctx) { JSValue agent; agent = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, agent, js_agent_funcs, countof(js_agent_funcs)); return agent; } #endif static JSValue js_createRealm(JSContext *ctx, JSValue this_val, int argc, JSValue *argv) { JSContext *ctx1; JSValue ret; ctx1 = JS_NewContext(JS_GetRuntime(ctx)); if (!ctx1) return JS_ThrowOutOfMemory(ctx); ret = add_helpers1(ctx1); /* ctx1 has a refcount so it stays alive */ JS_FreeContext(ctx1); return ret; } static JSValue add_helpers1(JSContext *ctx) { JSValue global_obj; JSValue obj262; global_obj = JS_GetGlobalObject(ctx); JS_SetPropertyStr(ctx, global_obj, "print", JS_NewCFunction(ctx, js_print, "print", 1)); /* $262 special object used by the tests */ obj262 = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj262, "detachArrayBuffer", JS_NewCFunction(ctx, js_detachArrayBuffer, "detachArrayBuffer", 1)); JS_SetPropertyStr(ctx, obj262, "evalScript", JS_NewCFunction(ctx, js_evalScript, "evalScript", 1)); JS_SetPropertyStr(ctx, obj262, "codePointRange", JS_NewCFunction(ctx, js_string_codePointRange, "codePointRange", 2)); #ifdef CONFIG_AGENT JS_SetPropertyStr(ctx, obj262, "agent", js_new_agent(ctx)); #endif JS_SetPropertyStr(ctx, obj262, "global", JS_DupValue(ctx, global_obj)); JS_SetPropertyStr(ctx, obj262, "createRealm", JS_NewCFunction(ctx, js_createRealm, "createRealm", 0)); JS_SetPropertyStr(ctx, global_obj, "$262", JS_DupValue(ctx, obj262)); JS_FreeValue(ctx, global_obj); return obj262; } static void add_helpers(JSContext *ctx) { JS_FreeValue(ctx, add_helpers1(ctx)); } static char *load_file(const char *filename, size_t *lenp) { char *buf; size_t buf_len; buf = (char *)js_load_file(NULL, &buf_len, filename); if (!buf) perror_exit(1, filename); if (lenp) *lenp = buf_len; return buf; } static JSModuleDef *js_module_loader_test(JSContext *ctx, const char *module_name, void *opaque) { size_t buf_len; uint8_t *buf; JSModuleDef *m; JSValue func_val; buf = js_load_file(ctx, &buf_len, module_name); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (JS_IsException(func_val)) return NULL; /* the module is already referenced, so we must free it */ m = JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); return m; } int is_line_sep(char c) { return (c == '\0' || c == '\n' || c == '\r'); } char *find_line(const char *str, const char *line) { if (str) { const char *p; int len = strlen(line); for (p = str; (p = strstr(p, line)) != NULL; p += len + 1) { if ((p == str || is_line_sep(p[-1])) && is_line_sep(p[len])) return (char *)p; } } return NULL; } int is_word_sep(char c) { return (c == '\0' || isspace((unsigned char)c) || c == ','); } char *find_word(const char *str, const char *word) { const char *p; int len = strlen(word); if (str && len) { for (p = str; (p = strstr(p, word)) != NULL; p += len) { if ((p == str || is_word_sep(p[-1])) && is_word_sep(p[len])) return (char *)p; } } return NULL; } /* handle exclude directories */ void update_exclude_dirs(void) { namelist_t *lp = &test_list; namelist_t *ep = &exclude_list; namelist_t *dp = &exclude_dir_list; char *name; int i, j, count; /* split directpries from exclude_list */ for (count = i = 0; i < ep->count; i++) { name = ep->array[i]; if (has_suffix(name, "/")) { namelist_add(dp, NULL, name); free(name); } else { ep->array[count++] = name; } } ep->count = count; namelist_sort(dp); /* filter out excluded directories */ for (count = i = 0; i < lp->count; i++) { name = lp->array[i]; for (j = 0; j < dp->count; j++) { if (has_prefix(name, dp->array[j])) { test_excluded++; free(name); name = NULL; break; } } if (name) { lp->array[count++] = name; } } lp->count = count; } void load_config(const char *filename) { char buf[1024]; FILE *f; char *base_name; enum { SECTION_NONE = 0, SECTION_CONFIG, SECTION_EXCLUDE, SECTION_FEATURES, SECTION_TESTS, } section = SECTION_NONE; int lineno = 0; f = fopen(filename, "rb"); if (!f) { perror_exit(1, filename); } base_name = get_basename(filename); while (fgets(buf, sizeof(buf), f) != NULL) { char *p, *q; lineno++; p = str_strip(buf); if (*p == '#' || *p == ';' || *p == '\0') continue; /* line comment */ if (*p == "[]"[0]) { /* new section */ p++; p[strcspn(p, "]")] = '\0'; if (str_equal(p, "config")) section = SECTION_CONFIG; else if (str_equal(p, "exclude")) section = SECTION_EXCLUDE; else if (str_equal(p, "features")) section = SECTION_FEATURES; else if (str_equal(p, "tests")) section = SECTION_TESTS; else section = SECTION_NONE; continue; } q = strchr(p, '='); if (q) { /* setting: name=value */ *q++ = '\0'; q = str_strip(q); } switch (section) { case SECTION_CONFIG: if (!q) { printf("%s:%d: syntax error\n", filename, lineno); continue; } if (str_equal(p, "style")) { new_style = str_equal(q, "new"); continue; } if (str_equal(p, "testdir")) { char *testdir = compose_path(base_name, q); enumerate_tests(testdir); free(testdir); continue; } if (str_equal(p, "harnessdir")) { harness_dir = compose_path(base_name, q); continue; } if (str_equal(p, "harnessexclude")) { str_append(&harness_exclude, " ", q); continue; } if (str_equal(p, "features")) { str_append(&harness_features, " ", q); continue; } if (str_equal(p, "skip-features")) { str_append(&harness_skip_features, " ", q); continue; } if (str_equal(p, "mode")) { if (str_equal(q, "default") || str_equal(q, "default-nostrict")) test_mode = TEST_DEFAULT_NOSTRICT; else if (str_equal(q, "default-strict")) test_mode = TEST_DEFAULT_STRICT; else if (str_equal(q, "nostrict")) test_mode = TEST_NOSTRICT; else if (str_equal(q, "strict")) test_mode = TEST_STRICT; else if (str_equal(q, "all") || str_equal(q, "both")) test_mode = TEST_ALL; else fatal(2, "unknown test mode: %s", q); continue; } if (str_equal(p, "strict")) { if (str_equal(q, "skip") || str_equal(q, "no")) test_mode = TEST_NOSTRICT; continue; } if (str_equal(p, "nostrict")) { if (str_equal(q, "skip") || str_equal(q, "no")) test_mode = TEST_STRICT; continue; } if (str_equal(p, "async")) { skip_async = !str_equal(q, "yes"); continue; } if (str_equal(p, "module")) { skip_module = !str_equal(q, "yes"); continue; } if (str_equal(p, "verbose")) { verbose = str_equal(q, "yes"); continue; } if (str_equal(p, "errorfile")) { error_filename = compose_path(base_name, q); continue; } if (str_equal(p, "excludefile")) { char *path = compose_path(base_name, q); namelist_load(&exclude_list, path); free(path); continue; } if (str_equal(p, "reportfile")) { report_filename = compose_path(base_name, q); continue; } case SECTION_EXCLUDE: namelist_add(&exclude_list, base_name, p); break; case SECTION_FEATURES: if (!q || str_equal(q, "yes")) str_append(&harness_features, " ", p); else str_append(&harness_skip_features, " ", p); break; case SECTION_TESTS: namelist_add(&test_list, base_name, p); break; default: /* ignore settings in other sections */ break; } } fclose(f); free(base_name); } char *find_error(const char *filename, int *pline, int is_strict) { if (error_file) { size_t len = strlen(filename); const char *p, *q, *r; int line; for (p = error_file; (p = strstr(p, filename)) != NULL; p += len) { if ((p == error_file || p[-1] == '\n' || p[-1] == '(') && p[len] == ':') { q = p + len; line = 1; if (*q == ':') { line = strtol(q + 1, (char**)&q, 10); if (*q == ':') q++; } while (*q == ' ') { q++; } /* check strict mode indicator */ if (!strstart(q, "strict mode: ", &q) != !is_strict) continue; r = q = skip_prefix(q, "unexpected error: "); r += strcspn(r, "\n"); while (r[0] == '\n' && r[1] && strncmp(r + 1, filename, 8)) { r++; r += strcspn(r, "\n"); } if (pline) *pline = line; return strdup_len(q, r - q); } } } return NULL; } int skip_comments(const char *str, int line, int *pline) { const char *p; int c; p = str; while ((c = (unsigned char)*p++) != '\0') { if (isspace(c)) { if (c == '\n') line++; continue; } if (c == '/' && *p == '/') { while (*++p && *p != '\n') continue; continue; } if (c == '/' && *p == '*') { for (p += 1; *p; p++) { if (*p == '\n') { line++; continue; } if (*p == '*' && p[1] == '/') { p += 2; break; } } continue; } break; } if (pline) *pline = line; return p - str; } int longest_match(const char *str, const char *find, int pos, int *ppos, int line, int *pline) { int len, maxlen; maxlen = 0; if (*find) { const char *p; for (p = str + pos; *p; p++) { if (*p == *find) { for (len = 1; p[len] && p[len] == find[len]; len++) continue; if (len > maxlen) { maxlen = len; if (ppos) *ppos = p - str; if (pline) *pline = line; if (!find[len]) break; } } if (*p == '\n') line++; } } return maxlen; } static int eval_buf(JSContext *ctx, const char *buf, size_t buf_len, const char *filename, int is_test, int is_negative, const char *error_type, FILE *outfile, int eval_flags, int is_async) { JSValue res_val, exception_val; int ret, error_line, pos, pos_line; BOOL is_error, has_error_line; const char *error_name; pos = skip_comments(buf, 1, &pos_line); error_line = pos_line; has_error_line = FALSE; exception_val = JS_UNDEFINED; error_name = NULL; async_done = 0; /* counter of "Test262:AsyncTestComplete" messages */ res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags); if (is_async && !JS_IsException(res_val)) { JS_FreeValue(ctx, res_val); for(;;) { JSContext *ctx1; ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (ret < 0) { res_val = JS_EXCEPTION; break; } else if (ret == 0) { /* test if the test called $DONE() once */ if (async_done != 1) { res_val = JS_ThrowTypeError(ctx, "$DONE() not called"); } else { res_val = JS_UNDEFINED; } break; } } } if (JS_IsException(res_val)) { exception_val = JS_GetException(ctx); is_error = JS_IsError(ctx, exception_val); /* XXX: should get the filename and line number */ if (outfile) { if (!is_error) fprintf(outfile, "%sThrow: ", (eval_flags & JS_EVAL_FLAG_STRICT) ? "strict mode: " : ""); js_print(ctx, JS_NULL, 1, &exception_val); } if (is_error) { JSValue name, stack; const char *stack_str; name = JS_GetPropertyStr(ctx, exception_val, "name"); error_name = JS_ToCString(ctx, name); stack = JS_GetPropertyStr(ctx, exception_val, "stack"); if (!JS_IsUndefined(stack)) { stack_str = JS_ToCString(ctx, stack); if (stack_str) { const char *p; int len; if (outfile) fprintf(outfile, "%s", stack_str); len = strlen(filename); p = strstr(stack_str, filename); if (p != NULL && p[len] == ':') { error_line = atoi(p + len + 1); has_error_line = TRUE; } JS_FreeCString(ctx, stack_str); } } JS_FreeValue(ctx, stack); JS_FreeValue(ctx, name); } if (is_negative) { ret = 0; if (error_type) { char *error_class; const char *msg; msg = JS_ToCString(ctx, exception_val); error_class = strdup_len(msg, strcspn(msg, ":")); if (!str_equal(error_class, error_type)) ret = -1; free(error_class); JS_FreeCString(ctx, msg); } } else { ret = -1; } } else { if (is_negative) ret = -1; else ret = 0; } if (verbose && is_test) { JSValue msg_val = JS_UNDEFINED; const char *msg = NULL; int s_line; char *s = find_error(filename, &s_line, eval_flags & JS_EVAL_FLAG_STRICT); const char *strict_mode = (eval_flags & JS_EVAL_FLAG_STRICT) ? "strict mode: " : ""; if (!JS_IsUndefined(exception_val)) { msg_val = JS_ToString(ctx, exception_val); msg = JS_ToCString(ctx, msg_val); } if (is_negative) { // expect error if (ret == 0) { if (msg && s && (str_equal(s, "expected error") || strstart(s, "unexpected error type:", NULL) || str_equal(s, msg))) { // did not have error yet if (!has_error_line) { longest_match(buf, msg, pos, &pos, pos_line, &error_line); } printf("%s:%d: %sOK, now has error %s\n", filename, error_line, strict_mode, msg); fixed_errors++; } } else { if (!s) { // not yet reported if (msg) { fprintf(error_out, "%s:%d: %sunexpected error type: %s\n", filename, error_line, strict_mode, msg); } else { fprintf(error_out, "%s:%d: %sexpected error\n", filename, error_line, strict_mode); } new_errors++; } } } else { // should not have error if (msg) { if (!s || !str_equal(s, msg)) { if (!has_error_line) { char *p = skip_prefix(msg, "Test262 Error: "); if (strstr(p, "Test case returned non-true value!")) { longest_match(buf, "runTestCase", pos, &pos, pos_line, &error_line); } else { longest_match(buf, p, pos, &pos, pos_line, &error_line); } } fprintf(error_out, "%s:%d: %s%s%s\n", filename, error_line, strict_mode, error_file ? "unexpected error: " : "", msg); if (s && (!str_equal(s, msg) || error_line != s_line)) { printf("%s:%d: %sprevious error: %s\n", filename, s_line, strict_mode, s); changed_errors++; } else { new_errors++; } } } else { if (s) { printf("%s:%d: %sOK, fixed error: %s\n", filename, s_line, strict_mode, s); fixed_errors++; } } } JS_FreeValue(ctx, msg_val); JS_FreeCString(ctx, msg); free(s); } JS_FreeCString(ctx, error_name); JS_FreeValue(ctx, exception_val); JS_FreeValue(ctx, res_val); return ret; } static int eval_file(JSContext *ctx, const char *base, const char *p, int eval_flags) { char *buf; size_t buf_len; char *filename = compose_path(base, p); buf = load_file(filename, &buf_len); if (!buf) { warning("cannot load %s", filename); goto fail; } if (eval_buf(ctx, buf, buf_len, filename, FALSE, FALSE, NULL, stderr, eval_flags, FALSE)) { warning("error evaluating %s", filename); goto fail; } free(buf); free(filename); return 0; fail: free(buf); free(filename); return 1; } char *extract_desc(const char *buf, char style) { const char *p, *desc_start; char *desc; int len; p = buf; while (*p != '\0') { if (p[0] == '/' && p[1] == '*' && p[2] == style && p[3] != '/') { p += 3; desc_start = p; while (*p != '\0' && (p[0] != '*' || p[1] != '/')) p++; if (*p == '\0') { warning("Expecting end of desc comment"); return NULL; } len = p - desc_start; desc = malloc(len + 1); memcpy(desc, desc_start, len); desc[len] = '\0'; return desc; } else { p++; } } return NULL; } static char *find_tag(char *desc, const char *tag, int *state) { char *p; p = strstr(desc, tag); if (p) { p += strlen(tag); *state = 0; } return p; } static char *get_option(char **pp, int *state) { char *p, *p0, *option = NULL; if (*pp) { for (p = *pp;; p++) { switch (*p) { case '[': *state += 1; continue; case ']': *state -= 1; if (*state > 0) continue; p = NULL; break; case ' ': case '\t': case '\r': case ',': case '-': continue; case '\n': if (*state > 0 || p[1] == ' ') continue; p = NULL; break; case '\0': p = NULL; break; default: p0 = p; p += strcspn(p0, " \t\r\n,]"); option = strdup_len(p0, p - p0); break; } break; } *pp = p; } return option; } void update_stats(JSRuntime *rt, const char *filename) { JSMemoryUsage stats; JS_ComputeMemoryUsage(rt, &stats); if (stats_count++ == 0) { stats_avg = stats_all = stats_min = stats_max = stats; stats_min_filename = strdup(filename); stats_max_filename = strdup(filename); } else { if (stats_max.malloc_size < stats.malloc_size) { stats_max = stats; free(stats_max_filename); stats_max_filename = strdup(filename); } if (stats_min.malloc_size > stats.malloc_size) { stats_min = stats; free(stats_min_filename); stats_min_filename = strdup(filename); } #define update(f) stats_avg.f = (stats_all.f += stats.f) / stats_count update(malloc_count); update(malloc_size); update(memory_used_count); update(memory_used_size); update(atom_count); update(atom_size); update(str_count); update(str_size); update(obj_count); update(obj_size); update(prop_count); update(prop_size); update(shape_count); update(shape_size); update(js_func_count); update(js_func_size); update(js_func_code_size); update(js_func_pc2line_count); update(js_func_pc2line_size); update(c_func_count); update(array_count); update(fast_array_count); update(fast_array_elements); } #undef update } int run_test_buf(const char *filename, char *harness, namelist_t *ip, char *buf, size_t buf_len, const char* error_type, int eval_flags, BOOL is_negative, BOOL is_async, BOOL can_block) { JSRuntime *rt; JSContext *ctx; int i, ret; rt = JS_NewRuntime(); if (rt == NULL) { fatal(1, "JS_NewRuntime failure"); } ctx = JS_NewContext(rt); if (ctx == NULL) { JS_FreeRuntime(rt); fatal(1, "JS_NewContext failure"); } JS_SetRuntimeInfo(rt, filename); JS_SetCanBlock(rt, can_block); /* loader for ES6 modules */ JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL); add_helpers(ctx); for (i = 0; i < ip->count; i++) { if (eval_file(ctx, harness, ip->array[i], JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_STRIP)) { fatal(1, "error including %s for %s", ip->array[i], filename); } } ret = eval_buf(ctx, buf, buf_len, filename, TRUE, is_negative, error_type, outfile, eval_flags, is_async); ret = (ret != 0); if (dump_memory) { update_stats(rt, filename); } #ifdef CONFIG_AGENT js_agent_free(ctx); #endif JS_FreeContext(ctx); JS_FreeRuntime(rt); test_count++; if (ret) { test_failed++; if (outfile) { /* do not output a failure number to minimize diff */ fprintf(outfile, " FAILED\n"); } } return ret; } int run_test(const char *filename, int index) { char harnessbuf[1024]; char *harness; char *buf; size_t buf_len; char *desc, *p; char *error_type; int ret, eval_flags, use_strict, use_nostrict; BOOL is_negative, is_nostrict, is_onlystrict, is_async, is_module, skip; BOOL can_block; namelist_t include_list = { 0 }, *ip = &include_list; is_nostrict = is_onlystrict = is_negative = is_async = is_module = skip = FALSE; can_block = TRUE; error_type = NULL; buf = load_file(filename, &buf_len); harness = harness_dir; if (new_style) { if (!harness) { p = strstr(filename, "test/"); if (p) { snprintf(harnessbuf, sizeof(harnessbuf), "%.*s%s", (int)(p - filename), filename, "harness"); } harness = harnessbuf; } namelist_add(ip, NULL, "sta.js"); namelist_add(ip, NULL, "assert.js"); /* extract the YAML frontmatter */ desc = extract_desc(buf, '-'); if (desc) { char *ifile, *option; int state; p = find_tag(desc, "includes:", &state); if (p) { while ((ifile = get_option(&p, &state)) != NULL) { // skip unsupported harness files if (find_word(harness_exclude, ifile)) { skip |= 1; } else { namelist_add(ip, NULL, ifile); } free(ifile); } } p = find_tag(desc, "flags:", &state); if (p) { while ((option = get_option(&p, &state)) != NULL) { if (str_equal(option, "noStrict") || str_equal(option, "raw")) { is_nostrict = TRUE; skip |= (test_mode == TEST_STRICT); } else if (str_equal(option, "onlyStrict")) { is_onlystrict = TRUE; skip |= (test_mode == TEST_NOSTRICT); } else if (str_equal(option, "async")) { is_async = TRUE; skip |= skip_async; } else if (str_equal(option, "module")) { is_module = TRUE; skip |= skip_module; } else if (str_equal(option, "CanBlockIsFalse")) { can_block = FALSE; } free(option); } } p = find_tag(desc, "negative:", &state); if (p) { /* XXX: should extract the phase */ char *q = find_tag(p, "type:", &state); if (q) { while (isspace(*q)) q++; error_type = strdup_len(q, strcspn(q, " \n")); } is_negative = TRUE; } p = find_tag(desc, "features:", &state); if (p) { while ((option = get_option(&p, &state)) != NULL) { if (find_word(harness_features, option)) { /* feature is enabled */ } else if (find_word(harness_skip_features, option)) { /* skip disabled feature */ skip |= 1; } else { /* feature is not listed: skip and warn */ printf("%s:%d: unknown feature: %s\n", filename, 1, option); skip |= 1; } free(option); } } free(desc); } if (is_async) namelist_add(ip, NULL, "doneprintHandle.js"); } else { char *ifile; if (!harness) { p = strstr(filename, "test/"); if (p) { snprintf(harnessbuf, sizeof(harnessbuf), "%.*s%s", (int)(p - filename), filename, "test/harness"); } harness = harnessbuf; } namelist_add(ip, NULL, "sta.js"); /* include extra harness files */ for (p = buf; (p = strstr(p, "$INCLUDE(\"")) != NULL; p++) { p += 10; ifile = strdup_len(p, strcspn(p, "\"")); // skip unsupported harness files if (find_word(harness_exclude, ifile)) { skip |= 1; } else { namelist_add(ip, NULL, ifile); } free(ifile); } /* locate the old style configuration comment */ desc = extract_desc(buf, '*'); if (desc) { if (strstr(desc, "@noStrict")) { is_nostrict = TRUE; skip |= (test_mode == TEST_STRICT); } if (strstr(desc, "@onlyStrict")) { is_onlystrict = TRUE; skip |= (test_mode == TEST_NOSTRICT); } if (strstr(desc, "@negative")) { /* XXX: should extract the regex to check error type */ is_negative = TRUE; } free(desc); } } if (outfile && index >= 0) { fprintf(outfile, "%d: %s%s%s%s%s%s%s\n", index, filename, is_nostrict ? " @noStrict" : "", is_onlystrict ? " @onlyStrict" : "", is_async ? " async" : "", is_module ? " module" : "", is_negative ? " @negative" : "", skip ? " SKIPPED" : ""); fflush(outfile); } use_strict = use_nostrict = 0; /* XXX: should remove 'test_mode' or simplify it just to force strict or non strict mode for single file tests */ switch (test_mode) { case TEST_DEFAULT_NOSTRICT: if (is_onlystrict) use_strict = 1; else use_nostrict = 1; break; case TEST_DEFAULT_STRICT: if (is_nostrict) use_nostrict = 1; else use_strict = 1; break; case TEST_NOSTRICT: if (!is_onlystrict) use_nostrict = 1; break; case TEST_STRICT: if (!is_nostrict) use_strict = 1; break; case TEST_ALL: if (is_module) { use_nostrict = 1; } else { if (!is_nostrict) use_strict = 1; if (!is_onlystrict) use_nostrict = 1; } break; } if (skip || use_strict + use_nostrict == 0) { test_skipped++; ret = -2; } else { clock_t clocks; if (is_module) { eval_flags = JS_EVAL_TYPE_MODULE; } else { eval_flags = JS_EVAL_TYPE_GLOBAL; } clocks = clock(); ret = 0; if (use_nostrict) { ret = run_test_buf(filename, harness, ip, buf, buf_len, error_type, eval_flags, is_negative, is_async, can_block); } if (use_strict) { ret |= run_test_buf(filename, harness, ip, buf, buf_len, error_type, eval_flags | JS_EVAL_FLAG_STRICT, is_negative, is_async, can_block); } clocks = clock() - clocks; if (outfile && index >= 0 && clocks >= CLOCKS_PER_SEC / 10) { /* output timings for tests that take more than 100 ms */ fprintf(outfile, " time: %d ms\n", (int)(clocks * 1000LL / CLOCKS_PER_SEC)); } } namelist_free(&include_list); free(error_type); free(buf); return ret; } /* run a test when called by test262-harness+eshost */ int run_test262_harness_test(const char *filename, BOOL is_module) { JSRuntime *rt; JSContext *ctx; char *buf; size_t buf_len; int eval_flags, ret_code, ret; JSValue res_val; BOOL can_block; outfile = stdout; /* for js_print */ rt = JS_NewRuntime(); if (rt == NULL) { fatal(1, "JS_NewRuntime failure"); } ctx = JS_NewContext(rt); if (ctx == NULL) { JS_FreeRuntime(rt); fatal(1, "JS_NewContext failure"); } JS_SetRuntimeInfo(rt, filename); can_block = TRUE; JS_SetCanBlock(rt, can_block); /* loader for ES6 modules */ JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL); add_helpers(ctx); buf = load_file(filename, &buf_len); if (is_module) { eval_flags = JS_EVAL_TYPE_MODULE; } else { eval_flags = JS_EVAL_TYPE_GLOBAL; } res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags); ret_code = 0; if (JS_IsException(res_val)) { js_std_dump_error(ctx); ret_code = 1; } else { JS_FreeValue(ctx, res_val); for(;;) { JSContext *ctx1; ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (ret < 0) { js_std_dump_error(ctx1); ret_code = 1; } else if (ret == 0) { break; } } } free(buf); #ifdef CONFIG_AGENT js_agent_free(ctx); #endif JS_FreeContext(ctx); JS_FreeRuntime(rt); return ret_code; } clock_t last_clock; void show_progress(int force) { clock_t t = clock(); if (force || !last_clock || (t - last_clock) > CLOCKS_PER_SEC / 20) { last_clock = t; /* output progress indicator: erase end of line and return to col 0 */ fprintf(stderr, "%d/%d/%d\033[K\r", test_failed, test_count, test_skipped); fflush(stderr); } } static int slow_test_threshold; void run_test_dir_list(namelist_t *lp, int start_index, int stop_index) { int i; namelist_sort(lp); for (i = 0; i < lp->count; i++) { const char *p = lp->array[i]; if (namelist_find(&exclude_list, p) >= 0) { test_excluded++; } else if (test_index < start_index) { test_skipped++; } else if (stop_index >= 0 && test_index > stop_index) { test_skipped++; } else { int ti; if (slow_test_threshold != 0) { ti = get_clock_ms(); } else { ti = 0; } run_test(p, test_index); if (slow_test_threshold != 0) { ti = get_clock_ms() - ti; if (ti >= slow_test_threshold) fprintf(stderr, "\n%s (%d ms)\n", p, ti); } show_progress(FALSE); } test_index++; } show_progress(TRUE); } void help(void) { printf("run-test262 version " CONFIG_VERSION "\n" "usage: run-test262 [options] {-f file ... | [dir_list] [index range]}\n" "-h help\n" "-a run tests in strict and nostrict modes\n" "-m print memory usage summary\n" "-n use new style harness\n" "-N run test prepared by test262-harness+eshost\n" "-s run tests in strict mode, skip @nostrict tests\n" "-E only run tests from the error file\n" "-u update error file\n" "-v verbose: output error messages\n" "-T duration display tests taking more than 'duration' ms\n" "-c file read configuration from 'file'\n" "-d dir run all test files in directory tree 'dir'\n" "-e file load the known errors from 'file'\n" "-f file execute single test from 'file'\n" "-r file set the report file name (default=none)\n" "-x file exclude tests listed in 'file'\n"); exit(1); } char *get_opt_arg(const char *option, char *arg) { if (!arg) { fatal(2, "missing argument for option %s", option); } return arg; } int main(int argc, char **argv) { int optind, start_index, stop_index; BOOL is_dir_list; BOOL only_check_errors = FALSE; const char *filename; BOOL is_test262_harness = FALSE; BOOL is_module = FALSE; #if !defined(_WIN32) /* Date tests assume California local time */ setenv("TZ", "America/Los_Angeles", 1); #endif /* cannot use getopt because we want to pass the command line to the script */ optind = 1; is_dir_list = TRUE; while (optind < argc) { char *arg = argv[optind]; if (*arg != '-') break; optind++; if (str_equal(arg, "-h")) { help(); } else if (str_equal(arg, "-m")) { dump_memory++; } else if (str_equal(arg, "-n")) { new_style++; } else if (str_equal(arg, "-s")) { test_mode = TEST_STRICT; } else if (str_equal(arg, "-a")) { test_mode = TEST_ALL; } else if (str_equal(arg, "-u")) { update_errors++; } else if (str_equal(arg, "-v")) { verbose++; } else if (str_equal(arg, "-c")) { load_config(get_opt_arg(arg, argv[optind++])); } else if (str_equal(arg, "-d")) { enumerate_tests(get_opt_arg(arg, argv[optind++])); } else if (str_equal(arg, "-e")) { error_filename = get_opt_arg(arg, argv[optind++]); } else if (str_equal(arg, "-x")) { namelist_load(&exclude_list, get_opt_arg(arg, argv[optind++])); } else if (str_equal(arg, "-f")) { is_dir_list = FALSE; } else if (str_equal(arg, "-r")) { report_filename = get_opt_arg(arg, argv[optind++]); } else if (str_equal(arg, "-E")) { only_check_errors = TRUE; } else if (str_equal(arg, "-T")) { slow_test_threshold = atoi(get_opt_arg(arg, argv[optind++])); } else if (str_equal(arg, "-N")) { is_test262_harness = TRUE; } else if (str_equal(arg, "--module")) { is_module = TRUE; } else { fatal(1, "unknown option: %s", arg); break; } } if (optind >= argc && !test_list.count) help(); if (is_test262_harness) { return run_test262_harness_test(argv[optind], is_module); } error_out = stdout; if (error_filename) { error_file = load_file(error_filename, NULL); if (only_check_errors && error_file) { namelist_free(&test_list); namelist_add_from_error_file(&test_list, error_file); } if (update_errors) { free(error_file); error_file = NULL; error_out = fopen(error_filename, "w"); if (!error_out) { perror_exit(1, error_filename); } } } update_exclude_dirs(); if (is_dir_list) { if (optind < argc && !isdigit(argv[optind][0])) { filename = argv[optind++]; namelist_load(&test_list, filename); } start_index = 0; stop_index = -1; if (optind < argc) { start_index = atoi(argv[optind++]); if (optind < argc) { stop_index = atoi(argv[optind++]); } } if (!report_filename || str_equal(report_filename, "none")) { outfile = NULL; } else if (str_equal(report_filename, "-")) { outfile = stdout; } else { outfile = fopen(report_filename, "wb"); if (!outfile) { perror_exit(1, report_filename); } } run_test_dir_list(&test_list, start_index, stop_index); if (outfile && outfile != stdout) { fclose(outfile); outfile = NULL; } } else { outfile = stdout; while (optind < argc) { run_test(argv[optind++], -1); } } if (dump_memory) { if (dump_memory > 1 && stats_count > 1) { printf("\nMininum memory statistics for %s:\n\n", stats_min_filename); JS_DumpMemoryUsage(stdout, &stats_min, NULL); printf("\nMaximum memory statistics for %s:\n\n", stats_max_filename); JS_DumpMemoryUsage(stdout, &stats_max, NULL); } printf("\nAverage memory statistics for %d tests:\n\n", stats_count); JS_DumpMemoryUsage(stdout, &stats_avg, NULL); printf("\n"); } if (is_dir_list) { fprintf(stderr, "Result: %d/%d error%s", test_failed, test_count, test_count != 1 ? "s" : ""); if (test_excluded) fprintf(stderr, ", %d excluded", test_excluded); if (test_skipped) fprintf(stderr, ", %d skipped", test_skipped); if (error_file) { if (new_errors) fprintf(stderr, ", %d new", new_errors); if (changed_errors) fprintf(stderr, ", %d changed", changed_errors); if (fixed_errors) fprintf(stderr, ", %d fixed", fixed_errors); } fprintf(stderr, "\n"); } if (error_out && error_out != stdout) { fclose(error_out); error_out = NULL; } namelist_free(&test_list); namelist_free(&exclude_list); namelist_free(&exclude_dir_list); free(harness_dir); free(harness_features); free(harness_exclude); free(error_file); return 0; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/run-test262.c
C
apache-2.0
62,367
/* * QuickJS: binary JSON module (test only) * * Copyright (c) 2017-2019 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "../quickjs-libc.h" #include "../cutils.h" static JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; uint64_t pos, len; JSValue obj; size_t size; int flags; if (JS_ToIndex(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[2])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "array buffer overflow"); flags = 0; if (JS_ToBool(ctx, argv[3])) flags |= JS_READ_OBJ_REFERENCE; obj = JS_ReadObject(ctx, buf + pos, len, flags); return obj; } static JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { size_t len; uint8_t *buf; JSValue array; int flags; flags = 0; if (JS_ToBool(ctx, argv[1])) flags |= JS_WRITE_OBJ_REFERENCE; buf = JS_WriteObject(ctx, &len, argv[0], flags); if (!buf) return JS_EXCEPTION; array = JS_NewArrayBufferCopy(ctx, buf, len); js_free(ctx, buf); return array; } static const JSCFunctionListEntry js_bjson_funcs[] = { JS_CFUNC_DEF("read", 4, js_bjson_read ), JS_CFUNC_DEF("write", 2, js_bjson_write ), }; static int js_bjson_init(JSContext *ctx, JSModuleDef *m) { return JS_SetModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs)); } #ifdef JS_SHARED_LIBRARY #define JS_INIT_MODULE js_init_module #else #define JS_INIT_MODULE js_init_module_bjson #endif JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_bjson_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs)); return m; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/bjson.c
C
apache-2.0
3,139
/* * Javascript Micro benchmark * * Copyright (c) 2017-2019 Fabrice Bellard * Copyright (c) 2017-2019 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import * as std from "std"; function pad(str, n) { str += ""; while (str.length < n) str += " "; return str; } function pad_left(str, n) { str += ""; while (str.length < n) str = " " + str; return str; } function pad_center(str, n) { str += ""; while (str.length < n) { if ((n - str.length) & 1) str = str + " "; else str = " " + str; } return str; } function toPrec(n, prec) { var i, s; for (i = 0; i < prec; i++) n *= 10; s = "" + Math.round(n); for (i = s.length - prec; i <= 0; i++) s = "0" + s; if (prec > 0) s = s.substring(0, i) + "." + s.substring(i); return s; } var ref_data; var log_data; var heads = [ "TEST", "N", "TIME (ns)", "REF (ns)", "SCORE (%)" ]; var widths = [ 22, 10, 9, 9, 9 ]; var precs = [ 0, 0, 2, 2, 2 ]; var total = [ 0, 0, 0, 0, 0 ]; var total_score = 0; var total_scale = 0; if (typeof console == "undefined") { var console = { log: print }; } function log_line() { var i, n, s, a; s = ""; for (i = 0, n = arguments.length; i < n; i++) { if (i > 0) s += " "; a = arguments[i]; if (typeof a == "number") { total[i] += a; a = toPrec(a, precs[i]); s += pad_left(a, widths[i]); } else { s += pad_left(a, widths[i]); } } console.log(s); } var clocks_per_sec = 1000000; var max_iterations = 100; var clock_threshold = 2000; /* favoring short measuring spans */ var min_n_argument = 1; var get_clock; if (typeof globalThis.__date_clock != "function") { console.log("using fallback millisecond clock"); clocks_per_sec = 1000; max_iterations = 10; clock_threshold = 100; get_clock = Date.now; } else { get_clock = globalThis.__date_clock; } function log_one(text, n, ti) { var ref; if (ref_data) ref = ref_data[text]; else ref = null; ti = Math.round(ti * 100) / 100; log_data[text] = ti; if (typeof ref === "number") { log_line(text, n, ti, ref, ti * 100 / ref); total_score += ti * 100 / ref; total_scale += 100; } else { log_line(text, n, ti); total_score += 100; total_scale += 100; } } function bench(f, text) { var i, j, n, t, t1, ti, nb_its, ref, ti_n, ti_n1, min_ti; nb_its = n = 1; if (f.bench) { ti_n = f(text); } else { ti_n = 1000000000; min_ti = clock_threshold / 10; for(i = 0; i < 30; i++) { ti = 1000000000; for (j = 0; j < max_iterations; j++) { t = get_clock(); while ((t1 = get_clock()) == t) continue; nb_its = f(n); if (nb_its < 0) return; // test failure t1 = get_clock() - t1; if (ti > t1) ti = t1; } if (ti >= min_ti) { ti_n1 = ti / nb_its; if (ti_n > ti_n1) ti_n = ti_n1; } if (ti >= clock_threshold && n >= min_n_argument) break; n = n * [ 2, 2.5, 2 ][i % 3]; } // to use only the best timing from the last loop, uncomment below //ti_n = ti / nb_its; } /* nano seconds per iteration */ log_one(text, n, ti_n * 1e9 / clocks_per_sec); } var global_res; /* to be sure the code is not optimized */ function empty_loop(n) { var j; for(j = 0; j < n; j++) { } return n; } function date_now(n) { var j; for(j = 0; j < n; j++) { Date.now(); } return n; } function prop_read(n) { var obj, sum, j; obj = {a: 1, b: 2, c:3, d:4 }; sum = 0; for(j = 0; j < n; j++) { sum += obj.a; sum += obj.b; sum += obj.c; sum += obj.d; } global_res = sum; return n * 4; } function prop_write(n) { var obj, j; obj = {a: 1, b: 2, c:3, d:4 }; for(j = 0; j < n; j++) { obj.a = j; obj.b = j; obj.c = j; obj.d = j; } return n * 4; } function prop_create(n) { var obj, j; for(j = 0; j < n; j++) { obj = new Object(); obj.a = 1; obj.b = 2; obj.c = 3; obj.d = 4; } return n * 4; } function prop_delete(n) { var obj, j; obj = {}; for(j = 0; j < n; j++) { obj[j] = 1; } for(j = 0; j < n; j++) { delete obj[j]; } return n; } function array_read(n) { var tab, len, sum, i, j; tab = []; len = 10; for(i = 0; i < len; i++) tab[i] = i; sum = 0; for(j = 0; j < n; j++) { sum += tab[0]; sum += tab[1]; sum += tab[2]; sum += tab[3]; sum += tab[4]; sum += tab[5]; sum += tab[6]; sum += tab[7]; sum += tab[8]; sum += tab[9]; } global_res = sum; return len * n; } function array_write(n) { var tab, len, i, j; tab = []; len = 10; for(i = 0; i < len; i++) tab[i] = i; for(j = 0; j < n; j++) { tab[0] = j; tab[1] = j; tab[2] = j; tab[3] = j; tab[4] = j; tab[5] = j; tab[6] = j; tab[7] = j; tab[8] = j; tab[9] = j; } return len * n; } function array_prop_create(n) { var tab, i, j, len; len = 1000; for(j = 0; j < n; j++) { tab = []; for(i = 0; i < len; i++) tab[i] = i; } return len * n; } function array_length_decr(n) { var tab, i, j, len; len = 1000; tab = []; for(i = 0; i < len; i++) tab[i] = i; for(j = 0; j < n; j++) { for(i = len - 1; i >= 0; i--) tab.length = i; } return len * n; } function array_hole_length_decr(n) { var tab, i, j, len; len = 1000; tab = []; for(i = 0; i < len; i++) { if (i != 3) tab[i] = i; } for(j = 0; j < n; j++) { for(i = len - 1; i >= 0; i--) tab.length = i; } return len * n; } function array_push(n) { var tab, i, j, len; len = 500; for(j = 0; j < n; j++) { tab = []; for(i = 0; i < len; i++) tab.push(i); } return len * n; } function array_pop(n) { var tab, i, j, len, sum; len = 500; for(j = 0; j < n; j++) { tab = []; for(i = 0; i < len; i++) tab[i] = i; sum = 0; for(i = 0; i < len; i++) sum += tab.pop(); global_res = sum; } return len * n; } function typed_array_read(n) { var tab, len, sum, i, j; len = 10; tab = new Int32Array(len); for(i = 0; i < len; i++) tab[i] = i; sum = 0; for(j = 0; j < n; j++) { sum += tab[0]; sum += tab[1]; sum += tab[2]; sum += tab[3]; sum += tab[4]; sum += tab[5]; sum += tab[6]; sum += tab[7]; sum += tab[8]; sum += tab[9]; } global_res = sum; return len * n; } function typed_array_write(n) { var tab, len, i, j; len = 10; tab = new Int32Array(len); for(i = 0; i < len; i++) tab[i] = i; for(j = 0; j < n; j++) { tab[0] = j; tab[1] = j; tab[2] = j; tab[3] = j; tab[4] = j; tab[5] = j; tab[6] = j; tab[7] = j; tab[8] = j; tab[9] = j; } return len * n; } var global_var0; function global_read(n) { var sum, j; global_var0 = 0; sum = 0; for(j = 0; j < n; j++) { sum += global_var0; sum += global_var0; sum += global_var0; sum += global_var0; } global_res = sum; return n * 4; } var global_write = (1, eval)(`(function global_write(n) { var j; for(j = 0; j < n; j++) { global_var0 = j; global_var0 = j; global_var0 = j; global_var0 = j; } return n * 4; })`); function global_write_strict(n) { var j; for(j = 0; j < n; j++) { global_var0 = j; global_var0 = j; global_var0 = j; global_var0 = j; } return n * 4; } function local_destruct(n) { var j, v1, v2, v3, v4; var array = [ 1, 2, 3, 4, 5]; var o = { a:1, b:2, c:3, d:4 }; var a, b, c, d; for(j = 0; j < n; j++) { [ v1, v2,, v3, ...v4] = array; ({ a, b, c, d } = o); ({ a: a, b: b, c: c, d: d } = o); } return n * 12; } var global_v1, global_v2, global_v3, global_v4; var global_a, global_b, global_c, global_d; var global_destruct = (1, eval)(`(function global_destruct(n) { var j, v1, v2, v3, v4; var array = [ 1, 2, 3, 4, 5 ]; var o = { a:1, b:2, c:3, d:4 }; var a, b, c, d; for(j = 0; j < n; j++) { [ global_v1, global_v2,, global_v3, ...global_v4] = array; ({ a: global_a, b: global_b, c: global_c, d: global_d } = o); } return n * 8; })`); function global_destruct_strict(n) { var j, v1, v2, v3, v4; var array = [ 1, 2, 3, 4, 5 ]; var o = { a:1, b:2, c:3, d:4 }; var a, b, c, d; for(j = 0; j < n; j++) { [ global_v1, global_v2,, global_v3, ...global_v4] = array; ({ a: global_a, b: global_b, c: global_c, d: global_d } = o); } return n * 8; } function func_call(n) { function f(a) { return 1; } var j, sum; sum = 0; for(j = 0; j < n; j++) { sum += f(j); sum += f(j); sum += f(j); sum += f(j); } global_res = sum; return n * 4; } function closure_var(n) { function f(a) { sum++; } var j, sum; sum = 0; for(j = 0; j < n; j++) { f(j); f(j); f(j); f(j); } global_res = sum; return n * 4; } function int_arith(n) { var i, j, sum; global_res = 0; for(j = 0; j < n; j++) { sum = 0; for(i = 0; i < 1000; i++) { sum += i * i; } global_res += sum; } return n * 1000; } function float_arith(n) { var i, j, sum, a, incr, a0; global_res = 0; a0 = 0.1; incr = 1.1; for(j = 0; j < n; j++) { sum = 0; a = a0; for(i = 0; i < 1000; i++) { sum += a * a; a += incr; } global_res += sum; } return n * 1000; } function bigfloat_arith(n) { var i, j, sum, a, incr, a0; global_res = 0; a0 = BigFloat("0.1"); incr = BigFloat("1.1"); for(j = 0; j < n; j++) { sum = 0; a = a0; for(i = 0; i < 1000; i++) { sum += a * a; a += incr; } global_res += sum; } return n * 1000; } function float256_arith(n) { return BigFloatEnv.setPrec(bigfloat_arith.bind(null, n), 237, 19); } function bigint_arith(n, bits) { var i, j, sum, a, incr, a0, sum0; sum0 = global_res = BigInt(0); a0 = BigInt(1) << BigInt(Math.floor((bits - 10) * 0.5)); incr = BigInt(1); for(j = 0; j < n; j++) { sum = sum0; a = a0; for(i = 0; i < 1000; i++) { sum += a * a; a += incr; } global_res += sum; } return n * 1000; } function bigint64_arith(n) { return bigint_arith(n, 64); } function bigint256_arith(n) { return bigint_arith(n, 256); } function set_collection_add(n) { var s, i, j, len = 100; s = new Set(); for(j = 0; j < n; j++) { for(i = 0; i < len; i++) { s.add(String(i), i); } for(i = 0; i < len; i++) { if (!s.has(String(i))) throw Error("bug in Set"); } } return n * len; } function array_for(n) { var r, i, j, sum; r = []; for(i = 0; i < 100; i++) r[i] = i; for(j = 0; j < n; j++) { sum = 0; for(i = 0; i < 100; i++) { sum += r[i]; } global_res = sum; } return n * 100; } function array_for_in(n) { var r, i, j, sum; r = []; for(i = 0; i < 100; i++) r[i] = i; for(j = 0; j < n; j++) { sum = 0; for(i in r) { sum += r[i]; } global_res = sum; } return n * 100; } function array_for_of(n) { var r, i, j, sum; r = []; for(i = 0; i < 100; i++) r[i] = i; for(j = 0; j < n; j++) { sum = 0; for(i of r) { sum += i; } global_res = sum; } return n * 100; } function math_min(n) { var i, j, r; r = 0; for(j = 0; j < n; j++) { for(i = 0; i < 1000; i++) r = Math.min(i, 500); global_res = r; } return n * 1000; } /* incremental string contruction as local var */ function string_build1(n) { var i, j, r; r = ""; for(j = 0; j < n; j++) { for(i = 0; i < 100; i++) r += "x"; global_res = r; } return n * 100; } /* incremental string contruction as arg */ function string_build2(n, r) { var i, j; r = ""; for(j = 0; j < n; j++) { for(i = 0; i < 100; i++) r += "x"; global_res = r; } return n * 100; } /* incremental string contruction by prepending */ function string_build3(n, r) { var i, j; r = ""; for(j = 0; j < n; j++) { for(i = 0; i < 100; i++) r = "x" + r; global_res = r; } return n * 100; } /* incremental string contruction with multiple reference */ function string_build4(n) { var i, j, r, s; r = ""; for(j = 0; j < n; j++) { for(i = 0; i < 100; i++) { s = r; r += "x"; } global_res = r; } return n * 100; } /* sort bench */ function sort_bench(text) { function random(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[(Math.random() * n) >> 0]; } function random8(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[(Math.random() * 256) >> 0]; } function random1(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[(Math.random() * 2) >> 0]; } function hill(arr, n, def) { var mid = n >> 1; for (var i = 0; i < mid; i++) arr[i] = def[i]; for (var i = mid; i < n; i++) arr[i] = def[n - i]; } function comb(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[(i & 1) * i]; } function crisscross(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[(i & 1) ? n - i : i]; } function zero(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[0]; } function increasing(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[i]; } function decreasing(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[n - 1 - i]; } function alternate(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[i ^ 1]; } function jigsaw(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[i % (n >> 4)]; } function incbutone(arr, n, def) { for (var i = 0; i < n; i++) arr[i] = def[i]; if (n > 0) arr[n >> 2] = def[n]; } function incbutfirst(arr, n, def) { if (n > 0) arr[0] = def[n]; for (var i = 1; i < n; i++) arr[i] = def[i]; } function incbutlast(arr, n, def) { for (var i = 0; i < n - 1; i++) arr[i] = def[i + 1]; if (n > 0) arr[n - 1] = def[0]; } var sort_cases = [ random, random8, random1, jigsaw, hill, comb, crisscross, zero, increasing, decreasing, alternate, incbutone, incbutlast, incbutfirst ]; var n = sort_bench.array_size || 10000; var array_type = sort_bench.array_type || Array; var def, arr; var i, j, x, y; var total = 0; var save_total_score = total_score; var save_total_scale = total_scale; // initialize default sorted array (n + 1 elements) def = new array_type(n + 1); if (array_type == Array) { for (i = 0; i <= n; i++) { def[i] = i + ""; } } else { for (i = 0; i <= n; i++) { def[i] = i; } } def.sort(); for (var f of sort_cases) { var ti = 0, tx = 0; for (j = 0; j < 100; j++) { arr = new array_type(n); f(arr, n, def); var t1 = get_clock(); arr.sort(); t1 = get_clock() - t1; tx += t1; if (!ti || ti > t1) ti = t1; if (tx >= clocks_per_sec) break; } total += ti; i = 0; x = arr[0]; if (x !== void 0) { for (i = 1; i < n; i++) { y = arr[i]; if (y === void 0) break; if (x > y) break; x = y; } } while (i < n && arr[i] === void 0) i++; if (i < n) { console.log("sort_bench: out of order error for " + f.name + " at offset " + (i - 1) + ": " + arr[i - 1] + " > " + arr[i]); } if (sort_bench.verbose) log_one("sort_" + f.name, n, ti, n * 100); } total_score = save_total_score; total_scale = save_total_scale; return total / n / 1000; } sort_bench.bench = true; sort_bench.verbose = false; function int_to_string(n) { var s, r, j; r = 0; for(j = 0; j < n; j++) { s = (j + 1).toString(); } return n; } function float_to_string(n) { var s, r, j; r = 0; for(j = 0; j < n; j++) { s = (j + 0.1).toString(); } return n; } function string_to_int(n) { var s, r, j; r = 0; s = "12345"; r = 0; for(j = 0; j < n; j++) { r += (s | 0); } global_res = r; return n; } function string_to_float(n) { var s, r, j; r = 0; s = "12345.6"; r = 0; for(j = 0; j < n; j++) { r -= s; } global_res = r; return n; } function load_result(filename) { var f, str, res; if (typeof std === "undefined") return null; f = std.open(filename, "r"); if (!f) return null; str = f.readAsString(); res = JSON.parse(str); f.close(); return res; } function save_result(filename, obj) { var f; if (typeof std === "undefined") return; f = std.open(filename, "w"); f.puts(JSON.stringify(obj, null, 2)); f.puts("\n"); f.close(); } function main(argc, argv, g) { var test_list = [ empty_loop, date_now, prop_read, prop_write, prop_create, prop_delete, array_read, array_write, array_prop_create, array_length_decr, array_hole_length_decr, array_push, array_pop, typed_array_read, typed_array_write, global_read, global_write, global_write_strict, local_destruct, global_destruct, global_destruct_strict, func_call, closure_var, int_arith, float_arith, set_collection_add, array_for, array_for_in, array_for_of, math_min, string_build1, string_build2, //string_build3, //string_build4, sort_bench, int_to_string, float_to_string, string_to_int, string_to_float, ]; var tests = []; var i, j, n, f, name; if (typeof BigInt == "function") { /* BigInt test */ test_list.push(bigint64_arith); test_list.push(bigint256_arith); } if (typeof BigFloat == "function") { /* BigFloat test */ test_list.push(float256_arith); } for (i = 1; i < argc;) { name = argv[i++]; if (name == "-a") { sort_bench.verbose = true; continue; } if (name == "-t") { name = argv[i++]; sort_bench.array_type = g[name]; if (typeof sort_bench.array_type != "function") { console.log("unknown array type: " + name); return 1; } continue; } if (name == "-n") { sort_bench.array_size = +argv[i++]; continue; } for (j = 0; j < test_list.length; j++) { f = test_list[j]; if (name === f.name) { tests.push(f); break; } } if (j == test_list.length) { console.log("unknown benchmark: " + name); return 1; } } if (tests.length == 0) tests = test_list; ref_data = load_result("microbench.txt"); log_data = {}; log_line.apply(null, heads); n = 0; for(i = 0; i < tests.length; i++) { f = tests[i]; bench(f, f.name, ref_data, log_data); if (ref_data && ref_data[f.name]) n++; } if (ref_data) log_line("total", "", total[2], total[3], total_score * 100 / total_scale); else log_line("total", "", total[2]); if (tests == test_list) save_result("microbench-new.txt", log_data); } if (!scriptArgs) scriptArgs = []; main(scriptArgs.length, scriptArgs, this);
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/microbench.js
JavaScript
apache-2.0
23,224
"use strict"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } function assertThrows(err, func) { var ex; ex = false; try { func(); } catch(e) { ex = true; assert(e instanceof err); } assert(ex, true, "exception expected"); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function bigint_pow(a, n) { var r, i; r = 1n; for(i = 0n; i < n; i++) r *= a; return r; } /* a must be < b */ function test_less(a, b) { assert(a < b); assert(!(b < a)); assert(a <= b); assert(!(b <= a)); assert(b > a); assert(!(a > b)); assert(b >= a); assert(!(a >= b)); assert(a != b); assert(!(a == b)); } /* a must be numerically equal to b */ function test_eq(a, b) { assert(a == b); assert(b == a); assert(!(a != b)); assert(!(b != a)); assert(a <= b); assert(b <= a); assert(!(a < b)); assert(a >= b); assert(b >= a); assert(!(a > b)); } function test_bigint1() { var a, r; test_less(2n, 3n); test_eq(3n, 3n); test_less(2, 3n); test_eq(3, 3n); test_less(2.1, 3n); test_eq(Math.sqrt(4), 2n); a = bigint_pow(3n, 100n); assert((a - 1n) != a); assert(a == 515377520732011331036461129765621272702107522001n); assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1n); r = 1n << 31n; assert(r, 2147483648n, "1 << 31n === 2147483648n"); r = 1n << 32n; assert(r, 4294967296n, "1 << 32n === 4294967296n"); } function test_bigint2() { assert(BigInt(""), 0n); assert(BigInt(" 123"), 123n); assert(BigInt(" 123 "), 123n); assertThrows(SyntaxError, () => { BigInt("+") } ); assertThrows(SyntaxError, () => { BigInt("-") } ); assertThrows(SyntaxError, () => { BigInt("\x00a") } ); assertThrows(SyntaxError, () => { BigInt(" 123 r") } ); } function test_divrem(div1, a, b, q) { var div, divrem, t; div = BigInt[div1]; divrem = BigInt[div1 + "rem"]; assert(div(a, b) == q); t = divrem(a, b); assert(t[0] == q); assert(a == b * q + t[1]); } function test_idiv1(div, a, b, r) { test_divrem(div, a, b, r[0]); test_divrem(div, -a, b, r[1]); test_divrem(div, a, -b, r[2]); test_divrem(div, -a, -b, r[3]); } /* QuickJS BigInt extensions */ function test_bigint_ext() { var r; assert(BigInt.floorLog2(0n) === -1n); assert(BigInt.floorLog2(7n) === 2n); assert(BigInt.sqrt(0xffffffc000000000000000n) === 17592185913343n); r = BigInt.sqrtrem(0xffffffc000000000000000n); assert(r[0] === 17592185913343n); assert(r[1] === 35167191957503n); test_idiv1("tdiv", 3n, 2n, [1n, -1n, -1n, 1n]); test_idiv1("fdiv", 3n, 2n, [1n, -2n, -2n, 1n]); test_idiv1("cdiv", 3n, 2n, [2n, -1n, -1n, 2n]); test_idiv1("ediv", 3n, 2n, [1n, -2n, -1n, 2n]); } function test_bigfloat() { var e, a, b, sqrt2; assert(typeof 1n === "bigint"); assert(typeof 1l === "bigfloat"); assert(1 == 1.0l); assert(1 !== 1.0l); test_less(2l, 3l); test_eq(3l, 3l); test_less(2, 3l); test_eq(3, 3l); test_less(2.1, 3l); test_eq(Math.sqrt(9), 3l); test_less(2n, 3l); test_eq(3n, 3l); e = new BigFloatEnv(128); assert(e.prec == 128); a = BigFloat.sqrt(2l, e); assert(a === BigFloat.parseFloat("0x1.6a09e667f3bcc908b2fb1366ea957d3e", 0, e)); assert(e.inexact === true); assert(BigFloat.fpRound(a) == 0x1.6a09e667f3bcc908b2fb1366ea95l); b = BigFloatEnv.setPrec(BigFloat.sqrt.bind(null, 2), 128); assert(a === b); assert(BigFloat.isNaN(BigFloat(NaN))); assert(BigFloat.isFinite(1l)); assert(!BigFloat.isFinite(1l/0l)); assert(BigFloat.abs(-3l) === 3l); assert(BigFloat.sign(-3l) === -1l); assert(BigFloat.exp(0.2l) === 1.2214027581601698339210719946396742l); assert(BigFloat.log(3l) === 1.0986122886681096913952452369225256l); assert(BigFloat.pow(2.1l, 1.6l) === 3.277561666451861947162828744873745l); assert(BigFloat.sin(-1l) === -0.841470984807896506652502321630299l); assert(BigFloat.cos(1l) === 0.5403023058681397174009366074429766l); assert(BigFloat.tan(0.1l) === 0.10033467208545054505808004578111154l); assert(BigFloat.asin(0.3l) === 0.30469265401539750797200296122752915l); assert(BigFloat.acos(0.4l) === 1.1592794807274085998465837940224159l); assert(BigFloat.atan(0.7l) === 0.610725964389208616543758876490236l); assert(BigFloat.atan2(7.1l, -5.1l) === 2.1937053809751415549388104628759813l); assert(BigFloat.floor(2.5l) === 2l); assert(BigFloat.ceil(2.5l) === 3l); assert(BigFloat.trunc(-2.5l) === -2l); assert(BigFloat.round(2.5l) === 3l); assert(BigFloat.fmod(3l,2l) === 1l); assert(BigFloat.remainder(3l,2l) === -1l); /* string conversion */ assert((1234.125l).toString(), "1234.125"); assert((1234.125l).toFixed(2), "1234.13"); assert((1234.125l).toFixed(2, "down"), "1234.12"); assert((1234.125l).toExponential(), "1.234125e+3"); assert((1234.125l).toExponential(5), "1.23413e+3"); assert((1234.125l).toExponential(5, BigFloatEnv.RNDZ), "1.23412e+3"); assert((1234.125l).toPrecision(6), "1234.13"); assert((1234.125l).toPrecision(6, BigFloatEnv.RNDZ), "1234.12"); /* string conversion with binary base */ assert((0x123.438l).toString(16), "123.438"); assert((0x323.438l).toString(16), "323.438"); assert((0x723.438l).toString(16), "723.438"); assert((0xf23.438l).toString(16), "f23.438"); assert((0x123.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "123.44"); assert((0x323.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "323.44"); assert((0x723.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "723.44"); assert((0xf23.438l).toFixed(2, BigFloatEnv.RNDNA, 16), "f23.44"); assert((0x0.0000438l).toFixed(6, BigFloatEnv.RNDNA, 16), "0.000044"); assert((0x1230000000l).toFixed(1, BigFloatEnv.RNDNA, 16), "1230000000.0"); assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "123.44"); assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDZ, 16), "123.43"); assert((0x323.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "323.44"); assert((0x723.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), "723.44"); assert((-0xf23.438l).toPrecision(5, BigFloatEnv.RNDD, 16), "-f23.44"); assert((0x123.438l).toExponential(4, BigFloatEnv.RNDNA, 16), "1.2344p+8"); } function test_bigdecimal() { assert(1m === 1m); assert(1m !== 2m); test_less(1m, 2m); test_eq(2m, 2m); test_less(1, 2m); test_eq(2, 2m); test_less(1.1, 2m); test_eq(Math.sqrt(4), 2m); test_less(2n, 3m); test_eq(3n, 3m); assert(BigDecimal("1234.1") === 1234.1m); assert(BigDecimal(" 1234.1") === 1234.1m); assert(BigDecimal(" 1234.1 ") === 1234.1m); assert(BigDecimal(0.1) === 0.1m); assert(BigDecimal(123) === 123m); assert(BigDecimal(true) === 1m); assert(123m + 1m === 124m); assert(123m - 1m === 122m); assert(3.2m * 3m === 9.6m); assert(10m / 2m === 5m); assertThrows(RangeError, () => { 10m / 3m } ); assert(10m % 3m === 1m); assert(-10m % 3m === -1m); assert(1234.5m ** 3m === 1881365963.625m); assertThrows(RangeError, () => { 2m ** 3.1m } ); assertThrows(RangeError, () => { 2m ** -3m } ); assert(BigDecimal.sqrt(2m, { roundingMode: "half-even", maximumSignificantDigits: 4 }) === 1.414m); assert(BigDecimal.sqrt(101m, { roundingMode: "half-even", maximumFractionDigits: 3 }) === 10.050m); assert(BigDecimal.sqrt(0.002m, { roundingMode: "half-even", maximumFractionDigits: 3 }) === 0.045m); assert(BigDecimal.round(3.14159m, { roundingMode: "half-even", maximumFractionDigits: 3 }) === 3.142m); assert(BigDecimal.add(3.14159m, 0.31212m, { roundingMode: "half-even", maximumFractionDigits: 2 }) === 3.45m); assert(BigDecimal.sub(3.14159m, 0.31212m, { roundingMode: "down", maximumFractionDigits: 2 }) === 2.82m); assert(BigDecimal.mul(3.14159m, 0.31212m, { roundingMode: "half-even", maximumFractionDigits: 3 }) === 0.981m); assert(BigDecimal.mod(3.14159m, 0.31211m, { roundingMode: "half-even", maximumFractionDigits: 4 }) === 0.0205m); assert(BigDecimal.div(20m, 3m, { roundingMode: "half-even", maximumSignificantDigits: 3 }) === 6.67m); assert(BigDecimal.div(20m, 3m, { roundingMode: "half-even", maximumFractionDigits: 50 }) === 6.66666666666666666666666666666666666666666666666667m); /* string conversion */ assert((1234.125m).toString(), "1234.125"); assert((1234.125m).toFixed(2), "1234.13"); assert((1234.125m).toFixed(2, "down"), "1234.12"); assert((1234.125m).toExponential(), "1.234125e+3"); assert((1234.125m).toExponential(5), "1.23413e+3"); assert((1234.125m).toExponential(5, "down"), "1.23412e+3"); assert((1234.125m).toPrecision(6), "1234.13"); assert((1234.125m).toPrecision(6, "down"), "1234.12"); assert((-1234.125m).toPrecision(6, "floor"), "-1234.13"); } test_bigint1(); test_bigint2(); test_bigint_ext(); test_bigfloat(); test_bigdecimal();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_bignum.js
JavaScript
apache-2.0
10,143
import * as bjson from "./bjson.so"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } function toHex(a) { var i, s = "", tab, v; tab = new Uint8Array(a); for(i = 0; i < tab.length; i++) { v = tab[i].toString(16); if (v.length < 2) v = "0" + v; if (i !== 0) s += " "; s += v; } return s; } function isArrayLike(a) { return Array.isArray(a) || (a instanceof Uint8ClampedArray) || (a instanceof Uint8Array) || (a instanceof Uint16Array) || (a instanceof Uint32Array) || (a instanceof Int8Array) || (a instanceof Int16Array) || (a instanceof Int32Array) || (a instanceof Float32Array) || (a instanceof Float64Array); } function toStr(a) { var s, i, props, prop; switch(typeof(a)) { case "object": if (a === null) return "null"; if (a instanceof Date) { s = "Date(" + toStr(a.valueOf()) + ")"; } else if (a instanceof Number) { s = "Number(" + toStr(a.valueOf()) + ")"; } else if (a instanceof String) { s = "String(" + toStr(a.valueOf()) + ")"; } else if (a instanceof Boolean) { s = "Boolean(" + toStr(a.valueOf()) + ")"; } else if (isArrayLike(a)) { s = "["; for(i = 0; i < a.length; i++) { if (i != 0) s += ","; s += toStr(a[i]); } s += "]"; } else { props = Object.keys(a); s = "{"; for(i = 0; i < props.length; i++) { if (i != 0) s += ","; prop = props[i]; s += prop + ":" + toStr(a[prop]); } s += "}"; } return s; case "undefined": return "undefined"; case "string": return a.__quote(); case "number": case "bigfloat": if (a == 0 && 1 / a < 0) return "-0"; else return a.toString(); break; default: return a.toString(); } } function bjson_test(a) { var buf, r, a_str, r_str; a_str = toStr(a); buf = bjson.write(a); if (0) { print(a_str, "->", toHex(buf)); } r = bjson.read(buf, 0, buf.byteLength); r_str = toStr(r); if (a_str != r_str) { print(a_str); print(r_str); assert(false); } } /* test multiple references to an object including circular references */ function bjson_test_reference() { var array, buf, i, n, array_buffer; n = 16; array = []; for(i = 0; i < n; i++) array[i] = {}; array_buffer = new ArrayBuffer(n); for(i = 0; i < n; i++) { array[i].next = array[(i + 1) % n]; array[i].idx = i; array[i].typed_array = new Uint8Array(array_buffer, i, 1); } buf = bjson.write(array, true); array = bjson.read(buf, 0, buf.byteLength, true); /* check the result */ for(i = 0; i < n; i++) { assert(array[i].next, array[(i + 1) % n]); assert(array[i].idx, i); assert(array[i].typed_array.buffer, array_buffer); assert(array[i].typed_array.length, 1); assert(array[i].typed_array.byteOffset, i); } } function bjson_test_all() { var obj; bjson_test({x:1, y:2, if:3}); bjson_test([1, 2, 3]); bjson_test([1.0, "aa", true, false, undefined, null, NaN, -Infinity, -0.0]); if (typeof BigInt !== "undefined") { bjson_test([BigInt("1"), -BigInt("0x123456789"), BigInt("0x123456789abcdef123456789abcdef")]); } if (typeof BigFloat !== "undefined") { BigFloatEnv.setPrec(function () { bjson_test([BigFloat("0.1"), BigFloat("-1e30"), BigFloat("0"), BigFloat("-0"), BigFloat("Infinity"), BigFloat("-Infinity"), 0.0 / BigFloat("0"), BigFloat.MAX_VALUE, BigFloat.MIN_VALUE]); }, 113, 15); } if (typeof BigDecimal !== "undefined") { bjson_test([BigDecimal("0"), BigDecimal("0.8"), BigDecimal("123321312321321e100"), BigDecimal("-1233213123213214332333223332e100"), BigDecimal("1.233e-1000")]); } bjson_test([new Date(1234), new String("abc"), new Number(-12.1), new Boolean(true)]); bjson_test(new Int32Array([123123, 222111, -32222])); bjson_test(new Float64Array([123123, 222111.5])); /* tested with a circular reference */ obj = {}; obj.x = obj; try { bjson.write(obj); assert(false); } catch(e) { assert(e instanceof TypeError); } bjson_test_reference(); } bjson_test_all();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_bjson.js
JavaScript
apache-2.0
5,224
"use strict"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function my_func(a, b) { return a + b; } function test_function() { function f(a, b) { var i, tab = []; tab.push(this); for(i = 0; i < arguments.length; i++) tab.push(arguments[i]); return tab; } function constructor1(a) { this.x = a; } var r, g; r = my_func.call(null, 1, 2); assert(r, 3, "call"); r = my_func.apply(null, [1, 2]); assert(r, 3, "apply"); r = new Function("a", "b", "return a + b;"); assert(r(2,3), 5, "function"); g = f.bind(1, 2); assert(g.length, 1); assert(g.name, "bound f"); assert(g(3), [1,2,3]); g = constructor1.bind(null, 1); r = new g(); assert(r.x, 1); } function test() { var r, a, b, c, err; r = Error("hello"); assert(r.message, "hello", "Error"); a = new Object(); a.x = 1; assert(a.x, 1, "Object"); assert(Object.getPrototypeOf(a), Object.prototype, "getPrototypeOf"); Object.defineProperty(a, "y", { value: 3, writable: true, configurable: true, enumerable: true }); assert(a.y, 3, "defineProperty"); Object.defineProperty(a, "z", { get: function () { return 4; }, set: function(val) { this.z_val = val; }, configurable: true, enumerable: true }); assert(a.z, 4, "get"); a.z = 5; assert(a.z_val, 5, "set"); a = { get z() { return 4; }, set z(val) { this.z_val = val; } }; assert(a.z, 4, "get"); a.z = 5; assert(a.z_val, 5, "set"); b = Object.create(a); assert(Object.getPrototypeOf(b), a, "create"); c = {u:2}; /* XXX: refcount bug in 'b' instead of 'a' */ Object.setPrototypeOf(a, c); assert(Object.getPrototypeOf(a), c, "setPrototypeOf"); a = {}; assert(a.toString(), "[object Object]", "toString"); a = {x:1}; assert(Object.isExtensible(a), true, "extensible"); Object.preventExtensions(a); err = false; try { a.y = 2; } catch(e) { err = true; } assert(Object.isExtensible(a), false, "extensible"); assert(typeof a.y, "undefined", "extensible"); assert(err, true, "extensible"); } function test_enum() { var a, tab; a = {x:1, "18014398509481984": 1, "9007199254740992": 1, "9007199254740991": 1, "4294967296": 1, "4294967295": 1, y:1, "4294967294": 1, "1": 2}; tab = Object.keys(a); // console.log("tab=" + tab.toString()); assert(tab, ["1","4294967294","x","18014398509481984","9007199254740992","9007199254740991","4294967296","4294967295","y"], "keys"); } function test_array() { var a, err; a = [1, 2, 3]; assert(a.length, 3, "array"); assert(a[2], 3, "array1"); a = new Array(10); assert(a.length, 10, "array2"); a = new Array(1, 2); assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, "array3"); a = [1, 2, 3]; a.length = 2; assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, "array4"); a = []; a[1] = 10; a[4] = 3; assert(a.length, 5); a = [1,2]; a.length = 5; a[4] = 1; a.length = 4; assert(a[4] !== 1, true, "array5"); a = [1,2]; a.push(3,4); assert(a.join(), "1,2,3,4", "join"); a = [1,2,3,4,5]; Object.defineProperty(a, "3", { configurable: false }); err = false; try { a.length = 2; } catch(e) { err = true; } assert(err && a.toString() === "1,2,3,4"); } function test_string() { var a; a = String("abc"); assert(a.length, 3, "string"); assert(a[1], "b", "string"); assert(a.charCodeAt(1), 0x62, "string"); assert(String.fromCharCode(65), "A", "string"); assert(String.fromCharCode.apply(null, [65, 66, 67]), "ABC", "string"); assert(a.charAt(1), "b"); assert(a.charAt(-1), ""); assert(a.charAt(3), ""); a = "abcd"; assert(a.substring(1, 3), "bc", "substring"); a = String.fromCharCode(0x20ac); assert(a.charCodeAt(0), 0x20ac, "unicode"); assert(a, "€", "unicode"); assert(a, "\u20ac", "unicode"); assert(a, "\u{20ac}", "unicode"); assert("a", "\x61", "unicode"); a = "\u{10ffff}"; assert(a.length, 2, "unicode"); assert(a, "\u{dbff}\u{dfff}", "unicode"); assert(a.codePointAt(0), 0x10ffff); assert(String.fromCodePoint(0x10ffff), a); assert("a".concat("b", "c"), "abc"); assert("abcabc".indexOf("cab"), 2); assert("abcabc".indexOf("cab2"), -1); assert("abc".indexOf("c"), 2); assert("aaa".indexOf("a"), 0); assert("aaa".indexOf("a", NaN), 0); assert("aaa".indexOf("a", -Infinity), 0); assert("aaa".indexOf("a", -1), 0); assert("aaa".indexOf("a", -0), 0); assert("aaa".indexOf("a", 0), 0); assert("aaa".indexOf("a", 1), 1); assert("aaa".indexOf("a", 2), 2); assert("aaa".indexOf("a", 3), -1); assert("aaa".indexOf("a", 4), -1); assert("aaa".indexOf("a", Infinity), -1); assert("aaa".indexOf(""), 0); assert("aaa".indexOf("", NaN), 0); assert("aaa".indexOf("", -Infinity), 0); assert("aaa".indexOf("", -1), 0); assert("aaa".indexOf("", -0), 0); assert("aaa".indexOf("", 0), 0); assert("aaa".indexOf("", 1), 1); assert("aaa".indexOf("", 2), 2); assert("aaa".indexOf("", 3), 3); assert("aaa".indexOf("", 4), 3); assert("aaa".indexOf("", Infinity), 3); assert("aaa".lastIndexOf("a"), 2); assert("aaa".lastIndexOf("a", NaN), 2); assert("aaa".lastIndexOf("a", -Infinity), 0); assert("aaa".lastIndexOf("a", -1), 0); assert("aaa".lastIndexOf("a", -0), 0); assert("aaa".lastIndexOf("a", 0), 0); assert("aaa".lastIndexOf("a", 1), 1); assert("aaa".lastIndexOf("a", 2), 2); assert("aaa".lastIndexOf("a", 3), 2); assert("aaa".lastIndexOf("a", 4), 2); assert("aaa".lastIndexOf("a", Infinity), 2); assert("aaa".lastIndexOf(""), 3); assert("aaa".lastIndexOf("", NaN), 3); assert("aaa".lastIndexOf("", -Infinity), 0); assert("aaa".lastIndexOf("", -1), 0); assert("aaa".lastIndexOf("", -0), 0); assert("aaa".lastIndexOf("", 0), 0); assert("aaa".lastIndexOf("", 1), 1); assert("aaa".lastIndexOf("", 2), 2); assert("aaa".lastIndexOf("", 3), 3); assert("aaa".lastIndexOf("", 4), 3); assert("aaa".lastIndexOf("", Infinity), 3); assert("a,b,c".split(","), ["a","b","c"]); assert(",b,c".split(","), ["","b","c"]); assert("a,b,".split(","), ["a","b",""]); assert("aaaa".split(), [ "aaaa" ]); assert("aaaa".split(undefined, 0), [ ]); assert("aaaa".split(""), [ "a", "a", "a", "a" ]); assert("aaaa".split("", 0), [ ]); assert("aaaa".split("", 1), [ "a" ]); assert("aaaa".split("", 2), [ "a", "a" ]); assert("aaaa".split("a"), [ "", "", "", "", "" ]); assert("aaaa".split("a", 2), [ "", "" ]); assert("aaaa".split("aa"), [ "", "", "" ]); assert("aaaa".split("aa", 0), [ ]); assert("aaaa".split("aa", 1), [ "" ]); assert("aaaa".split("aa", 2), [ "", "" ]); assert("aaaa".split("aaa"), [ "", "a" ]); assert("aaaa".split("aaaa"), [ "", "" ]); assert("aaaa".split("aaaaa"), [ "aaaa" ]); assert("aaaa".split("aaaaa", 0), [ ]); assert("aaaa".split("aaaaa", 1), [ "aaaa" ]); assert(eval('"\0"'), "\0"); } function test_math() { var a; a = 1.4; assert(Math.floor(a), 1); assert(Math.ceil(a), 2); assert(Math.imul(0x12345678, 123), -1088058456); assert(Math.fround(0.1), 0.10000000149011612); assert(Math.hypot() == 0); assert(Math.hypot(-2) == 2); assert(Math.hypot(3, 4) == 5); assert(Math.abs(Math.hypot(3, 4, 5) - 7.0710678118654755) <= 1e-15); } function test_number() { assert(parseInt("123"), 123); assert(parseInt(" 123r"), 123); assert(parseInt("0x123"), 0x123); assert(parseInt("0o123"), 0); assert(+" 123 ", 123); assert(+"0b111", 7); assert(+"0o123", 83); assert(parseFloat("0x1234"), 0); assert(parseFloat("Infinity"), Infinity); assert(parseFloat("-Infinity"), -Infinity); assert(parseFloat("123.2"), 123.2); assert(parseFloat("123.2e3"), 123200); assert(Number.isNaN(Number("+"))); assert(Number.isNaN(Number("-"))); assert(Number.isNaN(Number("\x00a"))); assert((25).toExponential(0), "3e+1"); assert((-25).toExponential(0), "-3e+1"); assert((2.5).toPrecision(1), "3"); assert((-2.5).toPrecision(1), "-3"); assert((1.125).toFixed(2), "1.13"); assert((-1.125).toFixed(2), "-1.13"); } function test_eval2() { var g_call_count = 0; /* force non strict mode for f1 and f2 */ var f1 = new Function("eval", "eval(1, 2)"); var f2 = new Function("eval", "eval(...[1, 2])"); function g(a, b) { assert(a, 1); assert(b, 2); g_call_count++; } f1(g); f2(g); assert(g_call_count, 2); } function test_eval() { function f(b) { var x = 1; return eval(b); } var r, a; r = eval("1+1;"); assert(r, 2, "eval"); r = eval("var my_var=2; my_var;"); assert(r, 2, "eval"); assert(typeof my_var, "undefined"); assert(eval("if (1) 2; else 3;"), 2); assert(eval("if (0) 2; else 3;"), 3); assert(f.call(1, "this"), 1); a = 2; assert(eval("a"), 2); eval("a = 3"); assert(a, 3); assert(f("arguments.length", 1), 2); assert(f("arguments[1]", 1), 1); a = 4; assert(f("a"), 4); f("a=3"); assert(a, 3); test_eval2(); } function test_typed_array() { var buffer, a, i; a = new Uint8Array(4); assert(a.length, 4); for(i = 0; i < a.length; i++) a[i] = i; assert(a.join(","), "0,1,2,3"); a[0] = -1; assert(a[0], 255); a = new Int8Array(3); a[0] = 255; assert(a[0], -1); a = new Int32Array(3); a[0] = Math.pow(2, 32) - 1; assert(a[0], -1); assert(a.BYTES_PER_ELEMENT, 4); a = new Uint8ClampedArray(4); a[0] = -100; a[1] = 1.5; a[2] = 0.5; a[3] = 1233.5; assert(a.toString(), "0,2,0,255"); buffer = new ArrayBuffer(16); assert(buffer.byteLength, 16); a = new Uint32Array(buffer, 12, 1); assert(a.length, 1); a[0] = -1; a = new Uint16Array(buffer, 2); a[0] = -1; a = new Float32Array(buffer, 8, 1); a[0] = 1; a = new Uint8Array(buffer); assert(a.toString(), "0,0,255,255,0,0,0,0,0,0,128,63,255,255,255,255"); assert(a.buffer, buffer); a = new Uint8Array([1, 2, 3, 4]); assert(a.toString(), "1,2,3,4"); a.set([10, 11], 2); assert(a.toString(), "1,2,10,11"); } function test_json() { var a, s; s = '{"x":1,"y":true,"z":null,"a":[1,2,3],"s":"str"}'; a = JSON.parse(s); assert(a.x, 1); assert(a.y, true); assert(a.z, null); assert(JSON.stringify(a), s); /* indentation test */ assert(JSON.stringify([[{x:1,y:{},z:[]},2,3]],undefined,1), `[ [ { "x": 1, "y": {}, "z": [] }, 2, 3 ] ]`); } function test_date() { var d = new Date(1506098258091), a, s; assert(d.toISOString(), "2017-09-22T16:37:38.091Z"); d.setUTCHours(18, 10, 11); assert(d.toISOString(), "2017-09-22T18:10:11.091Z"); a = Date.parse(d.toISOString()); assert((new Date(a)).toISOString(), d.toISOString()); s = new Date("2020-01-01T01:01:01.1Z").toISOString(); assert(s == "2020-01-01T01:01:01.100Z"); s = new Date("2020-01-01T01:01:01.12Z").toISOString(); assert(s == "2020-01-01T01:01:01.120Z"); s = new Date("2020-01-01T01:01:01.123Z").toISOString(); assert(s == "2020-01-01T01:01:01.123Z"); s = new Date("2020-01-01T01:01:01.1234Z").toISOString(); assert(s == "2020-01-01T01:01:01.123Z"); s = new Date("2020-01-01T01:01:01.12345Z").toISOString(); assert(s == "2020-01-01T01:01:01.123Z"); s = new Date("2020-01-01T01:01:01.1235Z").toISOString(); assert(s == "2020-01-01T01:01:01.124Z"); s = new Date("2020-01-01T01:01:01.9999Z").toISOString(); assert(s == "2020-01-01T01:01:02.000Z"); } function test_regexp() { var a, str; str = "abbbbbc"; a = /(b+)c/.exec(str); assert(a[0], "bbbbbc"); assert(a[1], "bbbbb"); assert(a.index, 1); assert(a.input, str); a = /(b+)c/.test(str); assert(a, true); assert(/\x61/.exec("a")[0], "a"); assert(/\u0061/.exec("a")[0], "a"); assert(/\ca/.exec("\x01")[0], "\x01"); assert(/\\a/.exec("\\a")[0], "\\a"); assert(/\c0/.exec("\\c0")[0], "\\c0"); a = /(\.(?=com|org)|\/)/.exec("ah.com"); assert(a.index === 2 && a[0] === "."); a = /(\.(?!com|org)|\/)/.exec("ah.com"); assert(a, null); a = /(?=(a+))/.exec("baaabac"); assert(a.index === 1 && a[0] === "" && a[1] === "aaa"); a = /(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac"); assert(a, ["zaacbbbcac","z","ac","a",,"c"]); a = eval("/\0a/"); assert(a.toString(), "/\0a/"); assert(a.exec("\0a")[0], "\0a"); assert(/{1a}/.toString(), "/{1a}/"); a = /a{1+/.exec("a{11"); assert(a, ["a{11"] ); } function test_symbol() { var a, b, obj, c; a = Symbol("abc"); obj = {}; obj[a] = 2; assert(obj[a], 2); assert(typeof obj["abc"], "undefined"); assert(String(a), "Symbol(abc)"); b = Symbol("abc"); assert(a == a); assert(a === a); assert(a != b); assert(a !== b); b = Symbol.for("abc"); c = Symbol.for("abc"); assert(b === c); assert(b !== a); assert(Symbol.keyFor(b), "abc"); assert(Symbol.keyFor(a), undefined); a = Symbol("aaa"); assert(a.valueOf(), a); assert(a.toString(), "Symbol(aaa)"); b = Object(a); assert(b.valueOf(), a); assert(b.toString(), "Symbol(aaa)"); } function test_map() { var a, i, n, tab, o, v; n = 1000; a = new Map(); tab = []; for(i = 0; i < n; i++) { v = { }; o = { id: i }; tab[i] = [o, v]; a.set(o, v); } assert(a.size, n); for(i = 0; i < n; i++) { assert(a.get(tab[i][0]), tab[i][1]); } i = 0; a.forEach(function (v, o) { assert(o, tab[i++][0]); assert(a.has(o)); assert(a.delete(o)); assert(!a.has(o)); }); assert(a.size, 0); } function test_weak_map() { var a, i, n, tab, o, v, n2; a = new WeakMap(); n = 10; tab = []; for(i = 0; i < n; i++) { v = { }; o = { id: i }; tab[i] = [o, v]; a.set(o, v); } o = null; n2 = n >> 1; for(i = 0; i < n2; i++) { a.delete(tab[i][0]); } for(i = n2; i < n; i++) { tab[i][0] = null; /* should remove the object from the WeakMap too */ } /* the WeakMap should be empty here */ } function test_generator() { function *f() { var ret; yield 1; ret = yield 2; assert(ret, "next_arg"); return 3; } function *f2() { yield 1; yield 2; return "ret_val"; } function *f1() { var ret = yield *f2(); assert(ret, "ret_val"); return 3; } var g, v; g = f(); v = g.next(); assert(v.value === 1 && v.done === false); v = g.next(); assert(v.value === 2 && v.done === false); v = g.next("next_arg"); assert(v.value === 3 && v.done === true); v = g.next(); assert(v.value === undefined && v.done === true); g = f1(); v = g.next(); assert(v.value === 1 && v.done === false); v = g.next(); assert(v.value === 2 && v.done === false); v = g.next(); assert(v.value === 3 && v.done === true); v = g.next(); assert(v.value === undefined && v.done === true); } test(); test_function(); test_enum(); test_array(); test_string(); test_math(); test_number(); test_eval(); test_typed_array(); test_json(); test_date(); test_regexp(); test_symbol(); test_map(); test_weak_map(); test_generator();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_builtin.js
JavaScript
apache-2.0
16,513
function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ var log_str = ""; function log(str) { log_str += str + ","; } function f(a, b, c) { var x = 10; log("a="+a); function g(d) { function h() { log("d=" + d); log("x=" + x); } log("b=" + b); log("c=" + c); h(); } g(4); return g; } var g1 = f(1, 2, 3); g1(5); assert(log_str, "a=1,b=2,c=3,d=4,x=10,b=2,c=3,d=5,x=10,", "closure1"); function test_closure1() { function f2() { var val = 1; function set(a) { val = a; } function get(a) { return val; } return { "set": set, "get": get }; } var obj = f2(); obj.set(10); var r; r = obj.get(); assert(r, 10, "closure2"); } function test_closure2() { var expr_func = function myfunc1(n) { function myfunc2(n) { return myfunc1(n - 1); } if (n == 0) return 0; else return myfunc2(n); }; var r; r = expr_func(1); assert(r, 0, "expr_func"); } function test_closure3() { function fib(n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); } var fib_func = function fib1(n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib1(n - 1) + fib1(n - 2); }; assert(fib(6), 8, "fib"); assert(fib_func(6), 8, "fib_func"); } function test_arrow_function() { "use strict"; function f1() { return (() => arguments)(); } function f2() { return (() => this)(); } function f3() { return (() => eval("this"))(); } function f4() { return (() => eval("new.target"))(); } var a; a = f1(1, 2); assert(a.length, 2); assert(a[0] === 1 && a[1] === 2); assert(f2.call("this_val") === "this_val"); assert(f3.call("this_val") === "this_val"); assert(new f4() === f4); var o1 = { f() { return this; } }; var o2 = { f() { return (() => eval("super.f()"))(); } }; o2.__proto__ = o1; assert(o2.f() === o2); } function test_with() { var o1 = { x: "o1", y: "o1" }; var x = "local"; eval('var z="var_obj";'); assert(z === "var_obj"); with (o1) { assert(x === "o1"); assert(eval("x") === "o1"); var f = function () { o2 = { x: "o2" }; with (o2) { assert(x === "o2"); assert(y === "o1"); assert(z === "var_obj"); assert(eval("x") === "o2"); assert(eval("y") === "o1"); assert(eval("z") === "var_obj"); assert(eval('eval("x")') === "o2"); } }; f(); } } function test_eval_closure() { var tab; tab = []; for(let i = 0; i < 3; i++) { eval("tab.push(function g1() { return i; })"); } for(let i = 0; i < 3; i++) { assert(tab[i]() === i); } tab = []; for(let i = 0; i < 3; i++) { let f = function f() { eval("tab.push(function g2() { return i; })"); }; f(); } for(let i = 0; i < 3; i++) { assert(tab[i]() === i); } } function test_eval_const() { const a = 1; var success = false; var f = function () { eval("a = 1"); }; try { f(); } catch(e) { success = (e instanceof TypeError); } assert(success); } test_closure1(); test_closure2(); test_closure3(); test_arrow_function(); test_with(); test_eval_closure(); test_eval_const();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_closure.js
JavaScript
apache-2.0
4,359
function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function test_op1() { var r, a; r = 1 + 2; assert(r, 3, "1 + 2 === 3"); r = 1 - 2; assert(r, -1, "1 - 2 === -1"); r = -1; assert(r, -1, "-1 === -1"); r = +2; assert(r, 2, "+2 === 2"); r = 2 * 3; assert(r, 6, "2 * 3 === 6"); r = 4 / 2; assert(r, 2, "4 / 2 === 2"); r = 4 % 3; assert(r, 1, "4 % 3 === 3"); r = 4 << 2; assert(r, 16, "4 << 2 === 16"); r = 1 << 0; assert(r, 1, "1 << 0 === 1"); r = 1 << 31; assert(r, -2147483648, "1 << 31 === -2147483648"); r = 1 << 32; assert(r, 1, "1 << 32 === 1"); r = (1 << 31) < 0; assert(r, true, "(1 << 31) < 0 === true"); r = -4 >> 1; assert(r, -2, "-4 >> 1 === -2"); r = -4 >>> 1; assert(r, 0x7ffffffe, "-4 >>> 1 === 0x7ffffffe"); r = 1 & 1; assert(r, 1, "1 & 1 === 1"); r = 0 | 1; assert(r, 1, "0 | 1 === 1"); r = 1 ^ 1; assert(r, 0, "1 ^ 1 === 0"); r = ~1; assert(r, -2, "~1 === -2"); r = !1; assert(r, false, "!1 === false"); assert((1 < 2), true, "(1 < 2) === true"); assert((2 > 1), true, "(2 > 1) === true"); assert(('b' > 'a'), true, "('b' > 'a') === true"); assert(2 ** 8, 256, "2 ** 8 === 256"); } function test_cvt() { assert((NaN | 0) === 0); assert((Infinity | 0) === 0); assert(((-Infinity) | 0) === 0); assert(("12345" | 0) === 12345); assert(("0x12345" | 0) === 0x12345); assert(((4294967296 * 3 - 4) | 0) === -4); assert(("12345" >>> 0) === 12345); assert(("0x12345" >>> 0) === 0x12345); assert((NaN >>> 0) === 0); assert((Infinity >>> 0) === 0); assert(((-Infinity) >>> 0) === 0); assert(((4294967296 * 3 - 4) >>> 0) === (4294967296 - 4)); } function test_eq() { assert(null == undefined); assert(undefined == null); assert(true == 1); assert(0 == false); assert("" == 0); assert("123" == 123); assert("122" != 123); assert((new Number(1)) == 1); assert(2 == (new Number(2))); assert((new String("abc")) == "abc"); assert({} != "abc"); } function test_inc_dec() { var a, r; a = 1; r = a++; assert(r === 1 && a === 2, true, "++"); a = 1; r = ++a; assert(r === 2 && a === 2, true, "++"); a = 1; r = a--; assert(r === 1 && a === 0, true, "--"); a = 1; r = --a; assert(r === 0 && a === 0, true, "--"); a = {x:true}; a.x++; assert(a.x, 2, "++"); a = {x:true}; a.x--; assert(a.x, 0, "--"); a = [true]; a[0]++; assert(a[0], 2, "++"); a = {x:true}; r = a.x++; assert(r === 1 && a.x === 2, true, "++"); a = {x:true}; r = a.x--; assert(r === 1 && a.x === 0, true, "--"); a = [true]; r = a[0]++; assert(r === 1 && a[0] === 2, true, "++"); a = [true]; r = a[0]--; assert(r === 1 && a[0] === 0, true, "--"); } function F(x) { this.x = x; } function test_op2() { var a, b; a = new Object; a.x = 1; assert(a.x, 1, "new"); b = new F(2); assert(b.x, 2, "new"); a = {x : 2}; assert(("x" in a), true, "in"); assert(("y" in a), false, "in"); a = {}; assert((a instanceof Object), true, "instanceof"); assert((a instanceof String), false, "instanceof"); assert((typeof 1), "number", "typeof"); assert((typeof Object), "function", "typeof"); assert((typeof null), "object", "typeof"); assert((typeof unknown_var), "undefined", "typeof"); a = {x: 1, if: 2, async: 3}; assert(a.if === 2); assert(a.async === 3); } function test_delete() { var a, err; a = {x: 1, y: 1}; assert((delete a.x), true, "delete"); assert(("x" in a), false, "delete"); /* the following are not tested by test262 */ assert(delete "abc"[100], true); err = false; try { delete null.a; } catch(e) { err = (e instanceof TypeError); } assert(err, true, "delete"); err = false; try { a = { f() { delete super.a; } }; a.f(); } catch(e) { err = (e instanceof ReferenceError); } assert(err, true, "delete"); } function test_prototype() { function f() { } assert(f.prototype.constructor, f, "prototype"); } function test_arguments() { function f2() { assert(arguments.length, 2, "arguments"); assert(arguments[0], 1, "arguments"); assert(arguments[1], 3, "arguments"); } f2(1, 3); } function test_class() { var o; class C { constructor() { this.x = 10; } f() { return 1; } static F() { return -1; } get y() { return 12; } }; class D extends C { constructor() { super(); this.z = 20; } g() { return 2; } static G() { return -2; } h() { return super.f(); } static H() { return super["F"](); } } assert(C.F() === -1); assert(Object.getOwnPropertyDescriptor(C.prototype, "y").get.name === "get y"); o = new C(); assert(o.f() === 1); assert(o.x === 10); assert(D.F() === -1); assert(D.G() === -2); assert(D.H() === -1); o = new D(); assert(o.f() === 1); assert(o.g() === 2); assert(o.x === 10); assert(o.z === 20); assert(o.h() === 1); /* test class name scope */ var E1 = class E { static F() { return E; } }; assert(E1 === E1.F()); }; function test_template() { var a, b; b = 123; a = `abc${b}d`; assert(a, "abc123d"); a = String.raw `abc${b}d`; assert(a, "abc123d"); a = "aaa"; b = "bbb"; assert(`aaa${a, b}ccc`, "aaabbbccc"); } function test_template_skip() { var a = "Bar"; var { b = `${a + `a${a}` }baz` } = {}; assert(b, "BaraBarbaz"); } function test_object_literal() { var x = 0, get = 1, set = 2; async = 3; a = { get: 2, set: 3, async: 4 }; assert(JSON.stringify(a), '{"get":2,"set":3,"async":4}'); a = { x, get, set, async }; assert(JSON.stringify(a), '{"x":0,"get":1,"set":2,"async":3}'); } function test_regexp_skip() { var a, b; [a, b = /abc\(/] = [1]; assert(a === 1); [a, b =/abc\(/] = [2]; assert(a === 2); } function test_labels() { do x: { break x; } while(0); if (1) x: { break x; } else x: { break x; } with ({}) x: { break x; }; while (0) x: { break x; }; } test_op1(); test_cvt(); test_eq(); test_inc_dec(); test_op2(); test_delete(); test_prototype(); test_arguments(); test_class(); test_template(); test_template_skip(); test_object_literal(); test_regexp_skip(); test_labels();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_language.js
JavaScript
apache-2.0
7,438
function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function test_while() { var i, c; i = 0; c = 0; while (i < 3) { c++; i++; } assert(c === 3); } function test_while_break() { var i, c; i = 0; c = 0; while (i < 3) { c++; if (i == 1) break; i++; } assert(c === 2 && i === 1); } function test_do_while() { var i, c; i = 0; c = 0; do { c++; i++; } while (i < 3); assert(c === 3 && i === 3); } function test_for() { var i, c; c = 0; for(i = 0; i < 3; i++) { c++; } assert(c === 3 && i === 3); c = 0; for(var j = 0; j < 3; j++) { c++; } assert(c === 3 && j === 3); } function test_for_in() { var i, tab, a, b; tab = []; for(i in {x:1, y: 2}) { tab.push(i); } assert(tab.toString(), "x,y", "for_in"); /* prototype chain test */ a = {x:2, y: 2, "1": 3}; b = {"4" : 3 }; Object.setPrototypeOf(a, b); tab = []; for(i in a) { tab.push(i); } assert(tab.toString(), "1,x,y,4", "for_in"); /* non enumerable properties hide enumerables ones in the prototype chain */ a = {y: 2, "1": 3}; Object.defineProperty(a, "x", { value: 1 }); b = {"x" : 3 }; Object.setPrototypeOf(a, b); tab = []; for(i in a) { tab.push(i); } assert(tab.toString(), "1,y", "for_in"); /* array optimization */ a = []; for(i = 0; i < 10; i++) a.push(i); tab = []; for(i in a) { tab.push(i); } assert(tab.toString(), "0,1,2,3,4,5,6,7,8,9", "for_in"); /* iterate with a field */ a={x:0}; tab = []; for(a.x in {x:1, y: 2}) { tab.push(a.x); } assert(tab.toString(), "x,y", "for_in"); /* iterate with a variable field */ a=[0]; tab = []; for(a[0] in {x:1, y: 2}) { tab.push(a[0]); } assert(tab.toString(), "x,y", "for_in"); /* variable definition in the for in */ tab = []; for(var j in {x:1, y: 2}) { tab.push(j); } assert(tab.toString(), "x,y", "for_in"); /* variable assigment in the for in */ tab = []; for(var k = 2 in {x:1, y: 2}) { tab.push(k); } assert(tab.toString(), "x,y", "for_in"); } function test_for_in2() { var i; tab = []; for(i in {x:1, y: 2, z:3}) { if (i === "y") continue; tab.push(i); } assert(tab.toString() == "x,z"); tab = []; for(i in {x:1, y: 2, z:3}) { if (i === "z") break; tab.push(i); } assert(tab.toString() == "x,y"); } function test_for_break() { var i, c; c = 0; L1: for(i = 0; i < 3; i++) { c++; if (i == 0) continue; while (1) { break L1; } } assert(c === 2 && i === 1); } function test_switch1() { var i, a, s; s = ""; for(i = 0; i < 3; i++) { a = "?"; switch(i) { case 0: a = "a"; break; case 1: a = "b"; break; default: a = "c"; break; } s += a; } assert(s === "abc" && i === 3); } function test_switch2() { var i, a, s; s = ""; for(i = 0; i < 4; i++) { a = "?"; switch(i) { case 0: a = "a"; break; case 1: a = "b"; break; case 2: continue; default: a = "" + i; break; } s += a; } assert(s === "ab3" && i === 4); } function test_try_catch1() { try { throw "hello"; } catch (e) { assert(e, "hello", "catch"); return; } assert(false, "catch"); } function test_try_catch2() { var a; try { a = 1; } catch (e) { a = 2; } assert(a, 1, "catch"); } function test_try_catch3() { var s; s = ""; try { s += "t"; } catch (e) { s += "c"; } finally { s += "f"; } assert(s, "tf", "catch"); } function test_try_catch4() { var s; s = ""; try { s += "t"; throw "c"; } catch (e) { s += e; } finally { s += "f"; } assert(s, "tcf", "catch"); } function test_try_catch5() { var s; s = ""; for(;;) { try { s += "t"; break; s += "b"; } finally { s += "f"; } } assert(s, "tf", "catch"); } function test_try_catch6() { function f() { try { s += 't'; return 1; } finally { s += "f"; } } var s = ""; assert(f() === 1); assert(s, "tf", "catch6"); } function test_try_catch7() { var s; s = ""; try { try { s += "t"; throw "a"; } finally { s += "f"; } } catch(e) { s += e; } finally { s += "g"; } assert(s, "tfag", "catch"); } function test_try_catch8() { var i, s; s = ""; for(var i in {x:1, y:2}) { try { s += i; throw "a"; } catch (e) { s += e; } finally { s += "f"; } } assert(s === "xafyaf"); } test_while(); test_while_break(); test_do_while(); test_for(); test_for_break(); test_switch1(); test_switch2(); test_for_in(); test_for_in2(); test_try_catch1(); test_try_catch2(); test_try_catch3(); test_try_catch4(); test_try_catch5(); test_try_catch6(); test_try_catch7(); test_try_catch8();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_loop.js
JavaScript
apache-2.0
6,286
"use strict"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } /* operators overloading with Operators.create() */ function test_operators_create() { class Vec2 { constructor(x, y) { this.x = x; this.y = y; } static mul_scalar(p1, a) { var r = new Vec2(); r.x = p1.x * a; r.y = p1.y * a; return r; } toString() { return "Vec2(" + this.x + "," + this.y + ")"; } } Vec2.prototype[Symbol.operatorSet] = Operators.create( { "+"(p1, p2) { var r = new Vec2(); r.x = p1.x + p2.x; r.y = p1.y + p2.y; return r; }, "-"(p1, p2) { var r = new Vec2(); r.x = p1.x - p2.x; r.y = p1.y - p2.y; return r; }, "=="(a, b) { return a.x == b.x && a.y == b.y; }, "<"(a, b) { var r; /* lexicographic order */ if (a.x == b.x) r = (a.y < b.y); else r = (a.x < b.x); return r; }, "++"(a) { var r = new Vec2(); r.x = a.x + 1; r.y = a.y + 1; return r; } }, { left: Number, "*"(a, b) { return Vec2.mul_scalar(b, a); } }, { right: Number, "*"(a, b) { return Vec2.mul_scalar(a, b); } }); var a = new Vec2(1, 2); var b = new Vec2(3, 4); var r; r = a * 2 + 3 * b; assert(r.x === 11 && r.y === 16); assert(a == a, true); assert(a == b, false); assert(a != a, false); assert(a < b, true); assert(a <= b, true); assert(b < a, false); assert(b <= a, false); assert(a <= a, true); assert(a >= a, true); a++; assert(a.x === 2 && a.y === 3); r = ++a; assert(a.x === 3 && a.y === 4); assert(r === a); } /* operators overloading thru inheritance */ function test_operators() { var Vec2; function mul_scalar(p1, a) { var r = new Vec2(); r.x = p1.x * a; r.y = p1.y * a; return r; } var vec2_ops = Operators({ "+"(p1, p2) { var r = new Vec2(); r.x = p1.x + p2.x; r.y = p1.y + p2.y; return r; }, "-"(p1, p2) { var r = new Vec2(); r.x = p1.x - p2.x; r.y = p1.y - p2.y; return r; }, "=="(a, b) { return a.x == b.x && a.y == b.y; }, "<"(a, b) { var r; /* lexicographic order */ if (a.x == b.x) r = (a.y < b.y); else r = (a.x < b.x); return r; }, "++"(a) { var r = new Vec2(); r.x = a.x + 1; r.y = a.y + 1; return r; } }, { left: Number, "*"(a, b) { return mul_scalar(b, a); } }, { right: Number, "*"(a, b) { return mul_scalar(a, b); } }); Vec2 = class Vec2 extends vec2_ops { constructor(x, y) { super(); this.x = x; this.y = y; } toString() { return "Vec2(" + this.x + "," + this.y + ")"; } } var a = new Vec2(1, 2); var b = new Vec2(3, 4); var r; r = a * 2 + 3 * b; assert(r.x === 11 && r.y === 16); assert(a == a, true); assert(a == b, false); assert(a != a, false); assert(a < b, true); assert(a <= b, true); assert(b < a, false); assert(b <= a, false); assert(a <= a, true); assert(a >= a, true); a++; assert(a.x === 2 && a.y === 3); r = ++a; assert(a.x === 3 && a.y === 4); assert(r === a); } function test_default_op() { assert(Object(1) + 2, 3); assert(Object(1) + true, 2); assert(-Object(1), -1); } test_operators_create(); test_operators(); test_default_op();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_op_overloading.js
JavaScript
apache-2.0
4,581
"use math"; "use strict"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } function assertThrows(err, func) { var ex; ex = false; try { func(); } catch(e) { ex = true; assert(e instanceof err); } assert(ex, true, "exception expected"); } // load more elaborate version of assert if available try { __loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function pow(a, n) { var r, i; r = 1; for(i = 0; i < n; i++) r *= a; return r; } function test_integer() { var a, r; a = pow(3, 100); assert((a - 1) != a); assert(a == 515377520732011331036461129765621272702107522001); assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1); assert(Integer.isInteger(1) === true); assert(Integer.isInteger(1.0) === false); assert(Integer.floorLog2(0) === -1); assert(Integer.floorLog2(7) === 2); r = 1 << 31; assert(r, 2147483648, "1 << 31 === 2147483648"); r = 1 << 32; assert(r, 4294967296, "1 << 32 === 4294967296"); r = (1 << 31) < 0; assert(r, false, "(1 << 31) < 0 === false"); assert(typeof 1 === "number"); assert(typeof 9007199254740991 === "number"); assert(typeof 9007199254740992 === "bigint"); } function test_float() { assert(typeof 1.0 === "bigfloat"); assert(1 == 1.0); assert(1 !== 1.0); } /* jscalc tests */ function test_modulo() { var i, p, a, b; /* Euclidian modulo operator */ assert((-3) % 2 == 1); assert(3 % (-2) == 1); p = 101; for(i = 1; i < p; i++) { a = Integer.invmod(i, p); assert(a >= 0 && a < p); assert((i * a) % p == 1); } assert(Integer.isPrime(2^107-1)); assert(!Integer.isPrime((2^107-1) * (2^89-1))); a = Integer.factor((2^89-1)*2^3*11*13^2*1009); assert(a == [ 2,2,2,11,13,13,1009,618970019642690137449562111 ]); } function test_fraction() { assert((1/3 + 1).toString(), "4/3") assert((2/3)^30, 1073741824/205891132094649); assert(1/3 < 2/3); assert(1/3 < 1); assert(1/3 == 1.0/3); assert(1.0/3 < 2/3); } function test_mod() { var a, b, p; a = Mod(3, 101); b = Mod(-1, 101); assert((a + b) == Mod(2, 101)); assert(a ^ 100 == Mod(1, 101)); p = 2 ^ 607 - 1; /* mersenne prime */ a = Mod(3, p) ^ (p - 1); assert(a == Mod(1, p)); } function test_polynomial() { var a, b, q, r, t, i; a = (1 + X) ^ 4; assert(a == X^4+4*X^3+6*X^2+4*X+1); r = (1 + X); q = (1+X+X^2); b = (1 - X^2); a = q * b + r; t = Polynomial.divrem(a, b); assert(t[0] == q); assert(t[1] == r); a = 1 + 2*X + 3*X^2; assert(a.apply(0.1) == 1.23); a = 1-2*X^2+2*X^3; assert(deriv(a) == (6*X^2-4*X)); assert(deriv(integ(a)) == a); a = (X-1)*(X-2)*(X-3)*(X-4)*(X-0.1); r = polroots(a); for(i = 0; i < r.length; i++) { b = abs(a.apply(r[i])); assert(b <= 1e-13); } } function test_poly_mod() { var a, p; /* modulo using polynomials */ p = X^2 + X + 1; a = PolyMod(3+X, p) ^ 10; assert(a == PolyMod(-3725*X-18357, p)); a = PolyMod(1/X, 1+X^2); assert(a == PolyMod(-X, X^2+1)); } function test_rfunc() { var a; a = (X+1)/((X+1)*(X-1)); assert(a == 1/(X-1)); a = (X + 2) / (X - 2); assert(a.apply(1/3) == -7/5); assert(deriv((X^2-X+1)/(X-1)) == (X^2-2*X)/(X^2-2*X+1)); } function test_series() { var a, b; a = 1+X+O(X^5); b = a.inverse(); assert(b == 1-X+X^2-X^3+X^4+O(X^5)); assert(deriv(b) == -1+2*X-3*X^2+4*X^3+O(X^4)); assert(deriv(integ(b)) == b); a = Series(1/(1-X), 5); assert(a == 1+X+X^2+X^3+X^4+O(X^5)); b = a.apply(0.1); assert(b == 1.1111); 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)); assert(sin(X+O(X^6)) == X-1/6*X^3+1/120*X^5+O(X^6)); assert(cos(X+O(X^6)) == 1-1/2*X^2+1/24*X^4+O(X^6)); assert(tan(X+O(X^8)) == X+1/3*X^3+2/15*X^5+17/315*X^7+O(X^8)); 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)); } function test_matrix() { var a, b, r; a = [[1, 2],[3, 4]]; b = [3, 4]; r = a * b; assert(r == [11, 25]); r = (a^-1) * 2; assert(r == [[-4, 2],[3, -1]]); assert(norm2([1,2,3]) == 14); assert(diag([1,2,3]) == [ [ 1, 0, 0 ], [ 0, 2, 0 ], [ 0, 0, 3 ] ]); assert(trans(a) == [ [ 1, 3 ], [ 2, 4 ] ]); assert(trans([1,2,3]) == [[1,2,3]]); assert(trace(a) == 5); assert(charpoly(Matrix.hilbert(4)) == X^4-176/105*X^3+3341/12600*X^2-41/23625*X+1/6048000); assert(det(Matrix.hilbert(4)) == 1/6048000); a = [[1,2,1],[-2,-3,1],[3,5,0]]; assert(rank(a) == 2); assert(ker(a) == [ [ 5 ], [ -3 ], [ 1 ] ]); assert(dp([1, 2, 3], [3, -4, -7]) === -26); assert(cp([1, 2, 3], [3, -4, -7]) == [ -2, 16, -10 ]); } function assert_eq(a, ref) { assert(abs(a / ref - 1.0) <= 1e-15); } function test_trig() { assert_eq(sin(1/2), 0.479425538604203); assert_eq(sin(2+3*I), 9.154499146911428-4.168906959966565*I); assert_eq(cos(2+3*I), -4.189625690968807-9.109227893755337*I); assert_eq((2+0.5*I)^(1.1-0.5*I), 2.494363021357619-0.23076804554558092*I); assert_eq(sqrt(2*I), 1 + I); } test_integer(); test_float(); test_modulo(); test_fraction(); test_mod(); test_polynomial(); test_poly_mod(); test_rfunc(); test_series(); test_matrix(); test_trig();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_qjscalc.js
JavaScript
apache-2.0
5,876
import * as std from "std"; import * as os from "os"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } // load more elaborate version of assert if available try { std.loadScript("test_assert.js"); } catch(e) {} /*----------------*/ function test_printf() { assert(std.sprintf("a=%d s=%s", 123, "abc"), "a=123 s=abc"); assert(std.sprintf("%010d", 123), "0000000123"); assert(std.sprintf("%x", -2), "fffffffe"); assert(std.sprintf("%lx", -2), "fffffffffffffffe"); assert(std.sprintf("%10.1f", 2.1), " 2.1"); assert(std.sprintf("%*.*f", 10, 2, -2.13), " -2.13"); assert(std.sprintf("%#lx", 0x7fffffffffffffffn), "0x7fffffffffffffff"); } function test_file1() { var f, len, str, size, buf, ret, i, str1; f = std.tmpfile(); str = "hello world\n"; f.puts(str); f.seek(0, std.SEEK_SET); str1 = f.readAsString(); assert(str1 === str); f.seek(0, std.SEEK_END); size = f.tell(); assert(size === str.length); f.seek(0, std.SEEK_SET); buf = new Uint8Array(size); ret = f.read(buf.buffer, 0, size); assert(ret === size); for(i = 0; i < size; i++) assert(buf[i] === str.charCodeAt(i)); f.close(); } function test_file2() { var f, str, i, size; f = std.tmpfile(); str = "hello world\n"; size = str.length; for(i = 0; i < size; i++) f.putByte(str.charCodeAt(i)); f.seek(0, std.SEEK_SET); for(i = 0; i < size; i++) { assert(str.charCodeAt(i) === f.getByte()); } assert(f.getByte() === -1); f.close(); } function test_getline() { var f, line, line_count, lines, i; lines = ["hello world", "line 1", "line 2" ]; f = std.tmpfile(); for(i = 0; i < lines.length; i++) { f.puts(lines[i], "\n"); } f.seek(0, std.SEEK_SET); assert(!f.eof()); line_count = 0; for(;;) { line = f.getline(); if (line === null) break; assert(line == lines[line_count]); line_count++; } assert(f.eof()); assert(line_count === lines.length); f.close(); } function test_popen() { var str, f, fname = "tmp_file.txt"; var content = "hello world"; f = std.open(fname, "w"); f.puts(content); f.close(); /* test loadFile */ assert(std.loadFile(fname), content); /* execute the 'cat' shell command */ f = std.popen("cat " + fname, "r"); str = f.readAsString(); f.close(); assert(str, content); os.remove(fname); } function test_ext_json() { var expected, input, obj; expected = '{"x":false,"y":true,"z2":null,"a":[1,8,160],"s":"str"}'; input = `{ "x":false, /*comments are allowed */ "y":true, // also a comment z2:null, // unquoted property names "a":[+1,0o10,0xa0,], // plus prefix, octal, hexadecimal "s":"str",} // trailing comma in objects and arrays `; obj = std.parseExtJSON(input); assert(JSON.stringify(obj), expected); } function test_os() { var fd, fpath, fname, fdir, buf, buf2, i, files, err, fdate, st, link_path; assert(os.isatty(0)); fdir = "test_tmp_dir"; fname = "tmp_file.txt"; fpath = fdir + "/" + fname; link_path = fdir + "/test_link"; os.remove(link_path); os.remove(fpath); os.remove(fdir); err = os.mkdir(fdir, 0o755); assert(err === 0); fd = os.open(fpath, os.O_RDWR | os.O_CREAT | os.O_TRUNC); assert(fd >= 0); buf = new Uint8Array(10); for(i = 0; i < buf.length; i++) buf[i] = i; assert(os.write(fd, buf.buffer, 0, buf.length) === buf.length); assert(os.seek(fd, 0, std.SEEK_SET) === 0); buf2 = new Uint8Array(buf.length); assert(os.read(fd, buf2.buffer, 0, buf2.length) === buf2.length); for(i = 0; i < buf.length; i++) assert(buf[i] == buf2[i]); if (typeof BigInt !== "undefined") { assert(os.seek(fd, BigInt(6), std.SEEK_SET), BigInt(6)); assert(os.read(fd, buf2.buffer, 0, 1) === 1); assert(buf[6] == buf2[0]); } assert(os.close(fd) === 0); [files, err] = os.readdir(fdir); assert(err, 0); assert(files.indexOf(fname) >= 0); fdate = 10000; err = os.utimes(fpath, fdate, fdate); assert(err, 0); [st, err] = os.stat(fpath); assert(err, 0); assert(st.mode & os.S_IFMT, os.S_IFREG); assert(st.mtime, fdate); err = os.symlink(fname, link_path); assert(err === 0); [st, err] = os.lstat(link_path); assert(err, 0); assert(st.mode & os.S_IFMT, os.S_IFLNK); [buf, err] = os.readlink(link_path); assert(err, 0); assert(buf, fname); assert(os.remove(link_path) === 0); [buf, err] = os.getcwd(); assert(err, 0); [buf2, err] = os.realpath("."); assert(err, 0); assert(buf, buf2); assert(os.remove(fpath) === 0); fd = os.open(fpath, os.O_RDONLY); assert(fd < 0); assert(os.remove(fdir) === 0); } function test_os_exec() { var ret, fds, pid, f, status; ret = os.exec(["true"]); assert(ret, 0); ret = os.exec(["/bin/sh", "-c", "exit 1"], { usePath: false }); assert(ret, 1); fds = os.pipe(); pid = os.exec(["sh", "-c", "echo $FOO"], { stdout: fds[1], block: false, env: { FOO: "hello" }, } ); assert(pid >= 0); os.close(fds[1]); /* close the write end (as it is only in the child) */ f = std.fdopen(fds[0], "r"); assert(f.getline(), "hello"); assert(f.getline(), null); f.close(); [ret, status] = os.waitpid(pid, 0); assert(ret, pid); assert(status & 0x7f, 0); /* exited */ assert(status >> 8, 0); /* exit code */ pid = os.exec(["cat"], { block: false } ); assert(pid >= 0); os.kill(pid, os.SIGQUIT); [ret, status] = os.waitpid(pid, 0); assert(ret, pid); assert(status & 0x7f, os.SIGQUIT); } function test_timer() { var th, i; /* just test that a timer can be inserted and removed */ th = []; for(i = 0; i < 3; i++) th[i] = os.setTimeout(function () { }, 1000); for(i = 0; i < 3; i++) os.clearTimeout(th[i]); } test_printf(); test_file1(); test_file2(); test_getline(); test_popen(); test_os(); test_os_exec(); test_timer(); test_ext_json();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_std.js
JavaScript
apache-2.0
6,776
/* os.Worker API test */ import * as std from "std"; import * as os from "os"; function assert(actual, expected, message) { if (arguments.length == 1) expected = true; if (actual === expected) return; if (actual !== null && expected !== null && typeof actual == 'object' && typeof expected == 'object' && actual.toString() === expected.toString()) return; throw Error("assertion failed: got |" + actual + "|" + ", expected |" + expected + "|" + (message ? " (" + message + ")" : "")); } var worker; function test_worker() { var counter; /* Note: can use std.loadFile() to read from a file */ worker = new os.Worker(` import * as std from "std"; import * as os from "os"; var parent = os.Worker.parent; function handle_msg(e) { var ev = e.data; // print("child_recv", JSON.stringify(ev)); switch(ev.type) { case "abort": parent.postMessage({ type: "done" }); break; case "sab": /* modify the SharedArrayBuffer */ ev.buf[2] = 10; parent.postMessage({ type: "sab_done", buf: ev.buf }); break; } } function worker_main() { var i; parent.onmessage = handle_msg; for(i = 0; i < 10; i++) { parent.postMessage({ type: "num", num: i }); } } worker_main(); `); counter = 0; worker.onmessage = function (e) { var ev = e.data; // print("recv", JSON.stringify(ev)); switch(ev.type) { case "num": assert(ev.num, counter); counter++; if (counter == 10) { /* test SharedArrayBuffer modification */ let sab = new SharedArrayBuffer(10); let buf = new Uint8Array(sab); worker.postMessage({ type: "sab", buf: buf }); } break; case "sab_done": { let buf = ev.buf; /* check that the SharedArrayBuffer was modified */ assert(buf[2], 10); worker.postMessage({ type: "abort" }); } break; case "done": /* terminate */ worker.onmessage = null; break; } }; } test_worker();
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/tests/test_worker.js
JavaScript
apache-2.0
2,447
#!/bin/sh set -e url="ftp://ftp.unicode.org/Public/13.0.0/ucd" emoji_url="${url}/emoji/emoji-data.txt" files="CaseFolding.txt DerivedNormalizationProps.txt PropList.txt \ SpecialCasing.txt CompositionExclusions.txt ScriptExtensions.txt \ UnicodeData.txt DerivedCoreProperties.txt NormalizationTest.txt Scripts.txt \ PropertyValueAliases.txt" mkdir -p unicode #for f in $files; do # g="${url}/${f}" # wget $g -O unicode/$f #done wget $emoji_url -O unicode/emoji-data.txt
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/unicode_download.sh
Shell
apache-2.0
485
/* * Generation of Unicode tables * * Copyright (c) 2017-2018 Fabrice Bellard * Copyright (c) 2017-2018 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <inttypes.h> #include <string.h> #include <assert.h> #include <ctype.h> #include <time.h> #include "cutils.h" /* define it to be able to test unicode.c */ //#define USE_TEST /* profile tests */ //#define PROFILE //#define DUMP_CASE_CONV_TABLE //#define DUMP_TABLE_SIZE //#define DUMP_CC_TABLE //#define DUMP_DECOMP_TABLE /* Ideas: - Generalize run length encoding + index for all tables - remove redundant tables for ID_start, ID_continue, Case_Ignorable, Cased Case conversion: - use a single entry for consecutive U/LF runs - allow EXT runs of length > 1 Decomposition: - Greek lower case (+1f10/1f10) ? - allow holes in B runs - suppress more upper / lower case redundancy */ #ifdef USE_TEST #include "libunicode.c" #endif #define CHARCODE_MAX 0x10ffff #define CC_LEN_MAX 3 void *mallocz(size_t size) { void *ptr; ptr = malloc(size); memset(ptr, 0, size); return ptr; } const char *get_field(const char *p, int n) { int i; for(i = 0; i < n; i++) { while (*p != ';' && *p != '\0') p++; if (*p == '\0') return NULL; p++; } return p; } const char *get_field_buf(char *buf, size_t buf_size, const char *p, int n) { char *q; p = get_field(p, n); q = buf; while (*p != ';' && *p != '\0') { if ((q - buf) < buf_size - 1) *q++ = *p; p++; } *q = '\0'; return buf; } void add_char(int **pbuf, int *psize, int *plen, int c) { int len, size, *buf; buf = *pbuf; size = *psize; len = *plen; if (len >= size) { size = *psize; size = max_int(len + 1, size * 3 / 2); buf = realloc(buf, sizeof(buf[0]) * size); *pbuf = buf; *psize = size; } buf[len++] = c; *plen = len; } int *get_field_str(int *plen, const char *str, int n) { const char *p; int *buf, len, size; p = get_field(str, n); if (!p) { *plen = 0; return NULL; } len = 0; size = 0; buf = NULL; for(;;) { while (isspace(*p)) p++; if (!isxdigit(*p)) break; add_char(&buf, &size, &len, strtoul(p, (char **)&p, 16)); } *plen = len; return buf; } char *get_line(char *buf, int buf_size, FILE *f) { int len; if (!fgets(buf, buf_size, f)) return NULL; len = strlen(buf); if (len > 0 && buf[len - 1] == '\n') buf[len - 1] = '\0'; return buf; } #define UNICODE_GENERAL_CATEGORY typedef enum { #define DEF(id, str) GCAT_ ## id, #include "unicode_gen_def.h" #undef DEF GCAT_COUNT, } UnicodeGCEnum1; static const char *unicode_gc_name[] = { #define DEF(id, str) #id, #include "unicode_gen_def.h" #undef DEF }; static const char *unicode_gc_short_name[] = { #define DEF(id, str) str, #include "unicode_gen_def.h" #undef DEF }; #undef UNICODE_GENERAL_CATEGORY #define UNICODE_SCRIPT typedef enum { #define DEF(id, str) SCRIPT_ ## id, #include "unicode_gen_def.h" #undef DEF SCRIPT_COUNT, } UnicodeScriptEnum1; static const char *unicode_script_name[] = { #define DEF(id, str) #id, #include "unicode_gen_def.h" #undef DEF }; const char *unicode_script_short_name[] = { #define DEF(id, str) str, #include "unicode_gen_def.h" #undef DEF }; #undef UNICODE_SCRIPT #define UNICODE_PROP_LIST typedef enum { #define DEF(id, str) PROP_ ## id, #include "unicode_gen_def.h" #undef DEF PROP_COUNT, } UnicodePropEnum1; static const char *unicode_prop_name[] = { #define DEF(id, str) #id, #include "unicode_gen_def.h" #undef DEF }; static const char *unicode_prop_short_name[] = { #define DEF(id, str) str, #include "unicode_gen_def.h" #undef DEF }; #undef UNICODE_SPROP_LIST typedef struct { /* case conv */ uint8_t u_len; uint8_t l_len; int u_data[CC_LEN_MAX]; int l_data[CC_LEN_MAX]; int f_code; uint8_t combining_class; uint8_t is_compat:1; uint8_t is_excluded:1; uint8_t general_category; uint8_t script; uint8_t script_ext_len; uint8_t *script_ext; uint32_t prop_bitmap_tab[3]; /* decomposition */ int decomp_len; int *decomp_data; } CCInfo; CCInfo *unicode_db; int find_name(const char **tab, int tab_len, const char *name) { int i, len, name_len; const char *p, *r; name_len = strlen(name); for(i = 0; i < tab_len; i++) { p = tab[i]; for(;;) { r = strchr(p, ','); if (!r) len = strlen(p); else len = r - p; if (len == name_len && memcmp(p, name, len) == 0) return i; if (!r) break; p = r + 1; } } return -1; } static int get_prop(uint32_t c, int prop_idx) { return (unicode_db[c].prop_bitmap_tab[prop_idx >> 5] >> (prop_idx & 0x1f)) & 1; } static void set_prop(uint32_t c, int prop_idx, int val) { uint32_t mask; mask = 1U << (prop_idx & 0x1f); if (val) unicode_db[c].prop_bitmap_tab[prop_idx >> 5] |= mask; else unicode_db[c].prop_bitmap_tab[prop_idx >> 5] &= ~mask; } void parse_unicode_data(const char *filename) { FILE *f; char line[1024]; char buf1[256]; const char *p; int code, lc, uc, last_code; CCInfo *ci, *tab = unicode_db; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } last_code = 0; for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#') continue; p = get_field(line, 0); if (!p) continue; code = strtoul(p, NULL, 16); lc = 0; uc = 0; p = get_field(line, 12); if (p && *p != ';') { uc = strtoul(p, NULL, 16); } p = get_field(line, 13); if (p && *p != ';') { lc = strtoul(p, NULL, 16); } ci = &tab[code]; if (uc > 0 || lc > 0) { assert(code <= CHARCODE_MAX); if (uc > 0) { assert(ci->u_len == 0); ci->u_len = 1; ci->u_data[0] = uc; } if (lc > 0) { assert(ci->l_len == 0); ci->l_len = 1; ci->l_data[0] = lc; } } { int i; get_field_buf(buf1, sizeof(buf1), line, 2); i = find_name(unicode_gc_name, countof(unicode_gc_name), buf1); if (i < 0) { fprintf(stderr, "General category '%s' not found\n", buf1); exit(1); } ci->general_category = i; } p = get_field(line, 3); if (p && *p != ';' && *p != '\0') { int cc; cc = strtoul(p, NULL, 0); if (cc != 0) { assert(code <= CHARCODE_MAX); ci->combining_class = cc; // printf("%05x: %d\n", code, ci->combining_class); } } p = get_field(line, 5); if (p && *p != ';' && *p != '\0') { int size; assert(code <= CHARCODE_MAX); ci->is_compat = 0; if (*p == '<') { while (*p != '\0' && *p != '>') p++; if (*p == '>') p++; ci->is_compat = 1; } size = 0; for(;;) { while (isspace(*p)) p++; if (!isxdigit(*p)) break; add_char(&ci->decomp_data, &size, &ci->decomp_len, strtoul(p, (char **)&p, 16)); } #if 0 { int i; static int count, d_count; printf("%05x: %c", code, ci->is_compat ? 'C': ' '); for(i = 0; i < ci->decomp_len; i++) printf(" %05x", ci->decomp_data[i]); printf("\n"); count++; d_count += ci->decomp_len; // printf("%d %d\n", count, d_count); } #endif } p = get_field(line, 9); if (p && *p == 'Y') { set_prop(code, PROP_Bidi_Mirrored, 1); } /* handle ranges */ get_field_buf(buf1, sizeof(buf1), line, 1); if (strstr(buf1, " Last>")) { int i; // printf("range: 0x%x-%0x\n", last_code, code); assert(ci->decomp_len == 0); assert(ci->script_ext_len == 0); for(i = last_code + 1; i < code; i++) { unicode_db[i] = *ci; } } last_code = code; } fclose(f); } void parse_special_casing(CCInfo *tab, const char *filename) { FILE *f; char line[1024]; const char *p; int code; CCInfo *ci; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#') continue; p = get_field(line, 0); if (!p) continue; code = strtoul(p, NULL, 16); assert(code <= CHARCODE_MAX); ci = &tab[code]; p = get_field(line, 4); if (p) { /* locale dependent casing */ while (isspace(*p)) p++; if (*p != '#' && *p != '\0') continue; } p = get_field(line, 1); if (p && *p != ';') { ci->l_len = 0; for(;;) { while (isspace(*p)) p++; if (*p == ';') break; assert(ci->l_len < CC_LEN_MAX); ci->l_data[ci->l_len++] = strtoul(p, (char **)&p, 16); } if (ci->l_len == 1 && ci->l_data[0] == code) ci->l_len = 0; } p = get_field(line, 3); if (p && *p != ';') { ci->u_len = 0; for(;;) { while (isspace(*p)) p++; if (*p == ';') break; assert(ci->u_len < CC_LEN_MAX); ci->u_data[ci->u_len++] = strtoul(p, (char **)&p, 16); } if (ci->u_len == 1 && ci->u_data[0] == code) ci->u_len = 0; } } fclose(f); } void parse_case_folding(CCInfo *tab, const char *filename) { FILE *f; char line[1024]; const char *p; int code; CCInfo *ci; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#') continue; p = get_field(line, 0); if (!p) continue; code = strtoul(p, NULL, 16); assert(code <= CHARCODE_MAX); ci = &tab[code]; p = get_field(line, 1); if (!p) continue; /* locale dependent casing */ while (isspace(*p)) p++; if (*p != 'C' && *p != 'S') continue; p = get_field(line, 2); assert(p != 0); assert(ci->f_code == 0); ci->f_code = strtoul(p, NULL, 16); assert(ci->f_code != 0 && ci->f_code != code); } fclose(f); } void parse_composition_exclusions(const char *filename) { FILE *f; char line[4096], *p; uint32_t c0; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); assert(c0 > 0 && c0 <= CHARCODE_MAX); unicode_db[c0].is_excluded = TRUE; } fclose(f); } void parse_derived_core_properties(const char *filename) { FILE *f; char line[4096], *p, buf[256], *q; uint32_t c0, c1, c; int i; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); if (*p == '.' && p[1] == '.') { p += 2; c1 = strtoul(p, (char **)&p, 16); } else { c1 = c0; } assert(c1 <= CHARCODE_MAX); p += strspn(p, " \t"); if (*p == ';') { p++; p += strspn(p, " \t"); q = buf; while (*p != '\0' && *p != ' ' && *p != '#' && *p != '\t') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; i = find_name(unicode_prop_name, countof(unicode_prop_name), buf); if (i < 0) { if (!strcmp(buf, "Grapheme_Link")) goto next; fprintf(stderr, "Property not found: %s\n", buf); exit(1); } for(c = c0; c <= c1; c++) { set_prop(c, i, 1); } next: ; } } fclose(f); } void parse_derived_norm_properties(const char *filename) { FILE *f; char line[4096], *p, buf[256], *q; uint32_t c0, c1, c; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); if (*p == '.' && p[1] == '.') { p += 2; c1 = strtoul(p, (char **)&p, 16); } else { c1 = c0; } assert(c1 <= CHARCODE_MAX); p += strspn(p, " \t"); if (*p == ';') { p++; p += strspn(p, " \t"); q = buf; while (*p != '\0' && *p != ' ' && *p != '#' && *p != '\t') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; if (!strcmp(buf, "Changes_When_NFKC_Casefolded")) { for(c = c0; c <= c1; c++) { set_prop(c, PROP_Changes_When_NFKC_Casefolded, 1); } } } } fclose(f); } void parse_prop_list(const char *filename) { FILE *f; char line[4096], *p, buf[256], *q; uint32_t c0, c1, c; int i; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); if (*p == '.' && p[1] == '.') { p += 2; c1 = strtoul(p, (char **)&p, 16); } else { c1 = c0; } assert(c1 <= CHARCODE_MAX); p += strspn(p, " \t"); if (*p == ';') { p++; p += strspn(p, " \t"); q = buf; while (*p != '\0' && *p != ' ' && *p != '#' && *p != '\t') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; i = find_name(unicode_prop_name, countof(unicode_prop_name), buf); if (i < 0) { fprintf(stderr, "Property not found: %s\n", buf); exit(1); } for(c = c0; c <= c1; c++) { set_prop(c, i, 1); } } } fclose(f); } void parse_scripts(const char *filename) { FILE *f; char line[4096], *p, buf[256], *q; uint32_t c0, c1, c; int i; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); if (*p == '.' && p[1] == '.') { p += 2; c1 = strtoul(p, (char **)&p, 16); } else { c1 = c0; } assert(c1 <= CHARCODE_MAX); p += strspn(p, " \t"); if (*p == ';') { p++; p += strspn(p, " \t"); q = buf; while (*p != '\0' && *p != ' ' && *p != '#' && *p != '\t') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; i = find_name(unicode_script_name, countof(unicode_script_name), buf); if (i < 0) { fprintf(stderr, "Unknown script: '%s'\n", buf); exit(1); } for(c = c0; c <= c1; c++) unicode_db[c].script = i; } } fclose(f); } void parse_script_extensions(const char *filename) { FILE *f; char line[4096], *p, buf[256], *q; uint32_t c0, c1, c; int i; uint8_t script_ext[255]; int script_ext_len; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } for(;;) { if (!get_line(line, sizeof(line), f)) break; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@' || *p == '\0') continue; c0 = strtoul(p, (char **)&p, 16); if (*p == '.' && p[1] == '.') { p += 2; c1 = strtoul(p, (char **)&p, 16); } else { c1 = c0; } assert(c1 <= CHARCODE_MAX); p += strspn(p, " \t"); script_ext_len = 0; if (*p == ';') { p++; for(;;) { p += strspn(p, " \t"); q = buf; while (*p != '\0' && *p != ' ' && *p != '#' && *p != '\t') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; if (buf[0] == '\0') break; i = find_name(unicode_script_short_name, countof(unicode_script_short_name), buf); if (i < 0) { fprintf(stderr, "Script not found: %s\n", buf); exit(1); } assert(script_ext_len < sizeof(script_ext)); script_ext[script_ext_len++] = i; } for(c = c0; c <= c1; c++) { CCInfo *ci = &unicode_db[c]; ci->script_ext_len = script_ext_len; ci->script_ext = malloc(sizeof(ci->script_ext[0]) * script_ext_len); for(i = 0; i < script_ext_len; i++) ci->script_ext[i] = script_ext[i]; } } } fclose(f); } void dump_cc_info(CCInfo *ci, int i) { int j; printf("%05x:", i); if (ci->u_len != 0) { printf(" U:"); for(j = 0; j < ci->u_len; j++) printf(" %05x", ci->u_data[j]); } if (ci->l_len != 0) { printf(" L:"); for(j = 0; j < ci->l_len; j++) printf(" %05x", ci->l_data[j]); } if (ci->f_code != 0) { printf(" F: %05x", ci->f_code); } printf("\n"); } void dump_data(CCInfo *tab) { int i; CCInfo *ci; for(i = 0; i <= CHARCODE_MAX; i++) { ci = &tab[i]; if (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0) { dump_cc_info(ci, i); } } } BOOL is_complicated_case(const CCInfo *ci) { return (ci->u_len > 1 || ci->l_len > 1 || (ci->u_len > 0 && ci->l_len > 0) || (ci->f_code != 0) != ci->l_len || (ci->f_code != 0 && ci->l_data[0] != ci->f_code)); } #ifndef USE_TEST enum { RUN_TYPE_U, RUN_TYPE_L, RUN_TYPE_UF, RUN_TYPE_LF, RUN_TYPE_UL, RUN_TYPE_LSU, RUN_TYPE_U2L_399_EXT2, RUN_TYPE_UF_D20, RUN_TYPE_UF_D1_EXT, RUN_TYPE_U_EXT, RUN_TYPE_LF_EXT, RUN_TYPE_U_EXT2, RUN_TYPE_L_EXT2, RUN_TYPE_U_EXT3, }; #endif const char *run_type_str[] = { "U", "L", "UF", "LF", "UL", "LSU", "U2L_399_EXT2", "UF_D20", "UF_D1_EXT", "U_EXT", "LF_EXT", "U_EXT2", "L_EXT2", "U_EXT3", }; typedef struct { int code; int len; int type; int data; int ext_len; int ext_data[3]; int data_index; /* 'data' coming from the table */ } TableEntry; /* code (17), len (7), type (4) */ void find_run_type(TableEntry *te, CCInfo *tab, int code) { int is_lower, len; CCInfo *ci, *ci1, *ci2; ci = &tab[code]; ci1 = &tab[code + 1]; ci2 = &tab[code + 2]; te->code = code; if (ci->l_len == 1 && ci->l_data[0] == code + 2 && ci->f_code == ci->l_data[0] && ci->u_len == 0 && ci1->l_len == 1 && ci1->l_data[0] == code + 2 && ci1->f_code == ci1->l_data[0] && ci1->u_len == 1 && ci1->u_data[0] == code && ci2->l_len == 0 && ci2->f_code == 0 && ci2->u_len == 1 && ci2->u_data[0] == code) { te->len = 3; te->data = 0; te->type = RUN_TYPE_LSU; return; } if (is_complicated_case(ci)) { len = 1; while (code + len <= CHARCODE_MAX) { ci1 = &tab[code + len]; if (ci1->u_len != 1 || ci1->u_data[0] != ci->u_data[0] + len || ci1->l_len != 0 || ci1->f_code != ci1->u_data[0]) break; len++; } if (len > 1) { te->len = len; te->type = RUN_TYPE_UF; te->data = ci->u_data[0]; return; } if (ci->u_len == 2 && ci->u_data[1] == 0x399 && ci->f_code == 0 && ci->l_len == 0) { len = 1; while (code + len <= CHARCODE_MAX) { ci1 = &tab[code + len]; if (!(ci1->u_len == 2 && ci1->u_data[1] == 0x399 && ci1->u_data[0] == ci->u_data[0] + len && ci1->f_code == 0 && ci1->l_len == 0)) break; len++; } te->len = len; te->type = RUN_TYPE_U_EXT2; te->ext_data[0] = ci->u_data[0]; te->ext_data[1] = ci->u_data[1]; te->ext_len = 2; return; } if (ci->u_len == 2 && ci->u_data[1] == 0x399 && ci->l_len == 1 && ci->f_code == ci->l_data[0]) { len = 1; while (code + len <= CHARCODE_MAX) { ci1 = &tab[code + len]; if (!(ci1->u_len == 2 && ci1->u_data[1] == 0x399 && ci1->u_data[0] == ci->u_data[0] + len && ci1->l_len == 1 && ci1->l_data[0] == ci->l_data[0] + len && ci1->f_code == ci1->l_data[0])) break; len++; } te->len = len; te->type = RUN_TYPE_U2L_399_EXT2; te->ext_data[0] = ci->u_data[0]; te->ext_data[1] = ci->l_data[0]; te->ext_len = 2; return; } if (ci->l_len == 1 && ci->u_len == 0 && ci->f_code == 0) { len = 1; while (code + len <= CHARCODE_MAX) { ci1 = &tab[code + len]; if (!(ci1->l_len == 1 && ci1->l_data[0] == ci->l_data[0] + len && ci1->u_len == 0 && ci1->f_code == 0)) break; len++; } te->len = len; te->type = RUN_TYPE_L; te->data = ci->l_data[0]; return; } if (ci->l_len == 0 && ci->u_len == 1 && ci->u_data[0] < 0x1000 && ci->f_code == ci->u_data[0] + 0x20) { te->len = 1; te->type = RUN_TYPE_UF_D20; te->data = ci->u_data[0]; } else if (ci->l_len == 0 && ci->u_len == 1 && ci->f_code == ci->u_data[0] + 1) { te->len = 1; te->type = RUN_TYPE_UF_D1_EXT; te->ext_data[0] = ci->u_data[0]; te->ext_len = 1; } else if (ci->l_len == 2 && ci->u_len == 0 && ci->f_code == 0) { te->len = 1; te->type = RUN_TYPE_L_EXT2; te->ext_data[0] = ci->l_data[0]; te->ext_data[1] = ci->l_data[1]; te->ext_len = 2; } else if (ci->u_len == 2 && ci->l_len == 0 && ci->f_code == 0) { te->len = 1; te->type = RUN_TYPE_U_EXT2; te->ext_data[0] = ci->u_data[0]; te->ext_data[1] = ci->u_data[1]; te->ext_len = 2; } else if (ci->u_len == 3 && ci->l_len == 0 && ci->f_code == 0) { te->len = 1; te->type = RUN_TYPE_U_EXT3; te->ext_data[0] = ci->u_data[0]; te->ext_data[1] = ci->u_data[1]; te->ext_data[2] = ci->u_data[2]; te->ext_len = 3; } else { printf("unsupported encoding case:\n"); dump_cc_info(ci, code); abort(); } } else { /* look for a run of identical conversions */ len = 0; for(;;) { if (code >= CHARCODE_MAX || len >= 126) break; ci = &tab[code + len]; ci1 = &tab[code + len + 1]; if (is_complicated_case(ci) || is_complicated_case(ci1)) { break; } if (ci->l_len != 1 || ci->l_data[0] != code + len + 1) break; if (ci1->u_len != 1 || ci1->u_data[0] != code + len) break; len += 2; } if (len > 0) { te->len = len; te->type = RUN_TYPE_UL; te->data = 0; return; } ci = &tab[code]; is_lower = ci->l_len > 0; len = 1; while (code + len <= CHARCODE_MAX) { ci1 = &tab[code + len]; if (is_complicated_case(ci1)) break; if (is_lower) { if (ci1->l_len != 1 || ci1->l_data[0] != ci->l_data[0] + len) break; } else { if (ci1->u_len != 1 || ci1->u_data[0] != ci->u_data[0] + len) break; } len++; } te->len = len; if (is_lower) { te->type = RUN_TYPE_LF; te->data = ci->l_data[0]; } else { te->type = RUN_TYPE_U; te->data = ci->u_data[0]; } } } TableEntry conv_table[1000]; int conv_table_len; int ext_data[1000]; int ext_data_len; void dump_case_conv_table1(void) { int i, j; const TableEntry *te; for(i = 0; i < conv_table_len; i++) { te = &conv_table[i]; printf("%05x %02x %-10s %05x", te->code, te->len, run_type_str[te->type], te->data); for(j = 0; j < te->ext_len; j++) { printf(" %05x", te->ext_data[j]); } printf("\n"); } printf("table_len=%d ext_len=%d\n", conv_table_len, ext_data_len); } int find_data_index(const TableEntry *conv_table, int len, int data) { int i; const TableEntry *te; for(i = 0; i < len; i++) { te = &conv_table[i]; if (te->code == data) return i; } return -1; } int find_ext_data_index(int data) { int i; for(i = 0; i < ext_data_len; i++) { if (ext_data[i] == data) return i; } assert(ext_data_len < countof(ext_data)); ext_data[ext_data_len++] = data; return ext_data_len - 1; } void build_conv_table(CCInfo *tab) { int code, i, j; CCInfo *ci; TableEntry *te; te = conv_table; for(code = 0; code <= CHARCODE_MAX; code++) { ci = &tab[code]; if (ci->u_len == 0 && ci->l_len == 0 && ci->f_code == 0) continue; assert(te - conv_table < countof(conv_table)); find_run_type(te, tab, code); #if 0 if (te->type == RUN_TYPE_TODO) { printf("TODO: "); dump_cc_info(ci, code); } #endif assert(te->len <= 127); code += te->len - 1; te++; } conv_table_len = te - conv_table; /* find the data index */ for(i = 0; i < conv_table_len; i++) { int data_index; te = &conv_table[i]; switch(te->type) { case RUN_TYPE_U: case RUN_TYPE_L: case RUN_TYPE_UF: case RUN_TYPE_LF: data_index = find_data_index(conv_table, conv_table_len, te->data); if (data_index < 0) { switch(te->type) { case RUN_TYPE_U: te->type = RUN_TYPE_U_EXT; te->ext_len = 1; te->ext_data[0] = te->data; break; case RUN_TYPE_LF: te->type = RUN_TYPE_LF_EXT; te->ext_len = 1; te->ext_data[0] = te->data; break; default: printf("%05x: index not found\n", te->code); exit(1); } } else { te->data_index = data_index; } break; case RUN_TYPE_UF_D20: te->data_index = te->data; break; } } /* find the data index for ext_data */ for(i = 0; i < conv_table_len; i++) { te = &conv_table[i]; if (te->type == RUN_TYPE_U_EXT3) { int p, v; v = 0; for(j = 0; j < 3; j++) { p = find_ext_data_index(te->ext_data[j]); assert(p < 16); v = (v << 4) | p; } te->data_index = v; } } for(i = 0; i < conv_table_len; i++) { te = &conv_table[i]; if (te->type == RUN_TYPE_L_EXT2 || te->type == RUN_TYPE_U_EXT2 || te->type == RUN_TYPE_U2L_399_EXT2) { int p, v; v = 0; for(j = 0; j < 2; j++) { p = find_ext_data_index(te->ext_data[j]); assert(p < 64); v = (v << 6) | p; } te->data_index = v; } } for(i = 0; i < conv_table_len; i++) { te = &conv_table[i]; if (te->type == RUN_TYPE_UF_D1_EXT || te->type == RUN_TYPE_U_EXT || te->type == RUN_TYPE_LF_EXT) { te->data_index = find_ext_data_index(te->ext_data[0]); } } #ifdef DUMP_CASE_CONV_TABLE dump_case_conv_table1(); #endif } void dump_case_conv_table(FILE *f) { int i; uint32_t v; const TableEntry *te; fprintf(f, "static const uint32_t case_conv_table1[%u] = {", conv_table_len); for(i = 0; i < conv_table_len; i++) { if (i % 4 == 0) fprintf(f, "\n "); te = &conv_table[i]; v = te->code << (32 - 17); v |= te->len << (32 - 17 - 7); v |= te->type << (32 - 17 - 7 - 4); v |= te->data_index >> 8; fprintf(f, " 0x%08x,", v); } fprintf(f, "\n};\n\n"); fprintf(f, "static const uint8_t case_conv_table2[%u] = {", conv_table_len); for(i = 0; i < conv_table_len; i++) { if (i % 8 == 0) fprintf(f, "\n "); te = &conv_table[i]; fprintf(f, " 0x%02x,", te->data_index & 0xff); } fprintf(f, "\n};\n\n"); fprintf(f, "static const uint16_t case_conv_ext[%u] = {", ext_data_len); for(i = 0; i < ext_data_len; i++) { if (i % 8 == 0) fprintf(f, "\n "); fprintf(f, " 0x%04x,", ext_data[i]); } fprintf(f, "\n};\n\n"); } int tabcmp(const int *tab1, const int *tab2, int n) { int i; for(i = 0; i < n; i++) { if (tab1[i] != tab2[i]) return -1; } return 0; } void dump_str(const char *str, const int *buf, int len) { int i; printf("%s=", str); for(i = 0; i < len; i++) printf(" %05x", buf[i]); printf("\n"); } void compute_internal_props(void) { int i; BOOL has_ul; for(i = 0; i <= CHARCODE_MAX; i++) { CCInfo *ci = &unicode_db[i]; has_ul = (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0); if (has_ul) { assert(get_prop(i, PROP_Cased)); } else { set_prop(i, PROP_Cased1, get_prop(i, PROP_Cased)); } set_prop(i, PROP_ID_Continue1, get_prop(i, PROP_ID_Continue) & (get_prop(i, PROP_ID_Start) ^ 1)); set_prop(i, PROP_XID_Start1, get_prop(i, PROP_ID_Start) ^ get_prop(i, PROP_XID_Start)); set_prop(i, PROP_XID_Continue1, get_prop(i, PROP_ID_Continue) ^ get_prop(i, PROP_XID_Continue)); set_prop(i, PROP_Changes_When_Titlecased1, get_prop(i, PROP_Changes_When_Titlecased) ^ (ci->u_len != 0)); set_prop(i, PROP_Changes_When_Casefolded1, get_prop(i, PROP_Changes_When_Casefolded) ^ (ci->f_code != 0)); /* XXX: reduce table size (438 bytes) */ set_prop(i, PROP_Changes_When_NFKC_Casefolded1, get_prop(i, PROP_Changes_When_NFKC_Casefolded) ^ (ci->f_code != 0)); #if 0 /* TEST */ #define M(x) (1U << GCAT_ ## x) { int b; b = ((M(Mn) | M(Cf) | M(Lm) | M(Sk)) >> unicode_db[i].general_category) & 1; set_prop(i, PROP_Cased1, get_prop(i, PROP_Case_Ignorable) ^ b); } #undef M #endif } } void dump_byte_table(FILE *f, const char *cname, const uint8_t *tab, int len) { int i; fprintf(f, "static const uint8_t %s[%d] = {", cname, len); for(i = 0; i < len; i++) { if (i % 8 == 0) fprintf(f, "\n "); fprintf(f, " 0x%02x,", tab[i]); } fprintf(f, "\n};\n\n"); } #define PROP_BLOCK_LEN 32 void build_prop_table(FILE *f, int prop_index, BOOL add_index) { int i, j, n, v, offset, code; DynBuf dbuf_s, *dbuf = &dbuf_s; DynBuf dbuf1_s, *dbuf1 = &dbuf1_s; DynBuf dbuf2_s, *dbuf2 = &dbuf2_s; const uint32_t *buf; int buf_len, block_end_pos, bit; char cname[128]; dbuf_init(dbuf1); for(i = 0; i <= CHARCODE_MAX;) { v = get_prop(i, prop_index); j = i + 1; while (j <= CHARCODE_MAX && get_prop(j, prop_index) == v) { j++; } n = j - i; if (j == (CHARCODE_MAX + 1) && v == 0) break; /* no need to encode last zero run */ //printf("%05x: %d %d\n", i, n, v); dbuf_put_u32(dbuf1, n - 1); i += n; } dbuf_init(dbuf); dbuf_init(dbuf2); buf = (uint32_t *)dbuf1->buf; buf_len = dbuf1->size / sizeof(buf[0]); /* the first value is assumed to be 0 */ assert(get_prop(0, prop_index) == 0); block_end_pos = PROP_BLOCK_LEN; i = 0; code = 0; bit = 0; while (i < buf_len) { if (add_index && dbuf->size >= block_end_pos && bit == 0) { offset = (dbuf->size - block_end_pos); /* XXX: offset could be larger in case of runs of small lengths. Could add code to change the encoding to prevent it at the expense of one byte loss */ assert(offset <= 7); v = code | (offset << 21); dbuf_putc(dbuf2, v); dbuf_putc(dbuf2, v >> 8); dbuf_putc(dbuf2, v >> 16); block_end_pos += PROP_BLOCK_LEN; } v = buf[i]; code += v + 1; bit ^= 1; if (v < 8 && (i + 1) < buf_len && buf[i + 1] < 8) { code += buf[i + 1] + 1; bit ^= 1; dbuf_putc(dbuf, (v << 3) | buf[i + 1]); i += 2; } else if (v < 128) { dbuf_putc(dbuf, 0x80 + v); i++; } else if (v < (1 << 13)) { dbuf_putc(dbuf, 0x40 + (v >> 8)); dbuf_putc(dbuf, v); i++; } else { assert(v < (1 << 21)); dbuf_putc(dbuf, 0x60 + (v >> 16)); dbuf_putc(dbuf, v >> 8); dbuf_putc(dbuf, v); i++; } } if (add_index) { /* last index entry */ v = code; dbuf_putc(dbuf2, v); dbuf_putc(dbuf2, v >> 8); dbuf_putc(dbuf2, v >> 16); } #ifdef DUMP_TABLE_SIZE printf("prop %s: length=%d bytes\n", unicode_prop_name[prop_index], (int)(dbuf->size + dbuf2->size)); #endif snprintf(cname, sizeof(cname), "unicode_prop_%s_table", unicode_prop_name[prop_index]); dump_byte_table(f, cname, dbuf->buf, dbuf->size); if (add_index) { snprintf(cname, sizeof(cname), "unicode_prop_%s_index", unicode_prop_name[prop_index]); dump_byte_table(f, cname, dbuf2->buf, dbuf2->size); } dbuf_free(dbuf); dbuf_free(dbuf1); dbuf_free(dbuf2); } void build_flags_tables(FILE *f) { build_prop_table(f, PROP_Cased1, TRUE); build_prop_table(f, PROP_Case_Ignorable, TRUE); build_prop_table(f, PROP_ID_Start, TRUE); build_prop_table(f, PROP_ID_Continue1, TRUE); } void dump_name_table(FILE *f, const char *cname, const char **tab_name, int len, const char **tab_short_name) { int i, w, maxw; maxw = 0; for(i = 0; i < len; i++) { w = strlen(tab_name[i]); if (tab_short_name[i][0] != '\0') { w += 1 + strlen(tab_short_name[i]); } if (maxw < w) maxw = w; } /* generate a sequence of strings terminated by an empty string */ fprintf(f, "static const char %s[] =\n", cname); for(i = 0; i < len; i++) { fprintf(f, " \""); w = fprintf(f, "%s", tab_name[i]); if (tab_short_name[i][0] != '\0') { w += fprintf(f, ",%s", tab_short_name[i]); } fprintf(f, "\"%*s\"\\0\"\n", 1 + maxw - w, ""); } fprintf(f, ";\n\n"); } void build_general_category_table(FILE *f) { int i, v, j, n, n1; DynBuf dbuf_s, *dbuf = &dbuf_s; int cw_count, cw_len_count[4], cw_start; fprintf(f, "typedef enum {\n"); for(i = 0; i < GCAT_COUNT; i++) fprintf(f, " UNICODE_GC_%s,\n", unicode_gc_name[i]); fprintf(f, " UNICODE_GC_COUNT,\n"); fprintf(f, "} UnicodeGCEnum;\n\n"); dump_name_table(f, "unicode_gc_name_table", unicode_gc_name, GCAT_COUNT, unicode_gc_short_name); dbuf_init(dbuf); cw_count = 0; for(i = 0; i < 4; i++) cw_len_count[i] = 0; for(i = 0; i <= CHARCODE_MAX;) { v = unicode_db[i].general_category; j = i + 1; while (j <= CHARCODE_MAX && unicode_db[j].general_category == v) j++; n = j - i; /* compress Lu/Ll runs */ if (v == GCAT_Lu) { n1 = 1; while ((i + n1) <= CHARCODE_MAX && unicode_db[i + n1].general_category == (v + (n1 & 1))) { n1++; } if (n1 > n) { v = 31; n = n1; } } // printf("%05x %05x %d\n", i, n, v); cw_count++; n--; cw_start = dbuf->size; if (n < 7) { dbuf_putc(dbuf, (n << 5) | v); } else if (n < 7 + 128) { n1 = n - 7; assert(n1 < 128); dbuf_putc(dbuf, (0xf << 5) | v); dbuf_putc(dbuf, n1); } else if (n < 7 + 128 + (1 << 14)) { n1 = n - (7 + 128); assert(n1 < (1 << 14)); dbuf_putc(dbuf, (0xf << 5) | v); dbuf_putc(dbuf, (n1 >> 8) + 128); dbuf_putc(dbuf, n1); } else { n1 = n - (7 + 128 + (1 << 14)); assert(n1 < (1 << 22)); dbuf_putc(dbuf, (0xf << 5) | v); dbuf_putc(dbuf, (n1 >> 16) + 128 + 64); dbuf_putc(dbuf, n1 >> 8); dbuf_putc(dbuf, n1); } cw_len_count[dbuf->size - cw_start - 1]++; i += n + 1; } #ifdef DUMP_TABLE_SIZE printf("general category: %d entries [", cw_count); for(i = 0; i < 4; i++) printf(" %d", cw_len_count[i]); printf(" ], length=%d bytes\n", (int)dbuf->size); #endif dump_byte_table(f, "unicode_gc_table", dbuf->buf, dbuf->size); dbuf_free(dbuf); } void build_script_table(FILE *f) { int i, v, j, n, n1, type; DynBuf dbuf_s, *dbuf = &dbuf_s; int cw_count, cw_len_count[4], cw_start; fprintf(f, "typedef enum {\n"); for(i = 0; i < SCRIPT_COUNT; i++) fprintf(f, " UNICODE_SCRIPT_%s,\n", unicode_script_name[i]); fprintf(f, " UNICODE_SCRIPT_COUNT,\n"); fprintf(f, "} UnicodeScriptEnum;\n\n"); i = 1; dump_name_table(f, "unicode_script_name_table", unicode_script_name + i, SCRIPT_COUNT - i, unicode_script_short_name + i); dbuf_init(dbuf); cw_count = 0; for(i = 0; i < 4; i++) cw_len_count[i] = 0; for(i = 0; i <= CHARCODE_MAX;) { v = unicode_db[i].script; j = i + 1; while (j <= CHARCODE_MAX && unicode_db[j].script == v) j++; n = j - i; if (v == 0 && j == (CHARCODE_MAX + 1)) break; // printf("%05x %05x %d\n", i, n, v); cw_count++; n--; cw_start = dbuf->size; if (v == 0) type = 0; else type = 1; if (n < 96) { dbuf_putc(dbuf, n | (type << 7)); } else if (n < 96 + (1 << 12)) { n1 = n - 96; assert(n1 < (1 << 12)); dbuf_putc(dbuf, ((n1 >> 8) + 96) | (type << 7)); dbuf_putc(dbuf, n1); } else { n1 = n - (96 + (1 << 12)); assert(n1 < (1 << 20)); dbuf_putc(dbuf, ((n1 >> 16) + 112) | (type << 7)); dbuf_putc(dbuf, n1 >> 8); dbuf_putc(dbuf, n1); } if (type != 0) dbuf_putc(dbuf, v); cw_len_count[dbuf->size - cw_start - 1]++; i += n + 1; } #if defined(DUMP_TABLE_SIZE) printf("script: %d entries [", cw_count); for(i = 0; i < 4; i++) printf(" %d", cw_len_count[i]); printf(" ], length=%d bytes\n", (int)dbuf->size); #endif dump_byte_table(f, "unicode_script_table", dbuf->buf, dbuf->size); dbuf_free(dbuf); } void build_script_ext_table(FILE *f) { int i, j, n, n1, script_ext_len; DynBuf dbuf_s, *dbuf = &dbuf_s; int cw_count; dbuf_init(dbuf); cw_count = 0; for(i = 0; i <= CHARCODE_MAX;) { script_ext_len = unicode_db[i].script_ext_len; j = i + 1; while (j <= CHARCODE_MAX && unicode_db[j].script_ext_len == script_ext_len && !memcmp(unicode_db[j].script_ext, unicode_db[i].script_ext, script_ext_len)) { j++; } n = j - i; cw_count++; n--; if (n < 128) { dbuf_putc(dbuf, n); } else if (n < 128 + (1 << 14)) { n1 = n - 128; assert(n1 < (1 << 14)); dbuf_putc(dbuf, (n1 >> 8) + 128); dbuf_putc(dbuf, n1); } else { n1 = n - (128 + (1 << 14)); assert(n1 < (1 << 22)); dbuf_putc(dbuf, (n1 >> 16) + 128 + 64); dbuf_putc(dbuf, n1 >> 8); dbuf_putc(dbuf, n1); } dbuf_putc(dbuf, script_ext_len); for(j = 0; j < script_ext_len; j++) dbuf_putc(dbuf, unicode_db[i].script_ext[j]); i += n + 1; } #ifdef DUMP_TABLE_SIZE printf("script_ext: %d entries", cw_count); printf(", length=%d bytes\n", (int)dbuf->size); #endif dump_byte_table(f, "unicode_script_ext_table", dbuf->buf, dbuf->size); dbuf_free(dbuf); } /* the following properties are synthetized so no table is necessary */ #define PROP_TABLE_COUNT PROP_ASCII void build_prop_list_table(FILE *f) { int i; for(i = 0; i < PROP_TABLE_COUNT; i++) { if (i == PROP_ID_Start || i == PROP_Case_Ignorable || i == PROP_ID_Continue1) { /* already generated */ } else { build_prop_table(f, i, FALSE); } } fprintf(f, "typedef enum {\n"); for(i = 0; i < PROP_COUNT; i++) fprintf(f, " UNICODE_PROP_%s,\n", unicode_prop_name[i]); fprintf(f, " UNICODE_PROP_COUNT,\n"); fprintf(f, "} UnicodePropertyEnum;\n\n"); i = PROP_ASCII_Hex_Digit; dump_name_table(f, "unicode_prop_name_table", unicode_prop_name + i, PROP_XID_Start - i + 1, unicode_prop_short_name + i); fprintf(f, "static const uint8_t * const unicode_prop_table[] = {\n"); for(i = 0; i < PROP_TABLE_COUNT; i++) { fprintf(f, " unicode_prop_%s_table,\n", unicode_prop_name[i]); } fprintf(f, "};\n\n"); fprintf(f, "static const uint16_t unicode_prop_len_table[] = {\n"); for(i = 0; i < PROP_TABLE_COUNT; i++) { fprintf(f, " countof(unicode_prop_%s_table),\n", unicode_prop_name[i]); } fprintf(f, "};\n\n"); } #ifdef USE_TEST int check_conv(uint32_t *res, uint32_t c, int conv_type) { return lre_case_conv(res, c, conv_type); } void check_case_conv(void) { CCInfo *tab = unicode_db; uint32_t res[3]; int l, error; CCInfo ci_s, *ci1, *ci = &ci_s; int code; for(code = 0; code <= CHARCODE_MAX; code++) { ci1 = &tab[code]; *ci = *ci1; if (ci->l_len == 0) { ci->l_len = 1; ci->l_data[0] = code; } if (ci->u_len == 0) { ci->u_len = 1; ci->u_data[0] = code; } if (ci->f_code == 0) ci->f_code = code; error = 0; l = check_conv(res, code, 0); if (l != ci->u_len || tabcmp((int *)res, ci->u_data, l)) { printf("ERROR: L\n"); error++; } l = check_conv(res, code, 1); if (l != ci->l_len || tabcmp((int *)res, ci->l_data, l)) { printf("ERROR: U\n"); error++; } l = check_conv(res, code, 2); if (l != 1 || res[0] != ci->f_code) { printf("ERROR: F\n"); error++; } if (error) { dump_cc_info(ci, code); exit(1); } } } #ifdef PROFILE static int64_t get_time_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; } #endif void check_flags(void) { int c; BOOL flag_ref, flag; for(c = 0; c <= CHARCODE_MAX; c++) { flag_ref = get_prop(c, PROP_Cased); flag = lre_is_cased(c); if (flag != flag_ref) { printf("ERROR: c=%05x cased=%d ref=%d\n", c, flag, flag_ref); exit(1); } flag_ref = get_prop(c, PROP_Case_Ignorable); flag = lre_is_case_ignorable(c); if (flag != flag_ref) { printf("ERROR: c=%05x case_ignorable=%d ref=%d\n", c, flag, flag_ref); exit(1); } flag_ref = get_prop(c, PROP_ID_Start); flag = lre_is_id_start(c); if (flag != flag_ref) { printf("ERROR: c=%05x id_start=%d ref=%d\n", c, flag, flag_ref); exit(1); } flag_ref = get_prop(c, PROP_ID_Continue); flag = lre_is_id_continue(c); if (flag != flag_ref) { printf("ERROR: c=%05x id_cont=%d ref=%d\n", c, flag, flag_ref); exit(1); } } #ifdef PROFILE { int64_t ti, count; ti = get_time_ns(); count = 0; for(c = 0x20; c <= 0xffff; c++) { flag_ref = get_prop(c, PROP_ID_Start); flag = lre_is_id_start(c); assert(flag == flag_ref); count++; } ti = get_time_ns() - ti; printf("flags time=%0.1f ns/char\n", (double)ti / count); } #endif } #endif #define CC_BLOCK_LEN 32 void build_cc_table(FILE *f) { int i, cc, n, cc_table_len, type, n1; DynBuf dbuf_s, *dbuf = &dbuf_s; DynBuf dbuf1_s, *dbuf1 = &dbuf1_s; int cw_len_tab[3], cw_start, block_end_pos; uint32_t v; dbuf_init(dbuf); dbuf_init(dbuf1); cc_table_len = 0; for(i = 0; i < countof(cw_len_tab); i++) cw_len_tab[i] = 0; block_end_pos = CC_BLOCK_LEN; for(i = 0; i <= CHARCODE_MAX;) { cc = unicode_db[i].combining_class; assert(cc <= 255); /* check increasing values */ n = 1; while ((i + n) <= CHARCODE_MAX && unicode_db[i + n].combining_class == (cc + n)) n++; if (n >= 2) { type = 1; } else { type = 0; n = 1; while ((i + n) <= CHARCODE_MAX && unicode_db[i + n].combining_class == cc) n++; } /* no need to encode the last run */ if (cc == 0 && (i + n - 1) == CHARCODE_MAX) break; #ifdef DUMP_CC_TABLE printf("%05x %6d %d %d\n", i, n, type, cc); #endif if (type == 0) { if (cc == 0) type = 2; else if (cc == 230) type = 3; } n1 = n - 1; /* add an entry to the index if necessary */ if (dbuf->size >= block_end_pos) { v = i | ((dbuf->size - block_end_pos) << 21); dbuf_putc(dbuf1, v); dbuf_putc(dbuf1, v >> 8); dbuf_putc(dbuf1, v >> 16); block_end_pos += CC_BLOCK_LEN; } cw_start = dbuf->size; if (n1 < 48) { dbuf_putc(dbuf, n1 | (type << 6)); } else if (n1 < 48 + (1 << 11)) { n1 -= 48; dbuf_putc(dbuf, ((n1 >> 8) + 48) | (type << 6)); dbuf_putc(dbuf, n1); } else { n1 -= 48 + (1 << 11); assert(n1 < (1 << 20)); dbuf_putc(dbuf, ((n1 >> 16) + 56) | (type << 6)); dbuf_putc(dbuf, n1 >> 8); dbuf_putc(dbuf, n1); } cw_len_tab[dbuf->size - cw_start - 1]++; if (type == 0 || type == 1) dbuf_putc(dbuf, cc); cc_table_len++; i += n; } /* last index entry */ v = i; dbuf_putc(dbuf1, v); dbuf_putc(dbuf1, v >> 8); dbuf_putc(dbuf1, v >> 16); dump_byte_table(f, "unicode_cc_table", dbuf->buf, dbuf->size); dump_byte_table(f, "unicode_cc_index", dbuf1->buf, dbuf1->size); #if defined(DUMP_CC_TABLE) || defined(DUMP_TABLE_SIZE) printf("CC table: size=%d (%d entries) [", (int)(dbuf->size + dbuf1->size), cc_table_len); for(i = 0; i < countof(cw_len_tab); i++) printf(" %d", cw_len_tab[i]); printf(" ]\n"); #endif dbuf_free(dbuf); dbuf_free(dbuf1); } /* maximum length of decomposition: 18 chars (1), then 8 */ #ifndef USE_TEST typedef enum { DECOMP_TYPE_C1, /* 16 bit char */ DECOMP_TYPE_L1, /* 16 bit char table */ DECOMP_TYPE_L2, DECOMP_TYPE_L3, DECOMP_TYPE_L4, DECOMP_TYPE_L5, /* XXX: not used */ DECOMP_TYPE_L6, /* XXX: could remove */ DECOMP_TYPE_L7, /* XXX: could remove */ DECOMP_TYPE_LL1, /* 18 bit char table */ DECOMP_TYPE_LL2, DECOMP_TYPE_S1, /* 8 bit char table */ DECOMP_TYPE_S2, DECOMP_TYPE_S3, DECOMP_TYPE_S4, DECOMP_TYPE_S5, DECOMP_TYPE_I1, /* increment 16 bit char value */ DECOMP_TYPE_I2_0, DECOMP_TYPE_I2_1, DECOMP_TYPE_I3_1, DECOMP_TYPE_I3_2, DECOMP_TYPE_I4_1, DECOMP_TYPE_I4_2, DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */ DECOMP_TYPE_B2, DECOMP_TYPE_B3, DECOMP_TYPE_B4, DECOMP_TYPE_B5, DECOMP_TYPE_B6, DECOMP_TYPE_B7, DECOMP_TYPE_B8, DECOMP_TYPE_B18, DECOMP_TYPE_LS2, DECOMP_TYPE_PAT3, DECOMP_TYPE_S2_UL, DECOMP_TYPE_LS2_UL, } DecompTypeEnum; #endif const char *decomp_type_str[] = { "C1", "L1", "L2", "L3", "L4", "L5", "L6", "L7", "LL1", "LL2", "S1", "S2", "S3", "S4", "S5", "I1", "I2_0", "I2_1", "I3_1", "I3_2", "I4_1", "I4_2", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B18", "LS2", "PAT3", "S2_UL", "LS2_UL", }; const int decomp_incr_tab[4][4] = { { DECOMP_TYPE_I1, 0, -1 }, { DECOMP_TYPE_I2_0, 0, 1, -1 }, { DECOMP_TYPE_I3_1, 1, 2, -1 }, { DECOMP_TYPE_I4_1, 1, 2, -1 }, }; /* entry size: type bits code 18 len 7 compat 1 type 5 index 16 total 47 */ typedef struct { int code; uint8_t len; uint8_t type; uint8_t c_len; uint16_t c_min; uint16_t data_index; int cost; /* size in bytes from this entry to the end */ } DecompEntry; int get_decomp_run_size(const DecompEntry *de) { int s; s = 6; if (de->type <= DECOMP_TYPE_C1) { /* nothing more */ } else if (de->type <= DECOMP_TYPE_L7) { s += de->len * de->c_len * 2; } else if (de->type <= DECOMP_TYPE_LL2) { /* 18 bits per char */ s += (de->len * de->c_len * 18 + 7) / 8; } else if (de->type <= DECOMP_TYPE_S5) { s += de->len * de->c_len; } else if (de->type <= DECOMP_TYPE_I4_2) { s += de->c_len * 2; } else if (de->type <= DECOMP_TYPE_B18) { s += 2 + de->len * de->c_len; } else if (de->type <= DECOMP_TYPE_LS2) { s += de->len * 3; } else if (de->type <= DECOMP_TYPE_PAT3) { s += 4 + de->len * 2; } else if (de->type <= DECOMP_TYPE_S2_UL) { s += de->len; } else if (de->type <= DECOMP_TYPE_LS2_UL) { s += (de->len / 2) * 3; } else { abort(); } return s; } static const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 }; /* return -1 if not found */ int get_short_code(int c) { int i; if (c < 0x80) { return c; } else if (c >= 0x300 && c < 0x350) { return c - 0x300 + 0x80; } else { for(i = 0; i < countof(unicode_short_table); i++) { if (c == unicode_short_table[i]) return i + 0x80 + 0x50; } return -1; } } static BOOL is_short(int code) { return get_short_code(code) >= 0; } static BOOL is_short_tab(const int *tab, int len) { int i; for(i = 0; i < len; i++) { if (!is_short(tab[i])) return FALSE; } return TRUE; } static BOOL is_16bit(const int *tab, int len) { int i; for(i = 0; i < len; i++) { if (tab[i] > 0xffff) return FALSE; } return TRUE; } static uint32_t to_lower_simple(uint32_t c) { /* Latin1 and Cyrillic */ if (c < 0x100 || (c >= 0x410 && c <= 0x42f)) c += 0x20; else c++; return c; } /* select best encoding with dynamic programming */ void find_decomp_run(DecompEntry *tab_de, int i) { DecompEntry de_s, *de = &de_s; CCInfo *ci, *ci1, *ci2; int l, j, n, len_max; ci = &unicode_db[i]; l = ci->decomp_len; if (l == 0) { tab_de[i].cost = tab_de[i + 1].cost; return; } /* the offset for the compose table has only 6 bits, so we must limit if it can be used by the compose table */ if (!ci->is_compat && !ci->is_excluded && l == 2) len_max = 64; else len_max = 127; tab_de[i].cost = 0x7fffffff; if (!is_16bit(ci->decomp_data, l)) { assert(l <= 2); n = 1; for(;;) { de->code = i; de->len = n; de->type = DECOMP_TYPE_LL1 + l - 1; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; /* Note: we accept a hole */ if (!(ci1->decomp_len == 0 || (ci1->decomp_len == l && ci1->is_compat == ci->is_compat))) break; n++; } return; } if (l <= 7) { n = 1; for(;;) { de->code = i; de->len = n; if (l == 1 && n == 1) { de->type = DECOMP_TYPE_C1; } else { assert(l <= 8); de->type = DECOMP_TYPE_L1 + l - 1; } de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; /* Note: we accept a hole */ if (!(ci1->decomp_len == 0 || (ci1->decomp_len == l && ci1->is_compat == ci->is_compat && is_16bit(ci1->decomp_data, l)))) break; n++; } } if (l <= 8 || l == 18) { int c_min, c_max, c; c_min = c_max = -1; n = 1; for(;;) { ci1 = &unicode_db[i + n - 1]; for(j = 0; j < l; j++) { c = ci1->decomp_data[j]; if (c == 0x20) { /* we accept space for Arabic */ } else if (c_min == -1) { c_min = c_max = c; } else { c_min = min_int(c_min, c); c_max = max_int(c_max, c); } } if ((c_max - c_min) > 254) break; de->code = i; de->len = n; if (l == 18) de->type = DECOMP_TYPE_B18; else de->type = DECOMP_TYPE_B1 + l - 1; de->c_len = l; de->c_min = c_min; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; if (!(ci1->decomp_len == l && ci1->is_compat == ci->is_compat)) break; n++; } } /* find an ascii run */ if (l <= 5 && is_short_tab(ci->decomp_data, l)) { n = 1; for(;;) { de->code = i; de->len = n; de->type = DECOMP_TYPE_S1 + l - 1; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; /* Note: we accept a hole */ if (!(ci1->decomp_len == 0 || (ci1->decomp_len == l && ci1->is_compat == ci->is_compat && is_short_tab(ci1->decomp_data, l)))) break; n++; } } /* check if a single char is increasing */ if (l <= 4) { int idx1, idx; for(idx1 = 1; (idx = decomp_incr_tab[l - 1][idx1]) >= 0; idx1++) { n = 1; for(;;) { de->code = i; de->len = n; de->type = decomp_incr_tab[l - 1][0] + idx1 - 1; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; if (!(ci1->decomp_len == l && ci1->is_compat == ci->is_compat)) goto next1; for(j = 0; j < l; j++) { if (j == idx) { if (ci1->decomp_data[j] != ci->decomp_data[j] + n) goto next1; } else { if (ci1->decomp_data[j] != ci->decomp_data[j]) goto next1; } } n++; } next1: ; } } if (l == 3) { n = 1; for(;;) { de->code = i; de->len = n; de->type = DECOMP_TYPE_PAT3; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; if (!(ci1->decomp_len == l && ci1->is_compat == ci->is_compat && ci1->decomp_data[1] <= 0xffff && ci1->decomp_data[0] == ci->decomp_data[0] && ci1->decomp_data[l - 1] == ci->decomp_data[l - 1])) break; n++; } } if (l == 2 && is_short(ci->decomp_data[1])) { n = 1; for(;;) { de->code = i; de->len = n; de->type = DECOMP_TYPE_LS2; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } if (!((i + n) <= CHARCODE_MAX && n < len_max)) break; ci1 = &unicode_db[i + n]; if (!(ci1->decomp_len == 0 || (ci1->decomp_len == l && ci1->is_compat == ci->is_compat && ci1->decomp_data[0] <= 0xffff && is_short(ci1->decomp_data[1])))) break; n++; } } if (l == 2) { BOOL is_16bit; n = 0; is_16bit = FALSE; for(;;) { if (!((i + n + 1) <= CHARCODE_MAX && n + 2 <= len_max)) break; ci1 = &unicode_db[i + n]; if (!(ci1->decomp_len == l && ci1->is_compat == ci->is_compat && is_short(ci1->decomp_data[1]))) break; if (!is_16bit && !is_short(ci1->decomp_data[0])) is_16bit = TRUE; ci2 = &unicode_db[i + n + 1]; if (!(ci2->decomp_len == l && ci2->is_compat == ci->is_compat && ci2->decomp_data[0] == to_lower_simple(ci1->decomp_data[0]) && ci2->decomp_data[1] == ci1->decomp_data[1])) break; n += 2; de->code = i; de->len = n; de->type = DECOMP_TYPE_S2_UL + is_16bit; de->c_len = l; de->cost = get_decomp_run_size(de) + tab_de[i + n].cost; if (de->cost < tab_de[i].cost) { tab_de[i] = *de; } } } } void put16(uint8_t *data_buf, int *pidx, uint16_t c) { int idx; idx = *pidx; data_buf[idx++] = c; data_buf[idx++] = c >> 8; *pidx = idx; } void add_decomp_data(uint8_t *data_buf, int *pidx, DecompEntry *de) { int i, j, idx, c; CCInfo *ci; idx = *pidx; de->data_index = idx; if (de->type <= DECOMP_TYPE_C1) { ci = &unicode_db[de->code]; assert(ci->decomp_len == 1); de->data_index = ci->decomp_data[0]; } else if (de->type <= DECOMP_TYPE_L7) { for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; for(j = 0; j < de->c_len; j++) { if (ci->decomp_len == 0) c = 0; else c = ci->decomp_data[j]; put16(data_buf, &idx, c); } } } else if (de->type <= DECOMP_TYPE_LL2) { int n, p, k; n = (de->len * de->c_len * 18 + 7) / 8; p = de->len * de->c_len * 2; memset(data_buf + idx, 0, n); k = 0; for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; for(j = 0; j < de->c_len; j++) { if (ci->decomp_len == 0) c = 0; else c = ci->decomp_data[j]; data_buf[idx + k * 2] = c; data_buf[idx + k * 2 + 1] = c >> 8; data_buf[idx + p + (k / 4)] |= (c >> 16) << ((k % 4) * 2); k++; } } idx += n; } else if (de->type <= DECOMP_TYPE_S5) { for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; for(j = 0; j < de->c_len; j++) { if (ci->decomp_len == 0) c = 0; else c = ci->decomp_data[j]; c = get_short_code(c); assert(c >= 0); data_buf[idx++] = c; } } } else if (de->type <= DECOMP_TYPE_I4_2) { ci = &unicode_db[de->code]; assert(ci->decomp_len == de->c_len); for(j = 0; j < de->c_len; j++) put16(data_buf, &idx, ci->decomp_data[j]); } else if (de->type <= DECOMP_TYPE_B18) { c = de->c_min; data_buf[idx++] = c; data_buf[idx++] = c >> 8; for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; for(j = 0; j < de->c_len; j++) { assert(ci->decomp_len == de->c_len); c = ci->decomp_data[j]; if (c == 0x20) { c = 0xff; } else { c -= de->c_min; assert((uint32_t)c <= 254); } data_buf[idx++] = c; } } } else if (de->type <= DECOMP_TYPE_LS2) { assert(de->c_len == 2); for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; if (ci->decomp_len == 0) c = 0; else c = ci->decomp_data[0]; put16(data_buf, &idx, c); if (ci->decomp_len == 0) c = 0; else c = ci->decomp_data[1]; c = get_short_code(c); assert(c >= 0); data_buf[idx++] = c; } } else if (de->type <= DECOMP_TYPE_PAT3) { ci = &unicode_db[de->code]; assert(ci->decomp_len == 3); put16(data_buf, &idx, ci->decomp_data[0]); put16(data_buf, &idx, ci->decomp_data[2]); for(i = 0; i < de->len; i++) { ci = &unicode_db[de->code + i]; assert(ci->decomp_len == 3); put16(data_buf, &idx, ci->decomp_data[1]); } } else if (de->type <= DECOMP_TYPE_S2_UL) { for(i = 0; i < de->len; i += 2) { ci = &unicode_db[de->code + i]; c = ci->decomp_data[0]; c = get_short_code(c); assert(c >= 0); data_buf[idx++] = c; c = ci->decomp_data[1]; c = get_short_code(c); assert(c >= 0); data_buf[idx++] = c; } } else if (de->type <= DECOMP_TYPE_LS2_UL) { for(i = 0; i < de->len; i += 2) { ci = &unicode_db[de->code + i]; c = ci->decomp_data[0]; put16(data_buf, &idx, c); c = ci->decomp_data[1]; c = get_short_code(c); assert(c >= 0); data_buf[idx++] = c; } } else { abort(); } *pidx = idx; } #if 0 void dump_large_char(void) { int i, j; for(i = 0; i <= CHARCODE_MAX; i++) { CCInfo *ci = &unicode_db[i]; for(j = 0; j < ci->decomp_len; j++) { if (ci->decomp_data[j] > 0xffff) printf("%05x\n", ci->decomp_data[j]); } } } #endif void build_compose_table(FILE *f, const DecompEntry *tab_de); void build_decompose_table(FILE *f) { int i, array_len, code_max, data_len, count; DecompEntry *tab_de, de_s, *de = &de_s; uint8_t *data_buf; code_max = CHARCODE_MAX; tab_de = mallocz((code_max + 2) * sizeof(*tab_de)); for(i = code_max; i >= 0; i--) { find_decomp_run(tab_de, i); } /* build the data buffer */ data_buf = malloc(100000); data_len = 0; array_len = 0; for(i = 0; i <= code_max; i++) { de = &tab_de[i]; if (de->len != 0) { add_decomp_data(data_buf, &data_len, de); i += de->len - 1; array_len++; } } #ifdef DUMP_DECOMP_TABLE /* dump */ { int size, size1; printf("START LEN TYPE L C SIZE\n"); size = 0; for(i = 0; i <= code_max; i++) { de = &tab_de[i]; if (de->len != 0) { size1 = get_decomp_run_size(de); printf("%05x %3d %6s %2d %1d %4d\n", i, de->len, decomp_type_str[de->type], de->c_len, unicode_db[i].is_compat, size1); i += de->len - 1; size += size1; } } printf("array_len=%d estimated size=%d bytes actual=%d bytes\n", array_len, size, array_len * 6 + data_len); } #endif fprintf(f, "static const uint32_t unicode_decomp_table1[%u] = {", array_len); count = 0; for(i = 0; i <= code_max; i++) { de = &tab_de[i]; if (de->len != 0) { uint32_t v; if (count++ % 4 == 0) fprintf(f, "\n "); v = (de->code << (32 - 18)) | (de->len << (32 - 18 - 7)) | (de->type << (32 - 18 - 7 - 6)) | unicode_db[de->code].is_compat; fprintf(f, " 0x%08x,", v); i += de->len - 1; } } fprintf(f, "\n};\n\n"); fprintf(f, "static const uint16_t unicode_decomp_table2[%u] = {", array_len); count = 0; for(i = 0; i <= code_max; i++) { de = &tab_de[i]; if (de->len != 0) { if (count++ % 8 == 0) fprintf(f, "\n "); fprintf(f, " 0x%04x,", de->data_index); i += de->len - 1; } } fprintf(f, "\n};\n\n"); fprintf(f, "static const uint8_t unicode_decomp_data[%u] = {", data_len); for(i = 0; i < data_len; i++) { if (i % 8 == 0) fprintf(f, "\n "); fprintf(f, " 0x%02x,", data_buf[i]); } fprintf(f, "\n};\n\n"); build_compose_table(f, tab_de); free(data_buf); free(tab_de); } typedef struct { uint32_t c[2]; uint32_t p; } ComposeEntry; #define COMPOSE_LEN_MAX 10000 static int ce_cmp(const void *p1, const void *p2) { const ComposeEntry *ce1 = p1; const ComposeEntry *ce2 = p2; int i; for(i = 0; i < 2; i++) { if (ce1->c[i] < ce2->c[i]) return -1; else if (ce1->c[i] > ce2->c[i]) return 1; } return 0; } static int get_decomp_pos(const DecompEntry *tab_de, int c) { int i, v, k; const DecompEntry *de; k = 0; for(i = 0; i <= CHARCODE_MAX; i++) { de = &tab_de[i]; if (de->len != 0) { if (c >= de->code && c < de->code + de->len) { v = c - de->code; assert(v < 64); v |= k << 6; assert(v < 65536); return v; } i += de->len - 1; k++; } } return -1; } void build_compose_table(FILE *f, const DecompEntry *tab_de) { int i, v, tab_ce_len; ComposeEntry *ce, *tab_ce; tab_ce = malloc(sizeof(*tab_ce) * COMPOSE_LEN_MAX); tab_ce_len = 0; for(i = 0; i <= CHARCODE_MAX; i++) { CCInfo *ci = &unicode_db[i]; if (ci->decomp_len == 2 && !ci->is_compat && !ci->is_excluded) { assert(tab_ce_len < COMPOSE_LEN_MAX); ce = &tab_ce[tab_ce_len++]; ce->c[0] = ci->decomp_data[0]; ce->c[1] = ci->decomp_data[1]; ce->p = i; } } qsort(tab_ce, tab_ce_len, sizeof(*tab_ce), ce_cmp); #if 0 { printf("tab_ce_len=%d\n", tab_ce_len); for(i = 0; i < tab_ce_len; i++) { ce = &tab_ce[i]; printf("%05x %05x %05x\n", ce->c[0], ce->c[1], ce->p); } } #endif fprintf(f, "static const uint16_t unicode_comp_table[%u] = {", tab_ce_len); for(i = 0; i < tab_ce_len; i++) { if (i % 8 == 0) fprintf(f, "\n "); v = get_decomp_pos(tab_de, tab_ce[i].p); if (v < 0) { printf("ERROR: entry for c=%04x not found\n", tab_ce[i].p); exit(1); } fprintf(f, " 0x%04x,", v); } fprintf(f, "\n};\n\n"); free(tab_ce); } #ifdef USE_TEST void check_decompose_table(void) { int c; CCInfo *ci; int res[UNICODE_DECOMP_LEN_MAX], *ref; int len, ref_len, is_compat; for(is_compat = 0; is_compat <= 1; is_compat++) { for(c = 0; c < CHARCODE_MAX; c++) { ci = &unicode_db[c]; ref_len = ci->decomp_len; ref = ci->decomp_data; if (!is_compat && ci->is_compat) { ref_len = 0; } len = unicode_decomp_char((uint32_t *)res, c, is_compat); if (len != ref_len || tabcmp(res, ref, ref_len) != 0) { printf("ERROR c=%05x compat=%d\n", c, is_compat); dump_str("res", res, len); dump_str("ref", ref, ref_len); exit(1); } } } } void check_compose_table(void) { int i, p; /* XXX: we don't test all the cases */ for(i = 0; i <= CHARCODE_MAX; i++) { CCInfo *ci = &unicode_db[i]; if (ci->decomp_len == 2 && !ci->is_compat && !ci->is_excluded) { p = unicode_compose_pair(ci->decomp_data[0], ci->decomp_data[1]); if (p != i) { printf("ERROR compose: c=%05x %05x -> %05x ref=%05x\n", ci->decomp_data[0], ci->decomp_data[1], p, i); exit(1); } } } } #endif #ifdef USE_TEST void check_str(const char *msg, int num, const int *in_buf, int in_len, const int *buf1, int len1, const int *buf2, int len2) { if (len1 != len2 || tabcmp(buf1, buf2, len1) != 0) { printf("%d: ERROR %s:\n", num, msg); dump_str(" in", in_buf, in_len); dump_str("res", buf1, len1); dump_str("ref", buf2, len2); exit(1); } } void check_cc_table(void) { int cc, cc_ref, c; for(c = 0; c <= CHARCODE_MAX; c++) { cc_ref = unicode_db[c].combining_class; cc = unicode_get_cc(c); if (cc != cc_ref) { printf("ERROR: c=%04x cc=%d cc_ref=%d\n", c, cc, cc_ref); exit(1); } } #ifdef PROFILE { int64_t ti, count; ti = get_time_ns(); count = 0; /* only do it on meaningful chars */ for(c = 0x20; c <= 0xffff; c++) { cc_ref = unicode_db[c].combining_class; cc = unicode_get_cc(c); count++; } ti = get_time_ns() - ti; printf("cc time=%0.1f ns/char\n", (double)ti / count); } #endif } void normalization_test(const char *filename) { FILE *f; char line[4096], *p; int *in_str, *nfc_str, *nfd_str, *nfkc_str, *nfkd_str; int in_len, nfc_len, nfd_len, nfkc_len, nfkd_len; int *buf, buf_len, pos; f = fopen(filename, "rb"); if (!f) { perror(filename); exit(1); } pos = 0; for(;;) { if (!get_line(line, sizeof(line), f)) break; pos++; p = line; while (isspace(*p)) p++; if (*p == '#' || *p == '@') continue; in_str = get_field_str(&in_len, p, 0); nfc_str = get_field_str(&nfc_len, p, 1); nfd_str = get_field_str(&nfd_len, p, 2); nfkc_str = get_field_str(&nfkc_len, p, 3); nfkd_str = get_field_str(&nfkd_len, p, 4); // dump_str("in", in_str, in_len); buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFD, NULL, NULL); check_str("nfd", pos, in_str, in_len, buf, buf_len, nfd_str, nfd_len); free(buf); buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKD, NULL, NULL); check_str("nfkd", pos, in_str, in_len, buf, buf_len, nfkd_str, nfkd_len); free(buf); buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFC, NULL, NULL); check_str("nfc", pos, in_str, in_len, buf, buf_len, nfc_str, nfc_len); free(buf); buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKC, NULL, NULL); check_str("nfkc", pos, in_str, in_len, buf, buf_len, nfkc_str, nfkc_len); free(buf); free(in_str); free(nfc_str); free(nfd_str); free(nfkc_str); free(nfkd_str); } fclose(f); } #endif int main(int argc, char **argv) { const char *unicode_db_path, *outfilename; char filename[1024]; if (argc < 2) { printf("usage: %s unicode_db_path [output_file]\n" "\n" "If no output_file is given, a self test is done using the current unicode library\n", argv[0]); exit(1); } unicode_db_path = argv[1]; outfilename = NULL; if (argc >= 3) outfilename = argv[2]; unicode_db = mallocz(sizeof(unicode_db[0]) * (CHARCODE_MAX + 1)); snprintf(filename, sizeof(filename), "%s/UnicodeData.txt", unicode_db_path); parse_unicode_data(filename); snprintf(filename, sizeof(filename), "%s/SpecialCasing.txt", unicode_db_path); parse_special_casing(unicode_db, filename); snprintf(filename, sizeof(filename), "%s/CaseFolding.txt", unicode_db_path); parse_case_folding(unicode_db, filename); snprintf(filename, sizeof(filename), "%s/CompositionExclusions.txt", unicode_db_path); parse_composition_exclusions(filename); snprintf(filename, sizeof(filename), "%s/DerivedCoreProperties.txt", unicode_db_path); parse_derived_core_properties(filename); snprintf(filename, sizeof(filename), "%s/DerivedNormalizationProps.txt", unicode_db_path); parse_derived_norm_properties(filename); snprintf(filename, sizeof(filename), "%s/PropList.txt", unicode_db_path); parse_prop_list(filename); snprintf(filename, sizeof(filename), "%s/Scripts.txt", unicode_db_path); parse_scripts(filename); snprintf(filename, sizeof(filename), "%s/ScriptExtensions.txt", unicode_db_path); parse_script_extensions(filename); snprintf(filename, sizeof(filename), "%s/emoji-data.txt", unicode_db_path); parse_prop_list(filename); // dump_data(unicode_db); build_conv_table(unicode_db); // dump_table(); if (!outfilename) { #ifdef USE_TEST check_case_conv(); check_flags(); check_decompose_table(); check_compose_table(); check_cc_table(); snprintf(filename, sizeof(filename), "%s/NormalizationTest.txt", unicode_db_path); normalization_test(filename); #else fprintf(stderr, "Tests are not compiled\n"); exit(1); #endif } else { FILE *fo = fopen(outfilename, "wb"); if (!fo) { perror(outfilename); exit(1); } fprintf(fo, "/* Compressed unicode tables */\n" "/* Automatically generated file - do not edit */\n" "\n" "#include <stdint.h>\n" "\n"); dump_case_conv_table(fo); compute_internal_props(); build_flags_tables(fo); fprintf(fo, "#ifdef CONFIG_ALL_UNICODE\n\n"); build_cc_table(fo); build_decompose_table(fo); build_general_category_table(fo); build_script_table(fo); build_script_ext_table(fo); build_prop_list_table(fo); fprintf(fo, "#endif /* CONFIG_ALL_UNICODE */\n"); fclose(fo); } return 0; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/unicode_gen.c
C
apache-2.0
83,240
#ifdef UNICODE_GENERAL_CATEGORY DEF(Cn, "Unassigned") /* must be zero */ DEF(Lu, "Uppercase_Letter") DEF(Ll, "Lowercase_Letter") DEF(Lt, "Titlecase_Letter") DEF(Lm, "Modifier_Letter") DEF(Lo, "Other_Letter") DEF(Mn, "Nonspacing_Mark") DEF(Mc, "Spacing_Mark") DEF(Me, "Enclosing_Mark") DEF(Nd, "Decimal_Number,digit") DEF(Nl, "Letter_Number") DEF(No, "Other_Number") DEF(Sm, "Math_Symbol") DEF(Sc, "Currency_Symbol") DEF(Sk, "Modifier_Symbol") DEF(So, "Other_Symbol") DEF(Pc, "Connector_Punctuation") DEF(Pd, "Dash_Punctuation") DEF(Ps, "Open_Punctuation") DEF(Pe, "Close_Punctuation") DEF(Pi, "Initial_Punctuation") DEF(Pf, "Final_Punctuation") DEF(Po, "Other_Punctuation") DEF(Zs, "Space_Separator") DEF(Zl, "Line_Separator") DEF(Zp, "Paragraph_Separator") DEF(Cc, "Control,cntrl") DEF(Cf, "Format") DEF(Cs, "Surrogate") DEF(Co, "Private_Use") /* synthetic properties */ DEF(LC, "Cased_Letter") DEF(L, "Letter") DEF(M, "Mark,Combining_Mark") DEF(N, "Number") DEF(S, "Symbol") DEF(P, "Punctuation,punct") DEF(Z, "Separator") DEF(C, "Other") #endif #ifdef UNICODE_SCRIPT /* scripts aliases names in PropertyValueAliases.txt */ DEF(Unknown, "Zzzz") DEF(Adlam, "Adlm") DEF(Ahom, "Ahom") DEF(Anatolian_Hieroglyphs, "Hluw") DEF(Arabic, "Arab") DEF(Armenian, "Armn") DEF(Avestan, "Avst") DEF(Balinese, "Bali") DEF(Bamum, "Bamu") DEF(Bassa_Vah, "Bass") DEF(Batak, "Batk") DEF(Bengali, "Beng") DEF(Bhaiksuki, "Bhks") DEF(Bopomofo, "Bopo") DEF(Brahmi, "Brah") DEF(Braille, "Brai") DEF(Buginese, "Bugi") DEF(Buhid, "Buhd") DEF(Canadian_Aboriginal, "Cans") DEF(Carian, "Cari") DEF(Caucasian_Albanian, "Aghb") DEF(Chakma, "Cakm") DEF(Cham, "Cham") DEF(Cherokee, "Cher") DEF(Chorasmian, "Chrs") DEF(Common, "Zyyy") DEF(Coptic, "Copt,Qaac") DEF(Cuneiform, "Xsux") DEF(Cypriot, "Cprt") DEF(Cyrillic, "Cyrl") DEF(Deseret, "Dsrt") DEF(Devanagari, "Deva") DEF(Dives_Akuru, "Diak") DEF(Dogra, "Dogr") DEF(Duployan, "Dupl") DEF(Egyptian_Hieroglyphs, "Egyp") DEF(Elbasan, "Elba") DEF(Elymaic, "Elym") DEF(Ethiopic, "Ethi") DEF(Georgian, "Geor") DEF(Glagolitic, "Glag") DEF(Gothic, "Goth") DEF(Grantha, "Gran") DEF(Greek, "Grek") DEF(Gujarati, "Gujr") DEF(Gunjala_Gondi, "Gong") DEF(Gurmukhi, "Guru") DEF(Han, "Hani") DEF(Hangul, "Hang") DEF(Hanifi_Rohingya, "Rohg") DEF(Hanunoo, "Hano") DEF(Hatran, "Hatr") DEF(Hebrew, "Hebr") DEF(Hiragana, "Hira") DEF(Imperial_Aramaic, "Armi") DEF(Inherited, "Zinh,Qaai") DEF(Inscriptional_Pahlavi, "Phli") DEF(Inscriptional_Parthian, "Prti") DEF(Javanese, "Java") DEF(Kaithi, "Kthi") DEF(Kannada, "Knda") DEF(Katakana, "Kana") DEF(Kayah_Li, "Kali") DEF(Kharoshthi, "Khar") DEF(Khmer, "Khmr") DEF(Khojki, "Khoj") DEF(Khitan_Small_Script, "Kits") DEF(Khudawadi, "Sind") DEF(Lao, "Laoo") DEF(Latin, "Latn") DEF(Lepcha, "Lepc") DEF(Limbu, "Limb") DEF(Linear_A, "Lina") DEF(Linear_B, "Linb") DEF(Lisu, "Lisu") DEF(Lycian, "Lyci") DEF(Lydian, "Lydi") DEF(Makasar, "Maka") DEF(Mahajani, "Mahj") DEF(Malayalam, "Mlym") DEF(Mandaic, "Mand") DEF(Manichaean, "Mani") DEF(Marchen, "Marc") DEF(Masaram_Gondi, "Gonm") DEF(Medefaidrin, "Medf") DEF(Meetei_Mayek, "Mtei") DEF(Mende_Kikakui, "Mend") DEF(Meroitic_Cursive, "Merc") DEF(Meroitic_Hieroglyphs, "Mero") DEF(Miao, "Plrd") DEF(Modi, "Modi") DEF(Mongolian, "Mong") DEF(Mro, "Mroo") DEF(Multani, "Mult") DEF(Myanmar, "Mymr") DEF(Nabataean, "Nbat") DEF(Nandinagari, "Nand") DEF(New_Tai_Lue, "Talu") DEF(Newa, "Newa") DEF(Nko, "Nkoo") DEF(Nushu, "Nshu") DEF(Nyiakeng_Puachue_Hmong, "Hmnp") DEF(Ogham, "Ogam") DEF(Ol_Chiki, "Olck") DEF(Old_Hungarian, "Hung") DEF(Old_Italic, "Ital") DEF(Old_North_Arabian, "Narb") DEF(Old_Permic, "Perm") DEF(Old_Persian, "Xpeo") DEF(Old_Sogdian, "Sogo") DEF(Old_South_Arabian, "Sarb") DEF(Old_Turkic, "Orkh") DEF(Oriya, "Orya") DEF(Osage, "Osge") DEF(Osmanya, "Osma") DEF(Pahawh_Hmong, "Hmng") DEF(Palmyrene, "Palm") DEF(Pau_Cin_Hau, "Pauc") DEF(Phags_Pa, "Phag") DEF(Phoenician, "Phnx") DEF(Psalter_Pahlavi, "Phlp") DEF(Rejang, "Rjng") DEF(Runic, "Runr") DEF(Samaritan, "Samr") DEF(Saurashtra, "Saur") DEF(Sharada, "Shrd") DEF(Shavian, "Shaw") DEF(Siddham, "Sidd") DEF(SignWriting, "Sgnw") DEF(Sinhala, "Sinh") DEF(Sogdian, "Sogd") DEF(Sora_Sompeng, "Sora") DEF(Soyombo, "Soyo") DEF(Sundanese, "Sund") DEF(Syloti_Nagri, "Sylo") DEF(Syriac, "Syrc") DEF(Tagalog, "Tglg") DEF(Tagbanwa, "Tagb") DEF(Tai_Le, "Tale") DEF(Tai_Tham, "Lana") DEF(Tai_Viet, "Tavt") DEF(Takri, "Takr") DEF(Tamil, "Taml") DEF(Tangut, "Tang") DEF(Telugu, "Telu") DEF(Thaana, "Thaa") DEF(Thai, "Thai") DEF(Tibetan, "Tibt") DEF(Tifinagh, "Tfng") DEF(Tirhuta, "Tirh") DEF(Ugaritic, "Ugar") DEF(Vai, "Vaii") DEF(Wancho, "Wcho") DEF(Warang_Citi, "Wara") DEF(Yezidi, "Yezi") DEF(Yi, "Yiii") DEF(Zanabazar_Square, "Zanb") #endif #ifdef UNICODE_PROP_LIST /* Prop list not exported to regexp */ DEF(Hyphen, "") DEF(Other_Math, "") DEF(Other_Alphabetic, "") DEF(Other_Lowercase, "") DEF(Other_Uppercase, "") DEF(Other_Grapheme_Extend, "") DEF(Other_Default_Ignorable_Code_Point, "") DEF(Other_ID_Start, "") DEF(Other_ID_Continue, "") DEF(Prepended_Concatenation_Mark, "") /* additional computed properties for smaller tables */ DEF(ID_Continue1, "") DEF(XID_Start1, "") DEF(XID_Continue1, "") DEF(Changes_When_Titlecased1, "") DEF(Changes_When_Casefolded1, "") DEF(Changes_When_NFKC_Casefolded1, "") /* Prop list exported to JS */ DEF(ASCII_Hex_Digit, "AHex") DEF(Bidi_Control, "Bidi_C") DEF(Dash, "") DEF(Deprecated, "Dep") DEF(Diacritic, "Dia") DEF(Extender, "Ext") DEF(Hex_Digit, "Hex") DEF(IDS_Binary_Operator, "IDSB") DEF(IDS_Trinary_Operator, "IDST") DEF(Ideographic, "Ideo") DEF(Join_Control, "Join_C") DEF(Logical_Order_Exception, "LOE") DEF(Noncharacter_Code_Point, "NChar") DEF(Pattern_Syntax, "Pat_Syn") DEF(Pattern_White_Space, "Pat_WS") DEF(Quotation_Mark, "QMark") DEF(Radical, "") DEF(Regional_Indicator, "RI") DEF(Sentence_Terminal, "STerm") DEF(Soft_Dotted, "SD") DEF(Terminal_Punctuation, "Term") DEF(Unified_Ideograph, "UIdeo") DEF(Variation_Selector, "VS") DEF(White_Space, "space") DEF(Bidi_Mirrored, "Bidi_M") DEF(Emoji, "") DEF(Emoji_Component, "EComp") DEF(Emoji_Modifier, "EMod") DEF(Emoji_Modifier_Base, "EBase") DEF(Emoji_Presentation, "EPres") DEF(Extended_Pictographic, "ExtPict") DEF(Default_Ignorable_Code_Point, "DI") DEF(ID_Start, "IDS") DEF(Case_Ignorable, "CI") /* other binary properties */ DEF(ASCII,"") DEF(Alphabetic, "Alpha") DEF(Any, "") DEF(Assigned,"") DEF(Cased, "") DEF(Changes_When_Casefolded, "CWCF") DEF(Changes_When_Casemapped, "CWCM") DEF(Changes_When_Lowercased, "CWL") DEF(Changes_When_NFKC_Casefolded, "CWKCF") DEF(Changes_When_Titlecased, "CWT") DEF(Changes_When_Uppercased, "CWU") DEF(Grapheme_Base, "Gr_Base") DEF(Grapheme_Extend, "Gr_Ext") DEF(ID_Continue, "IDC") DEF(Lowercase, "Lower") DEF(Math, "") DEF(Uppercase, "Upper") DEF(XID_Continue, "XIDC") DEF(XID_Start, "XIDS") /* internal tables with index */ DEF(Cased1, "") #endif
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/quickjs/unicode_gen_def.h
C
apache-2.0
6,840
#include "amp_config.h" #include "aos/list.h" #include "aos_system.h" #include "quickjs-libc.h" #include "quickjs.h" #include "quickjs_addon.h" #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #define MOD_STR "QUICKJS_INIT" static JSRuntime *rt = NULL; static JSContext *ctx = NULL; static JSValue val; extern int g_repl_config; extern JSModuleDef *quickjs_module_loader(JSContext *ctx, const char *module_name, void *opaque); JSContext *js_get_context(void) { return ctx; } static void jsengine_register_addons() { module_builtin_register(); #if 1 extern uint32_t jslib_events_size; extern uint8_t jslib_events[]; quickjs_add_prebuild_module("events", jslib_events, jslib_events_size); #endif #ifdef JSE_HW_ADDON_GPIO module_gpio_register(); extern uint32_t jslib_gpio_size; extern uint8_t jslib_gpio[]; quickjs_add_prebuild_module("gpio", jslib_gpio, jslib_gpio_size); #endif #ifdef JSE_HW_ADDON_IR module_ir_register(); #endif #ifdef JSE_HW_ADDON_PWM module_pwm_register(); extern uint32_t jslib_pwm_size; extern uint8_t jslib_pwm[]; quickjs_add_prebuild_module("pwm", jslib_pwm, jslib_pwm_size); #endif #ifdef JSE_HW_ADDON_ONEWIRE module_onewire_register(); extern uint32_t jslib_onewire_size; extern uint8_t jslib_onewire[]; quickjs_add_prebuild_module("onewire", jslib_onewire, jslib_onewire_size); #endif #ifdef JSE_HW_ADDON_RTC module_rtc_register(); extern uint32_t jslib_rtc_size; extern uint8_t jslib_rtc[]; quickjs_add_prebuild_module("rtc", jslib_rtc, jslib_rtc_size); #endif #ifdef JSE_CORE_ADDON_CRYPTO module_crypto_register(); extern uint32_t jslib_crypto_size; extern uint8_t jslib_crypto[]; quickjs_add_prebuild_module("crypto", jslib_crypto, jslib_crypto_size); #endif #ifdef JSE_HW_ADDON_WDG module_wdg_register(); extern uint32_t jslib_wdg_size; extern uint8_t jslib_wdg[]; quickjs_add_prebuild_module("wdg", jslib_wdg, jslib_wdg_size); #endif #ifdef JSE_HW_ADDON_UART module_uart_register(); extern uint32_t jslib_uart_size; extern uint8_t jslib_uart[]; quickjs_add_prebuild_module("uart", jslib_uart, jslib_uart_size); #endif #ifdef JSE_HW_ADDON_SPI module_spi_register(); extern uint32_t jslib_spi_size; extern uint8_t jslib_spi[]; quickjs_add_prebuild_module("spi", jslib_spi, jslib_spi_size); #endif #ifdef JSE_HW_ADDON_ADC module_adc_register(); extern uint32_t jslib_adc_size; extern uint8_t jslib_adc[]; quickjs_add_prebuild_module("adc", jslib_adc, jslib_adc_size); #endif #ifdef JSE_HW_ADDON_TIMER module_timer_register(); #endif #ifdef JSE_HW_ADDON_DAC module_dac_register(); extern uint32_t jslib_dac_size; extern uint8_t jslib_dac[]; quickjs_add_prebuild_module("dac", jslib_dac, jslib_dac_size); #endif #ifdef JSE_HW_ADDON_DS18B20 extern uint32_t jslib_ds18b20_size; extern uint8_t jslib_ds18b20[]; quickjs_add_prebuild_module("ds18b20", jslib_ds18b20, jslib_ds18b20_size); #endif #ifdef JSE_CORE_ADDON_SYSTIMER module_systimer_register(); #endif #ifdef JSE_NET_ADDON_TCP module_tcp_register(); extern uint32_t jslib_tcp_size; extern uint8_t jslib_tcp[]; quickjs_add_prebuild_module("tcp", jslib_tcp, jslib_tcp_size); #endif #ifdef JSE_NET_ADDON_UDP module_udp_register(); extern uint32_t jslib_udp_size; extern uint8_t jslib_udp[]; quickjs_add_prebuild_module("udp", jslib_udp, jslib_udp_size); #endif #ifdef JSE_NET_ADDON_HTTP module_http_register(); #endif #ifdef JSE_NET_ADDON_MQTT module_mqtt_register(); extern uint32_t jslib_mqtt_size; extern uint8_t jslib_mqtt[]; quickjs_add_prebuild_module("mqtt", jslib_mqtt, jslib_mqtt_size); #endif #ifdef JSE_NET_ADDON_NETMGR module_netmgr_register(); extern uint32_t jslib_netmgr_size; extern uint8_t jslib_netmgr[]; quickjs_add_prebuild_module("netmgr", jslib_netmgr, jslib_netmgr_size); #endif #ifdef JSE_CORE_ADDON_SYSTEM module_system_register(); #endif #ifdef JSE_ADVANCED_ADDON_OTA module_app_ota_register(); extern uint32_t jslib_appota_size; extern uint8_t jslib_appota[]; quickjs_add_prebuild_module("appota", jslib_appota, jslib_appota_size); #endif #ifdef JSE_ADVANCED_ADDON_UI page_entry_register(); app_entry_register(); // module_vm_register(); module_ui_register(); #endif #ifdef JSE_HW_ADDON_LCD module_lcd_register(); #endif #ifdef JSE_HW_ADDON_I2C module_i2c_register(); extern uint32_t jslib_i2c_size; extern uint8_t jslib_i2c[]; quickjs_add_prebuild_module("i2c", jslib_i2c, jslib_i2c_size); #endif #ifdef JSE_ADVANCED_ADDON_AIOT_DEVICE module_aiot_device_register(); module_aiot_gateway_register(); extern uint32_t jslib_iot_size; extern uint8_t jslib_iot[]; quickjs_add_prebuild_module("iot", jslib_iot, jslib_iot_size); #endif #ifdef JSE_CORE_ADDON_LOG module_log_register(); #endif #ifdef JSE_WIRELESS_ADDON_BT_HOST module_bt_host_register(); extern uint32_t jslib_bt_host_size; extern uint8_t jslib_bt_host[]; quickjs_add_prebuild_module("bt_host", jslib_bt_host, jslib_bt_host_size); #endif #ifdef JSE_CORE_ADDON_FS module_fs_register(); extern uint32_t jslib_fs_size; extern uint8_t jslib_fs[]; quickjs_add_prebuild_module("fs", jslib_fs, jslib_fs_size); #endif #ifdef JSE_CORE_ADDON_KV module_kv_register(); #endif #ifdef JSE_ADVANCED_ADDON_AUDIOPLAYER module_audioplayer_register(); extern uint32_t jslib_audioplayer_size; extern uint8_t jslib_audioplayer[]; quickjs_add_prebuild_module("audioplayer", jslib_audioplayer, jslib_audioplayer_size); #endif #ifdef JSE_ADVANCED_ADDON_BLECFGNET module_blecfgnet_register(); #endif #ifdef JSE_NET_ADDON_CELLULAR module_cellular_register(); #endif #if defined(JSE_NET_ADDON_NETMGR) || defined(JSE_NET_ADDON_CELLULAR) module_network_register(); extern uint32_t jslib_network_size; extern uint8_t jslib_network[]; quickjs_add_prebuild_module("network", jslib_network, jslib_network_size); #endif #if (defined(JSE_NET_ADDON_NETMGR) || defined(JSE_NET_ADDON_CELLULAR)) && defined(JSE_ADVANCED_ADDON_LOCATION) extern uint32_t jslib_location_size; extern uint8_t jslib_location[]; quickjs_add_prebuild_module("location", jslib_location, jslib_location_size); #endif #ifdef JSE_ADVANCED_ADDON_OSS module_oss_register(); #endif } int amp_context_set(JSContext *context) { if (!context) { aos_printf("%s: context null", __func__); return -1; } ctx = context; aos_printf("%s: js context set\r\n", __func__); return 0; } JSModuleDef *amp_modules_load(JSContext *ctx, const char *module_name, void *opaque) { aos_printf("%s: load module %s\r\n", __func__, module_name ? module_name : "null"); return quickjs_module_loader(ctx, module_name, opaque); } int jsengine_init(void) { #ifndef HAASUI_AMP_BUILD rt = JS_NewRuntime(); if (rt == NULL) { aos_printf("JS_NewRuntime failure"); aos_task_exit(1); } js_std_init_handlers(rt); ctx = JS_NewContext(rt); if (ctx == NULL) { aos_printf("JS_NewContext failure"); } JS_SetCanBlock(rt, 1); /* loader for ES6 modules */ JS_SetModuleLoaderFunc(rt, NULL, quickjs_module_loader, NULL); js_std_add_helpers(ctx, -1, NULL); /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); jsengine_register_addons(); if (g_repl_config) { module_repl_register(); } #else js_std_add_helpers(ctx, -1, NULL); /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); jsengine_register_addons(); #endif aos_printf("quickjs engine started !\n"); return 0; } void qjs_dump_obj(JSContext *ctx, JSValueConst val) { const char *str; str = JS_ToCString(ctx, val); if (str) { aos_printf("%s", str); JS_FreeCString(ctx, str); } else { aos_printf("[exception]\n"); } } void qjs_std_dump_error1(JSContext *ctx, JSValueConst exception_val) { JSValue val; bool is_error; is_error = JS_IsError(ctx, exception_val); qjs_dump_obj(ctx, exception_val); if (is_error) { val = JS_GetPropertyStr(ctx, exception_val, "stack"); if (!JS_IsUndefined(val)) { qjs_dump_obj(ctx, val); } JS_FreeValue(ctx, val); } } void qjs_std_dump_error(JSContext *ctx) { JSValue exception_val; exception_val = JS_GetException(ctx); qjs_std_dump_error1(ctx, exception_val); JS_FreeValue(ctx, exception_val); } void jsengine_eval_file(const char *filename) { uint8_t *buf = NULL; size_t buf_len = 0; int eval_flags = JS_EVAL_TYPE_MODULE; aos_printf("begin eval file: %s\n", filename); buf = js_load_file(ctx, &buf_len, filename); if (buf == NULL) { aos_printf("read js file %s error\n", filename); return; } if (filename[strlen(filename) - 1] == 's') { val = JS_Eval(ctx, buf, buf_len, filename, eval_flags); if (JS_IsException(val)) { aos_printf("js engine eval %s error\n", filename); aos_printf("app.js content: \r\n"); aos_printf("%s\r\n", buf); qjs_std_dump_error(ctx); } JS_FreeValue(ctx, val); } else { js_std_eval_binary(ctx, buf, buf_len, 0); } js_free(ctx, buf); if (g_repl_config) { extern uint32_t jslib_repl_size; extern uint8_t jslib_repl[]; js_std_eval_binary(ctx, jslib_repl, jslib_repl_size, 0); } } void jsengine_loop_once(void) { js_std_loop_once(ctx); } void jsengine_exit(void) { JS_FreeValue(ctx, val); js_std_loop(ctx); JS_FreeContext(ctx); JS_FreeRuntime(rt); } void dump_quickjs_memory(void) { JS_RunGC(rt); JSMemoryUsage stats; JS_ComputeMemoryUsage(rt, &stats); JS_DumpMemoryUsage(stdout, &stats, rt); }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/startup/quickjs_init.c
C
apache-2.0
10,059
#include <stdio.h> #include <stdint.h> #include <stdbool.h> #include "quickjs.h" #include "amp_config.h" #include "amp_defines.h" #include "aos/list.h" #include "quickjs-libc.h" #include "aos_system.h" #define MOD_STR "quickjs_module_load" static dlist_t g_prebuild_module_list = AOS_DLIST_HEAD_INIT(g_prebuild_module_list); extern JSValue js_load_binary_module(JSContext *ctx, const uint8_t *buf, size_t buf_len); typedef struct { char *name; uint8_t *module_data; uint32_t module_len; dlist_t node; } prebuild_module_info_t; void quickjs_add_prebuild_module(char *module_name, uint8_t *module_data, uint32_t module_len) { prebuild_module_info_t *module_info = NULL; module_info = aos_malloc(sizeof(prebuild_module_info_t)); if (!module_info) { aos_printf("alloc gpio_module_info info fail!"); return; } module_info->name = module_name; module_info->module_data = module_data; module_info->module_len = module_len; dlist_add_tail(&module_info->node, &g_prebuild_module_list); } static uint8_t *find_prebuild_module(char *module_name, uint32_t *module_len) { prebuild_module_info_t *module_info = NULL; dlist_for_each_entry(&g_prebuild_module_list, module_info, prebuild_module_info_t, node) { if (strcmp(module_info->name, module_name) == 0) { *module_len = module_info->module_len; return module_info->module_data; } } return NULL; } JSModuleDef *quickjs_module_loader(JSContext *ctx, const char *module_name, void *opaque) { size_t buf_len = 0; uint8_t *buf = NULL; JSModuleDef *m = NULL; JSValue func_val = JS_UNDEFINED; char *path = NULL; int path_flag = 0; aos_printf("begin load module %s\n", module_name); if (strchr(module_name, '/') != NULL) { if (*module_name != '/') { buf_len = strlen(AMP_FS_ROOT_DIR) + 1 + strlen(module_name) + 1; path = aos_malloc(buf_len); memset(path, 0, buf_len); snprintf(path, buf_len, "%s/%s", AMP_FS_ROOT_DIR, module_name); path_flag = 1; } else { buf_len = strlen(module_name) + 1; path = module_name; } buf = js_load_file(ctx, &buf_len, path); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); if (path_flag) { aos_free(path); } return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *) buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (path_flag) { aos_free(path); } } else { uint8_t *module_data = NULL; uint32_t module_len = 0; module_data = find_prebuild_module(module_name, &module_len); if (module_data != NULL) { aos_printf("find binary module %s, len %d, begin load\n", module_name, module_len); func_val = js_load_binary_module(ctx, module_data, module_len); } else { amp_error(MOD_STR, "find module %s fail\n", module_name); return NULL; } } if (JS_IsUndefined(func_val)) { aos_printf("load module %s fail, undefined\n", module_name); return NULL; } if (JS_IsException(func_val)) { aos_printf("load module %s fail, exception\n", module_name); return NULL; } m = JS_VALUE_GET_PTR(func_val); if (m) { aos_printf("load module %s success\n", module_name); } JS_FreeValue(ctx, func_val); return m; }
YifuLiu/AliOS-Things
components/amp/engine/quickjs_engine/startup/quickjs_module_load.c
C
apache-2.0
3,716
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdarg.h> extern int amp_main(); int main(void) { amp_main(); }
YifuLiu/AliOS-Things
components/amp/entry/amp_entry.c
C
apache-2.0
164
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as adc from 'ADC'; import * as pwm from 'PWM'; import * as NETMGR from 'NETMGR'; var pwm2 = pwm.open('PWM2'); var adc0 = adc.open('adc0'); var adc7 = adc.open('adc7'); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, /* 本示例是一分钟上云示例,SSID已经提前写入文件中。非一分钟上云示例,用户需写入SSID */ password: wifiPassword, /* 本示例是一分钟上云示例,PSWD已经提前写入文件中。非一分钟上云示例,用户需写入PSWD */ bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); var payload = JSON.parse(res.params); var duty = payload.pwm; console.log('cloud set pwm2 freq 200hz, duty ' + duty); pwm2.setConfig({ freq: 200, duty: duty }); device.postProps(JSON.stringify({ 'pwm': duty })); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportAdcValue(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default : break ; } }); } /* 3. 周期上报ADC数据至阿里云物联网平台 */ function reportAdcValue() { var Voltage0 = adc0.read(); var Voltage7 = adc7.read(); console.log('>> adc0 voltage is ' + Voltage0 + ', adc7 voltage is ' + Voltage7); device.postProps(JSON.stringify({ 'adc0': Voltage0, 'adc3': 0, 'adc4': 0, 'adc5': 0, 'adc6': 0, 'adc7': Voltage7 })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/adcsample/app.js
JavaScript
apache-2.0
3,428
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as adc from 'ADC'; import * as NETMGR from 'NETMGR'; import * as fire from './fire_mk002354.js'; var adcDev = adc.open('fire'); var fireDev = fire.Fire(adcDev); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportFireAlarm(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default : break ; } }); } /* 3. 周期上报火焰传感器数据至阿里云物联网平台 */ function reportFireAlarm() { var alarm_on = 0; console.log('reportFireAlarm'); var fireVoltage = fireDev.getVoltage(); if(fireVoltage > 200) { alarm_on = 0; } else { alarm_on = 1; } console.log('>> fireVoltage is ' + fireVoltage + ', alarm_on is ' + alarm_on); device.postProps(JSON.stringify({ 'fireVoltage': fireVoltage, 'alarmState': alarm_on })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/fire_detector/app.js
JavaScript
apache-2.0
2,949
class _Fire { constructor(adcObj) { this.adcInstance = adcObj; }; getVoltage() { var value = this.adcInstance.read(); return value; }; } export function Fire(adcObj) { return new _Fire(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/fire_detector/fire_mk002354.js
JavaScript
apache-2.0
228
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as i2c from 'i2c' import * as NETMGR from 'NETMGR'; import * as sht3x from './sht3x.js'; import * as gpio from 'GPIO'; var temperature = 25.0; var humidity = 0.0; var airconditioner_value = 0; var humidifier_value = 0; var i2cDev = i2c.open({ id: 'sht3x', success: function() { console.log('i2c: open success') }, fail: function() { console.log('i2c: open failed') } }); var sht3xDev = sht3x.SHT3X(i2cDev); var led_b = gpio.open('led_b'); var led_g = gpio.open('led_g'); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); var payload = JSON.parse(res.params); if (payload.humidifier !== undefined) { humidifier_value = payload.humidifier; if (humidifier_value == 1) { console.log('打开加湿器'); } else { console.log('关闭加湿器'); } led_g.write(humidifier_value); } if (payload.airconditioner !== undefined) { airconditioner_value = payload.airconditioner; if (airconditioner_value == 1) { console.log('打开空调'); } else { console.log('关闭空调'); } led_b.write(airconditioner_value); } /* post props */ device.postProps(JSON.stringify({ airconditioner: airconditioner_value, humidifier: humidifier_value })); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportEnvironmentData(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default : break ; } }); } /* 3. 周期上报土壤传感器数据至阿里云物联网平台 */ function reportEnvironmentData() { temperature = sht3xDev.getTemperature(); humidity = sht3xDev.getHumidity(); temperature = Math.round(temperature * 100) / 100; humidity = Math.round(humidity * 100) / 100; console.log('Temperature is ' + temperature + ' degrees, humidity is ' + humidity + "\r\n"); device.postProps(JSON.stringify({ 'CurrentTemperature': temperature, 'CurrentHumidity': humidity })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/floriculture/app.js
JavaScript
apache-2.0
4,185
class _SHT3X { constructor(i2cObj) { this.i2cInstance = i2cObj; var cmd = [0x30, 0x41]; //console.log('init cmd = ' + cmd); this.i2cInstance.write(cmd); sleepMs(20); }; getTempHumidity() { var sensorData = [0x0, 0x0]; var cmd = [0x24, 0x0b]; //console.log('get data cmd = ' + cmd); this.i2cInstance.write(cmd); sleepMs(20); var retval = this.i2cInstance.read(6); //console.log('get data retval = ' + retval); var temp = (retval[0] << 8) | (retval[1]); var humi = (retval[3] << 8) | (retval[4]); //console.log('get data temp = ' + temp); //console.log('get data humi = ' + humi); sensorData[0] = -45.0 + (temp) * 175.0 / (0xFFFF - 1); sensorData[1] = humi * 0.0015259022; //console.log('get sensorData[0] = ' + sensorData[0]); //console.log('get sensorData[1] = ' + sensorData[1]); return sensorData; }; getTemperature() { var data = this.getTempHumidity(); //console.log('getTemperature data = ' + data[0]); return data[0]; }; getHumidity() { var data = this.getTempHumidity(); //console.log('getHumidity data = ' + data[1]); return data[1]; }; } export function SHT3X(i2cObj) { return new _SHT3X(i2cObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/floriculture/sht3x.js
JavaScript
apache-2.0
1,339
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as adc from 'ADC'; import * as NETMGR from 'NETMGR'; import * as gas from './gas.js'; import * as gpio from 'GPIO'; var adcDev = adc.open('gas'); var gasDev = gas.Gas(adcDev); /* open GPIO led */ var ledDev = gpio.open('led'); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportGasAlarm(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default : break ; } }); } /* 3. 周期上报火焰传感器数据至阿里云物联网平台 */ function reportGasAlarm() { var alarm_on = 0; console.log('reportGasAlarm'); var gasVoltage = gasDev.getVoltage(); if(gasVoltage > 200) { alarm_on = 0; } else { alarm_on = 1; } ledDev.write(alarm_on); console.log('>> gasVoltage is ' + gasVoltage + ', alarm_on is ' + alarm_on); device.postProps(JSON.stringify({ 'gasVoltage': gasVoltage, 'alarmLight': alarm_on })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/gas_detector/app.js
JavaScript
apache-2.0
3,029
class _Gas { constructor(adcObj) { this.adcInstance = adcObj; }; getVoltage() { var value = this.adcInstance.read(); return value; }; } export function Gas(adcObj) { return new _Gas(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/gas_detector/gas.js
JavaScript
apache-2.0
225
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as adc from 'ADC'; import * as NETMGR from 'NETMGR'; import * as hcho from './hcho.js'; var adcDev = adc.open('hcho'); var hchoDev = hcho.Hcho(adcDev); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportHchoVoltage(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default : break ; } }); } /* 3. 周期上报甲醛检测传感器数据至阿里云物联网平台 */ function reportHchoVoltage() { var hchoVoltage = hchoDev.getPPM(); console.log('hchoVoltage is ' + hchoVoltage); /* post props */ device.postProps(JSON.stringify({ 'HCHO': hchoVoltage })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/hcho_detector/app.js
JavaScript
apache-2.0
2,764
class _Hcho { constructor(adcObj) { this.adcInstance = adcObj; }; getPPM() { var min = 400; var max = 0; var value = 0; var total = 0; var analogVoltage = 0; var ppm = 0; for (var i = 0; i < 32; i++) { var value = this.adcInstance.read(); //console.log('value is ' + value); total = total + value; if (min >= value) { min = value; } if (max <= value) { max = value; } } //console.log('total is ' + total); //console.log('min is ' + min); //console.log('max is ' + max); analogVoltage = (total - min - max) / 30; analogVoltage = analogVoltage + 23; analogVoltage = analogVoltage / 1000.0; ppm = 3.125 * analogVoltage - 1.25; //linear relationship(0.4V for 0 ppm and 2V for 5ppm) if (ppm < 0) { ppm = 0; } //console.log('analogVoltage is ' + analogVoltage); //console.log('ppm is ' + ppm); ppm = Math.round(ppm * 100) / 100; //console.log('ppm is ' + ppm); return ppm; }; } export function Hcho(adcObj) { return new _Hcho(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/hcho_detector/hcho.js
JavaScript
apache-2.0
1,027
setInterval(function() { console.log('helloworld'); }, 1000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/helloworld/app.js
JavaScript
apache-2.0
65
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as NETMGR from 'NETMGR'; import * as gpio from 'GPIO'; import * as ir from './ir.js' /* open GPIO ir */ var irObj = gpio.open('ir'); var irDev = ir.IR(irObj); /* open GPIO led */ var ledDev = gpio.open('led'); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; var last_have_human = 0; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportHumanDetect(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default: break ; } }); } /* 3. 周期上报人形检测传感器数据至阿里云物联网平台 */ function reportHumanDetect() { var have_human = irDev.irDetect(); console.log('human state is :' + have_human + '\r\n'); if (have_human == 1) { console.log('human is here .....\r\n'); } if (last_have_human != have_human) { //console.log('human state is change:' + have_human + '\r\n'); ledDev.write(have_human); /* post props */ device.postProps(JSON.stringify({ MotionDetected: have_human })); } last_have_human = have_human; }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/human_detector/app.js
JavaScript
apache-2.0
3,119
class _IR { constructor(gpioObj) { this.gpioInstance = gpioObj; }; irDetect() { var value = this.gpioInstance.read(); return value; }; } export function IR(gpioObj) { return new _IR(gpioObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/human_detector/ir.js
JavaScript
apache-2.0
226
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as adc from 'ADC'; import * as NETMGR from 'NETMGR'; import * as photoresistor from './photoresistor.js'; import * as gpio from 'GPIO'; var adcDev = adc.open('photoresistor'); var photoresistorDev = photoresistor.PhotoResistor(adcDev); /* open GPIO led */ var ledDev = gpio.open('led'); NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); setInterval(function() { reportPhotoresistorVoltage(); }, 5000); break; case 2: console.log('iot platform disconnect '); break; default: break ; } }); } /* 3. 周期上报光敏电阻传感器数据至阿里云物联网平台 */ function reportPhotoresistorVoltage() { var photoresistorVoltage = photoresistorDev.getLightness(); console.log('photoresistorVoltage is ' + photoresistorVoltage); var onoff = 0; if (photoresistorVoltage > 450) { onoff = 1; } else { onoff = 0; } console.log('led onoff is ' + onoff); ledDev.write(onoff); /* post props */ device.postProps(JSON.stringify({ 'Brightness': photoresistorVoltage, 'onoff': onoff })); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/smart_public_lighting/app.js
JavaScript
apache-2.0
3,160
class _PhotoResistor { constructor(adcObj) { this.adcInstance = adcObj; }; getLightness() { var value = this.adcInstance.read(); return value; }; } export function PhotoResistor(adcObj) { return new _PhotoResistor(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/smart_public_lighting/photoresistor.js
JavaScript
apache-2.0
257
import * as AIOT_DEVICE from 'AIOT_DEVICE'; import * as fs from 'FS'; import * as kv from 'kv'; import * as uart from 'UART'; import * as NETMGR from 'NETMGR'; import * as gps from './gps.js'; NETMGR.serviceInit(); var dev_handler = NETMGR.getDev('/dev/wifi0'); var device; /* 1. WIFI配网,连接路由器 */ var keySSID = 'oneMinuteCloudSSID'; var keyPassword = 'oneMinuteCloudPassword'; var wifiSSID = kv.getStorageSync(keySSID); var wifiPassword = kv.getStorageSync(keyPassword); console.log('wifi ssid: ' + wifiSSID + ', pswd ' + wifiPassword); if ((wifiSSID !==undefined) && (wifiPassword !==undefined)) { var wifiOptions = { ssid: wifiSSID, password: wifiPassword, bssid: '', timeout_ms: 18000 }; NETMGR.connect(dev_handler, wifiOptions, function (status) { if (status == 'DISCONNECT') { console.log('wifi disconnected'); } else { console.log('wifi connected'); connectAliyunCloud(); } }); } function connectAliyunCloud() { var filePath = '/DeviceInfo.json'; var data = fs.read(filePath); var jsonObj = JSON.parse(data); var deviceSecret = jsonObj.deviceSecret; var productKey = jsonObj.productKey; var deviceName = jsonObj.deviceName; var iotOptions = { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', keepaliveSec: 60 } device = AIOT_DEVICE.device(iotOptions, function(res) { if (!res.handle) { console.log("res.handle is empty"); return; } switch (res.code) { case 0: console.log('iot platform connect '); device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); /* 上报GPS位置信息到阿里云物联网平台显示位置 */ reportLocationData(); break; case 2: console.log('iot platform disconnect '); break; default: break ; } }); } /* 3. 上报GPS传感器数据至阿里云物联网平台 */ function reportLocationData() { var gps_port = uart.open('serial2'); gps_port.on(function(data, len) { var GGA; //console.log('gnss data = ' + data) var bbb = data.split("$"); GGA = "$" + bbb[1]; var gga_tag = GGA.split(","); if (gga_tag[0] == '$GNGGA') { // console.log('get GGA = ' + GGA) var geoLocation_data = gps.ParseData(GGA); console.log("reportLocationData: " + JSON.stringify(geoLocation_data, null, 4)) device.postProps(JSON.stringify({ GeoLocation: { Longitude: geoLocation_data['lon'], Latitude: geoLocation_data['lat'], Altitude: geoLocation_data['alt'], CoordinateSystem: 1 } }), function() {}); } }); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/vehicle_location/app.js
JavaScript
apache-2.0
3,241
/** * @license GPS.js v0.6.0 26/01/2016 * * Copyright (c) 2016, Robert Eisele (robert@xarg.org) * Dual licensed under the MIT or GPL Version 2 licenses. **/ function parseCoord(coord, dir) { if (coord === '') return null; var n, sgn = 1; switch (dir) { case 'S': sgn = -1; case 'N': n = 2; break; case 'W': sgn = -1; case 'E': n = 3; break; } return sgn * (parseFloat(coord.slice(0, n)) + parseFloat(coord.slice(n)) / 60); } function parseDist(num, unit) { if (num === '') { return null; } if (unit === 'M' || unit === '') { return parseFloat(num); } } function GGAFunction(str, gga) { if (gga.length !== 16 && gga.length !== 14) { console.log("Invalid GGA length: " + str); return false; } return { 'lat': parseCoord(gga[2], gga[3]), 'lon': parseCoord(gga[4], gga[5]), 'alt': parseDist(gga[9], gga[10]) }; } export function ParseData(line) { if (typeof line !== 'string') return false; var nmea = line.split(','); var last = nmea.pop(); if (nmea.length < 2 || line.charAt(0) !== '$' || last.indexOf('*') === -1) { return false; } last = last.split('*'); nmea.push(last[0]); nmea.push(last[1]); nmea[0] = nmea[0].slice(3); console.log('nmea[0] = ' + nmea[0]) if (nmea[0] == 'GGA') { var data = GGAFunction(line, nmea); return data; } return false; }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/examples/vehicle_location/gps.js
JavaScript
apache-2.0
1,627
import * as adc from 'adc' import * as fire from './fire_mk002354.js' console.log('Testing fire ...'); var adcDev = adc.open({ id: 'fire', success: function() { console.log('adc: open success') }, fail: function() { console.log('adc: open failed') } }); var fireDev = fire.Fire(adcDev); setInterval(function(){ var value = fireDev.getVoltage(); console.log('The fire Voltage ' + value); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/fire_mk002354/app.js
JavaScript
apache-2.0
443
class _Fire { constructor(adcObj) { this.adcInstance = adcObj; }; getVoltage() { var value = this.adcInstance.readValue(); return value; }; } export function Fire(adcObj) { return new _Fire(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/fire_mk002354/fire_mk002354.js
JavaScript
apache-2.0
233
import * as adc from 'adc' import * as gas from './gas.js' console.log('Testing gas ...'); var adcDev = adc.open({ id: 'gas', success: function() { console.log('adc: open success') }, fail: function() { console.log('adc: open failed') } }); var gasDev = gas.Gas(adcDev); setInterval(function(){ var value = gasDev.getVoltage(); console.log('The gas Voltage ' + value); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/gas/app.js
JavaScript
apache-2.0
425
class _Gas { constructor(adcObj) { this.adcInstance = adcObj; }; getVoltage() { var value = this.adcInstance.readValue(); return value; }; } export function Gas(adcObj) { return new _Gas(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/gas/gas.js
JavaScript
apache-2.0
230
import * as adc from 'adc' import * as hcho from './hcho.js' console.log('Testing hcho ...'); var adcDev = adc.open({ id: 'hcho', success: function() { console.log('adc: open success'); }, fail: function() { console.log('adc: open failed'); } }); var hchoDev = hcho.Hcho(adcDev); setInterval(function(){ var value = hchoDev.getPPM(); console.log('The hcho ppm value ' + value); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/hcho/app.js
JavaScript
apache-2.0
434
class _Hcho { constructor(adcObj) { this.adcInstance = adcObj; }; getPPM() { var min = 400; var max = 0; var value = 0; var total = 0; var analogVoltage = 0; var ppm = 0; for (var i = 0; i < 32; i++) { var value = this.adcInstance.readValue(); //console.log('value is ' + value); total = total + value; if (min >= value) { min = value; } if (max <= value) { max = value; } } //console.log('total is ' + total); //console.log('min is ' + min); //console.log('max is ' + max); analogVoltage = (total - min - max) / 30; analogVoltage = analogVoltage + 23; analogVoltage = analogVoltage / 1000.0; ppm = 3.125 * analogVoltage - 1.25; //linear relationship(0.4V for 0 ppm and 2V for 5ppm) if (ppm < 0) { ppm = 0; } //console.log('analogVoltage is ' + analogVoltage); //console.log('ppm is ' + ppm); ppm = Math.round(ppm * 100) / 100; //console.log('ppm is ' + ppm); return ppm; }; } export function Hcho(adcObj) { return new _Hcho(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/hcho/hcho.js
JavaScript
apache-2.0
1,032
import * as adc from 'adc' import * as photoresistor from './photoresistor.js' console.log('Testing photoresistor ...'); var adcDev = adc.open({ id: 'photoresistor', success: function() { console.log('adc: open success') }, fail: function() { console.log('adc: open failed') } }); var photoresistorDev = photoresistor.PhotoResistor(adcDev); setInterval(function(){ var value = photoresistorDev.getLightness(); console.log('The photoresistor lightness ' + value); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/photoresistor/app.js
JavaScript
apache-2.0
519
class _PhotoResistor { constructor(adcObj) { this.adcInstance = adcObj; }; getLightness() { var value = this.adcInstance.readValue(); return value; }; } export function PhotoResistor(adcObj) { return new _PhotoResistor(adcObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/adc/photoresistor/photoresistor.js
JavaScript
apache-2.0
262
import * as ble_pripheral from 'ble_pripheral' import * as network from 'network'; import * as http from 'http'; import * as fs from 'fs'; import * as kv from 'kv'; console.log('\r\n'); console.log('>>>>>>>>> boot.js >>>>>>>>>'); var key = 'oneMinuteCloudKey'; if(kv.getStorageSync(key) === 'SET') { console.log('KV oneMinuteCloudKey is SET, skip ble netconfig'); } else { console.log('KV oneMinuteCloudKey is RESET, start ble netconfig'); bleNetConfig(); } function bleNetConfig() { var appCmdJson; var wifiSsid, wifiPassword; var appScriptFile, appScriptURL; var appConfigFile, appConfigURL; var service = {service: "{\"s_uuid\":\"0xFFA0\",\"chars_list\":[\ {\"char_uuid\":\"0xFFA2\",\"char_permit\":\"RW\",},\ {\"char_uuid\":\"0xFFA3\",\"char_permit\":\"NOTIFY\"}]}"}; var adv_params = {type: 0, adv_data: '020106', scan_rsp_data: '', interval_min: 160, interval_max: 320, channel_map: 7}; var net = network.openNetWorkClient({devType: 'wifi'}); var ble_pripheral_instant = ble_pripheral.open({ deviceName: 'esp-node', success: function() { console.log('ble_pripheral init success'); }, fail: function() { console.log('ble_pripheral init failed'); } }); ble_pripheral_instant.add_service(service); ble_pripheral_instant.start_adv(adv_params); ble_pripheral_instant.on('connect', function() { console.log('ble_pripheral gap connected'); }); ble_pripheral_instant.on('disconnect', function() { console.log('ble_pripheral gap disconnected'); }); ble_pripheral_instant.on('onCharWrite', function(uuid, len, data) { var retJson, netConfig, jsonObj; if (data.startsWith('{\"cmd\":\"WiFiCon\"') || data.startsWith('{\"cmd\":\"PullCode\"') || data.startsWith('{\"cmd\":\"Reset\"') || data.startsWith('{\"cmd')) { if (data.startsWith('{\"cmd\":\"Reset\"')) { console.log('recv RESET cmd'); } appCmdJson = data; } else { appCmdJson += data; if (appCmdJson.includes('}}')) { if (appCmdJson.includes('{\"cmd\":\"WiFiCon\"')) { jsonObj = JSON.parse(appCmdJson); wifiSsid = jsonObj.param.ssid; wifiPassword = jsonObj.param.pswd; console.log('wifi ssid: ' + wifiSsid); console.log('wifi pswd: ' + wifiPassword); net.connect({ ssid: wifiSsid, password: wifiPassword, }); net.on('connect', function () { console.log('network connected'); netConfig = net.getInfo(); retJson = '{"cmd":"WiFiCon", "ret":{"state":"STAT_GOT_IP", "ifconfig":["' + netConfig.netInfo.ip_addr + '","' + netConfig.netInfo.gw + '"]}}'; ble_pripheral_instant.update_char({ uuid: 0xFFA3, value: retJson }); }); net.on('disconnect', function () { console.log('network disconnected'); }); } else if (appCmdJson.includes('\"cmd\":\"PullCode\"')) { retJson = '{"cmd":"PullCode", "ret":{"state":"START_DOWNLOAD"}}'; ble_pripheral_instant.update_char({ uuid: 0xFFA3, value: retJson }); jsonObj = JSON.parse(appCmdJson); for (var i = 0; i < jsonObj.param.filelist.length; i++) { console.log('type: ' + jsonObj.param.filelist[i].type); console.log('path: ' + jsonObj.param.filelist[i].path); if (jsonObj.param.filelist[i].type === '.json') { appConfigURL = jsonObj.param.filelist[i].url; appConfigFile = jsonObj.param.filelist[i].name; console.log('url: ' + appConfigURL); console.log('name: ' + appConfigFile); } else { appScriptURL = jsonObj.param.filelist[i].url; appScriptFile = jsonObj.param.filelist[i].name; console.log('url: ' + appScriptURL); console.log('name: ' + appScriptFile); } } } else { console.log('unrecognized json: ' + appCmdJson); } } else if (appCmdJson.startsWith('{\"cmd\":\"PullCodeCheck\"')) { console.log('recv PullCodeCheck cmd'); retJson = '{\"cmd\":\"PullCode\", \"ret\":{\"state\":[\"SUCCESS\", \"SUCCESS\"]}}'; ble_pripheral_instant.update_char({ uuid: 0xFFA3, value: retJson }); ble_pripheral_instant.close({ success: function() { console.log('ble_pripheral close success'); }, fail: function() { console.log('ble_pripheral close failed'); } }); http_download_appjs(appScriptURL); http_download_deviceinfo(appConfigURL); } } }); } function http_download_appjs(url) { var filePath = '/data/jsamp/app.js'; http.download({ url:url, filepath:filePath, success: function (data) { console.log('download ' + filePath + ' successfully!!'); system_reboot(); } }); } function http_download_deviceinfo(url) { var filePath = '/DeviceInfo.json'; http.download({ url:url, filepath:filePath, success: function (data) { console.log('download ' + filePath + ' successfully!!'); system_reboot(); } }); } var downloadCount = 0; function system_reboot() { downloadCount = downloadCount + 1; if (downloadCount > 1) { kv.setStorageSync(key, "SET"); console.log('SET KV oneMinuteCloudKey and Reboot'); sleepMs(2000); system.reboot(); } }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/bleprph/app.js
JavaScript
apache-2.0
5,570
import * as checksum from 'checksum' import * as crypto from 'crypto' function crypto_test() { let enc_param = { 'key': '000102030405060708090a0b0c0d0e0f', 'in': '3132333435363738' } let enc_result = crypto.encrypt(enc_param); console.log('encrypt:'+enc_result) let dec_param = { 'key': '000102030405060708090a0b0c0d0e0f', 'in': enc_result } let dec_result = crypto.decrypt(dec_param); console.log('decrypt:'+dec_result) } function checksum_test() { let check_param = { 'src': '000102030405060708090a0b0c0d0e0f' } let crc16_result = checksum.crc16(check_param); console.log('crc16:'+crc16_result) let crc32_result = checksum.crc32(check_param); console.log('crc32:'+crc32_result) let md5 = checksum.md5(check_param); console.log('md5:'+md5) } checksum_test() crypto_test()
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/checksum/app.js
JavaScript
apache-2.0
815
import * as fs from 'fs' var path = '/data/jsamp/test.data'; var content = 'this is javascript fs test file'; /** filesystem total size */ console.log('fs total size: ' + fs.totalSize()); /** write file */ fs.writeSync(path, content); console.log('fs write: ' + content); /** used size */ console.log('fs used size: ' + fs.usedSize()); /** free size */ console.log('fs free size: ' + fs.freeSize()); /** read file */ var data = fs.readSync(path); console.log('fs read: ' + data); if (data === content) { console.log('congratulations!! fs test pass ..'); fs.unlinkSync(path); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/fs/app.js
JavaScript
apache-2.0
592
import * as gpio from 'gpio' import * as dcmotor from './dcmotor.js' console.log('Testing dcmotor ...'); var gpioDev = gpio.open({ id: 'dcmotor', success: function() { console.log('gpio: open success') }, fail: function() { console.log('gpio: open failed') } }); var dcmotorDev = dcmotor.DCMOTOR(gpioDev); setInterval(function(){ dcmotorDev.ctrl(1); console.log('The dcmotor is started'); sleepMs(200); dcmotorDev.ctrl(0); console.log('The dcmotor is stopped'); sleepMs(200); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/dcmotor/app.js
JavaScript
apache-2.0
548
class _DCMOTOR { constructor(gpioObj) { this.gpioInstance = gpioObj; }; ctrl(onoff) { this.gpioInstance.writeValue(onoff); }; } export function DCMOTOR(gpioObj) { return new _DCMOTOR(gpioObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/dcmotor/dcmotor.js
JavaScript
apache-2.0
226
import * as gpio from 'gpio'; var inputobj = gpio.open({ id: 'gpio_input', success: function success() { console.log('gpio: open led success'); }, fail: function fail() { console.log('gpio: open led failed'); } }); setInterval(function() { var value = inputobj.readValue(); console.log('gpio: read gpio value ' + value); }, 1000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/input/app.js
JavaScript
apache-2.0
355
var gpio = require('gpio'); var irq = gpio.open({ id: 'gpio_irq', success: function() { console.log('gpio: open irq success') }, fail: function() { console.log('gpio: open irq failed') } }); irq.onIRQ({ cb: function() { console.log('gpio: irq interrupt happens'); } });
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/interrupt/app.js
JavaScript
apache-2.0
296
import * as gpio from 'gpio' import * as ir from './ir.js' console.log('Testing IR detector ...'); var gpioDev = gpio.open({ id: 'ir', success: function() { console.log('gpio: open success') }, fail: function() { console.log('gpio: open failed') } }); var irDev = ir.IR(gpioDev); setInterval(function(){ var value = irDev.irDetect(); console.log('The ir status ' + value); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/ir/app.js
JavaScript
apache-2.0
429
class _IR { constructor(gpioObj) { this.gpioInstance = gpioObj; }; irDetect() { var value = this.gpioInstance.readValue(); return value; }; } export function IR(gpioObj) { return new _IR(gpioObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/ir/ir.js
JavaScript
apache-2.0
231
var gpio = require('gpio'); var output = gpio.open({ id: 'gpio_output', success: function() { console.log('gpio: open output success') }, fail: function() { console.log('gpio: open output failed') } }); var value = 1; setInterval(function() { value = 1 - value; output.writeValue(value); console.log('gpio: gpio write value ' + output.readValue()); }, 1000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/gpio/output/app.js
JavaScript
apache-2.0
385
import * as bmp280 from './bmp280.js'; var temperature = 25.0; var pressure = 0.0; bmp280.bmp280_init(); setInterval(function(){ temperature = bmp280.bmp280TemperatureRead(); pressure = bmp280.bmp280PressureRead(); pressure = pressure / 100; // iot needs hPa console.log('Temperature is ' + temperature + 'degrees, Pressure is ' + pressure + "hPa"); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/i2c/bmp280/app.js
JavaScript
apache-2.0
377
var i2c = require('i2c'); var calibParamT1; var calibParamT2; var calibParamT3; var calibParamP1; var calibParamP2; var calibParamP3; var calibParamP4; var calibParamP5; var calibParamP6; var calibParamP7; var calibParamP8; var calibParamP9; var calibParamT_FINE; const INVALID_TEMP = -273.15; const INVALID_PRESS = 0; var sensor = i2c.open({ id: 'i2c_bmp280', success: function() { console.log('bmp280 sensor open success') }, fail: function() { console.log('bmp280 sensor open failed') } }); function bmp280SoftReset() { var regaddr = 0xe0; var regval = [0xb6]; sensor.writeMem(regaddr, regval); console.log('bmp280 soft reset'); } function bmp280PowerEnable() { var regval = sensor.readMem(0xf4, 1); regval[0] |= 0x03; sensor.writeMem(0xf4, regval); console.log('bmp280 power up'); } function bmp280PowerDisable() { var regval = sensor.readMem(0xf4, 1); regval[0] &= 0xfc; sensor.writeMem(0xf4, regval); console.log('bmp280 power down'); } function bmp280SetOdr() { var regval = sensor.readMem(0xf5, 1); regval[0] &= 0x1f; regval[0] |= 0x20; sensor.writeMem(0xf5, regval); console.log('bmp280 set odr'); } function bmp280SetWorkMode() { var regval = sensor.readMem(0xf4, 1); console.log('bmp280 old work mode ' + regval); regval[0] &= 0x03; regval[0] |= (0x03 << 5 | 0x03 << 2); sensor.writeMem(0xf4, regval); regval = sensor.readMem(0xf4, 1); console.log('bmp280 new work mode ' + regval); } function bmp280ReadCalibParams() { var calibTable = sensor.readMem(0x88, 24); console.log('bmp280 calib table ' + calibTable); calibParamT1 = (calibTable[1] << 8) | calibTable[0]; calibParamT2 = (calibTable[3] << 8) | calibTable[2]; calibParamT3 = (calibTable[5] << 8) | calibTable[4]; calibParamP1 = (calibTable[7] << 8) | calibTable[6]; calibParamP2 = (calibTable[9] << 8) | calibTable[8]; calibParamP3 = (calibTable[11] << 8) | calibTable[10]; calibParamP4 = (calibTable[13] << 8) | calibTable[12]; calibParamP5 = (calibTable[15] << 8) | calibTable[14]; calibParamP6 = (calibTable[17] << 8) | calibTable[16]; calibParamP7 = (calibTable[19] << 8) | calibTable[18]; calibParamP8 = (calibTable[21] << 8) | calibTable[20]; calibParamP9 = (calibTable[23] << 8) | calibTable[22]; } function bmp280RegRead(reg, len) { var regval = sensor.readMem(reg, len); if(!regval) { return; } return regval; } function bmp280TemperatureRead() { var regval = sensor.readMem(0xfa, 3); if(!regval) { return; } var tempval = (regval[0] << 12) | (regval[1] << 4) | (regval[2] >> 4); var ta = (((tempval >> 3) - (calibParamT1 << 1)) * calibParamT2) >> 11; var tb = (((((tempval >> 4) - calibParamT1) * ((tempval >> 4) - calibParamT1)) >> 12) * calibParamT3) >> 14; calibParamT_FINE = ta + tb; var temperature = ((ta + tb) * 4 + 128) >> 8; temperature /= 100; return temperature; } function bmp280PressureRead() { var pressure = INVALID_PRESS; var regval; // get t_fine value first if (bmp280TemperatureRead() == INVALID_TEMP) { console.error('Failed to get temperature'); return pressure; } regval = bmp280RegRead(0xf7, 3); if (regval) { var uncomp_press = (regval[0] << 12) | (regval[1] << 4) | (regval[2] >> 4); var var1 = (calibParamT_FINE >> 1) - 64000; var var2 = (((var1 >> 2) * (var1 >> 2)) >> 11) * calibParamP6; var2 = var2 + ((var1 * calibParamP5) << 1); var2 = (var2 >> 2) + (calibParamP4 << 16); var1 = (((calibParamP3 * (((var1 >> 2) * (var1 >> 2)) >> 13)) >> 3) + ((calibParamP2 * var1) >> 1)) >> 18; var1 = ((32768 + var1) * calibParamP1) >> 15; pressure = ((1048576 - uncomp_press) - (var2 >> 12)) * 3152; if (var1 != 0) { if (pressure < 0x80000000) { //pressure = (pressure << 1) / var1; pressure = (pressure / var1) << 1; } else { pressure = (pressure / var1) << 1; } var1 = (calibParamP9 * (((pressure >> 3) * (pressure >> 3)) >> 13)) >> 12; var2 = ((pressure >> 2) * calibParamP8) >> 13; pressure = (pressure + ((var1 + var2 + calibParamP7) >> 4)) } } else { console.error('Failed to get pressure'); } return pressure; } function bmp280_init() { console.log('1'); var chipID = sensor.readMem(0xd0, 1); console.log('2'); console.log('bmp280 chip id is ' + chipID); bmp280SoftReset(); bmp280SetOdr(); bmp280ReadCalibParams(); bmp280SetWorkMode(); bmp280PowerEnable(); } module.exports = { bmp280_init, bmp280TemperatureRead, bmp280PressureRead, }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/i2c/bmp280/bmp280.js
JavaScript
apache-2.0
4,865
import * as i2c from 'i2c' import * as sht3x from './sht3x.js' console.log('Testing sht3x ...'); var i2cDev = i2c.open({ id: 'sht3x', success: function() { console.log('i2c: open success') }, fail: function() { console.log('i2c: open failed') } }); var sht3xDev = sht3x.SHT3X(i2cDev); setInterval(function(){ var temperature = sht3xDev.getTemperature(); var humidity = sht3xDev.getHumidity(); console.log('temperature is ', temperature, '°C'); console.log('humidity is ', humidity, '%H'); var data = sht3xDev.getTempHumidity(); console.log('temperature is ', data[0], '°C'); console.log('humidity is ', data[1], '%H'); }, 5000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/i2c/sht3x/app.js
JavaScript
apache-2.0
697
class _SHT3X { constructor(i2cObj) { this.i2cInstance = i2cObj; var cmd = [0x30, 0x41]; //console.log('init cmd = ' + cmd); this.i2cInstance.write(cmd); sleepMs(20); }; getTempHumidity() { var sensorData = [0x0, 0x0]; var cmd = [0x24, 0x0b]; //console.log('get data cmd = ' + cmd); this.i2cInstance.write(cmd); sleepMs(20); var retval = this.i2cInstance.read(6); //console.log('get data retval = ' + retval); var temp = (retval[0] << 8) | (retval[1]); var humi = (retval[3] << 8) | (retval[4]); //console.log('get data temp = ' + temp); //console.log('get data humi = ' + humi); sensorData[0] = -45.0 + (temp) * 175.0 / (0xFFFF - 1); sensorData[1] = humi * 0.0015259022; //console.log('get sensorData[0] = ' + sensorData[0]); //console.log('get sensorData[1] = ' + sensorData[1]); return sensorData; }; getTemperature() { var data = this.getTempHumidity(); //console.log('getTemperature data = ' + data[0]); return data[0]; }; getHumidity() { var data = this.getTempHumidity(); //console.log('getHumidity data = ' + data[1]); return data[1]; }; } export function SHT3X(i2cObj) { return new _SHT3X(i2cObj); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/i2c/sht3x/sht3x.js
JavaScript
apache-2.0
1,339
import * as gpio from 'gpio'; import * as network from 'network'; import * as mqtt from 'mqtt'; import * as iot from 'iot'; /* open GPIO LED1 */ var LED1 = gpio.open({ id: 'led', success: function() { console.log('gpio: open LED1 success') }, fail: function() { console.log('gpio: open LED1 failed') } }); console.log('guyin: turn off led2'); var value = 1; LED1.writeValue(value); setInterval(function() { value = 1 - value; LED1.writeValue(value); }, 500); var net = network.openNetWorkClient({devType: 'wifi'}); /** * 获取网络类型 * 目前支持两种类型:wifi cellular(蜂窝网) */ var netType = net.getType(); console.log('net type is: ' + netType); /** * 获取网络状态 * 目前支持两种状态:connect disconnect */ var netStatus = net.getStatus(); console.log('net status is: ' + netStatus); if (netStatus == 'connect') { /* 网络状态已连接,获取网络状态 */ console.log('net status is connect'); iotDeviceCreate(); } else { /* wifi或者以太网,设置ifconfig */ if (netType === "wifi" || netType === "ethnet") { console.log('net setIfConfig'); net.setIfConfig({ dhcp_en: true, // true: 动态IP模式(以下参数可忽略); false: 静态IP模式(以下参数必填) ip_addr: '192.168.124.66', mask: '255.255.255.0', gw: '192.168.124.1', dns_server: '8.8.8.8' }); } /* 网络状态未连接,如果是wifi设备则主动联网(4G模组中系统会自动注网) */ if (netType === "wifi") { net.connect({ ssid: 'xxx', //请替换为自己的热点ssid password: 'xxx' //请替换为自己热点的密码 }); } /** * 监听网络连接成功事件,成功执行回调函数 */ net.on('connect', function () { console.log('network connected'); getNetInfo(); iotDeviceCreate(); }); net.on('disconnect', function () { console.log('network disconnected'); }); } function getNetInfo() { console.log('net status is connected, begin getting net information...'); var info = net.getInfo(); if (netType === "wifi" || netType === "ethnet") { /* 是否开启dhcp */ console.log('net dhcp_en is: ' + info.netInfo.dhcp_en); /* ip地址*/ console.log('net ip_addr is: ' + info.netInfo.ip_addr); /* dns */ console.log('net dns_server is: ' + info.netInfo.dns_server); /* 网关 */ console.log('net gateway is: ' + info.netInfo.gw); /* 子网掩码 */ console.log('net mask is: ' + info.netInfo.mask); /* mac地址 */ console.log('net mac is: ' + info.netInfo.mac); /* wifi信号强度 */ console.log('net wifi rssi is: ' + info.netInfo.rssi); return; } console.log('unkown net type'); } var iotdev; const productKey = 'xxx'; //请替换为自己的pk const deviceName = 'xxx'; //请替换为自己的dn const deviceSecret = 'xxx'; //请替换为自己的ds var topic = '/sys/' + productKey + '/' + deviceName + '/user/haas/info'; var lightSwitch = 0; var errCode = 0; function iotDeviceCreate() { iotdev = iot.device({ productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret }); iotdev.on('connect', function () { console.log('success connect to aliyun iot server'); iotDeviceOnConnect(); }); iotdev.on('reconnect', function () { console.log('success reconnect to aliyun iot server'); }); iotdev.on('disconnect', function () { console.log('aliyun iot server disconnected'); }); } function iotDeviceOnConnect() { iotdev.subscribe({ topic: topic, qos: 0 }); iotdev.unsubscribe(topic); iotdev.publish({ topic: topic, payload: 'haas amp perfect', qos: 1 }); setInterval(function() { lightSwitch = 1 - lightSwitch; // Post properity iotdev.postProps( JSON.stringify({ LightSwitch: lightSwitch }) ); //Post event iotdev.postEvent({ id: 'ErrorMessage', params: JSON.stringify({ ErrorCode: errCode }) }); iotdev.publish({ topic: topic, payload: 'haas amp perfect', qos: 0 }); console.log('post lightSwitch ' + lightSwitch + ', ErrorCode ' + errCode); console.log('system heapFree: ' + system.memory().heapFree); errCode++; }, 1000); iotdev.onService(function(service) { console.log('received cloud service id ' + service.service_id); console.log('received cloud service param ' + service.params); console.log('received cloud service param len ' + service.params_len); }); iotdev.onProps(function(properity) { console.log('received cloud properity param ' + properity.params); console.log('received cloud properity param len ' + properity.params_len); }); }
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/iot/iot-device/sanyuanzu/app.js
JavaScript
apache-2.0
5,156
import * as kv from 'kv' var key = 'key-test'; var value = 'this is amp kv test file'; // kv set kv.setStorageSync(key, value); // kv get var val = kv.getStorageSync(key); console.log('kv read: ' + val); // kv remove kv.removeStorageSync(key);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/kv/app.js
JavaScript
apache-2.0
248
import * as spi from 'spi'; var W25Q = spi.open({ id: "FLASH", success: function() { console.log('w25q flash open success') }, fail: function() { console.log('w25q flash open failed') } }); /** * 读取flash w25q128 的JEDEC ID值 * * @returns {objct} 返回 JEDEC 值值 */ function getJEDEC() { /* 根据w25q数据手册,读取JEDEC ID要先发送命令 [0x90, 0, 0, 0] */ var cmd = [0x90, 0, 0, 0]; /* 根据w25q数据手册,要读取的ID长度为2,因此定义长度为2的 Unit8Array,元素值可以是任意值 */ var val = [0xff, 0xff]; /* 拼接数组 为 [0x90, 0, 0, 0, 0xff, 0xff] */ var buf = cmd.concat(val); /* 发送长度为6 Byte的数据,同时读取6 Byte的数据 */ val = W25Q.readWrite(buf, buf.length); var res = {}; /* 提取制造商ID val[4] */ res.manufacturerId = "0x" + val[4].toString(16).toLocaleUpperCase(); /* 提取设备ID val[5] */ res.deviceId = "0x" + val[5].toString(16).toLocaleUpperCase(); return res; } /** * 忙等待 */ function waitReady() { /* 根据w25q数据手册,读取状态要先发送命令 0x05 */ var cmd = [0x05]; /* 根据w25q数据手册,要读取的数据长度为1,因此定义长度为1的 Unit8Array, 元素值可以是任意值 */ var val = [0]; /* 拼接数组为 [0x05, 0] */ var buf = cmd.concat(val); while (1) { val = W25Q.readWrite(buf, buf.length); if ((val[1] & 0x01) == 0x01) continue; else break; } } /** * 擦整个flash */ function eraseChip() { /* 写使能命令为 0x06 */ W25Q.write([0x06]); /* 芯片擦除命令为 0xc7 */ W25Q.write([0xc7]); /* 等待擦除完成 */ waitReady(); } var jedec = getJEDEC(); /* 正确ID为 0x17 */ console.log('ManufacturerID:', jedec.manufacturerId); /* 正确ID为 0xEF */ console.log('DeviceID:', jedec.deviceId); eraseChip();
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/spi/flash_w25q/app.js
JavaScript
apache-2.0
1,876
console.log('system versions().module is: ' + system.versions().module) console.log('system version is: ' + system.version()) console.log('system appversion is: ' + system.appversion()) console.log('system getSystemInfo().userjsVersion is: ' + system.getSystemInfo().userjsVersion) console.log('system getSystemInfo().appVersion is: ' + system.getSystemInfo().appVersion) console.log('system getSystemInfo().kernelVersion is: ' + system.getSystemInfo().kernelVersion) console.log('system getSystemInfo().systemVersion is: ' + system.getSystemInfo().systemVersion) console.log('system getSystemInfo().buildTime is: ' + system.getSystemInfo().buildTime) console.log('system getSystemInfo().hardwareVersion is: ' + system.getSystemInfo().hardwareVersion) console.log('system platform is: ' + system.platform()) console.log('system uptime is: ' + system.uptime()) console.log('system heapTotal is: ' + system.memory().heapTotal) console.log('system heapUsed is: ' + system.memory().heapUsed) console.log('system heapFree is: ' + system.memory().heapFree) console.log('system gc is: ' + system.gc()) console.log('system reboot: ' + system.reboot())
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/system/app.js
JavaScript
apache-2.0
1,144
/* 加载 timer 模块 */ import * as timer from 'timer' /* 创建 timer 实例 */ var timer0 = timer.open({ id: 'TIMER0' }); console.log('HardWare Timer Test'); /* 定义用来统计触发次数的变量 */ var count = 0; /* 定义定时到期回调函数,单次触发打印一行字符串及触发次数 */ function timeout_cb() { console.log('Timer0 Timeout count' + count); count++; } /* 设置单次定时,定时时间5000000us,回调函数打印一行字符串 */ timer0.setTimeout(timeout_cb, 5000000);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/timer/app.js
JavaScript
apache-2.0
531
import * as uart from 'uart'; import * as gpsObj from './gps.js'; var gps = gpsObj.GPS(); // gnss uart var gnss = uart.open({ id: 'serial2', success: function() { console.log('gnss open success') }, fail: function() { console.log('gnss open failed') } }); var geoLocation_data = {'lat':0, 'lon':0, 'alt':0} gps.on("data", function (parsed) { console.log(parsed); geoLocation_data['lat'] = parsed["lat"]; geoLocation_data['lon'] = parsed["lon"]; geoLocation_data['alt'] = parsed["alt"]; console.log("geo data " + JSON.stringify(geoLocation_data, null, 4)) }); function ArrayToString(fileData) { var dataString = ""; for (var i = 0; i < fileData.length; i++) { dataString += String.fromCharCode(fileData[i]); } return dataString; } var GGA; gnss.on('data', function(data, len) { console.log('gnss data = ' + data) var aaa = data; var bbb = aaa.split("$"); console.log('gnss bbb = ' + bbb) GGA = "$" + bbb[1]; console.log('gnss GGA = ' + GGA) var gga_tag = GGA.split(","); console.log('gnss gga_tag = ' + gga_tag) console.log('gnss gga_tag[0] = ' + gga_tag[0]) if (gga_tag[0] == '$GNGGA') { console.log('get GGA = ' + GGA) gps.update(GGA); } else { console.log('not get GGA = ' + GGA) } });
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/uart/gps_ht2828z3g5l/app.js
JavaScript
apache-2.0
1,344
/** * @license GPS.js v0.6.0 26/01/2016 * * Copyright (c) 2016, Robert Eisele (robert@xarg.org) * Dual licensed under the MIT or GPL Version 2 licenses. **/ (function (root) { 'use strict'; var D2R = Math.PI / 180; var collectSats = {}; var lastSeenSat = {}; function updateState(state, data) { // TODO: can we really use RMC time here or is it the time of fix? if (data['type'] === 'RMC' || data['type'] === 'GGA' || data['type'] === 'GLL' || data['type'] === 'GNS') { state['time'] = data['time']; state['lat'] = data['lat']; state['lon'] = data['lon']; } if (data['type'] === 'ZDA') { state['time'] = data['time']; } if (data['type'] === 'GGA') { state['alt'] = data['alt']; } if (data['type'] === 'RMC' /* || data['type'] === 'VTG'*/ ) { // TODO: is rmc speed/track really interchangeable with vtg speed/track? state['speed'] = data['speed']; state['track'] = data['track']; } if (data['type'] === 'GSA') { state['satsActive'] = data['satellites']; state['fix'] = data['fix']; state['hdop'] = data['hdop']; state['pdop'] = data['pdop']; state['vdop'] = data['vdop']; } if (data['type'] === 'GSV') { var now = new Date().getTime(); var sats = data['satellites']; for (var i = 0; i < sats.length; i++) { var prn = sats[i].prn; lastSeenSat[prn] = now; collectSats[prn] = sats[i]; } var ret = []; for (var prn in collectSats) { if (now - lastSeenSat[prn] < 3000) // Sats are visible for 3 seconds ret.push(collectSats[prn]) } state['satsVisible'] = ret; } } /** * * @param {String} time * @param {String=} date * @returns {Date} */ function parseTime(time, date) { if (time === '') { return null; } var ret = new Date; if (date) { var year = date.slice(4); var month = date.slice(2, 4) - 1; var day = date.slice(0, 2); if (year.length === 4) { ret.setUTCFullYear(Number(year), Number(month), Number(day)); } else { // If we need to parse older GPRMC data, we should hack something like // year < 73 ? 2000+year : 1900+year // Since GPS appeared in 1973 ret.setUTCFullYear(Number('20' + year), Number(month), Number(day)); } } ret.setUTCHours(Number(time.slice(0, 2))); ret.setUTCMinutes(Number(time.slice(2, 4))); ret.setUTCSeconds(Number(time.slice(4, 6))); // Extract the milliseconds, since they can be not present, be 3 decimal place, or 2 decimal places, or other? var msStr = time.slice(7); var msExp = msStr.length; var ms = 0; if (msExp !== 0) { ms = parseFloat(msStr) * Math.pow(10, 3 - msExp); } ret.setUTCMilliseconds(Number(ms)); return ret; } function parseCoord(coord, dir) { // Latitude can go from 0 to 90; longitude can go from -180 to 180. if (coord === '') return null; var n, sgn = 1; switch (dir) { case 'S': sgn = -1; case 'N': n = 2; break; case 'W': sgn = -1; case 'E': n = 3; break; } /* * Mathematically, but more expensive and not numerical stable: * * raw = 4807.038 * deg = Math.floor(raw / 100) * * dec = (raw - (100 * deg)) / 60 * res = deg + dec // 48.1173 */ return sgn * (parseFloat(coord.slice(0, n)) + parseFloat(coord.slice(n)) / 60); } function parseNumber(num) { if (num === '') { return null; } return parseFloat(num); } function parseKnots(knots) { if (knots === '') return null; return parseFloat(knots) * 1.852; } function parseGSAMode(mode) { switch (mode) { case 'M': return 'manual'; case 'A': return 'automatic'; case '': return null; } throw new Error('INVALID GSA MODE: ' + mode); } function parseGGAFix(fix) { if (fix === '') return null; switch (parseInt(fix, 10)) { case 0: return null; case 1: return 'fix'; // valid SPS fix case 2: return 'dgps-fix'; // valid DGPS fix case 3: return 'pps-fix'; // valid PPS fix case 4: return 'rtk'; // valid (real time kinematic) RTK fix case 5: return 'rtk-float'; // valid (real time kinematic) RTK float case 6: return 'estimated'; // dead reckoning case 7: return 'manual'; case 8: return 'simulated'; } throw new Error('INVALID GGA FIX: ' + fix); } function parseGSAFix(fix) { switch (fix) { case '1': case '': return null; case '2': return '2D'; case '3': return '3D'; } throw new Error('INVALID GSA FIX: ' + fix); } function parseRMC_GLLStatus(status) { switch (status) { case 'A': return 'active'; case 'V': return 'void'; case '': return null; } throw new Error('INVALID RMC/GLL STATUS: ' + status); } function parseFAA(faa) { // Only A and D will correspond to an Active and reliable Sentence switch (faa) { case '': return null; case 'A': return 'autonomous'; case 'D': return 'differential'; case 'E': return 'estimated'; // dead reckoning case 'M': return 'manual input'; case 'S': return 'simulated'; case 'N': return 'not valid'; case 'P': return 'precise'; case 'R': return 'rtk'; // valid (real time kinematic) RTK fix case 'F': return 'rtk-float'; // valid (real time kinematic) RTK float } throw new Error('INVALID FAA MODE: ' + faa); } function parseRMCVariation(vari, dir) { if (vari === '' || dir === '') return null; var q = (dir === 'W') ? -1.0 : 1.0; return parseFloat(vari) * q; } function isValid(str, crc) { var checksum = 0; for (var i = 1; i < str.length; i++) { var c = str.charCodeAt(i); if (c === 42) // Asterisk: * break; checksum ^= c; } return checksum === parseInt(crc, 16); } function parseDist(num, unit) { if (unit === 'M' || unit === '') { return parseNumber(num); } throw new Error('Unknown unit: ' + unit); } /** * * @constructor */ function GPS() { if (!(this instanceof GPS)) { return new GPS; } this['events'] = {}; this['state'] = { 'errors': 0, 'processed': 0 }; } GPS.prototype['events'] = null; GPS.prototype['state'] = null; GPS['mod'] = { // Global Positioning System Fix Data 'GGA': function (str, gga) { if (gga.length !== 16 && gga.length !== 14) { throw new Error("Invalid GGA length: " + str); } /* 11 1 2 3 4 5 6 7 8 9 10 | 12 13 14 15 | | | | | | | | | | | | | | | $--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh 1) Time (UTC) 2) Latitude 3) N or S (North or South) 4) Longitude 5) E or W (East or West) 6) GPS Quality Indicator, 0 = Invalid, 1 = Valid SPS, 2 = Valid DGPS, 3 = Valid PPS 7) Number of satellites in view, 00 - 12 8) Horizontal Dilution of precision, lower is better 9) Antenna Altitude above/below mean-sea-level (geoid) 10) Units of antenna altitude, meters 11) Geoidal separation, the difference between the WGS-84 earth ellipsoid and mean-sea-level (geoid), '-' means mean-sea-level below ellipsoid 12) Units of geoidal separation, meters 13) Age of differential GPS data, time in seconds since last SC104 type 1 or 9 update, null field when DGPS is not used 14) Differential reference station ID, 0000-1023 15) Checksum */ return { 'time': parseTime(gga[1]), 'lat': parseCoord(gga[2], gga[3]), 'lon': parseCoord(gga[4], gga[5]), 'alt': parseDist(gga[9], gga[10]), 'quality': parseGGAFix(gga[6]), 'satellites': parseNumber(gga[7]), 'hdop': parseNumber(gga[8]), // dilution 'geoidal': parseDist(gga[11], gga[12]), // aboveGeoid 'age': gga[13] === undefined ? null : parseNumber(gga[13]), // dgps time since update 'stationID': gga[14] === undefined ? null : parseNumber(gga[14]) // dgpsReference?? }; }, // GPS DOP and active satellites 'GSA': function (str, gsa) { if (gsa.length !== 19 && gsa.length !== 20) { throw new Error('Invalid GSA length: ' + str); } /* eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35 1 = Mode: M=Manual, forced to operate in 2D or 3D A=Automatic, 3D/2D 2 = Mode: 1=Fix not available 2=2D 3=3D 3-14 = PRNs of Satellite Vehicles (SVs) used in position fix (null for unused fields) 15 = PDOP 16 = HDOP 17 = VDOP (18) = systemID NMEA 4.10 18 = Checksum */ var sats = []; for (var i = 3; i < 15; i++) { if (gsa[i] !== '') { sats.push(parseInt(gsa[i], 10)); } } return { 'mode': parseGSAMode(gsa[1]), 'fix': parseGSAFix(gsa[2]), 'satellites': sats, 'pdop': parseNumber(gsa[15]), 'hdop': parseNumber(gsa[16]), 'vdop': parseNumber(gsa[17]), 'systemId': gsa.length > 19 ? parseNumber(gsa[18]) : null }; }, // Recommended Minimum data for gps 'RMC': function (str, rmc) { if (rmc.length !== 13 && rmc.length !== 14 && rmc.length !== 15) { throw new Error('Invalid RMC length: ' + str); } /* $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh RMC = Recommended Minimum Specific GPS/TRANSIT Data 1 = UTC of position fix 2 = Data status (A-ok, V-invalid) 3 = Latitude of fix 4 = N or S 5 = Longitude of fix 6 = E or W 7 = Speed over ground in knots 8 = Track made good in degrees True 9 = UT date 10 = Magnetic variation degrees (Easterly var. subtracts from true course) 11 = E or W (12) = NMEA 2.3 introduced FAA mode indicator (A=Autonomous, D=Differential, E=Estimated, N=Data not valid) (13) = NMEA 4.10 introduced nav status 12 = Checksum */ return { 'time': parseTime(rmc[1], rmc[9]), 'status': parseRMC_GLLStatus(rmc[2]), 'lat': parseCoord(rmc[3], rmc[4]), 'lon': parseCoord(rmc[5], rmc[6]), 'speed': parseKnots(rmc[7]), 'track': parseNumber(rmc[8]), // heading 'variation': parseRMCVariation(rmc[10], rmc[11]), 'faa': rmc.length > 13 ? parseFAA(rmc[12]) : null, 'navStatus': rmc.length > 14 ? rmc[13] : null }; }, // Track info 'VTG': function (str, vtg) { if (vtg.length !== 10 && vtg.length !== 11) { throw new Error('Invalid VTG length: ' + str); } /* ------------------------------------------------------------------------------ 1 2 3 4 5 6 7 8 9 10 | | | | | | | | | | $--VTG,x.x,T,x.x,M,x.x,N,x.x,K,m,*hh<CR><LF> ------------------------------------------------------------------------------ 1 = Track made good (degrees true) 2 = Fixed text 'T' indicates that track made good is relative to true north 3 = optional: Track made good (degrees magnetic) 4 = optional: M: track made good is relative to magnetic north 5 = Speed over ground in knots 6 = Fixed text 'N' indicates that speed over ground in in knots 7 = Speed over ground in kilometers/hour 8 = Fixed text 'K' indicates that speed over ground is in kilometers/hour (9) = FAA mode indicator (NMEA 2.3 and later) 9/10 = Checksum */ if (vtg[2] === '' && vtg[8] === '' && vtg[6] === '') { return { 'track': null, 'trackMagetic': null, 'speed': null, 'faa': null }; } if (vtg[2] !== 'T') { throw new Error('Invalid VTG track mode: ' + str); } if (vtg[8] !== 'K' || vtg[6] !== 'N') { throw new Error('Invalid VTG speed tag: ' + str); } return { 'track': parseNumber(vtg[1]), // heading 'trackMagnetic': vtg[3] === '' ? null : parseNumber(vtg[3]), // heading uncorrected to magnetic north 'speed': parseKnots(vtg[5]), 'faa': vtg.length === 11 ? parseFAA(vtg[9]) : null }; }, // satellites in view 'GSV': function (str, gsv) { if (gsv.length % 4 % 3 === 0) { throw new Error('Invalid GSV length: ' + str); } /* $GPGSV,1,1,13,02,02,213,,03,-3,000,,11,00,121,,14,13,172,05*67 1 = Total number of messages of this type in this cycle 2 = Message number 3 = Total number of SVs in view repeat [ 4 = SV PRN number 5 = Elevation in degrees, 90 maximum 6 = Azimuth, degrees from true north, 000 to 359 7 = SNR (signal to noise ratio), 00-99 dB (null when not tracking, higher is better) ] N+1 = signalID NMEA 4.10 N+2 = Checksum */ var sats = []; for (var i = 4; i < gsv.length - 3; i += 4) { var prn = parseNumber(gsv[i]); var snr = parseNumber(gsv[i + 3]); /* Plot satellites in Radar chart with north on top by linear map elevation from 0° to 90° into r to 0 centerX + cos(azimuth - 90) * (1 - elevation / 90) * radius centerY + sin(azimuth - 90) * (1 - elevation / 90) * radius */ sats.push({ 'prn': prn, 'elevation': parseNumber(gsv[i + 1]), 'azimuth': parseNumber(gsv[i + 2]), 'snr': snr, 'status': prn !== null ? (snr !== null ? 'tracking' : 'in view') : null }); } return { 'msgNumber': parseNumber(gsv[2]), 'msgsTotal': parseNumber(gsv[1]), //'satsInView' : parseNumber(gsv[3]), // Can be obtained by satellites.length 'satellites': sats, 'signalId': gsv.length % 4 === 2 ? parseNumber(gsv[gsv.length - 2]) : null // NMEA 4.10 addition }; }, // Geographic Position - Latitude/Longitude 'GLL': function (str, gll) { if (gll.length !== 9 && gll.length !== 8) { throw new Error('Invalid GLL length: ' + str); } /* ------------------------------------------------------------------------------ 1 2 3 4 5 6 7 8 | | | | | | | | $--GLL,llll.ll,a,yyyyy.yy,a,hhmmss.ss,a,m,*hh<CR><LF> ------------------------------------------------------------------------------ 1. Latitude 2. N or S (North or South) 3. Longitude 4. E or W (East or West) 5. Universal Time Coordinated (UTC) 6. Status A - Data Valid, V - Data Invalid 7. FAA mode indicator (NMEA 2.3 and later) 8. Checksum */ return { 'time': parseTime(gll[5]), 'status': parseRMC_GLLStatus(gll[6]), 'lat': parseCoord(gll[1], gll[2]), 'lon': parseCoord(gll[3], gll[4]), 'faa': gll.length === 9 ? parseFAA(gll[7]) : null }; }, // UTC Date / Time and Local Time Zone Offset 'ZDA': function (str, zda) { /* 1 = hhmmss.ss = UTC 2 = xx = Day, 01 to 31 3 = xx = Month, 01 to 12 4 = xxxx = Year 5 = xx = Local zone description, 00 to +/- 13 hours 6 = xx = Local zone minutes description (same sign as hours) */ // TODO: incorporate local zone information return { 'time': parseTime(zda[1], zda[2] + zda[3] + zda[4]) //'delta': time === null ? null : (Date.now() - time) / 1000 }; }, 'GST': function (str, gst) { if (gst.length !== 10) { throw new Error('Invalid GST length: ' + str); } /* 1 = Time (UTC) 2 = RMS value of the pseudorange residuals; includes carrier phase residuals during periods of RTK (float) and RTK (fixed) processing 3 = Error ellipse semi-major axis 1 sigma error, in meters 4 = Error ellipse semi-minor axis 1 sigma error, in meters 5 = Error ellipse orientation, degrees from true north 6 = Latitude 1 sigma error, in meters 7 = Longitude 1 sigma error, in meters 8 = Height 1 sigma error, in meters 9 = Checksum */ return { 'time': parseTime(gst[1]), 'rms': parseNumber(gst[2]), 'ellipseMajor': parseNumber(gst[3]), 'ellipseMinor': parseNumber(gst[4]), 'ellipseOrientation': parseNumber(gst[5]), 'latitudeError': parseNumber(gst[6]), 'longitudeError': parseNumber(gst[7]), 'heightError': parseNumber(gst[8]) }; }, // add HDT 'HDT': function (str, hdt) { if (hdt.length !== 4) { throw new Error('Invalid HDT length: ' + str); } /* ------------------------------------------------------------------------------ 1 2 3 | | | $--HDT,hhh.hhh,T*XX<CR><LF> ------------------------------------------------------------------------------ 1. Heading in degrees 2. T: indicates heading relative to True North 3. Checksum */ return { 'heading': parseFloat(hdt[1]), 'trueNorth': hdt[2] === 'T' }; }, 'GRS': function (str, grs) { if (grs.length !== 18) { throw new Error('Invalid GRS length: ' + str); } var res = []; for (var i = 3; i <= 14; i++) { var tmp = parseNumber(grs[i]); if (tmp !== null) res.push(tmp); } return { 'time': parseTime(grs[1]), 'mode': parseNumber(grs[2]), 'res': res }; }, 'GBS': function (str, gbs) { if (gbs.length !== 10 && gbs.length !== 12) { throw new Error('Invalid GBS length: ' + str); } /* 0 1 2 3 4 5 6 7 8 | | | | | | | | | $--GBS,hhmmss.ss,x.x,x.x,x.x,x.x,x.x,x.x,x.x*hh<CR><LF> 1. UTC time of the GGA or GNS fix associated with this sentence 2. Expected error in latitude (meters) 3. Expected error in longitude (meters) 4. Expected error in altitude (meters) 5. PRN (id) of most likely failed satellite 6. Probability of missed detection for most likely failed satellite 7. Estimate of bias in meters on most likely failed satellite 8. Standard deviation of bias estimate -- 9. systemID (NMEA 4.10) 10. signalID (NMEA 4.10) */ return { 'time': parseTime(gbs[1]), 'errLat': parseNumber(gbs[2]), 'errLon': parseNumber(gbs[3]), 'errAlt': parseNumber(gbs[4]), 'failedSat': parseNumber(gbs[5]), 'probFailedSat': parseNumber(gbs[6]), 'biasFailedSat': parseNumber(gbs[7]), 'stdFailedSat': parseNumber(gbs[8]), 'systemId': gbs.length === 12 ? parseNumber(gbs[9]) : null, 'signalId': gbs.length === 12 ? parseNumber(gbs[10]) : null }; }, 'GNS': function (str, gns) { if (gns.length !== 14 && gns.length !== 15) { throw new Error('Invalid GNS length: ' + str); } return { 'time': parseTime(gns[1]), 'lat': parseCoord(gns[2], gns[3]), 'lon': parseCoord(gns[4], gns[5]), 'mode': gns[6], 'satsUsed': parseNumber(gns[7]), 'hdop': parseNumber(gns[8]), 'alt': parseNumber(gns[9]), 'sep': parseNumber(gns[10]), 'diffAge': parseNumber(gns[11]), 'diffStation': parseNumber(gns[12]), 'navStatus': gns.length === 15 ? gns[13] : null // NMEA 4.10 }; } }; GPS['Parse'] = function (line) { if (typeof line !== 'string') return false; var nmea = line.split(','); var last = nmea.pop(); // HDT is 2 items length if (nmea.length < 2 || line.charAt(0) !== '$' || last.indexOf('*') === -1) { return false; } last = last.split('*'); nmea.push(last[0]); nmea.push(last[1]); // Remove $ character and first two chars from the beginning nmea[0] = nmea[0].slice(3); if (GPS['mod'][nmea[0]] !== undefined) { // set raw data here as well? var data = this['mod'][nmea[0]](line, nmea); data['raw'] = line; data['valid'] = isValid(line, nmea[nmea.length - 1]); data['type'] = nmea[0]; return data; } return false; }; // Heading (N=0, E=90, S=189, W=270) from point 1 to point 2 GPS['Heading'] = function (lat1, lon1, lat2, lon2) { var dlon = (lon2 - lon1) * D2R; lat1 = lat1 * D2R; lat2 = lat2 * D2R; var sdlon = Math.sin(dlon); var cdlon = Math.cos(dlon); var slat1 = Math.sin(lat1); var clat1 = Math.cos(lat1); var slat2 = Math.sin(lat2); var clat2 = Math.cos(lat2); var y = sdlon * clat2; var x = clat1 * slat2 - slat1 * clat2 * cdlon; var head = Math.atan2(y, x) * 180 / Math.PI; return (head + 360) % 360; }; GPS['Distance'] = function (lat1, lon1, lat2, lon2) { // Haversine Formula // R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159 // Because Earth is no exact sphere, rounding errors may be up to 0.5%. // var RADIUS = 6371; // Earth radius average // var RADIUS = 6378.137; // Earth radius at equator var RADIUS = 6372.8; // Earth radius in km var hLat = (lat2 - lat1) * D2R * 0.5; // Half of lat difference var hLon = (lon2 - lon1) * D2R * 0.5; // Half of lon difference lat1 = lat1 * D2R; lat2 = lat2 * D2R; var shLat = Math.sin(hLat); var shLon = Math.sin(hLon); var clat1 = Math.cos(lat1); var clat2 = Math.cos(lat2); var tmp = shLat * shLat + clat1 * clat2 * shLon * shLon; //return RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a)); return RADIUS * 2 * Math.asin(Math.sqrt(tmp)); }; GPS['TotalDistance'] = function (path) { if (path.length < 2) return 0; var len = 0; for (var i = 0; i < path.length - 1; i++) { var c = path[i]; var n = path[i + 1]; len += GPS['Distance'](c['lat'], c['lon'], n['lat'], n['lon']); } return len; }; GPS.prototype['update'] = function (line) { var parsed = GPS['Parse'](line); this['state']['processed']++; if (parsed === false) { this['state']['errors']++; return false; } updateState(this['state'], parsed); this['emit']('data', parsed); this['emit'](parsed.type, parsed); return true; }; GPS.prototype['partial'] = ""; GPS.prototype['updatePartial'] = function (chunk) { this['partial'] += chunk; while (true) { var pos = this['partial'].indexOf("\r\n"); if (pos === -1) break; var line = this['partial'].slice(0, pos); if (line.charAt(0) === '$') { this['update'](line); } this['partial'] = this['partial'].slice(pos + 2); } }; GPS.prototype['on'] = function (ev, cb) { if (this['events'][ev] === undefined) { this['events'][ev] = cb; return this; } return null; }; GPS.prototype['off'] = function (ev) { if (this['events'][ev] !== undefined) { this['events'][ev] = undefined; } return this; }; GPS.prototype['emit'] = function (ev, data) { if (this['events'][ev] !== undefined) { this['events'][ev].call(this, data); } }; if (typeof exports === 'object') { Object.defineProperty(exports, "__esModule", { 'value': true }); GPS['default'] = GPS; GPS['GPS'] = GPS; module['exports'] = GPS; } else { root['GPS'] = GPS; } })(this);
YifuLiu/AliOS-Things
components/amp/example-js/ESP32/jsapi/uart/gps_ht2828z3g5l/gps.js
JavaScript
apache-2.0
24,533
var adc = require('adc'); var vol = adc.open({ id: 'adc1', success: function() { console.log('adc: open adc success') }, fail: function() { console.log('adc: open adc failed') } }); setInterval(function() { console.log('adc: adc value ' + vol.readValue()) }, 2000);
YifuLiu/AliOS-Things
components/amp/example-js/common/adc.js
JavaScript
apache-2.0
291
var at = require('at'); function atTestCallback() { var s = at.atReadLine(-1); /* 从AT串口读一行字符串,参数为读字符串超时时间(单位毫秒,-1表示一直等待) */ at.atSendNoReply("AT+TEST value is " + s.toString() + "\n", 1); /* 发送响应命令,参数分别为: 响应字符串,是否发送命令间隔符 */ } function atWlogpCallback() { var s = at.atRead(1, -1); /* 从AT串口读字符串,第一个参数为读取字符串的长度, 第二个参数为读字符串超时时间(单位毫秒,-1表示一直等待) */ if (s.toString() == '?') { at.atSendNoReply('log print is open \n', 1); } else if (s.toString() == '=') { var log = at.atRead(1, -1); if (log.toString() == '1') { at.atSendNoReply('open log print \n', 1); } else if (log.toString() == '0') { at.atSendNoReply('close log print \n', 1); } else { at.atSendNoReply('AT Command error\n', 1); } } else { at.atSendNoReply('AT Command error\n', 1); } } at.atInit(3, 115200, '\r\n') /* 初始化at功能,参数分别为: uart端口号、波特率、命令间隔字符串 */ at.atSetEcho(1) /* 设置是否显示回显:0表示关闭回显,1表示打开回显 */ at.atRegisterCmdCallback('AT+TEST=', atTestCallback) /* 注册AT命令,参数分别为: AT命令字符串,回调函数 */ at.atRegisterCmdCallback('AT*WLOGP', atWlogpCallback) /* AT命令运行期间,REPL需要设置为disable,在app.json中增加: "repl": "disable" */
YifuLiu/AliOS-Things
components/amp/example-js/common/at.js
JavaScript
apache-2.0
1,612
import * as bt_host from 'bt_host' function onConnect() { // onConnect console.log('bt_host onConnect'); } function onDisconnect() { // onDisconnect console.log('bt_host onDisconnect'); app_start_adv(); } function app_add_service() { let service = { service: "{\ \"s_uuid\":\"0x1A1A\",\ \"chars_list\":[\ {\ \"char_uuid\":\"0x1B1B\",\ \"char_permit\":\"RW\",\ \"char_descr\":{\ \"descr_type\":\"CCC\",\ \"descr_uuid\":\"0x1C1C\"\ }\ },\ {\ \"char_uuid\":\"0x1D1D\",\ \"char_permit\":\"R\"\ }\ ]\ }" } bt_host_instant.add_service(service); } function app_start_adv() { bt_host_instant.start_adv({ type: 0, adv_data: '020106', scan_rsp_data: '', interval_min: 160, interval_max: 320, channel_map: 7, success: function() { console.log('bt_host start adv success'); setTimeout( function() { app_stop_adv(); }, 30000) }, failed: function() { console.log('bt_host start adv failed'); }, }); } function app_stop_adv() { bt_host_instant.stop_adv({ success: function() { console.log('bt_host stop adv success'); setTimeout( function() { app_start_scan(); }, 2000) }, failed: function() { console.log('bt_host stop adv failed'); }, }); } function app_start_scan() { bt_host_instant.start_scan({ type: 0, interval: 200, window: 50, success: function() { console.log('bt_host start scan success'); setTimeout( function() { app_stop_scan(); }, 10000) }, failed: function() { console.log('bt_host stop scan failed'); }, }); } function app_stop_scan() { bt_host_instant.stop_scan({ success: function() { console.log('bt_host stop scan success'); setTimeout( function() { app_start_adv(); }, 2000) }, failed: function() { console.log('bt_host stop scan failed'); }, }); } // create bt host var bt_host_instant = bt_host.open({ deviceName: 'ble_test', conn_num_max: 2, success: function() { console.log('bt_host init success'); setTimeout(() => { app_add_service() app_start_adv(); }, 1000) // app_start_adv(); }, fail: function() { console.log('bt_host init failed'); } }); bt_host_instant.on('connect', function() { onConnect(); }); bt_host_instant.on('disconnect', function() { onDisconnect(); }); bt_host_instant.on('onCharWrite', function() { console.log('app: onCharWrite'); });
YifuLiu/AliOS-Things
components/amp/example-js/common/bt_host.js
JavaScript
apache-2.0
2,597
var network = require('network'); var netinfo = network.openNetWorkClient(); /** 获取网络类型 * 目前支持两种类型:wifi cellular(蜂窝网) */ var type = netinfo.getType(); console.log('net type is: ' + type); /** 获取网络状态 * 目前支持两种状态:connect disconnect(蜂窝网) */ var status = netinfo.getStatus(); console.log('net status is: ' + status); var info = netinfo.getInfo(); /* imsi 国际移动用户识别码 */ console.log('net imsi is: ' + info.imsi); /* imei 国际移动设备识别码 */ console.log('net imei is: ' + info.imei); /* iccid 集成电路卡识别码 */ console.log('net iccid is: ' + info.iccid); /* cid 基站编号 */ console.log('net cid is: ' + info.cid); /* lac 位置区域码 */ console.log('net lac is: ' + info.lac); /* mcc 移动国家代码(中国的为460 */ console.log('net mcc is: ' + info.mcc); /* mnc 移动网络号码(中国移动为00,中国联通为01) */ console.log('net mnc is: ' + info.mnc); /* rssi 接收的信号强度值 */ console.log('net rssi is: ' + info.rssi);
YifuLiu/AliOS-Things
components/amp/example-js/common/cellular.js
JavaScript
apache-2.0
1,082
import * as checksum from 'checksum' import * as crypto from 'crypto' function crypto_test() { let enc_param = { 'key': '000102030405060708090a0b0c0d0e0f', 'in': '3132333435363738' } let enc_result = crypto.encrypt(enc_param); console.log('encrypt:'+enc_result) let dec_param = { 'key': '000102030405060708090a0b0c0d0e0f', 'in': enc_result } let dec_result = crypto.decrypt(dec_param); console.log('decrypt:'+dec_result) } function checksum_test() { let check_param = { 'src': '000102030405060708090a0b0c0d0e0f' } let crc16_result = checksum.crc16(check_param); console.log('crc16:'+crc16_result) let crc32_result = checksum.crc32(check_param); console.log('crc32:'+crc32_result) let md5 = checksum.md5(check_param); console.log('md5:'+md5) } //checksum_test() crypto_test()
YifuLiu/AliOS-Things
components/amp/example-js/common/crypto.js
JavaScript
apache-2.0
817
var dac = require('dac'); // led灯 var vol = dac.open({ id: 'light', success: function() { console.log('open dac success') }, fail: function() { console.log('open dac failed') } }); vol.writeValue(65536 / 2) var value = vol.readValue(); console.log('voltage value is ' + value) vol.close();
YifuLiu/AliOS-Things
components/amp/example-js/common/dac.js
JavaScript
apache-2.0
314
var event = require('events'); // console.log(event) var uartInstance = new event.EventEmitter(); uartInstance.on('data', function(arg, arg2) { console.log('uart event: ', arg, arg2); }) setInterval(function() { uartInstance.emit('data', 'this is uart data', 'data 2'); }, 1000);
YifuLiu/AliOS-Things
components/amp/example-js/common/events.js
JavaScript
apache-2.0
292
var fs = require('fs'); var path = './test.data'; var file_content = 'this is amp fs test file'; // write file fs.writeSync(path, file_content); // read file var data = fs.readSync(path); console.log('fs read: ' + data); fs.unlinkSync(path);
YifuLiu/AliOS-Things
components/amp/example-js/common/fs.js
JavaScript
apache-2.0
245
// import * as iot from 'iot' import * as iot from 'gateway' var productKey = 'a17rAb1ltpS'; var deviceName = '123454'; var deviceSecret = 'abf0028f3d7ccf2b9c555826f32381d8'; var lightSwitch = 0; var gateway; var subdev = [ { productKey: 'a1zK6eTWoZO', deviceName: 'test101', deviceSecret: 'caf25b3839a24a772be3d386f6c5bd74' }, { productKey: 'a1zK6eTWoZO', deviceName: 'test100', deviceSecret: '253ab8d388094c0087c4c9a2c58b7373' } ]; /* post property */ function postProperty(id, devInfo, content) { var topic = '/sys/' + devInfo.productKey + '/' + devInfo.deviceName + '/thing/event/property/post'; var payload = JSON.stringify({ id: id, version: '1.0', params: content, method: 'thing.event.property.post' }); gateway.publish({ topic: topic, payload: payload, qos: 1 }); } /* post event */ function postEvent(id, devInfo, eventId, content) { var topic = '/sys/' + devInfo.productKey + '/' + devInfo.deviceName + '/thing/event/' + eventId + '/post'; var payload = JSON.stringify({ id: id, version: '1.0', params: content, method: 'thing.event.' + eventId + '.post' }); gateway.publish({ topic: topic, payload: payload, qos: 1 }); } function createGateway() { gateway = iot.gateway({ productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret }); gateway.on('connect', function () { console.log('(re)connected'); // gateway.addTopo(subdev); gateway.login(subdev); setTimeout(function () { postProperty(1, subdev[0], { 'PowerSwitch_1': lightSwitch }); postEvent(1, subdev[0], 'Error', { 'ErrorCode': 0 }); }, 2000); }); /* 网络断开事件 */ gateway.on('disconnect', function () { console.log('disconnect '); }); /* mqtt消息 */ gateway.on('message', function (res) { /* 通过 topic中的pk和dn信息,判断是对哪个子设备的调用 */ var pk = res.topic.split('/')[2]; var dn = res.topic.split('/')[3]; console.log('mqtt message') console.log('mqtt topic is ' + res.topic); console.log('PK: ' + pk) console.log('DN: ' + dn) console.log('mqtt payload is ' + res.payload); }) /* 关闭连接事件 */ gateway.on('end', function () { console.log('iot client just closed'); }); /* 发生错误事件 */ gateway.on('error', function (err) { console.log('error ' + err); }); } console.log('====== create aiot gateway ======'); createGateway();
YifuLiu/AliOS-Things
components/amp/example-js/common/gateway.js
JavaScript
apache-2.0
2,743
var gpio = require('gpio'); var led = gpio.open({ id: 'led', success: function() { console.log('gpio: open led success') }, fail: function() { console.log('gpio: open led failed') } }); var key = gpio.open({ id: 'key', success: function() { console.log('gpio: open key success') }, fail: function() { console.log('gpio: open key failed') } }); var vol = 0; var irqCnt = 0; key.onIRQ({ cb: function() { irqCnt = irqCnt + 1; console.log('gpio: irq count ' + irqCnt); vol = 1 - vol; led.writeValue(vol); console.log('gpio: led set value ' + vol); vol = led.readValue(); console.log('gpio: led get value ' + vol); } }); console.log('gpio: ready to test')
YifuLiu/AliOS-Things
components/amp/example-js/common/gpio.js
JavaScript
apache-2.0
713
console.log('http: testing http...'); var http = require('http'); if (!(http && http.request)) { throw new Error("http: [failed] require(\'http\')"); } console.log('http: [success] require(\'http\')'); // request GET example var request_url = 'http://appengine.oss-cn-hangzhou.aliyuncs.com/httpTest.txt'; var defaultMessage = 'this is AMP HTTP test file'; http.request({ url: request_url, method: 'GET', headers: { 'content-type':'application/json' }, success: function (data) { console.log('http: [debug] receive data is ' + data); if(data === defaultMessage) { console.log('http: [success] http.request'); } } }); // request POST example // http.request({ // url: 'https://www.ixigua.com/tlb/comment/article/v5/tab_comments/', // method: 'POST', // headers: { // 'content-type':'application/x-www-form-urlencoded' // }, // params: 'tab_index=0&count=3&group_id=6914830518563373582&item_id=6914830518563373581&aid=1768', // success: function (data) { // console.log('http: [debug] receive data is ' + data); // } // }); // download example // http.download({ // url:'http://wangguan-498.oss-cn-beijing.aliyuncs.com/SHOPAD/public/mould5.png', // filepath:'/data/http_download_test.png', // success: function (data) { // console.log('http: [debug] downlad is ' + data); // } // });
YifuLiu/AliOS-Things
components/amp/example-js/common/http.js
JavaScript
apache-2.0
1,397
var i2c = require('i2c'); var memaddr = 0x18 var msgbuf = [0x10, 0xee] // led灯 var sensor = i2c.open({ id: 'sensor', success: function() { console.log('open i2c success') }, fail: function() { console.log('open i2c failed') } }); sensor.write(msgbuf) var value = sensor.read(2) console.log('sensor value is ' + value) sensor.writeMem(memaddr, msgbuf) var vol = sensor.readMem(memaddr, 2) console.log('sensor read mem vol is ' + vol) sensor.close();
YifuLiu/AliOS-Things
components/amp/example-js/common/i2c.js
JavaScript
apache-2.0
476
import * as iot from 'iot' var productKey = 'a1MOapE3PH8'; /* your productKey */ var deviceName = 'FjWNmTsPWfPSykfkBv1l'; /* your deviceName */ var deviceSecret = '2a6afba08a135efda3c49e4cc7684254'; /* your deviceSecret */ var device ; var topic = '/sys/' + productKey + '/' + deviceName + '/user/haas/info'; function createDevice() { device = iot.device({ productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', }); device.on('connect', function () { console.log('(re)connected'); device.subscribe({ topic: topic, qos: 0 }); device.unsubscribe({ topic: topic }); device.publish({ topic: topic, payload: 'haas haas haas', qos: 1 }); var lightswitch = 0; var eventid = 'alarmEvent'; setInterval(function () { if (lightswitch) { lightswitch = 0; } else { lightswitch = 1; } /* post props */ var propertyPayload = JSON.stringify({ LightSwitch: lightswitch }); device.postProps({ payload: propertyPayload }); /* post event */ var eventPayload = JSON.stringify({ alarmType: 0 }); device.postEvent({ id: eventid, params: eventPayload }); }, 3000); /* 云端设置属性事件 */ device.onProps(function (res) { console.log('cloud req msg_id is ' + res.msg_id); console.log('cloud req params_len is ' + res.params_len); console.log('cloud req params is ' + res.params); }); /* 云端下发服务事件 */ device.onService(function (res) { console.log('received cloud msg_id is ' + res.msg_id); console.log('received cloud service_id is ' + res.service_id); console.log('received cloud params_len is ' + res.params_len); console.log('received cloud params is ' + res.params); }); }); } console.log('====== create aiot device ======'); createDevice();
YifuLiu/AliOS-Things
components/amp/example-js/common/iot.js
JavaScript
apache-2.0
2,092
var mqtt = require('mqtt'); function ArrayToString(fileData) { var dataString = ""; for (var i = 0; i < fileData.length; i++) { dataString += String.fromCharCode(fileData[i]); } return dataString; } function onConnect() { // subscribe mqttClient.subscribe({ topic: '/hello', success: function() { console.log('subscribe [/hello] success'); } }); // publish setInterval(function () { mqttClient.publish({ topic: '/hello', message: 'this is AMP mqtt test', success: function() { console.log('publish [/hello] success'); } }); }, 2 * 1000); } // create mqtt client var mqttClient = mqtt.createClient({ host: 'mqtt.eclipse.org', port: 1883, username: 'aiot', password: '123', success: function() { console.log('mqtt connected'); }, fail: function() { console.log('mqtt connect failed'); } }); mqttClient.on('connect', function() { console.log('mqtt connected'); onConnect(); }); mqttClient.on('message', function(topic, payload) { console.log('[' + topic + '] message: ' + ArrayToString(payload)); });
YifuLiu/AliOS-Things
components/amp/example-js/common/mqtt.js
JavaScript
apache-2.0
1,187
var appota = require('appota'); var iot = require('iot'); /* device info */ var productKey = ''; /* your productKey */ var deviceName = ''; /* your deviceName */ var deviceSecret = ''; /* your deviceSecret */ var module_name = 'default'; var default_ver = '1.0.0'; var ota; var status; /* download info */ var info = { url: '', store_path: '/data/jsamp/pack.bin', install_path: '/data/jsamp/', length: 0, hashType: '', hash: '' } var device = iot.device({ productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret }); device.on('connect', function(iot_res) { console.log('device connected'); var iotDeviceHandle = device.getDeviceHandle(); ota = appota.open(iotDeviceHandle); console.log('report default module ver'); ota.report({ device_handle: iotDeviceHandle, product_key: productKey, device_name: deviceName, module_name: module_name, version: default_ver }); ota.on('new', function(res) { console.log('length is ' + res.length); console.log('module_name is ' + res.module_name); console.log('version is ' + res.version); console.log('url is ' + res.url); console.log('hash is ' + res.hash); console.log('hash_type is ' + res.hash_type); info.url = res.url; info.length = res.length; info.module_name = res.module_name; info.version = res.version; info.hash = res.hash; info.hashType = res.hash_type; ota.download({ url: info.url, store_path: info.store_path }, function(res) { if (res >= 0) { console.log('download success'); console.log('verify start'); console.log(info.hashType); ota.verify({ length: info.length, hash_type: info.hashType, hash: info.hash, store_path: info.store_path }, function(res) { if (res >= 0) { console.log('verify success'); console.log('upgrade start'); ota.upgrade({ length: info.length, store_path: info.store_path, install_path: info.install_path }, function(res) { if (res >= 0) { console.log('upgrade success') } else { console.log('upgrade failed') } }) } else { console.log('verify failed'); } }) } else { console.log('download failed'); } }); }); })
YifuLiu/AliOS-Things
components/amp/example-js/common/ota.js
JavaScript
apache-2.0
2,258
console.log(Promise); function test_setTimeout() { return new Promise(function (resolve, reject) { console.log('=================setTimeout'); setTimeout(function () { console.log('=================setTimeout---------------done'); resolve(""); }, 1000); }); } function test_http() { return new Promise(function (resolve, reject) { console.log('=================http'); HTTP.request("http://appengine.oss-cn-hangzhou.aliyuncs.com/httpTest.txt", function(data){ resolve(data); }); }); } test_setTimeout() .then(function(){ // setInterval异步测试返回 return test_http(); }) .then(function(data){ // http异步测试返回 console.log("接收到 HTTP 数据:", data); });
YifuLiu/AliOS-Things
components/amp/example-js/common/promise.js
JavaScript
apache-2.0
794