Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / engine / timezone_regexp_objects.lucb

#==============================================================================================
#
#   timezone_regexp_objects - The local time zone offset, and making RegExp objects
#
#   DESCRIPTION:
#       Port of quickjs.c lines 47450-47698: getTimezoneOffset (the OS-dependent part of
#       Date), and the RegExp object's finalizer, js_compile_regexp (flags and pattern to
#       the compiled program), JS_NewRegexp and js_regexp_set_internal. The Date helpers
#       under `#if 0` (js___date_getTimezoneOffset, js_get_prototype_from_ctor,
#       js___date_create) are not ported.
#
#       A RegExp object owns luce-regex's compiled program where QuickJS keeps a bytecode
#       JSString, so JS_NewRegexp takes the pattern and the flags and compiles them
#       (regexp_bridge.lucb explains the change).
#
#==============================================================================================

# mark: Time zone ===============================================================================

# The C library's `struct tm` on macOS and Linux (on Windows only pointers to it are used).
extern struct Tm:
    tm_sec: i32
    tm_min: i32
    tm_hour: i32
    tm_mday: i32
    tm_mon: i32
    tm_year: i32
    tm_wday: i32
    tm_yday: i32
    tm_isdst: i32
    tm_gmtoff: i64
    tm_zone: void*?

extern func localtime_r(timep: const i64*, result: Tm*) -> Tm*?
# Windows' C library names its 64-bit time functions with a prefix.
extern func win_localtime as "_localtime64"(timep: const i64*) -> Tm*?

# Deviation on Windows. Upstream's _WIN32 branch answers (mktime(gmtime(t)) -
# mktime(localtime(t))) / 60: gmtime's tm_isdst is 0, so the first mktime reads the
# UTC fields as standard time and daylight saving time is never counted (July in
# Pacific time answers 480, not 420), and the CRT's localtime fails before 1970 and
# after 3000, where upstream answers 0. This port reads the offset from localtime's
# fields directly, and maps a year outside 1971..2999 to an equivalent year (same
# leap-ness, same weekday of January 1) that the CRT supports, as V8 does.

## The first and last years whose times the Windows mapping leaves as they are.
let win_first_year: i64 = 1971
let win_last_year: i64 = 2999

## `ti` (seconds) moved to the equivalent year in 2008..2035 when its year is outside
## win_first_year..win_last_year.
func windows_supported_time(ti: i64) -> i64:
    var days = floor_div(ti, 86400)
    let year = year_from_days(&days)
    if year >= win_first_year and year <= win_last_year:
        return ti
    # the weekday of January 1 (1970-01-01 was a Thursday)
    let week_day = math_mod(days_from_year(year) + 4, 7)
    let is_leap = days_in_year(year) == 366
    let recent_year = (1956 if is_leap else 1967) + (week_day * 12) % 28
    let equivalent_year = 2008 + (recent_year + 3 * 28 - 2008) % 28
    return ti + (days_from_year(equivalent_year) - days_from_year(year)) * 86400

## The offset in minutes of UTC from local time at `ti` (seconds) on Windows, from the
## fields of _localtime64.
func windows_timezone_offset(ti: i64) -> i32:
    # under `if` because `luce-base test` compiles this function on every target
    if os.windows:
        let t = windows_supported_time(ti)
        let loc = win_localtime(&t) else return 0
        let local_days = days_from_year((i64)loc.tm_year + 1900) + (i64)loc.tm_yday
        let local_ti = (local_days * 86400 + (i64)loc.tm_hour * 3600 + (i64)loc.tm_min * 60 + (i64)loc.tm_sec)
        return (i32)floor_div(t - local_ti, 60)
    else:
        return 0

