Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / host / printf.lucb

#==============================================================================================
#
#   printf - std.printf, std.sprintf and FILE.printf: C formats over JavaScript values
#
#   DESCRIPTION:
#       Port of quickjs-libc.c js_printf_internal (lines 176-423). Each conversion is
#       copied into a small C format and handed to the C library's snprintf, as QuickJS
#       hands it to dbuf_printf; Base has no variadic functions, so there is one
#       dbuf_printf_* helper per argument type.
#
#==============================================================================================

# mark: C formatting into a DynBuf ==============================================================

## Append `len` formatted bytes: `format_into(buf, size)` writes at most `size` bytes,
## NUL included, and answers the full length. Shared by the dbuf_printf_* helpers.
func dbuf_put_formatted(s: DynBuf*, tmp: u8*, tmp_size: usize, len: i32) -> i32:
    if len < 0:
        return -1
    if (usize)len < tmp_size:
        return cutils.dbuf_put(s, tmp, (usize)len)
    return 1  # too long for `tmp`: the caller formats into the buffer itself

## Grow `s` for `len` more bytes and a NUL; the destination of a long conversion.
func dbuf_long_destination(s: DynBuf*, len: i32) -> u8*?:
    if cutils.dbuf_claim(s, (usize)len + 1) != 0:
        return none
    let buf = s.buf else return none
    return buf + s.size

# The C library's snprintf, which on Windows is MinGW's standard one (QuickJS builds with
# __USE_MINGW_ANSI_STDIO), for each argument type.

func format_i32(buf: u8*, size: usize, cformat: const u8*, v: i32) -> i32:
    if platform.windows:
        return win_snprintf(buf, size, cformat, v)
    else:
        return snprintf(buf, size, cformat, v)

func format_i64(buf: u8*, size: usize, cformat: const u8*, v: i64) -> i32:
    if platform.windows:
        return win_snprintf(buf, size, cformat, v)
    else:
        return snprintf(buf, size, cformat, v)

func format_f64(buf: u8*, size: usize, cformat: const u8*, v: f64) -> i32:
    if platform.windows:
        return win_snprintf(buf, size, cformat, v)
    else:
        return snprintf(buf, size, cformat, v)

func format_str(buf: u8*, size: usize, cformat: const u8*, v: const u8*) -> i32:
    if platform.windows:
        return win_snprintf(buf, size, cformat, v)
    else:
        return snprintf(buf, size, cformat, v)

func dbuf_printf_i32(s: DynBuf*, cformat: const u8*, v: i32) -> i32:
    var tmp: u8[128] = ---
    let len = format_i32(&tmp[0], 128, cformat, v)
    let r = dbuf_put_formatted(s, &tmp[0], 128, len)
    if r != 1: return r
    let dst = dbuf_long_destination(s, len) else return -1
    _ = format_i32(dst, (usize)len + 1, cformat, v)
    s.size += (usize)len
    return 0

func dbuf_printf_i64(s: DynBuf*, cformat: const u8*, v: i64) -> i32:
    var tmp: u8[128] = ---
    let len = format_i64(&tmp[0], 128, cformat, v)
    let r = dbuf_put_formatted(s, &tmp[0], 128, len)
    if r != 1: return r
    let dst = dbuf_long_destination(s, len) else return -1
    _ = format_i64(dst, (usize)len + 1, cformat, v)
    s.size += (usize)len
    return 0

func dbuf_printf_f64(s: DynBuf*, cformat: const u8*, v: f64) -> i32:
    var tmp: u8[128] = ---
    let len = format_f64(&tmp[0], 128, cformat, v)
    let r = dbuf_put_formatted(s, &tmp[0], 128, len)
    if r != 1: return r
    let dst = dbuf_long_destination(s, len) else return -1
    _ = format_f64(dst, (usize)len + 1, cformat, v)
    s.size += (usize)len
    return 0

