Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / engine / uri.lucb

#==============================================================================================
#
#   uri - URI encoding and decoding, escape and unescape, and the global functions
#
#   DESCRIPTION:
#       Port of quickjs.c lines 54710-55012: decodeURI, decodeURIComponent, encodeURI,
#       encodeURIComponent, escape and unescape, and the function list of the global
#       object. As in C, StringBuffer failures are sticky and reported by
#       string_buffer_end; the loops that can throw a URIError run in helpers so the
#       buffer is freed when they fail.
#
#==============================================================================================

# mark: Helpers =================================================================================

# The value of the `n` hex digits at `k` of `p`, or -1 if one is not a hex digit.
func string_get_hex(p: const String*, k: i32, n: i32) -> i32:
    var c: i32 = 0
    var i = k
    for _j in 0..<n:
        let h = cutils.from_hex(string_get(p, i))
        i += 1
        if h < 0:
            return -1
        c = (c << 4) | h
    return c

# Whether the character `c` is one of the bytes of `set`.
func char_in_set(set: str, c: i32) -> bool:
    if c < 0 or c >= 0x100:
        return false
    for x in set.bytes:
        if (i32)x == c:
            return true
    return false

func is_uri_reserved(c: i32) -> bool:
    return c < 0x100 and char_in_set(";/?:@&=+$,#", c)

## Throw a URIError with `message` (js_throw_URIError).
func js_throw_uri_error(ctx: Context*, message: fmt) -> never!:
    try js_throw_error(ctx, ErrorKind.uri_error, message)

# The byte encoded as "%XX" at `k` of `p`, else a URIError.
func hex_decode(ctx: Context*, p: const String*, k: i32) -> i32!:
    if k >= (i32)p.len or string_get(p, k) != (i32)'%':
        try js_throw_uri_error(ctx, "expecting %")
    let c = string_get_hex(p, k + 1, 2) if k + 2 < (i32)p.len else -1
    if c < 0:
        try js_throw_uri_error(ctx, "expecting hex digit")
    return c

# mark: decodeURI ===============================================================================

# Decode the characters of `p` into `b`; a URIError on a malformed escape.
func js_global_decode_uri_chars(ctx: Context*, b: StringBuffer*, p: const String*, is_component: i32) -> !:
    var k: i32 = 0
    while k < (i32)p.len:
        var c = string_get(p, k)
        if c == (i32)'%':
            c = try hex_decode(ctx, p, k)
            k += 3
            if c < 0x80:
                if is_component == 0 and is_uri_reserved(c):
                    c = (i32)'%'
                    k -= 2
            else:
                # Decode URI-encoded UTF-8 sequence
                var n: i32 = 0
                var c_min: i32 = 0
                if c >= 0xc0 and c <= 0xdf:
                    n = 1
                    c_min = 0x80
                    c &= 0x1f
                elif c >= 0xe0 and c <= 0xef:
                    n = 2
                    c_min = 0x800
                    c &= 0xf
                elif c >= 0xf0 and c <= 0xf7:
                    n = 3
                    c_min = 0x10000
                    c &= 0x7
                else:
                    n = 0
                    c_min = 1
                    c = 0
                while n > 0:
                    n -= 1
                    let c1 = try hex_decode(ctx, p, k)
                    k += 3
                    if (c1 & 0xc0) != 0x80:
                        c = 0
                        break
                    c = (c << 6) | (c1 & 0x3f)
                if c < c_min or c > 0x10FFFF or cutils.is_surrogate((u32)c):
                    try js_throw_uri_error(ctx, "malformed UTF-8")
        else:
            k += 1
        string_buffer_putc(b, (u32)c) catch: recover ()

## decodeURI (is_component 0) and decodeURIComponent (1).
func js_global_decode_uri(ctx: Context*, this_val: Value, argc: i32, argv: Value*, is_component: i32) -> Value!:
    let text = try js_to_string(ctx, argv[0])
    defer js_free_value(ctx, text)

    var b: StringBuffer = ---
    string_buffer_init(ctx, &b, 0) catch: recover ()
    js_global_decode_uri_chars(ctx, &b, text.u.string, is_component) catch failure:
        string_buffer_free(&b)
        error(failure.code, failure.message)
    return try string_buffer_end(&b)