# OS dependent. d = argv[0] is in ms from 1970. Return the difference
# between UTC time and local time 'd' in minutes
func get_timezone_offset(time: i64) -> i32:
    # convert to seconds; time_t is 64-bit on every supported target, so upstream's
    # clamping for a 32-bit time_t does not apply
    let ti = time // 1000
    if os.windows:
        return windows_timezone_offset(ti)
    var tm: Tm = ---
    _ = localtime_r(&ti, &tm)
    return (i32)(-tm.tm_gmtoff // 60)

# mark: RegExp objects ==========================================================================

func js_regexp_finalizer(rt: Runtime*, val: Value):
    let p = val.u.obj
    let re = &p.u.regexp
    # the fields are zero when the object was created but never set (a failed
    # construction), although the shared type declares the pattern non-null
    js_regexp_free_program(rt, re)
    if (usize)re.pattern != 0:
        js_free_value_rt(rt, js_mkptr(Tag.string, re.pattern))

# The lre_flag_* flags of a RegExp flags string, or -1 when a letter is unknown or
# repeated.
func js_regexp_parse_flags(flags_text: const u8*, flags_len: usize) -> i32:
    var re_flags: i32 = 0
    # XXX: re_flags = LRE_FLAG_OCTAL unless strict mode?
    for i in 0..<flags_len:
        let mask = match flags_text[i]:
            'd' => lre_flag_indices
            'g' => lre_flag_global
            'i' => lre_flag_ignorecase
            'm' => lre_flag_multiline
            's' => lre_flag_dotall
            'u' => lre_flag_unicode
            'v' => lre_flag_unicode_sets
            'y' => lre_flag_sticky
            _ => 0
        if mask == 0 or (re_flags & mask) != 0:
            return -1
        re_flags |= mask
    return re_flags

# compile the string `pattern` with the lre_flag_* flags `re_flags`
func js_compile_regexp_flags(ctx: Context*, pattern: Value, re_flags: i32) -> regex.Regex*!:
    var error_msg: u8[64] = ---

    var len: usize = 0
    let text = try js_to_c_string_len2(ctx, &len, pattern,
                                       (re_flags & (lre_flag_unicode | lre_flag_unicode_sets)) == 0)
    let host = js_regexp_host(ctx.rt)
    let program = regex.compile_ecmascript(u8[]((u8*)text, len), re_flags, error_msg, &host)
    js_free_c_string(ctx, text)
    if let compiled = program:
        return compiled
    let msg = str(error_msg[0..<cutils.strlen(&error_msg[0])]) catch: recover "invalid regular expression"
    try js_throw_syntax_error(ctx, msg)

# create the program of a RegExp from its pattern and flags
func js_compile_regexp(ctx: Context*, pattern: Value, flags: Value) -> regex.Regex*!:
    var re_flags: i32 = 0
    if not js_is_undefined(flags):
        var flags_len: usize = 0
        let flags_text = try js_to_c_string_len(ctx, &flags_len, flags)
        re_flags = js_regexp_parse_flags(flags_text, flags_len)
        js_free_c_string(ctx, flags_text)
        if re_flags < 0:
            try js_throw_syntax_error(ctx, "invalid regular expression flags")

    # 'u' and 'v' cannot be both set
    if (re_flags & lre_flag_unicode_sets) != 0 and (re_flags & lre_flag_unicode) != 0:
        try js_throw_syntax_error(ctx, "invalid regular expression flags")

    return try js_compile_regexp_flags(ctx, pattern, re_flags)

# The program of the literal of `b` whose constants are the strings `pattern` and `flags`:
# compiled at its first evaluation and kept in the function's regexp_cache.
func js_regexp_literal_program(ctx: Context*, b: FunctionBytecode*, pattern: Value, flags: Value) -> RegExpShared*!:
    var next = b.regexp_cache
    while let shared = next:
        if shared.pattern == pattern.u.string and shared.flags == flags.u.string:
            return shared
        next = shared.next
    let program = try js_compile_regexp(ctx, pattern, flags)
    let block = js_malloc(ctx, memory.size_of(RegExpShared)) catch failure:
        regex.free_ecmascript(program)
        error(failure.code, failure.message)
    let shared = (RegExpShared*)block
    shared.ref_count = 1  # the function's
    shared.program = program
    shared.pattern = pattern.u.string
    shared.flags = flags.u.string
    shared.next = b.regexp_cache
    b.regexp_cache = shared
    return shared

# fast regexp creation: the pattern and flags strings (the constants of a literal of the
# function `b`) give the literal's program, where QuickJS gets the bytecode string. Takes
# both values.
func js_new_regexp(ctx: Context*, b: FunctionBytecode*, pattern: Value, flags: Value) -> Value!:
    var props: Property[1] = ---

    errdefer js_free_value(ctx, pattern)
    defer js_free_value(ctx, flags)
    # sanity check
    if flags.tag != Tag.string or pattern.tag != Tag.string:
        try js_throw_type_error(ctx, "string expected")
    let shared = try js_regexp_literal_program(ctx, b, pattern, flags)
    props[0].u.value = js_new_int32(0)  # lastIndex
    let regexp_shape = ctx.regexp_shape else trap("js_new_regexp: no regexp shape")
    let obj = try js_new_object_from_shape(ctx, js_dup_shape(regexp_shape), (u32)ClassId.regexp, &props[0])
    let p = obj.u.obj
    let re = &p.u.regexp
    re.pattern = pattern.u.string
    shared.ref_count += 1
    re.shared = shared
    re.program = shared.program
    return obj

# set the RegExp fields; takes the object, the pattern and the program, also on failure
func js_regexp_set_internal(ctx: Context*, obj: Value, pattern: Value, program: regex.Regex*) -> Value!:
    # sanity check
    if pattern.tag != Tag.string:
        js_free_value(ctx, obj)
        regex.free_ecmascript(program)
        js_free_value(ctx, pattern)
        try js_throw_type_error(ctx, "string expected")

    let p = obj.u.obj
    let re = &p.u.regexp
    re.pattern = pattern.u.string
    re.program = program
    # Note: cannot fail because the field is preallocated
    js_define_property_value(ctx, obj, atom_lastIndex, js_new_int32(0), prop_writable) catch: recover false
    return obj