Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / dtoa / atod.lucb

#==============================================================================================
#
#   atod - Text to float64: js_atod
#
#   DESCRIPTION:
#       Port of QuickJS dtoa.c lines 1354-1620: to_digit, mpb_mul1_base and js_atod
#       (prefixes, legacy octal, digit separators, radix exponents, exact rounding).
#       C's gotos become an inner function answering the result bits, or none for `fail`.
#
#==============================================================================================

# mark: Digits ==================================================================================

import memory

func to_digit(c: u8) -> i32:
    if c >= '0' and c <= '9':
        return (i32)(c - '0')
    elif c >= 'A' and c <= 'Z':
        return (i32)(c - 'A') + 10
    elif c >= 'a' and c <= 'z':
        return (i32)(c - 'a') + 10
    else:
        return 36

# r = r * radix_base + a. radix_base = 0 means radix_base = 2^32
func mpb_mul1_base(r: Mpb*, radix_base: u32, a: u32):
    let tab = mpb_tab(r)
    if tab[0] == 0 and r.len == 1:
        tab[0] = a
    else:
        if radix_base == 0:
            var i = r.len
            while i >= 0:
                tab[(usize)(i + 1)] = tab[(usize)i]
                i -= 1
            tab[0] = a
        else:
            tab[(usize)r.len] = mp_mul1(tab, tab, (u32)r.len, radix_base, a)
        r.len += 1
        mpb_renorm(r)

# mark: js_atod =================================================================================

## Parse a number from the NUL-terminated `text` in `radix` (0 means 10 with an optional
## 0x prefix, or the prefixes `flags` allow) and answer it, NaN when there is no number. When
## `pnext` is given, `*pnext` is set to the first byte after what was parsed. Leading spaces
## are not skipped. `flags` are the `atod_*` values.
pub func js_atod(text: const u8*, pnext: const u8**?, radix: i32, flags: i32,
                 tmp_mem: ATODTempMem*) -> f64:
    let (bits, p) = atod_bits(text, radix, flags, tmp_mem)
    var dval: f64
    if let a = bits:
        dval = cutils.uint64_as_float64(a)
    else:
        # fail:
        dval = cutils.uint64_as_float64(0x7ff8000000000000)  # NAN
    # done1:
    if let next = pnext:
        *next = p
    return dval

