Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / engine / date_fields.lucb

#==============================================================================================
#
#   date_fields - Date time values: the calendar arithmetic, fields and their accessors
#
#   DESCRIPTION:
#       Port of quickjs.c lines 55014-55288: the time value of a Date object, the conversions
#       between a time value (milliseconds since 1970, UTC) and its fields (year, month, date,
#       hours, minutes, seconds, milliseconds, week day, time zone offset), and the getters
#       and setters of Date.prototype that go through them. The local time zone offset is
#       get_timezone_offset (timezone_regexp_objects.lucb). The C computation of fields from a
#       time is split out as date_fields_of_time, a pure function the tests drive.
#
#==============================================================================================

# mark: Calendar arithmetic =====================================================================

func math_mod(a: i64, b: i64) -> i64:
    # return positive modulo
    let m = a % b
    return m + (i64)(m < 0) * b

func floor_div(a: i64, b: i64) -> i64:
    # integer division rounding toward -Infinity
    let m = a % b
    return (a - (m + (i64)(m < 0) * b)) // b

func days_from_year(y: i64) -> i64:
    return (365 * (y - 1970) + floor_div(y - 1969, 4) - floor_div(y - 1901, 100) + floor_div(y - 1601, 400))

func days_in_year(y: i64) -> i64:
    return 365 + (i64)(y % 4 == 0) - (i64)(y % 100 == 0) + (i64)(y % 400 == 0)

# return the year, update days
func year_from_days(days: i64*) -> i64:
    let d = *days
    var y = floor_div(d * 10000, 3652425) + 1970
    var d1: i64 = 0
    # the initial approximation is very good, so only a few
    # iterations are necessary
    while true:
        d1 = d - days_from_year(y)
        if d1 < 0:
            y -= 1
            d1 += days_in_year(y)
        else:
            let nd = days_in_year(y)
            if d1 < nd:
                break
            d1 -= nd
            y += 1
    *days = d1
    return y

