Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / engine / array_constructor.lucb

#==============================================================================================
#
#   array_constructor - The Array constructor, Array.from/of/isArray, species and concat
#
#   DESCRIPTION:
#       Port of quickjs.c "Array" (lines 41669-42110): js_array_constructor, Array.from,
#       Array.of, Array.isArray, the species constructor lookup and array creation,
#       the Array constructor's table, IsConcatSpreadable, and Array.prototype.at,
#       with and concat. A builtin fails with the exception pending where QuickJS
#       returns JS_EXCEPTION; its `goto exception` cleanup is `defer`/`errdefer`.
#
#==============================================================================================

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

# mark: The constructor =========================================================================

## `new Array(...)` and `Array(...)`: an array of the arguments, or of the length given as
## the one numeric argument.
func js_array_constructor(ctx: Context*, new_target: Value, argc: i32, argv: Value*) -> Value!:
    let obj = try js_create_from_ctor(ctx, new_target, (u32)ClassId.array)
    errdefer js_free_value(ctx, obj)
    if argc == 1 and js_is_number(argv[0]):
        var len: u32 = 0
        try js_to_array_length_free(ctx, &len, js_dup_value(ctx, argv[0]), true)
        try js_set_property(ctx, obj, atom_length, js_new_uint32(len))
    else:
        for i in 0..<argc:
            try js_set_property_uint32(ctx, obj, (u32)i, js_dup_value(ctx, argv[(usize)i]))
    return obj