# The body of js_atod: answers the bits of the result, or none (C's `fail`: NaN), and
# where parsing stopped. C's `overflow`, `underflow` and `done` labels return from here.
func atod_bits(text: const u8*, radix0: i32, flags: i32,
               tmp_mem: ATODTempMem*) -> (u64?, const u8*):
    var mptr: u64* = &tmp_mem.mem[0]
    let tmp0 = (Mpb*)dtoa_malloc(&mptr, memory.size_of(Mpb) + memory.size_of(u32) * dbignum_len_max)
    assert((mptr - &tmp_mem.mem[0]) <= (isize)(memory.size_of(ATODTempMem) // memory.size_of(u64)))
    let tab = mpb_tab(tmp0)
    let infinity: u64 = (u64)0x7ff << 52
    var radix = radix0
    # optional separator between digits
    var sep: i32 = (i32)'_' if (flags & atod_accept_underscores) != 0 else 256

    var p = text
    var is_neg: u64 = 0
    if p[0] == '+':
        p += 1
    elif p[0] == '-':
        is_neg = 1
        p += 1
    let p_start = p

    if p[0] == '0':
        var has_prefix = true
        if (p[1] == 'x' or p[1] == 'X') and (radix == 0 or radix == 16):
            p += 2
            radix = 16
        elif ((p[1] == 'o' or p[1] == 'O') and radix == 0 and (flags & atod_accept_bin_oct) != 0):
            p += 2
            radix = 8
        elif ((p[1] == 'b' or p[1] == 'B') and radix == 0 and (flags & atod_accept_bin_oct) != 0):
            p += 2
            radix = 2
        elif ((p[1] >= '0' and p[1] <= '9') and radix == 0 and (flags & atod_accept_legacy_octal) != 0):
            sep = 256
            var i: usize = 1
            while p[i] >= '0' and p[i] <= '7':
                i += 1
            if p[i] == '8' or p[i] == '9':
                has_prefix = false  # goto no_prefix
            else:
                p += 1
                radix = 8
        else:
            has_prefix = false  # goto no_prefix
        # there must be a digit after the prefix
        if has_prefix and to_digit(*p) >= radix:
            return (none, p)
    else:
        if (flags & atod_int_only) == 0 and cutils.strstart(p, "Infinity", &p):
            return (infinity | (is_neg << 63), p)  # goto overflow
    if radix == 0:
        radix = 10

    var cur_limb: u32 = 0
    var digit_count: i32 = 0
    var limb_digit_count: i32 = 0
    let max_digits = (i32)atod_max_digits_table[(usize)(radix - 2)]
    let digits_per_limb = (i32)digits_per_limb_table[(usize)(radix - 2)]
    let radix_base = radix_base_table[(usize)(radix - 2)]
    let radix_shift = cutils.ctz32((u32)radix)
    let radix1 = radix >> radix_shift
    var radix_bits: i32
    if radix1 == 1:
        # radix = 2^radix_bits
        radix_bits = radix_shift
    else:
        radix_bits = 0
    tmp0.len = 1
    tab[0] = 0
    var extra_digits: u32 = 0
    var pos: i32 = 0
    var dot_pos: i32 = -1
    # skip leading zeros
    while true:
        if (*p == '.' and (p > p_start or to_digit(p[1]) < radix) and (flags & atod_int_only) == 0):
            if (i32)*p == sep:
                return (none, p)
            if dot_pos >= 0:
                break
            dot_pos = pos
            p += 1
        if (i32)*p == sep and p > p_start and p[1] == '0':
            p += 1
        if *p != '0':
            break
        p += 1
        pos += 1

    let sig_pos = pos
    while true:
        if (*p == '.' and (p > p_start or to_digit(p[1]) < radix) and (flags & atod_int_only) == 0):
            if (i32)*p == sep:
                return (none, p)
            if dot_pos >= 0:
                break
            dot_pos = pos
            p += 1
        if (i32)*p == sep and p > p_start and to_digit(p[1]) < radix:
            p += 1
        let c = (u32)to_digit(*p)
        if c >= (u32)radix:
            break
        p += 1
        pos += 1
        if digit_count < max_digits:
            # XXX: could be faster when radix_bits != 0
            cur_limb = cur_limb *% (u32)radix +% c
            limb_digit_count += 1
            if limb_digit_count == digits_per_limb:
                mpb_mul1_base(tmp0, radix_base, cur_limb)
                cur_limb = 0
                limb_digit_count = 0
            digit_count += 1
        else:
            extra_digits |= c
    if limb_digit_count != 0:
        mpb_mul1_base(tmp0, (u32)pow_ui((u32)radix, (u32)limb_digit_count), cur_limb)
    var is_zero: bool
    var expn_offset: i32
    if digit_count == 0:
        is_zero = true
        expn_offset = 0
    else:
        is_zero = false
        if dot_pos < 0:
            dot_pos = pos
        expn_offset = sig_pos + digit_count - dot_pos

    # Use the extra digits for rounding if the base is a power of two. Otherwise they are
    # just truncated.
    if radix_bits != 0 and extra_digits != 0:
        tab[0] |= 1

    # parse the exponent, if any
    var expn: i32 = 0
    var expn_overflow = false
    var is_bin_exp = false
    if ((flags & atod_int_only) == 0 and ((radix == 10 and (*p == 'e' or *p == 'E')) or (radix != 10 and (*p == '@' or (radix_bits >= 1 and radix_bits <= 4 and (*p == 'p' or *p == 'P'))))) and p > p_start):
        is_bin_exp = *p == 'p' or *p == 'P'
        p += 1
        var exp_is_neg = false
        if *p == '+':
            p += 1
        elif *p == '-':
            exp_is_neg = true
            p += 1
        var c = to_digit(*p)
        if c >= 10:
            return (none, p)  # XXX: could stop before the exponent part
        expn = c
        p += 1
        while true:
            if (i32)*p == sep and to_digit(p[1]) < 10:
                p += 1
            c = to_digit(*p)
            if c >= 10:
                break
            if not expn_overflow:
                if expn > ((2147483647 - 2 - 9) // 10):
                    expn_overflow = true
                else:
                    expn = expn * 10 + c
            p += 1
        if exp_is_neg:
            expn = -expn
        # if zero result, the exponent can be arbitrarily large
        if not is_zero and expn_overflow:
            if exp_is_neg:
                return (0 | (is_neg << 63), p)
            else:
                return (infinity | (is_neg << 63), p)  # infinity
    if p == p_start:
        return (none, p)

    var a: u64
    if is_zero:
        a = 0
    else:
        var e: i32 = 0
        var m: u64
        if radix_bits != 0:
            if not is_bin_exp:
                expn *= radix_bits
            expn -= expn_offset * radix_bits
            let expn1 = expn + digit_count * radix_bits
            if expn1 >= 1024 + radix_bits:
                return (infinity | (is_neg << 63), p)  # goto overflow
            elif expn1 <= -1075:
                return (0 | (is_neg << 63), p)  # goto underflow
            m = round_to_d(&e, tmp0, -expn, .rndn)
        else:
            expn -= expn_offset
            let expn1 = expn + digit_count
            if expn1 >= (i32)max_exponent[(usize)(radix - 2)] + 1:
                return (infinity | (is_neg << 63), p)  # goto overflow
            elif expn1 <= (i32)min_exponent[(usize)(radix - 2)]:
                return (0 | (is_neg << 63), p)  # goto underflow
            m = mul_pow_round_to_d(&e, tmp0, radix1, radix_shift, expn, .rndn)
        if m == 0:
            # underflow:
            a = 0
        elif e > 1024:
            # overflow
            a = infinity
        elif e < -1073:
            # underflow
            # XXX: check rounding
            a = 0
        elif e < -1021:
            # subnormal
            a = m >> (u64)(-e - 1021)
        else:
            a = ((u64)(e + 1022) << 52) | (m & (((u64)1 << 52) - 1))
    # done:
    return (a | (is_neg << 63), p)