Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / engine / interp_frames.lucb

#==============================================================================================
#
#   interp_frames - The frames of JS_CallInternal and its call opcodes
#
#   DESCRIPTION:
#       Port of quickjs.c lines 17746-20709, the parts of JS_CallInternal around the
#       dispatch loop of interpreter.lucb: the call opcodes the loop does not make itself
#       (OP_tail_call*, OP_call_constructor) and interp_call_done, which the loop's calls
#       share, the frame setup of a bytecode call or the
#       resumption of a suspended generator frame (interp_enter), the `exception:` label's
#       unwinding to the innermost catch offset (interp_unwind), and the exits that save a
#       generator's frame or release the locals and stack (interp_leave). Each is a
#       noinline function taking the InterpState, so js_call_internal's frame stays small.
#
#==============================================================================================

# mark: Calls ===================================================================================

# The bodies of the call opcodes. OP_call0 to OP_call and OP_call_method are made by the
# dispatch loop itself, as in C, so that one level of JavaScript recursion is one frame of
# js_call_internal; interp_call and interp_call_method run the tail calls.

## The argument count of a call opcode: the u16 operand of OP_call, OP_tail_call,
## OP_call_constructor, OP_call_method and OP_tail_call_method, or `opcode - OP_call0`
## for the short forms (SHORT_OPCODES).
func interp_call_argc(st: InterpState*) -> i32:
    if st.opcode == Op.call0 or st.opcode == Op.call1 or st.opcode == Op.call2 or st.opcode == Op.call3:
        return (i32)(u8)st.opcode - (i32)(u8)Op.call0
    let call_argc = (i32)cutils.get_u16(st.pc)
    st.pc += 2
    return call_argc

## After a call returned st.ret_val: release the function (and `this`, or new.target,
## when `extra` is 2) and the arguments, and push the result in their place. It runs after
## every call the dispatch loop makes, so values are released in place (as the loop's
## fast paths do) and the result is copied as its tag and payload.
func interp_call_done(st: InterpState*, call_argc: i32, extra: i32):
    var pv = st.sp - (usize)(call_argc + extra)
    let base = pv
    while pv < st.sp:
        if (i64)pv.tag < 0:
            *(i32*)((usize)pv.u.uint64 -% 4) -%= 1
            if *(i32*)((usize)pv.u.uint64 -% 4) <= 0:
                free_counted(st.ctx, pv.tag, pv.u.uint64)
        pv += 1
    base.u.uint64 = st.ret_val.u.uint64
    base.tag = st.ret_val.tag
    st.sp = base + 1

## The body of OP_call0 to OP_call3 (SHORT_OPCODES), OP_call and OP_tail_call. After a
## tail call the stack is left as it is: the frame returns st.ret_val (C: goto done).
noinline func interp_call(st: InterpState*) -> bool:
    let call_argc = interp_call_argc(st)
    # has_call_argc:
    let call_argv = st.sp - (usize)call_argc
    st.sf.cur_pc = st.pc
    st.ret_val = js_call_internal(st.ctx, call_argv[-1], js_undefined(), js_undefined(), call_argc, call_argv, 0) catch: return false
    if st.opcode == Op.tail_call:
        return true
    interp_call_done(st, call_argc, 1)
    return true

## The body of OP_call_constructor.
noinline func interp_call_constructor(st: InterpState*) -> bool:
    let call_argc = interp_call_argc(st)
    let call_argv = st.sp - (usize)call_argc
    st.sf.cur_pc = st.pc
    st.ret_val = js_call_constructor_internal(st.ctx, call_argv[-2], call_argv[-1], call_argc, call_argv, 0) catch: return false
    interp_call_done(st, call_argc, 2)
    return true