func dbuf_printf_str(s: DynBuf*, cformat: const u8*, v: const u8*) -> i32:
    var tmp: u8[128] = ---
    let len = format_str(&tmp[0], 128, cformat, v)
    let r = dbuf_put_formatted(s, &tmp[0], 128, len)
    if r != 1: return r
    let dst = dbuf_long_destination(s, len) else return -1
    _ = format_str(dst, (usize)len + 1, cformat, v)
    s.size += (usize)len
    return 0

# mark: js_printf_internal ======================================================================

## Why a conversion failed, beyond a pending exception (the `invalid` and `missing`
## labels of the C function).
enum PrintfFailure:
    ok
    invalid
    missing

# XXX: use 'o' and 'O' for object using JS_PrintValue() ?
## Format `argv[0]` with the following arguments: to the stream `fp` when given (the
## result is the number of bytes written), else into a new string.
func js_printf_internal(ctx: Context*, argc: i32, argv: Value*, fp: void*?) -> Value!:
    var dbuf: DynBuf
    js_std_dbuf_init(ctx, &dbuf)
    defer cutils.dbuf_free(&dbuf)

    if argc > 0:
        var fmt_len: usize = 0
        let fmt_str = try js.js_to_c_string_len(ctx, &fmt_len, argv[0])
        defer js.js_free_c_string(ctx, fmt_str)
        var failure = PrintfFailure.ok
        try printf_conversions(ctx, argc, argv, fmt_str, fmt_len, &dbuf, &failure)
        if failure == PrintfFailure.invalid:
            try js.js_throw_type_error(ctx, "invalid conversion specifier in format string")
        if failure == PrintfFailure.missing:
            try js.js_throw_reference_error(ctx, "missing argument for conversion specifier")
    if dbuf.error:
        try js.js_throw_out_of_memory(ctx)
    if let f = fp:
        var written: usize = 0
        if let buf = dbuf.buf:
            written = fwrite(buf, 1, dbuf.size, f)
        return js.js_new_int32((i32)written)
    if let buf = dbuf.buf:
        return try js.js_new_string_len(ctx, buf, dbuf.size)
    return try js.js_new_string_len(ctx, "".bytes.data, 0)