# mark: encodeURI ===============================================================================

func is_unescaped(c: i32) -> bool:
    return c < 0x100 and char_in_set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./", c)

func is_uri_unescaped(c: i32, is_component: i32) -> bool:
    return c < 0x100 and ((c >= 0x61 and c <= 0x7a) or (c >= 0x41 and c <= 0x5a) or (c >= 0x30 and c <= 0x39) or char_in_set("-_.!~*'()", c) or (is_component == 0 and is_uri_reserved(c)))

let uri_hex_digits: const u8[] = b"0123456789ABCDEF"

# Append "%XX", or "%uXXXX" when `c` >= 256.
func encode_uri_hex(b: StringBuffer*, c: i32) -> !:
    var buf: u8[6] = ---
    var n: usize = 0

    buf[n] = '%'
    n += 1
    if c >= 256:
        buf[n] = 'u'
        n += 1
        buf[n] = uri_hex_digits[(usize)((c >> 12) & 15)]
        n += 1
        buf[n] = uri_hex_digits[(usize)((c >> 8) & 15)]
        n += 1
    buf[n] = uri_hex_digits[(usize)((c >> 4) & 15)]
    n += 1
    buf[n] = uri_hex_digits[(usize)((c >> 0) & 15)]
    n += 1
    try string_buffer_write8(b, &buf[0], (i32)n)

# Encode the characters of `p` into `b`; a URIError on a lone surrogate.
func js_global_encode_uri_chars(ctx: Context*, b: StringBuffer*, p: const String*, is_component: i32) -> !:
    var k: i32 = 0
    while k < (i32)p.len:
        var c = string_get(p, k)
        k += 1
        if is_uri_unescaped(c, is_component):
            string_buffer_putc16(b, (u32)c) catch: recover ()
        else:
            if cutils.is_lo_surrogate((u32)c):
                try js_throw_uri_error(ctx, "invalid character")
            elif cutils.is_hi_surrogate((u32)c):
                if k >= (i32)p.len:
                    try js_throw_uri_error(ctx, "expecting surrogate pair")
                let c1 = string_get(p, k)
                k += 1
                if not cutils.is_lo_surrogate((u32)c1):
                    try js_throw_uri_error(ctx, "expecting surrogate pair")
                c = (i32)cutils.from_surrogate((u32)c, (u32)c1)
            if c < 0x80:
                encode_uri_hex(b, c) catch: recover ()
            else:
                # XXX: use C UTF-8 conversion ?
                if c < 0x800:
                    encode_uri_hex(b, (c >> 6) | 0xc0) catch: recover ()
                else:
                    if c < 0x10000:
                        encode_uri_hex(b, (c >> 12) | 0xe0) catch: recover ()
                    else:
                        encode_uri_hex(b, (c >> 18) | 0xf0) catch: recover ()
                        encode_uri_hex(b, ((c >> 12) & 0x3f) | 0x80) catch: recover ()
                    encode_uri_hex(b, ((c >> 6) & 0x3f) | 0x80) catch: recover ()
                encode_uri_hex(b, (c & 0x3f) | 0x80) catch: recover ()

## encodeURI (is_component 0) and encodeURIComponent (1).
func js_global_encode_uri(ctx: Context*, this_val: Value, argc: i32, argv: Value*, is_component: i32) -> Value!:
    let text = try js_to_string(ctx, argv[0])
    defer js_free_value(ctx, text)

    let p = text.u.string
    var b: StringBuffer = ---
    string_buffer_init(ctx, &b, (i32)p.len) catch: recover ()
    js_global_encode_uri_chars(ctx, &b, p, is_component) catch failure:
        string_buffer_free(&b)
        error(failure.code, failure.message)
    return try string_buffer_end(&b)