## The body of OP_call_method and OP_tail_call_method; after a tail call the frame
## returns st.ret_val (C: goto done).
noinline func interp_call_method(st: InterpState*) -> bool:
    let call_argc = interp_call_argc(st)
    let call_argv = st.sp - (usize)call_argc
    st.sf.cur_pc = st.pc
    st.ret_val = js_call_internal(st.ctx, call_argv[-1], call_argv[-2], js_undefined(), call_argc, call_argv, 0) catch: return false
    if st.opcode == Op.tail_call_method:
        return true
    interp_call_done(st, call_argc, 2)
    return true

# mark: Entering and leaving a frame ============================================================

## What interp_enter leaves js_call_internal to do.
enum InterpEntry:
    ## Run the frame from st.pc.
    run
    ## Resume a generator frame at the exception handler (its throw_flag is set).
    throwing
    ## The object was not a bytecode function: its class's call hook ran and st.ret_val
    ## is its result.
    returned
    ## The call failed (C: return JS_EXCEPTION): st.failure_code and st.failure_message
    ## are the failure to raise.
    failed

## Record a failure of interp_enter's for js_call_internal to raise. interp_enter answers
## its result without an error union: a fallible result is copied out through memcpy at
## every return, on every JavaScript call.
func enter_failed(st: InterpState*, code: ErrorCode, message: str) -> InterpEntry:
    st.failure_code = code
    st.failure_message = message
    return InterpEntry.failed

## Throw "not a function" (the not_a_function label) and record the failure.
func enter_not_a_function(st: InterpState*) -> InterpEntry:
    js_throw_type_error(st.caller_ctx, "not a function") catch failure: return enter_failed(st, failure.code, failure.message)

## The start of JS_CallInternal: js_call_internal has stored the call in `st`
## (caller_ctx, func_obj, this_obj, new_target, argc, argv); fill in the rest, then set up
## the frame of a bytecode function (its arguments, variables, stack and variable
## references in `frame_space`, or on the heap when they do not fit), or take the suspended
## frame of a generator, and make it the runtime's current frame.
##
## Every JavaScript call runs it, so the common path is written for the native code it
## becomes: the frame's values are written as tag and payload, the size arithmetic wraps
## as C's does (the operands are u16 counts), and the loops walk pointers.
## How many arguments a call of `b` copies into its frame: all of them when fewer are
## passed than it declares, or the call asks for a copy, else none.
func arguments_copied(b: FunctionBytecode*, argc: i32, flags: i32) -> usize:
    if argc < (i32)b.arg_count or (flags & call_flag_copy_argv) != 0:
        return (usize)b.arg_count
    return 0

## The bytes of the frame a call of `b` lays out (C QuickJS's alloca_size): the copied
## arguments, the variables, the operand stack, and the variable references.
func frame_bytes(b: FunctionBytecode*, argc: i32, flags: i32) -> usize:
    return (arguments_copied(b, argc, flags) +% (usize)b.var_count +% (usize)b.stack_size) *% memory.size_of(Value) +% (usize)b.var_ref_count *% memory.size_of(VarRef*)

## The values of `func_obj`'s frame that js_call_internal takes from its own frame
## (`memory.frame`, as C QuickJS takes them with alloca): 0 for a frame on the heap, a
## generator's, or a function that is not bytecode.
func frame_values(func_obj: Value, argc: i32, flags: i32) -> usize:
    if func_obj.tag != Tag.object or (flags & call_flag_generator) != 0:
        return 0
    let p = func_obj.u.obj
    if p.class_id != ClassId.bytecode_function:
        return 0
    let bytes = frame_bytes(p.u.func_.function_bytecode, argc, flags)
    if bytes > memory.size_of(Value) * js_call_inline_frame_values:
        return 0
    return (bytes +% memory.size_of(Value) -% 1) // memory.size_of(Value)