## The conversion loop of js_printf_internal. Stops early with `*failure` set for an
## invalid or missing conversion, and fails when a conversion of an argument throws.
func printf_conversions(ctx: Context*, argc: i32, argv: Value*, fmt_str: const u8*, fmt_len: usize,
                        dbuf: DynBuf*, failure: PrintfFailure*) -> !:
    var fmtbuf: u8[32] = ---
    var cbuf: u8[7] = ---  # UTF8_CHAR_LEN_MAX + 1
    var i: i32 = 1
    var fmtp = fmt_str
    let fmt_end = fmt_str + fmt_len
    let fmt_last: usize = 31  # the index of the last byte of fmtbuf
    while fmtp < fmt_end:
        let p = fmtp
        while fmtp < fmt_end and *fmtp != '%':
            fmtp += 1
        _ = cutils.dbuf_put(dbuf, p, (usize)(fmtp - p))
        if fmtp >= fmt_end:
            break
        var q: usize = 0
        fmtbuf[q] = *fmtp  # copy '%'
        q += 1
        fmtp += 1

        # flags
        while true:
            let ch = *fmtp
            if ch == '0' or ch == '#' or ch == '+' or ch == '-' or ch == ' ' or ch == '\'':
                if q >= fmt_last:
                    *failure = .invalid
                    return
                fmtbuf[q] = ch
                q += 1
                fmtp += 1
            else:
                break
        # width
        if *fmtp == '*':
            if i >= argc:
                *failure = .missing
                return
            var int32_arg: i32 = 0
            try js.js_to_int32(ctx, &int32_arg, argv[(usize)i])
            i += 1
            q += (usize)snprintf(&fmtbuf[q], 32 - q, "%d".bytes.data, int32_arg)
            fmtp += 1
        else:
            while my_isdigit(*fmtp):
                if q >= fmt_last:
                    *failure = .invalid
                    return
                fmtbuf[q] = *fmtp
                q += 1
                fmtp += 1
        if *fmtp == '.':
            if q >= fmt_last:
                *failure = .invalid
                return
            fmtbuf[q] = *fmtp
            q += 1
            fmtp += 1
            if *fmtp == '*':
                if i >= argc:
                    *failure = .missing
                    return
                var int32_arg: i32 = 0
                try js.js_to_int32(ctx, &int32_arg, argv[(usize)i])
                i += 1
                q += (usize)snprintf(&fmtbuf[q], 32 - q, "%d".bytes.data, int32_arg)
                fmtp += 1
            else:
                while my_isdigit(*fmtp):
                    if q >= fmt_last:
                        *failure = .invalid
                        return
                    fmtbuf[q] = *fmtp
                    q += 1
                    fmtp += 1

        # we only support the "l" modifier for 64 bit numbers
        var mod: u8 = ' '
        if *fmtp == 'l':
            mod = *fmtp
            fmtp += 1

        # type
        let ch = *fmtp
        fmtp += 1
        if q >= fmt_last:
            *failure = .invalid
            return
        fmtbuf[q] = ch
        q += 1
        fmtbuf[q] = 0

        match ch:
            'c':
                if i >= argc:
                    *failure = .missing
                    return
                var int32_arg: i32 = 0
                if js.js_is_string(argv[(usize)i]):
                    let string_arg = try js.js_to_c_string(ctx, argv[(usize)i])
                    i += 1
                    var end: const u8* = string_arg
                    int32_arg = cutils.unicode_from_utf8(string_arg, cutils.utf8_char_len_max, &end)
                    js.js_free_c_string(ctx, string_arg)
                else:
                    try js.js_to_int32(ctx, &int32_arg, argv[(usize)i])
                    i += 1
                # handle utf-8 encoding explicitly
                if (u32)int32_arg > 0x10FFFF:
                    int32_arg = 0xFFFD
                # ignore conversion flags, width and precision
                let len = cutils.unicode_to_utf8(&cbuf[0], (u32)int32_arg)
                _ = cutils.dbuf_put(dbuf, &cbuf[0], (usize)len)
            'd', 'i', 'o', 'u', 'x', 'X':
                if i >= argc:
                    *failure = .missing
                    return
                var int64_arg: i64 = 0
                try js.js_to_int64_ext(ctx, &int64_arg, argv[(usize)i])
                i += 1
                if mod == 'l':
                    if platform.windows:
                        # 64 bit number: "%...x" becomes "%...I64x"
                        if q >= fmt_last - 2:
                            *failure = .invalid
                            return
                        fmtbuf[q + 2] = fmtbuf[q - 1]
                        fmtbuf[q - 1] = 'I'
                        fmtbuf[q] = '6'
                        fmtbuf[q + 1] = '4'
                        fmtbuf[q + 3] = 0
                    else:
                        # 64 bit number: "%...x" becomes "%...llx"
                        if q >= fmt_last - 1:
                            *failure = .invalid
                            return
                        fmtbuf[q + 1] = fmtbuf[q - 1]
                        fmtbuf[q - 1] = 'l'
                        fmtbuf[q] = 'l'
                        fmtbuf[q + 2] = 0
                    _ = dbuf_printf_i64(dbuf, &fmtbuf[0], int64_arg)
                else:
                    _ = dbuf_printf_i32(dbuf, &fmtbuf[0], (i32)int64_arg)
            's':
                if i >= argc:
                    *failure = .missing
                    return
                # XXX: handle strings containing null characters
                let string_arg = try js.js_to_c_string(ctx, argv[(usize)i])
                i += 1
                _ = dbuf_printf_str(dbuf, &fmtbuf[0], string_arg)
                js.js_free_c_string(ctx, string_arg)
            'e', 'f', 'g', 'a', 'E', 'F', 'G', 'A':
                if i >= argc:
                    *failure = .missing
                    return
                var double_arg: f64 = 0.0
                try js.js_to_float64(ctx, &double_arg, argv[(usize)i])
                i += 1
                _ = dbuf_printf_f64(dbuf, &fmtbuf[0], double_arg)
            '%':
                _ = cutils.dbuf_putc(dbuf, '%')
            _:
                # XXX: should support an extension mechanism
                *failure = .invalid
                return