# mark: escape and unescape =====================================================================

## escape(string).
func js_global_escape(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let text = try js_to_string(ctx, argv[0])
    defer js_free_value(ctx, text)

    let p = text.u.string
    var b: StringBuffer = ---
    string_buffer_init(ctx, &b, (i32)p.len) catch: recover ()
    let len = (i32)p.len
    for i in 0..<len:
        let c = string_get(p, i)
        if is_unescaped(c):
            string_buffer_putc16(&b, (u32)c) catch: recover ()
        else:
            encode_uri_hex(&b, c) catch: recover ()
    return try string_buffer_end(&b)

## unescape(string).
func js_global_unescape(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let text = try js_to_string(ctx, argv[0])
    defer js_free_value(ctx, text)

    var b: StringBuffer = ---
    string_buffer_init(ctx, &b, 0) catch: recover ()
    let p = text.u.string
    let len = (i32)p.len
    var i: i32 = 0
    while i < len:
        var c = string_get(p, i)
        if c == (i32)'%':
            var n: i32 = -1
            if i + 6 <= len and string_get(p, i + 1) == (i32)'u':
                n = string_get_hex(p, i + 2, 4)
            if n >= 0:
                c = n
                i += 6 - 1
            else:
                if i + 3 <= len:
                    n = string_get_hex(p, i + 1, 2)
                if n >= 0:
                    c = n
                    i += 3 - 1
        string_buffer_putc16(&b, (u32)c) catch: recover ()
        i += 1
    return try string_buffer_end(&b)

# mark: The global object =======================================================================

## The function list of the global object (js_global_funcs).
let js_global_funcs: CFunctionListEntry[15] = [
    CFunctionListEntry(name = "parseInt", def_type = def_cfunc, length = 2, generic = js_parse_int),
    CFunctionListEntry(name = "parseFloat", def_type = def_cfunc, length = 1, generic = js_parse_float),
    CFunctionListEntry(name = "isNaN", def_type = def_cfunc, length = 1, generic = js_global_is_na_n),
    CFunctionListEntry(name = "isFinite", def_type = def_cfunc, length = 1, generic = js_global_is_finite),

    CFunctionListEntry(name = "decodeURI", def_type = def_cfunc, length = 1,
                       cproto = CFunctionEnum.generic_magic, generic_magic = js_global_decode_uri, magic = 0),
    CFunctionListEntry(name = "decodeURIComponent", def_type = def_cfunc, length = 1,
                       cproto = CFunctionEnum.generic_magic, generic_magic = js_global_decode_uri, magic = 1),
    CFunctionListEntry(name = "encodeURI", def_type = def_cfunc, length = 1,
                       cproto = CFunctionEnum.generic_magic, generic_magic = js_global_encode_uri, magic = 0),
    CFunctionListEntry(name = "encodeURIComponent", def_type = def_cfunc, length = 1,
                       cproto = CFunctionEnum.generic_magic, generic_magic = js_global_encode_uri, magic = 1),
    CFunctionListEntry(name = "escape", def_type = def_cfunc, length = 1, generic = js_global_escape),
    CFunctionListEntry(name = "unescape", def_type = def_cfunc, length = 1, generic = js_global_unescape),
    # 1.0 / 0.0 and NAN
    CFunctionListEntry(name = "Infinity", prop_flags = 0, def_type = def_prop_double,
                       f64_value = f64.bits(0x7ff0000000000000)),
    CFunctionListEntry(name = "NaN", prop_flags = 0, def_type = def_prop_double,
                       f64_value = f64.bits(0x7ff8000000000000)),
    CFunctionListEntry(name = "undefined", prop_flags = 0, def_type = def_prop_undefined),
    CFunctionListEntry(name = "[Symbol.toStringTag]", prop_flags = (u8)prop_configurable,
                       def_type = def_prop_string, string_value = "global"),
    CFunctionListEntry(name = "eval", def_type = def_cfunc, length = 1, generic = js_global_eval),
]