noinline func interp_enter(st: InterpState*, flags: i32, frame_space: Value*) -> InterpEntry:
    let caller_ctx = st.caller_ctx
    let rt = caller_ctx.rt
    st.rt = rt
    st.ctx = caller_ctx
    st.opcode = Op.invalid
    st.ret_val.u.uint64 = 0
    st.ret_val.tag = Tag.undefined
    st.var_refs = none
    st.heap_frame = none
    # js_poll_interrupts, whose countdown is taken here while the handler's call is more
    # than one step away (it is not expanded inline: it calls)
    if caller_ctx.interrupt_counter > 1:
        caller_ctx.interrupt_counter -%= 1
    else:
        js_poll_interrupts(caller_ctx) catch failure: return enter_failed(st, failure.code, failure.message)
    if st.func_obj.tag != Tag.object:
        if (flags & call_flag_generator) == 0:
            return enter_not_a_function(st)
        let s = (AsyncFunctionState*)st.func_obj.u.ptr
        # func_obj get contains a pointer to JSFuncAsyncState
        # the stack frame is already allocated
        st.sf = &s.frame
        st.p = st.sf.cur_func.u.obj
        st.b = st.p.u.func_.function_bytecode
        st.bc_buf = st.b.byte_code_buf
        st.ctx = st.b.realm
        st.var_refs = st.p.u.func_.var_refs
        st.arg_buf = st.sf.arg_buf else trap("generator frame without arguments")
        st.local_buf = st.arg_buf
        st.var_buf = st.sf.var_buf else trap("generator frame without variables")
        st.stack_buf = st.var_buf + (usize)st.b.var_count
        st.sp = st.sf.cur_sp else trap("generator frame is running")
        st.sf.cur_sp = none  # cur_sp is NULL if the function is running
        st.pc = st.sf.cur_pc else trap("generator frame without pc")
        st.sf.prev_frame = rt.current_stack_frame
        rt.current_stack_frame = st.sf
        if s.throw_flag:
            return InterpEntry.throwing
        return InterpEntry.run
    let p = st.func_obj.u.obj
    st.p = p
    if p.class_id != ClassId.bytecode_function:
        let class_array = rt.class_array else trap("the class array is not allocated")
        let call_func = class_array[(usize)(u16)p.class_id].call else return enter_not_a_function(st)
        st.ret_val = call_func(caller_ctx, st.func_obj, st.this_obj, st.argc, st.argv, flags) catch failure: return enter_failed(st, failure.code, failure.message)
        return InterpEntry.returned
    let b = p.u.func_.function_bytecode
    st.b = b
    st.bc_buf = b.byte_code_buf

    let argc = st.argc
    let arg_count = (usize)b.arg_count
    let arg_allocated_size = arguments_copied(b, argc, flags)
    let var_count = (usize)b.var_count
    let alloca_size = frame_bytes(b, argc, flags)
    if js_check_stack_overflow(rt, alloca_size):
        js_throw_stack_overflow(caller_ctx) catch failure: return enter_failed(st, failure.code, failure.message)

    let sf = st.sf
    sf.js_mode = (i32)b.js_mode
    sf.arg_count = argc
    sf.cur_func = st.func_obj
    st.var_refs = p.u.func_.var_refs

    var local_buf = frame_space
    if alloca_size > memory.size_of(Value) * js_call_inline_frame_values:
        let block = js_malloc(caller_ctx, alloca_size) catch failure: return enter_failed(st, failure.code, failure.message)
        st.heap_frame = block
        local_buf = (Value*)block
    st.local_buf = local_buf
    var arg_buf = st.argv
    if arg_allocated_size != 0:
        # the arguments, then undefined for the missing ones
        let n = (usize)cutils.min_int(argc, (i32)b.arg_count)
        let argv = st.argv
        arg_buf = local_buf
        var i: usize = 0
        while i < n:
            arg_buf[i] = argv[i]
            if (i64)arg_buf[i].tag < 0:
                *(i32*)((usize)arg_buf[i].u.uint64 -% 4) +%= 1
            i +%= 1
        while i < arg_count:
            arg_buf[i].u.uint64 = 0
            arg_buf[i].tag = Tag.undefined
            i +%= 1
        sf.arg_count = (i32)b.arg_count
    st.arg_buf = arg_buf
    let var_buf = local_buf + arg_allocated_size
    st.var_buf = var_buf
    sf.var_buf = var_buf
    sf.arg_buf = arg_buf

    var pv = var_buf
    let stack_buf = var_buf + var_count
    while pv < stack_buf:
        pv.u.uint64 = 0
        pv.tag = Tag.undefined
        pv += 1
    st.stack_buf = stack_buf
    var frame_var_refs = (VarRef*?*)(stack_buf + (usize)b.stack_size)
    sf.var_refs = frame_var_refs
    let var_refs_end = frame_var_refs + (usize)b.var_ref_count
    while frame_var_refs < var_refs_end:
        *frame_var_refs = none
        frame_var_refs += 1
    st.sp = stack_buf
    st.pc = b.byte_code_buf
    sf.prev_frame = rt.current_stack_frame
    rt.current_stack_frame = sf
    st.ctx = b.realm  # set the current realm
    return InterpEntry.run