## Array.from(items, mapfn = void 0, this_arg = void 0).
func js_array_from(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let items = argv[0]
    var mapfn = js_undefined()
    var this_arg = js_undefined()
    var args: Value[2] = ---
    var mapping = false

    if argc > 1:
        mapfn = argv[1]
        if not js_is_undefined(mapfn):
            try check_function(ctx, mapfn)
            mapping = true
            if argc > 2:
                this_arg = argv[2]
    let iter = try js_get_property(ctx, items, atom_Symbol_iterator)
    defer js_free_value(ctx, iter)
    var r = js_undefined()
    errdefer js_free_value_at(ctx, &r)
    var k: i64 = 0
    if not js_is_undefined(iter) and not js_is_null(iter):
        if not js_is_function(ctx, iter):
            try js_throw_type_error(ctx, "value is not iterable")
        if js_is_constructor(ctx, this_val):
            r = try js_call_constructor(ctx, this_val, 0, argv)
        else:
            r = try js_new_array(ctx)
        let enum_obj = try js_get_iterator2(ctx, items, iter)
        defer js_free_value(ctx, enum_obj)
        let next_method = try js_get_property(ctx, enum_obj, atom_next)
        defer js_free_value(ctx, next_method)
        while true:
            var done = false
            var v = try js_iterator_next(ctx, enum_obj, next_method, 0, argv, &done)
            if done:
                break
            if mapping:
                args[0] = v
                args[1] = js_new_int32((i32)k)
                let v2 = js_call(ctx, mapfn, this_arg, 2, &args[0]) catch failure:
                    js_free_value(ctx, v)
                    js_iterator_close_ignore(ctx, enum_obj, true)
                    error(failure.code, failure.message)
                js_free_value(ctx, v)
                v = v2
            js_define_property_value_int64(ctx, r, k, v, prop_c_w_e | prop_throw) catch failure:
                js_iterator_close_ignore(ctx, enum_obj, true)
                error(failure.code, failure.message)
            k += 1
    else:
        let array_like = try js_to_object(ctx, items)
        defer js_free_value(ctx, array_like)
        var len: i64 = 0
        try js_get_length64(ctx, &len, array_like)
        let len_val = js_new_int64(len)
        defer js_free_value(ctx, len_val)
        args[0] = len_val
        if js_is_constructor(ctx, this_val):
            r = try js_call_constructor(ctx, this_val, 1, &args[0])
        else:
            r = try js_array_constructor(ctx, js_undefined(), 1, &args[0])
        while k < len:
            var v = try js_get_property_int64(ctx, array_like, k)
            if mapping:
                args[0] = v
                args[1] = js_new_int32((i32)k)
                let v2 = js_call(ctx, mapfn, this_arg, 2, &args[0]) catch failure:
                    js_free_value(ctx, v)
                    error(failure.code, failure.message)
                js_free_value(ctx, v)
                v = v2
            try js_define_property_value_int64(ctx, r, k, v, prop_c_w_e | prop_throw)
            k += 1
    try js_set_property(ctx, r, atom_length, js_new_uint32((u32)k))
    return r

## Array.of(...items).
func js_array_of(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var obj: Value = ---
    if js_is_constructor(ctx, this_val):
        var args: Value[1] = [js_new_int32(argc)]
        obj = try js_call_constructor(ctx, this_val, 1, &args[0])
    else:
        obj = try js_new_array(ctx)
    errdefer js_free_value(ctx, obj)
    for i in 0..<argc:
        try js_create_data_property_uint32(ctx, obj, (i64)i, js_dup_value(ctx, argv[(usize)i]), prop_throw)
    try js_set_property(ctx, obj, atom_length, js_new_uint32((u32)argc))
    return obj

## Array.isArray(value).
func js_array_is_array(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let ret = try js_is_array(ctx, argv[0])
    return js_new_bool(ret)

## The `[Symbol.species]` getter of the constructors: `this` itself.
func js_get_this(ctx: Context*, this_val: Value) -> Value!:
    return js_dup_value(ctx, this_val)

# mark: Species =================================================================================

# XXX: optimize
## The constructor ArraySpeciesCreate uses for `obj`: undefined for the intrinsic Array
## (or when `obj` is not an array).
func js_array_species_get_ctor(ctx: Context*, obj: Value) -> Value!:
    let res = try js_is_array(ctx, obj)
    if not res:
        return js_undefined()
    var ctor = try js_get_property(ctx, obj, atom_constructor)
    if js_is_constructor(ctx, ctor):
        # legacy web compatibility
        let realm = js_get_function_realm(ctx, ctor) catch failure:
            js_free_value(ctx, ctor)
            error(failure.code, failure.message)
        if realm != ctx and js_same_value(ctx, ctor, realm.array_ctor):
            js_free_value(ctx, ctor)
            ctor = js_undefined()
    if js_is_object(ctor):
        let species = js_get_property(ctx, ctor, atom_Symbol_species) catch failure:
            js_free_value(ctx, ctor)
            error(failure.code, failure.message)
        js_free_value(ctx, ctor)
        ctor = species
        if js_is_null(ctor):
            ctor = js_undefined()
    if not js_is_undefined(ctor) and js_same_value(ctx, ctor, ctx.array_ctor):
        js_free_value(ctx, ctor)
        ctor = js_undefined()
    return ctor

## A new array of length `len` made by `ctor`, or by the intrinsic Array when `ctor` is
## undefined.
func js_array_create_from_ctor(ctx: Context*, ctor: Value, len: i64) -> Value!:
    var len_val = js_new_int64(len)
    defer js_free_value(ctx, len_val)
    if js_is_undefined(ctor):
        return try js_array_constructor(ctx, js_undefined(), 1, &len_val)
    return try js_call_constructor(ctx, ctor, 1, &len_val)

# len must be >= 0
## ArraySpeciesCreate(obj, len).
func js_array_species_create(ctx: Context*, obj: Value, len: i64) -> Value!:
    let ctor = try js_array_species_get_ctor(ctx, obj)
    defer js_free_value(ctx, ctor)
    return try js_array_create_from_ctor(ctx, ctor, len)

## The static methods of the Array constructor.
let js_array_funcs: CFunctionListEntry[4] = [
    CFunctionListEntry(name = "isArray", def_type = def_cfunc, length = 1, generic = js_array_is_array),
    CFunctionListEntry(name = "from", def_type = def_cfunc, length = 1, generic = js_array_from),
    CFunctionListEntry(name = "of", def_type = def_cfunc, length = 0, generic = js_array_of),
    CFunctionListEntry(name = "[Symbol.species]", prop_flags = 1, def_type = def_cgetset, getter = js_get_this),
]

## IsConcatSpreadable(obj).
func js_is_concat_spreadable(ctx: Context*, obj: Value) -> bool!:
    if not js_is_object(obj):
        return false
    let val = try js_get_property(ctx, obj, atom_Symbol_isConcatSpreadable)
    if not js_is_undefined(val):
        return try js_to_bool_free(ctx, val)
    return try js_is_array(ctx, obj)

# mark: at, with and concat =====================================================================

## Array.prototype.at(index).
func js_array_at(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let obj = try js_to_object(ctx, this_val)
    defer js_free_value(ctx, obj)
    var len: i64 = 0
    try js_get_length64(ctx, &len, obj)

    var idx: i64 = 0
    try js_to_int64_sat(ctx, &idx, argv[0])

    if idx < 0:
        idx = len + idx
    var arrp_opt: Value*? = none
    var count: u32 = 0
    if idx < 0 or idx >= len:
        return js_undefined()
    if js_get_fast_array(ctx, obj, &arrp_opt, &count) and idx < (i64)count:
        # none only for an empty array, whose elements are never read
        let arrp = arrp_opt else argv
        return js_dup_value(ctx, arrp[(usize)idx])
    var ret = js_undefined()
    let present = try js_try_get_property_int64(ctx, obj, idx, &ret)
    if not present:
        ret = js_undefined()
    return ret

## Array.prototype.with(index, value): a copy of the array with one element replaced.
func js_array_with(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let obj = try js_to_object(ctx, this_val)
    defer js_free_value(ctx, obj)
    var len: i64 = 0
    try js_get_length64(ctx, &len, obj)

    var idx: i64 = 0
    try js_to_int64_sat(ctx, &idx, argv[0])

    if idx < 0:
        idx = len + idx

    if idx < 0 or idx >= len:
        try js_throw_range_error(ctx, f"invalid array index: {idx}")

    let arr = try js_allocate_fast_array(ctx, len)
    errdefer js_free_value(ctx, arr)

    let p = arr.u.obj
    var i: i64 = 0
    var pval = p.u.array.u.values
    var arrp_opt: Value*? = none
    var count32: u32 = 0
    if js_get_fast_array(ctx, obj, &arrp_opt, &count32) and (i64)count32 == len:
        # none only for an empty array, whose elements are never read
        let arrp = arrp_opt else argv
        while i < idx:
            *pval = js_dup_value(ctx, arrp[(usize)i])
            i += 1
            pval += 1
        *pval = js_dup_value(ctx, argv[1])
        i += 1
        pval += 1
        while i < len:
            *pval = js_dup_value(ctx, arrp[(usize)i])
            i += 1
            pval += 1
    else:
        while i < idx:
            try js_try_get_property_int64(ctx, obj, i, pval)
            i += 1
            pval += 1
        *pval = js_dup_value(ctx, argv[1])
        i += 1
        pval += 1
        while i < len:
            try js_try_get_property_int64(ctx, obj, i, pval)
            i += 1
            pval += 1
    return arr

## Array.prototype.concat(...items).
func js_array_concat(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let obj = try js_to_object(ctx, this_val)
    defer js_free_value(ctx, obj)

    let arr = try js_array_species_create(ctx, obj, 0)
    errdefer js_free_value(ctx, arr)
    var n: i64 = 0
    var i: i32 = -1
    while i < argc:
        let e = obj if i < 0 else argv[(usize)i]

        if try js_is_concat_spreadable(ctx, e):
            var len: i64 = 0
            try js_get_length64(ctx, &len, e)
            if n + len > max_safe_integer:
                try js_throw_type_error(ctx, "Array loo long")
            var k: i64 = 0
            while k < len:
                var val = js_undefined()
                if try js_try_get_property_int64(ctx, e, k, &val):
                    try js_define_property_value_int64(ctx, arr, n, val, prop_c_w_e | prop_throw)
                k += 1
                n += 1
        else:
            if n >= max_safe_integer:
                try js_throw_type_error(ctx, "Array loo long")
            try js_define_property_value_int64(ctx, arr, n, js_dup_value(ctx, e), prop_c_w_e | prop_throw)
            n += 1
        i += 1
    try js_set_property(ctx, arr, atom_length, js_new_int64(n))
    return arr