let month_days: i32[12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let month_names: const u8[] = b"JanFebMarAprMayJunJulAugSepOctNovDec"
let day_names: const u8[] = b"SunMonTueWedThuFriSat"

# mark: Time values =============================================================================

## The time value of the Date `this_val` in `*valp`, else a TypeError (JS_ThisTimeValue).
func js_this_time_value(ctx: Context*, valp: f64*, this_val: Value) -> !:
    if this_val.tag == Tag.object:
        let p = js_value_get_obj(this_val)
        if p.class_id == ClassId.date and js_is_number(p.u.object_data):
            try js_to_float64(ctx, valp, p.u.object_data)
            return
    try js_throw_type_error(ctx, "not a Date object")

## Set the time value of the Date `this_val` to `v` and answer it (JS_SetThisTimeValue).
func js_set_this_time_value(ctx: Context*, this_val: Value, v: f64) -> Value!:
    if this_val.tag == Tag.object:
        let p = js_value_get_obj(this_val)
        if p.class_id == ClassId.date:
            js_free_value(ctx, p.u.object_data)
            p.u.object_data = js_new_float64(v)
            return js_dup_value(ctx, p.u.object_data)
    try js_throw_type_error(ctx, "not a Date object")

# Fill `fields` (at least 9) from the time `d` in milliseconds, already shifted to local
# time by `tz` minutes: year, month (0-11), date (1-31), hours, minutes, seconds,
# milliseconds, week day (0 = Sunday) and tz.
func date_fields_of_time(d: i64, tz: i64, fields: f64[]):
    # result is >= 0, we can use %
    var h = math_mod(d, 86400000)
    var days = (d - h) // 86400000
    let ms = h % 1000
    h = (h - ms) // 1000
    let s = h % 60
    h = (h - s) // 60
    let m = h % 60
    h = (h - m) // 60
    let wd = math_mod(days + 4, 7)  # week day
    let y = year_from_days(&days)

    var i: i64 = 0
    while i < 11:
        var md = (i64)month_days[(usize)i]
        if i == 1:
            md += days_in_year(y) - 365
        if days < md:
            break
        days -= md
        i += 1
    fields[0] = f64(y)
    fields[1] = f64(i)
    fields[2] = f64(days + 1)
    fields[3] = f64(h)
    fields[4] = f64(m)
    fields[5] = f64(s)
    fields[6] = f64(ms)
    fields[7] = f64(wd)
    fields[8] = f64(tz)

## The fields of the Date `obj` in `fields` (at least 9), in local time when `is_local`.
## False when its time value is NaN, unless `force`, which answers the fields of 0.
func get_date_fields(ctx: Context*, obj: Value, fields: f64[], is_local: bool, force: bool) -> bool!:
    var dval: f64 = 0.0
    var d: i64 = 0
    var tz: i64 = 0

    try js_this_time_value(ctx, &dval, obj)

    if math.is_nan(dval):
        if not force:
            return false  # NaN
        d = 0  # initialize all fields to 0
    else:
        d = (i64)dval  # assuming -8.64e15 <= dval <= -8.64e15
        if is_local:
            tz = -(i64)get_timezone_offset(d)
            d += tz * 60000
    date_fields_of_time(d, tz, fields)
    return true

func time_clip(t: f64) -> f64:
    if t >= -8.64e15 and t <= 8.64e15:
        return math.trunc(t) + 0.0  # convert -0 to +0
    else:
        return math.nan

# The spec mandates the use of 'double' and it specifies the order
# of the operations
## The time value of `fields` (at least 7), local time when `is_local`.
func set_date_fields(fields: const f64[], is_local: bool) -> f64:
    # emulate 21.4.1.15 MakeDay ( year, month, date )
    let y = fields[0]
    var m = fields[1]
    let dt = fields[2]
    let ym = y + math.floor(m / 12.0)
    var mn = math.mod(m, 12.0)
    if mn < 0.0:
        mn += 12.0
    if ym < -271821.0 or ym > 275760.0:
        return math.nan

    let yi = (i64)(i32)ym
    let mi = (i32)mn
    var days = days_from_year(yi)
    for i in 0..<mi:
        days += (i64)month_days[(usize)i]
        if i == 1:
            days += days_in_year(yi) - 365
    let day = f64(days) + dt - 1.0

    # emulate 21.4.1.14 MakeTime ( hour, min, sec, ms )
    let h = fields[3]
    m = fields[4]
    let s = fields[5]
    let milli = fields[6]
    # C uses a volatile intermediary variable to ensure order of evaluation as specified
    # in ECMA (test262/test/built-ins/Date/UTC/fp-evaluation-order.js) and to prevent the
    # generation of FMA. luce-base never contracts or reorders float arithmetic.
    var time = h * 3600000.0
    time += m * 60000.0
    time += s * 1000.0
    time += milli

    # emulate 21.4.1.16 MakeDate ( day, time )
    var tv = day * 86400000.0 + time
    if not math.is_finite(tv):
        return math.nan

    # adjust for local time and clip
    if is_local:
        # the cast saturates to the i64 range as C's explicit clamp does
        let ti = (i64)tv
        tv += f64(get_timezone_offset(ti)) * 60000.0
    return time_clip(tv)

## set_date_fields after truncating `fields` (at least 7) and mapping a year 0-99 to
## 1900-1999; NaN if a field is not finite.
func set_date_fields_checked(fields: f64[], is_local: bool) -> f64:
    for i: usize in 0..<7:
        let a = fields[i]
        if not math.is_finite(a):
            return math.nan
        fields[i] = math.trunc(a)
        if i == 0 and fields[0] >= 0.0 and fields[0] < 100.0:
            fields[0] += 1900.0
    return set_date_fields(fields, is_local)

# mark: Getters and setters =====================================================================

## The Date getters: `magic` is is_local, plus the field number times 0x10, plus 0x100
## for getYear.
func get_date_field(ctx: Context*, this_val: Value, argc: i32, argv: Value*, magic: i32) -> Value!:
    # get_date_field(obj, n, is_local)
    var fields: f64[9] = ---

    let is_local = (magic & 0x0F) != 0
    let n = (usize)((magic >> 4) & 0x0F)
    let res = try get_date_fields(ctx, this_val, fields, is_local, false)
    if not res:
        return js_nan()

    if (magic & 0x100) != 0:
        # getYear
        fields[0] -= 1900.0
    return js_new_float64(fields[n])

## The Date setters: `magic` is is_local, plus the end field times 0x10, plus the first
## field times 0x100.
func set_date_field(ctx: Context*, this_val: Value, argc: i32, argv: Value*, magic: i32) -> Value!:
    # _field(obj, first_field, end_field, args, is_local)
    var fields: f64[9] = ---

    var d = math.nan
    let first_field = (magic >> 8) & 0x0F
    let end_field = (magic >> 4) & 0x0F
    let is_local = (magic & 0x0F) != 0

    var res = try get_date_fields(ctx, this_val, fields, is_local, first_field == 0)
    let res1 = res

    # Argument coercion is observable and must be done unconditionally.
    let n = cutils.min_int(argc, end_field - first_field)
    for i in 0..<n:
        var a: f64 = 0.0
        try js_to_float64(ctx, &a, argv[(usize)i])
        if not math.is_finite(a):
            res = false
        fields[(usize)(first_field + i)] = math.trunc(a)

    if not res1:
        return js_nan()  # thisTimeValue is NaN

    if res and argc > 0:
        d = set_date_fields(fields, is_local)

    return try js_set_this_time_value(ctx, this_val, d)