## The `exception:` label of JS_CallInternal: record the backtrace, then unwind the stack
## to the innermost catch offset, closing the iterators of for-of loops on the way. True
## when a handler was found: the exception is pushed and st.pc is the handler.
noinline func interp_unwind(st: InterpState*) -> bool:
    if is_backtrace_needed(st.ctx, st.rt.current_exception):
        # add the backtrace information now (it is not done
        # before if the exception happens in a bytecode
        # operation
        st.sf.cur_pc = st.pc
        build_backtrace(st.ctx, st.rt.current_exception, none, 0, 0, 0)
    if not st.rt.current_exception_is_uncatchable:
        while st.sp > st.stack_buf:
            st.sp -= 1
            let val = *st.sp
            js_free_value(st.ctx, val)
            if val.tag == Tag.catch_offset:
                let pos = js_value_get_int(val)
                if pos == 0:
                    # enumerator: close it with a throw
                    js_free_value(st.ctx, st.sp[-1])  # drop the next method
                    st.sp -= 1
                    js_iterator_close(st.ctx, st.sp[-1], true) catch: recover ()
                else:
                    *st.sp = st.rt.current_exception
                    st.sp += 1
                    st.rt.current_exception = js_uninitialized()
                    st.pc = st.bc_buf + (usize)pos
                    return true
    return false

## The exits of JS_CallInternal: a suspended generator keeps its frame (pc and sp are
## saved); otherwise the variable references are closed and the locals and stack are
## released. Then the caller's frame becomes current again.
noinline func interp_leave(st: InterpState*, exit: FrameExit):
    # ret_val = JS_EXCEPTION on the exception exit.
    # the local variables are freed by the caller in the generator
    # case. Hence the label 'done' should never be reached in a
    # generator function.
    let sf = st.sf
    if exit == FrameExit.done_generator or (exit == FrameExit.exception and st.b.func_kind != js_func_normal):
        # done_generator:
        sf.cur_pc = st.pc
        sf.cur_sp = st.sp
    else:
        # done:
        if st.b.var_ref_count != 0:
            # variable references reference the stack: must close them
            close_var_refs(st.rt, st.b, sf)
        # free the local variables and stack (released in place, as the dispatch loop does)
        var pval = st.local_buf
        let end = st.sp
        while pval < end:
            if (i64)pval.tag < 0:
                *(i32*)((usize)pval.u.uint64 -% 4) -%= 1
                if *(i32*)((usize)pval.u.uint64 -% 4) <= 0:
                    free_counted(st.ctx, pval.tag, pval.u.uint64)
            pval += 1
    st.rt.current_stack_frame = sf.prev_frame
    if let block = st.heap_frame:
        js_free_rt(st.rt, block)