module scheme import reader import lexer // Only compiler-produced instruction operands and VM-owned stack indices reach // the handlers below. Public calls construct their argument ranges here; vector // indices and other user data remain checked inside the primitive procedures. // Direct array access avoids generic array_get/array_set calls in that trusted // execution machinery. Sanitizer tests cover the stack and capture invariants. // Return frames contain only execution registers. Arguments and intermediate // results share one value stack instead of allocating an array for every call. struct CallFrame { function &Function = unsafe { nil } env &Environment = unsafe { nil } ip int base int } @[heap] struct Machine { mut: context u64 logical_context u64 wind &WindFrame = unsafe { nil } function &Function = unsafe { nil } env &Environment = unsafe { nil } ip int base int origin reader.NodeId = reader.no_node stack []Value frames []CallFrame bridge_sites []BridgeSite steps int expansions int finished bool spares [8]&Environment wide_spares &Environment = unsafe { nil } cached int parameters &ParameterBinding = unsafe { nil } parameter_base &ParameterBinding = unsafe { nil } library_context &LibraryContext = unsafe { nil } close_failure &CustomCloseFailure = unsafe { nil } // Set only while a selected method enters its closure. The continuation // keeps the resulting lexical slot, not this transient machine field. goops_pending_next Value goops_migrations &GoopsMigrationScope = unsafe { nil } goops_cache_owner voidptr = v_arena_current() goops_borrowed_cache []GoopsBorrowedMethods goops_applicability_cache []GoopsBorrowedApplicability } fn (mut m Machine) charge(limit int) ! { if limit > 0 && m.steps >= limit { return failure('evaluation step limit exceeded') } m.steps++ } fn (m &Machine) located(err IError) IError { if is_control_transfer(err) { return err } if err is reader.ReadError || err is lexer.LexError { return err } if err is EvalError { if err.line > 0 || err.source_path != '' { return err } } site := m.error_site() if isnil(site.function) { return err } return site.function.code.source_failure(site.origin, err) } // V array pop/trim keep spare storage. Clear dead handles so conservative GC // does not retain returned closures/environments through unused stack capacity. @[direct_array_access] fn (mut m Machine) truncate(length int) { for i in length .. m.stack.len { container_store_validated(mut m.stack, i, Value{}) } // The stack owns its buffer. Its only slices are borrowed arguments whose // calls have finished before truncation. V's generic trim would copy the // buffer after such a slice; changing only the header is safe here. unsafe { m.stack.len = length } } @[direct_array_access] fn (mut m Machine) pop_value() Value { index := m.stack.len - 1 value := m.stack[index] m.truncate(index) return value } // This stack owns its buffer; argument views are borrowed only while a native // or primitive call runs. Reentry uses another Machine, and snapshots clone the // live prefix. Generic array push checks sharing and copies a type-erased value // even when spare capacity is already available. Keep that path only for growth. @[direct_array_access; inline] fn (mut m Machine) push(value Value) { if m.stack.len < m.stack.cap { unsafe { (&Value(m.stack.data))[m.stack.len] = value m.stack.len++ } } else { m.stack << value } } // Cached entry has checked spare capacity in this machine's private buffer. // Continuation and control snapshots own separate frame buffers. @[direct_array_access; inline] fn (mut m Machine) append_reserved_frame(frame CallFrame) { unsafe { (&CallFrame(m.frames.data))[m.frames.len] = frame m.frames.len++ } } fn (env &Environment) ancestor(depth int) &Environment { mut current := EnvironmentRef{ value: env } for _ in 0 .. depth { current = EnvironmentRef{ value: current.value.parent } } return current.value } @[direct_array_access] fn (mut m Machine) finish_call(value Value) { // An unescaped activation cannot be observed after return. Keep a bounded // set of small activations by slot count. While inactive, parent links the // free list; every value slot is cleared before the object enters the cache. if !isnil(m.env) && m.env.tail_parent { m.release_tail_parents(unsafe { nil }) } if !isnil(m.env) { m.cache_environment(mut m.env) } m.truncate(m.base) m.push(value) if m.frames.len == 0 { m.release_bridge_sites(-1) m.finished = true return } index := m.frames.len - 1 frame := m.frames[index] container_store_validated(mut m.frames, index, CallFrame{}) m.frames.trim(index) m.release_bridge_sites(m.frames.len) m.function = frame.function m.env = frame.env m.ip = frame.ip m.base = frame.base } // One dispatcher source specializes the ordinary loop, the host-controlled // loop and the private single-step test entry. Keeping dispatch inside its loop // avoids relying on a C compiler's translation-unit inlining budget. struct PlainMachineLoop {} struct ControlledMachineLoop {} struct SingleMachineStep {} fn (mut m Machine) run(mut vm VM) !Value { for { value := m.run_once(mut vm) or { // A failed method entry can leave this transient handoff pending. // Managed cleanup must enter its own callbacks without inheriting it. m.goops_pending_next = Value{} m.cleanup_goops_migrations() if is_control_transfer(err) { return m.abandon_process_exit_cleanup(mut vm, err) } if !isnil(m.close_failure) { original := m.close_failure.original // A budget/cancellation failure before a cleanup callback can start must // not rebuild the same queue indefinitely. Existing controls remain live. if !m.close_failure.in_flight { if m.recover_process_exit_cleanup(mut vm, m.close_failure.exit_recovery)! { continue } return m.abandon_process_exit_cleanup(mut vm, original) } if m.begin_custom_close_failure(vm.owner, original) { continue } if m.recover_process_exit_cleanup(mut vm, m.close_failure.exit_recovery)! { continue } return m.abandon_process_exit_cleanup(mut vm, original) } if m.begin_custom_close_failure(vm.owner, err) { continue } if m.recover_process_exit_cleanup(mut vm, unsafe { nil })! { continue } return m.abandon_process_exit_cleanup(mut vm, err) } return value } } fn (mut m Machine) run_once(mut vm VM) !Value { if !isnil(vm.system) && !isnil(vm.system.evaluation) { return m.run_controlled(mut vm, vm.system.evaluation) } return m.dispatch[PlainMachineLoop](mut vm, Instruction{}, unsafe { nil }) } fn (mut m Machine) execute(mut vm VM, instruction Instruction) ! { m.dispatch[SingleMachineStep](mut vm, instruction, unsafe { nil })! } @[direct_array_access] fn (mut m Machine) dispatch[T](mut vm VM, initial Instruction, control &EvaluationControl) !Value { mut instruction := initial for { $if T is ControlledMachineLoop { control.check_control() or { vm.cleanup_pending_exit_files(m, err) return m.located(err) } } $if T !is SingleMachineStep { if m.finished { break } instruction = m.function.instructions[m.ip] m.ip++ m.origin = instruction.origin m.charge(vm.options.max_steps) or { vm.cleanup_pending_exit_files(m, err) return m.located(err) } } mut dispatch_error := IError(unsafe { nil }) mut dispatch_failed := false a, b := int(instruction.a), int(instruction.b) match instruction.op { .constant { m.push(m.function.constants[a]) } .local { scope := m.env.ancestor(a) value := scope.slots[b] if value.tag == .uninitialized { dispatch_error = failure('variable used before initialization') dispatch_failed = true } else { m.push(value) } } .global { mut index := m.function.global_slots[a] if index >= 0 { value := vm.read_global(index) $if T is PlainMachineLoop { if isnil(vm.owner.bounded_files) && value.tag == .procedure && m.fuse_primitive_operands(vm, value) { continue } } m.push(value) } else if resolved := vm.global_index_in(m.function.code.namespace, m.function.names[a]) { m.function.global_slots[a] = resolved m.push(vm.read_global(resolved)) } else { dispatch_error = err dispatch_failed = true } } .define_local, .assign_local { mut scope := m.env.ancestor(a) scope.slots[b] = m.pop_value() m.push(unspecified()) } .closure { mut function := m.function.children[a] if function.capture_depth == 0 { closed := if isnil(function.closed) { function.new_closed_procedure(vm.owner) } else { function.closed } m.push(procedure_value(closed)) } else { escape_environment(m.env) m.push(procedure_value(&Procedure{ mode: .closure, owner: vm.owner, function: function, env: m.env })) } } .drop { m.pop_value() } .duplicate { m.push(m.stack.last()) } .swap { last := m.stack.len - 1 value := m.stack[last] container_store_validated(mut m.stack, last, m.stack[last - 1]) container_store_validated(mut m.stack, last - 1, value) } .jump { m.ip = a } .jump_false { if !m.pop_value().is_true() { m.ip = a } } .and_jump, .or_jump { if m.stack.last().is_true() == (instruction.op == .or_jump) { m.ip = a } else { m.pop_value() } } .case_match { key := m.stack.last() mut matched := false for datum in m.function.constants[b].vector_pointer().items { if eqv(key, datum) { matched = true break } } if matched { m.pop_value() } else { m.ip = a } } .call, .tail_call { mut handled := false if a == 2 && isnil(vm.owner.bounded_files) { base := m.stack.len - 3 callable := m.stack[base] if callable.tag == .procedure { p := callable.procedure_pointer() x, y := m.stack[base + 1], m.stack[base + 2] if p.mode == .primitive && isnil(p.env) && voidptr(p.owner) == voidptr(vm.owner) { mut value := Value{} mut ready := false if int(p.primitive) <= int(Primitive.greater_equal) && x.tag == .integer && y.tag == .integer { value = small_integer_call(p.primitive, x.whole(), y.whole()) ready = value.tag != .unspecified } else if x.tag == .integer && y.tag == .integer && p.primitive in [.quotient, .remainder, .modulo] { xv, yv := x.whole(), y.whole() // Keep promotion and zero errors on the ordinary path. if yv != 0 && !(p.primitive == .quotient && xv == exact_min && yv == -1) { value = small_integer_division(p.primitive, xv, yv, false, xv < 0, yv < 0) or { unspecified() } ready = value.tag != .unspecified } } else if p.primitive == .vector_ref && x.tag == .vector && y.tag == .integer { index := y.whole() items := x.vector_pointer().items if index >= 0 && index < items.len { value = items[int(index)] ready = true } } if ready { handled = true m.charge(vm.options.max_steps) or { dispatch_error = err dispatch_failed = true } if !dispatch_failed { if instruction.op == .tail_call { m.finish_call(value) } else { m.truncate(base + 1) container_store_validated(mut m.stack, base, value) } } } } } } // A write must charge its application before changing the vector. // Invalid operands and extended primitives retain the full dispatcher. if a == 3 && isnil(vm.owner.bounded_files) { base := m.stack.len - 4 callable := m.stack[base] if callable.tag == .procedure { p := callable.procedure_pointer() target, index := m.stack[base + 1], m.stack[base + 2] if p.mode == .primitive && p.primitive == .vector_set && isnil(p.env) && voidptr(p.owner) == voidptr(vm.owner) && target.tag == .vector && !target.read_only && index.tag == .integer { i := index.whole() mut content := target.vector_pointer() if i >= 0 && i < content.items.len { handled = true m.charge(vm.options.max_steps) or { dispatch_error = err dispatch_failed = true } if !dispatch_failed { container_store_validated(mut content.items, int(i), m.stack[base + 3]) if instruction.op == .tail_call { m.finish_call(unspecified()) } else { m.truncate(base + 1) container_store_validated(mut m.stack, base, unspecified()) } } } } } } if !handled { $if T is PlainMachineLoop { if isnil(vm.owner.bounded_files) && m.enter_cached_closure[T](vm, a, instruction.op == .tail_call) { continue } } $if T is PlainMachineLoop { m.apply_with_values_forward(mut vm, a, instruction.op == .tail_call, true) or { dispatch_error = err dispatch_failed = true } } $else { m.apply(mut vm, a, instruction.op == .tail_call) or { dispatch_error = err dispatch_failed = true } } } } .ret { m.finish_call(m.pop_value()) } else { m.execute_extended(mut vm, instruction) or { dispatch_error = err dispatch_failed = true } } } $if T is SingleMachineStep { if dispatch_failed { return dispatch_error } return unspecified() } if dispatch_failed { if m.accept_transfer(mut vm, dispatch_error) or { vm.cleanup_pending_exit_files(m, err) return m.located(err) } { continue } vm.cleanup_pending_exit_files(m, dispatch_error) return m.located(dispatch_error) } } return m.stack[0] } // Keep the cold cache miss outside the hot loop. Only a Procedure born in its // compiled Function's allocation owner may become a persistent cached value. @[noinline] fn (mut function Function) new_closed_procedure(owner &Owner) &Procedure { closed := &Procedure{ mode: if isnil(function.star) { .closure } else { .closure_star }, owner: owner, function: function } if (isnil(function.code) && v_arena_current() == unsafe { nil }) || (!isnil(function.code) && v_arena_current() == function.code.allocation_owner) { function.closed = closed } return closed } // Keep compound construction and control setup outside the common dispatch. // Otherwise GCC's inlining threshold can turn every instruction into an extra // call when a new cold handler is added. This boundary keeps that cost local. @[direct_array_access; noinline] fn (mut m Machine) execute_extended(mut vm VM, instruction Instruction) ! { a, b := int(instruction.a), int(instruction.b) match instruction.op { .syntax_match { m.match_syntax_case(mut vm, a)! } .syntax_scope_call, .syntax_scope_tail { m.call_syntax_scope(mut vm, instruction.op == .syntax_scope_tail)! } .syntax_accept { m.accept_syntax_clause()! } .syntax_return_call { m.call_syntax_return(mut vm, b)! } .syntax_expand { m.expand_syntax_value(a)! } .implicit_call { if m.stack.last().is_callable() { m.apply(mut vm, 0, a != 0)! } } .exit_mark { m.mark_exit(a) } .early_return { m.return_early(mut vm, a, b)! } .return_call { m.call_return(mut vm, a, b)! } .loop_continue { m.continue_loop(mut vm, a, b)! } .scope_function { m.push(payload_value(.scope_function, m.function.children[a])) } .scope_call, .scope_tail { m.call_scope(mut vm, a, instruction.op == .scope_tail)! } .define_global { slot := vm.bind_global_in(m.function.code.namespace, m.function.names[a], m.pop_value())! m.function.global_slots[a] = slot if b < 0 { vm.bind_global_alias_in(m.function.code.namespace, m.function.names[global_alias_index(instruction.b)], slot)! } m.push(unspecified()) } .case_lambda { m.make_case_lambda(vm.owner, a) } .assign_resolved_global { index := m.function.global_slots[a] vm.replace_global(index, m.pop_value()) m.push(unspecified()) } .enumeration_define { m.push(new_enumeration(m.function.constants[a].enumeration_pointer().enumeration.universe)) } .enumeration_select { m.push(enumeration_select(m.pop_value(), m.function.constants[a])!) } .record_define { m.define_record(vm.owner, record_spec_pointer(m.function.constants[a])) } .record_operations { m.record_operations(vm.owner, record_spec_pointer(m.function.constants[a])) } .record_make_type { start := m.stack.len - 6 value := record_make_type(mut vm, m.arguments(start))! m.truncate(start) m.push(value) } .record_make_cd { start := m.stack.len - 3 if b != 0 && !m.stack[start + 2].is_callable() { return failure('record protocol expression must produce a procedure') } if a != 0 && !m.stack[start + 1].record_false() { return failure('parent-rtd without protocol requires #f parent constructor descriptor') } value := record_make_cd(mut vm, m.arguments(start))! m.truncate(start) m.push(value) } .record_prepare { m.prepare_record(mut vm)! } .record_prepared { value := record_protocol_result(mut vm, m.pop_value())! m.finish_call(value) } .record_parent_prepare { m.prepare_record_parent() } .record_parent_apply { m.apply_record_parent(mut vm)! } .record_factory { argument := m.pop_value() m.push(vm.record_factory_value()) m.push(argument) m.apply(mut vm, 1, false)! } .record_default_cd { rtd := record_checked_type(m.pop_value())! m.push(vm.record_default_constructor_descriptor(rtd)) } .record_name_define { vm.install_record_name(m.function, a, b)! } .record_auto_uid { m.push(vm.record_auto_uid(m.function.constants[a])) } .global_reference { m.load_global_reference(mut vm, a, instruction)! } .assign_global_reference { m.assign_global_reference(mut vm, a, instruction)! } .unpack_values { m.unpack_values(a, b != 0)! } .source_form { m.enter_source_form(mut vm, reader.NodeId(a), b != 0)! } .load_enter { m.enter_load(mut vm)! } .process_exit_finish { m.finish_process_exit(mut vm, a)! } .sort_init { m.start_sort(unsafe { SortKind(a) })! } .sort_step { m.step_sort(mut vm)! } .sort_collect { m.collect_sort()! } .list_utility_init { m.start_list_utility(unsafe { ListUtilityKind(a) })! } .list_utility_step { m.step_list_utility(mut vm)! } .list_utility_collect { m.collect_list_utility()! } .port_io_enter { m.enter_custom_port_operation()! } .port_io_step { m.step_custom_port_operation(mut vm)! } .port_io_collect { m.collect_custom_port_operation()! } .port_error_close_step { m.step_custom_close_failure(mut vm)! } .port_error_close_collect { m.collect_custom_close_failure() } .hashtable_init { m.start_hashtable(unsafe { HashtableOperation(a) })! } .hashtable_step { m.step_hashtable(mut vm)! } .hashtable_collect { m.collect_hashtable()! } .library_define { vm.register_library(unsafe { &LibraryDeclaration(m.function.constants[a].pointer()) })! m.push(unspecified()) } .library_import { request := unsafe { &LibraryImports(m.function.constants[a].pointer()) } m.push(vm.import_driver(request, m.function.code.namespace, m.source_path(), unspecified())!) m.apply(mut vm, 0, false)! } .library_commit { m.push(vm.commit_library_imports(unsafe { &LibraryImportState(m.function.constants[a].pointer()) })!) } .library_complete { vm.complete_library(unsafe { &Library(m.function.constants[a].pointer()) })! m.push(unspecified()) } .library_mark_enter { m.enter_library_context(unsafe { &Library(m.function.constants[a].pointer()) }) m.push(unspecified()) } .library_init_guard { library := unsafe { &Library(m.function.constants[a].pointer()) } match library.status { .ready { m.finish_call(unspecified()) } .registered {} .failed { return failure('library ${library.name.display} initialization previously failed') } .suspended { return failure('library ${library.name.display} initialization is suspended; resume its continuation') } .initializing { return failure('library ${library.name.display} initialization is already in progress') } } } .library_mark_leave { m.leave_library_context(unsafe { &Library(m.function.constants[a].pointer()) }) m.push(unspecified()) } .define_syntax { definition := m.function.code.syntax_exports[a] vm.bind_syntax_in(m.function.code.namespace, definition.name, definition.transformer)! m.push(unspecified()) } .qq_cons, .qq_splice { tail := m.pop_value() head := m.pop_value() value := if instruction.op == .qq_cons { cons(head, tail) } else { splice_onto(head, tail)! } m.push(value) } .qq_prefix { items := m.function.constants[a].vector_pointer().items mut value := m.pop_value() for i := items.len - 1; i >= 0; i-- { value = cons(items[i], value) } m.push(value) } .qq_vector { flags := m.function.constants[a].text() start := m.stack.len - flags.len items := m.arguments(start) value := if b == 0 { vector(items) } else { splice_vector(items, flags)! } m.truncate(start) m.push(value) } .call_values_tail { result := m.pop_value() if result.tag == .multiple { if result.pointer() == unsafe { nil } { m.apply(mut vm, 0, true)! } else { items := result.vector_pointer().items m.stack << items m.apply(mut vm, items.len, true)! } } else { m.push(result) m.apply(mut vm, 1, true)! } } .map_init { m.start_iteration(a != 0)! } .map_step { m.step_iteration(mut vm)! } .map_collect { m.collect_iteration() } .indexed_init { m.start_indexed_iteration(a != 0, b != 0)! } .indexed_step { m.step_indexed_iteration(mut vm)! } .indexed_collect { m.collect_indexed_iteration()! } .search_init { m.start_comparison_search(a != 0)! } .search_step { m.step_comparison_search(mut vm, a != 0)! } .search_collect { m.collect_comparison_search(a != 0)! } .promise { function := m.function.children[a] mut env := if function.capture_depth == 0 { unsafe { &Environment(nil) } } else { m.env } escape_environment(env) m.push(payload_value(.promise, &Promise{ owner: vm.owner, function: function, env: env, lazy: b != 0 })) } .eval_enter { m.enter_eval(mut vm)! } .file_init { m.init_file_control(mut vm, unsafe { FileMode(a) })! } .file_enter { m.enter_file_control(mut vm)! } .file_leave { m.leave_file_control(mut vm)! } .file_return { m.return_file_body(mut vm, a != 0)! } .file_argument { m.push(m.file_extent().file) } .file_parameterize { m.parameterize_file_body(mut vm, a)! } .force_enter { m.enter_force(mut vm)! } .force_finish { m.finish_force(mut vm, a != 0)! } .make_promise { value := m.env.slots[0] m.finish_call(if value.tag == .promise { value } else { payload_value(.promise, &Promise{ owner: vm.owner, ready: true, result: value }) }) } .wind_init { m.start_wind(mut vm)! } .parameter_create { m.create_parameter(mut vm)! } .parameter_created { m.created_parameter(vm.owner)! } .parameter_set { m.convert_parameter_assignment(mut vm)! } .parameter_assigned { m.assign_parameter()! } .assignment_setter { base := m.stack.len - a - 1 getter := m.stack[base] primitive := vm.goops.primitive_setter if !isnil(primitive.procedure_pointer().env) && (getter.tag != .procedure || getter.procedure_pointer().mode !in [.with_setter, .goops_generic_setter, .goops_accessor]) { m.push(primitive.procedure_pointer().env.slots[0]) m.push(getter) m.apply(mut vm, 1, false)! } else { setter := vm.setter_for(getter)! container_store_validated(mut m.stack, base, setter) m.ip++ } } .assignment_setter_result { setter := m.pop_value() container_store_validated(mut m.stack, m.stack.len - a - 1, setter) } .assignment_finish { container_store_validated(mut m.stack, m.stack.len - 1, unspecified()) } .star_bound_skip { if m.env.slots[b].tag != .uninitialized { m.ip = a } } .star_closure { mut function := m.function.children[a] if function.capture_depth == 0 { closed := if isnil(function.closed) { function.new_closed_procedure(vm.owner) } else { function.closed } m.push(procedure_value(closed)) } else { escape_environment(m.env) m.push(procedure_value(&Procedure{ mode: .closure_star, owner: vm.owner, function: function, env: m.env })) } } .goops_make_class { vm.ensure_goops() start := m.stack.len - a if vm.goops.protocols_ready { // The evaluated class operands become an ordinary // call, so custom metaclasses share this machine's continuations. m.push(m.stack.last()) for index := a; index > 0; index-- { container_store_validated(mut m.stack, start + index, m.stack[start + index - 1]) } container_store_validated(mut m.stack, start, vm.goops.class_constructor) m.apply(mut vm, a, false)! } else { value := goops_make_class_native(mut vm, m.arguments(start))! m.truncate(start) m.push(value) } } .goops_top { vm.ensure_goops() m.push(goops_class_value(vm.goops.top)) } .goops_define_generic { vm.ensure_goops() start := m.stack.len - 1 generic := m.goops_definition_generic(mut vm, a, if b < 0 { -b - 1 } else { b }, m.stack[start], b >= 0, b < 0)! m.truncate(start) m.push(if b < 0 { generic } else { unspecified() }) } .goops_define_accessor { vm.ensure_goops() start := m.stack.len - 1 accessor := m.goops_definition_accessor(mut vm, a, if b < 0 { -b - 1 } else { b }, m.stack[start], b >= 0)! m.truncate(start) m.push(if b < 0 { accessor } else { unspecified() }) } .goops_define_method { vm.ensure_goops() start := m.stack.len - 5 rest := b < 0 slot := if rest { -b - 1 } else { b } method := vm.goops_new_method(m.stack[start + 1], m.stack[start + 2], rest)! mut metadata := method.goops_method_pointer() metadata.formals = m.stack[start + 3] metadata.body = m.stack[start + 4] generic := m.goops_definition_generic(mut vm, a, slot, m.stack[start], false, false)! vm.goops_add_method(generic, method)! m.truncate(start) m.push(unspecified()) } .goops_make_method { vm.ensure_goops() start := m.stack.len - 4 method := vm.goops_new_method(m.stack[start], m.stack[start + 1], a != 0)! mut metadata := method.goops_method_pointer() metadata.formals = m.stack[start + 2] metadata.body = m.stack[start + 3] m.truncate(start) m.push(method) } .goops_retry_enter { m.enter_goops_retry(mut vm)! } .goops_retry_finish { m.finish_goops_retry(mut vm)! } .goops_factory_apply { m.finish_goops_factory(mut vm)! } .goops_applicability_apply { m.finish_goops_applicability(mut vm)! } .goops_effective_apply { m.finish_goops_effective(mut vm)! } .goops_equal_init { m.start_goops_equal() } .goops_equal_step { m.step_goops_equal(mut vm)! } .goops_equal_resume { m.resume_goops_equal() } .goops_migration_start { m.start_goops_migration(mut vm)! } .goops_migration_retry { m.retry_goops_migration(mut vm)! } .goops_class_redefinition { m.redefine_goops_binding(mut vm, a, b)! } .goops_virtual_read_enter { m.enter_goops_virtual_read(mut vm)! } .goops_virtual_read_finish { m.finish_goops_virtual_read(mut vm)! } .goops_missing_enter { m.enter_goops_missing(mut vm)! } .goops_missing_read_finish { m.finish_goops_missing_read(mut vm)! } .goops_bound_enter { m.push(m.env.slots[0]) m.push(m.env.slots[1]) m.apply(mut vm, 1, false)! } .goops_bound_finish { m.finish_call(boolean(!vm.goops_unbound(m.pop_value()))) } .parameter_init { m.validate_parameter_bindings(mut vm, a)! } .parameter_convert { m.convert_parameter_binding(mut vm, a)! } .parameter_converted { m.converted_parameter_binding(a)! } .parameter_install { m.install_parameter_bindings(mut vm, a)! } .parameter_finish { m.finish_parameter_bindings(a) } .wind_enter { m.enter_wind(mut vm)! } .wind_leave { m.leave_wind(mut vm)! } .wind_finish { m.finish_wind() } .wind_step { m.step_wind_transfer(mut vm)! } .wind_resume { m.resume_wind_transfer() } .fail { return m.function.failures[a] } else { return failure('invalid extended instruction') } } } // Internal bridges and the independent single-step/control paths retain the // original packet protocol. Only the ordinary dispatcher enables forwarding. @[inline] fn (mut m Machine) apply(mut vm VM, count int, tail bool) ! { return m.apply_with_values_forward(mut vm, count, tail, false) } @[direct_array_access] fn (mut m Machine) apply_with_values_forward(mut vm VM, count int, tail bool, allow_values_forward bool) ! { mut argc := count mut call_base := m.stack.len - argc - 1 for { m.charge(vm.options.max_steps)! callable := m.stack[call_base] if callable.tag != .procedure { if callable.goops_kind() == .goops_instance { if vm.goops.has_redefinitions && goops_needs_migration(callable) { m.prepare_goops_migration(vm, callable, call_base)! argc = 3 continue } container_store_validated(mut m.stack, call_base, vm.goops_resolve_callable(callable)!) continue } return failure('attempt to call a ${callable.tag}') } p := callable.procedure_pointer() if voidptr(p.owner) != voidptr(vm.owner) { return failure('procedure belongs to another VM') } match p.mode { .native, .primitive { // Unary gcd/lcm share abs's extension even if only abs was extended. if argc == 1 && p.primitive in [.gcd, .lcm] && !is_integer_number(m.stack[call_base + 1]) { abs := vm.goops.primitive_abs if abs.tag == .procedure && (!isnil(p.env) || !isnil(abs.procedure_pointer().env)) { container_store_validated(mut m.stack, call_base, abs) continue } } if !isnil(p.env) { forwarded := m.prepare_goops_primitive(vm, p, call_base, argc)! if forwarded >= 0 { argc = forwarded continue } } if p.mode == .native && vm.goops.has_redefinitions { obsolete := m.goops_native_obsolete_argument(mut vm, p, call_base, argc)! if obsolete.tag != .unspecified { m.prepare_goops_migration(vm, obsolete, call_base)! argc = 3 continue } } // The application is already charged. Successful scalar reads avoid // slicing arguments and the general primitive/arity dispatchers. mut read := unspecified() if p.mode == .primitive && isnil(p.env) && isnil(vm.owner.bounded_files) && argc > 0 && argc <= 2 && int(p.primitive) > int(Primitive.greater_equal) { read = read_primitive(p.primitive, m.stack[call_base + 1], if argc == 2 { m.stack[call_base + 2] } else { Value{} }, argc) } value := if read.tag != .unspecified { read } else if p.mode == .primitive && !isnil(vm.owner.bounded_files) { vm.owner.bounded_files.apply_primitive(p.primitive, m.arguments(call_base + 1), p.name)! } else if p.mode == .primitive && argc == 2 && int(p.primitive) <= int(Primitive.greater_equal) && m.stack[call_base + 1].tag == .integer && m.stack[call_base + 2].tag == .integer { binary_integer(p.primitive, m.stack[call_base + 1], m.stack[call_base + 2])! } else { args := m.arguments(call_base + 1) if p.mode == .native { result := p.native(mut vm, args)! if !isnil(vm.owner.bounded_files) { if reason := vm.owner.bounded_files.interrupted { return bounded_allocation_request(reason) } } result } else { primitive_call(p.primitive, args, p.name)! } } if tail { m.finish_call(value) } else { // The callable already reserves the result slot. Clear only // arguments, then overwrite it without a pop-and-push cycle. m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .closure { function := p.function check_arity(if p.name == '' { 'lambda' } else { p.name }, argc, function.params, if function.rest { -1 } else { function.params })! if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames { return failure('continuation frame limit exceeded') } $if vile_native ? { if !isnil(vm.native_execution_scope) { if value := m.try_native_execution(mut vm, callable, call_base, argc) { if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } } } if !tail { m.reserve_frame_slot(vm)! } if isnil(function.code) { m.enter_bridge(vm, tail)! } mut scope := m.checked_activation(vm, p, tail)! for index in 0 .. function.params { scope.slots[index] = m.stack[call_base + 1 + index] } if function.rest { scope.slots[function.params] = m.rest_arguments(vm, call_base, function.params, argc)! } if m.goops_pending_next.tag != .unspecified { m.bind_goops_next(vm, mut scope, function, call_base, argc, argc)! } if !tail { m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base } m.base = call_base } m.truncate(if tail { m.base } else { call_base }) m.function = function m.env = scope m.ip = 0 return } .closure_star { function := p.function formals := function.star check_arity('lambda*', argc, formals.required, if formals.has_keys || formals.rest_slot >= 0 { -1 } else { formals.required + formals.optional })! optional_end := m.validate_star_arguments(formals, call_base, argc)! if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames { return failure('continuation frame limit exceeded') } if !tail { m.reserve_frame_slot(vm)! } if isnil(function.code) { m.enter_bridge(vm, tail)! } mut scope := m.checked_activation(vm, p, tail)! m.bind_star_arguments(vm, mut scope, formals, call_base, argc, optional_end)! if m.goops_pending_next.tag != .unspecified { m.bind_goops_next(vm, mut scope, function, call_base, argc, optional_end)! } if !tail { m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base } m.base = call_base } m.truncate(if tail { m.base } else { call_base }) m.function = function m.env = scope m.ip = 0 return } .goops_method_factory { check_arity('method factory', argc, 1, 1)! next := m.stack[call_base + 1] if next.is_callable() { vm.check_callable_owner(next)! } value := procedure_value(&Procedure{ owner: vm.owner mode: .goops_method_procedure name: 'bound method' env: &Environment{ slots: [ p.env.slots[0], next, ] escaped: true } }) if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .goops_migration_enter, .goops_migration_leave { check_arity('migration scope', argc, 0, 0)! state := unsafe { &GoopsMigrationState(p.env.slots[0].pointer()) } if p.mode == .goops_migration_enter { m.enter_goops_migration(vm, state)! } else { m.leave_goops_migration(state) } if tail { m.finish_call(unspecified()) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, unspecified()) } return } .goops_method_procedure { m.goops_pending_next = p.env.slots[1] container_store_validated(mut m.stack, call_base, p.env.slots[0]) continue } .goops_forward_next { if argc == 0 { argc = m.forward_goops_next(p, call_base)! } else { container_store_validated(mut m.stack, call_base, p.env.slots[0]) } continue } .goops_make { value, completed := vm.goops_fast_make(m.arguments(call_base + 1))! if completed { if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } container_store_validated(mut m.stack, call_base, p.env.slots[1]) continue } .goops_low_get, .goops_low_checked_get, .goops_low_set { if vm.goops.has_redefinitions && argc > 0 && goops_needs_migration(m.stack[call_base + 1]) { m.prepare_goops_migration(vm, m.stack[call_base + 1], call_base)! argc = 3 continue } forwarded := m.apply_goops_low(mut vm, p, call_base, argc, tail)! if forwarded == 0 { return } argc = forwarded continue } .goops_generic { if vm.goops.has_redefinitions && goops_needs_migration(callable) { m.prepare_goops_migration(vm, callable, call_base)! argc = 3 continue } obsolete := if vm.goops.has_redefinitions { m.goops_obsolete_argument(call_base, argc) } else { Value{} } if obsolete.tag != .unspecified { m.prepare_goops_migration(vm, obsolete, call_base)! argc = 3 continue } generic := p.env.slots[0].goops_generic_data_pointer() if generic.procedure_override.tag != .unspecified && generic.procedure_override.is_true() { container_store_validated(mut m.stack, call_base, generic.procedure_override) continue } if vm.goops.has_redefinitions { checking := vm.goops_all_methods(generic)! obsolete_method := goops_obsolete_method(checking.values) checking.release() if obsolete_method.tag != .unspecified { m.prepare_goops_migration(vm, obsolete_method, call_base)! argc = 3 continue } } mut view := GoopsMethodsView{} custom := vm.goops_uses_applicability(generic) if !custom { view = vm.goops_all_methods(generic)! } if custom || (vm.goops.protocols_ready && !generic.intrinsic_applicability && vm.goops_needs_effective_methods(view.values)) { hook := if custom { vm.globals[vm.goops.applicability_binding] } else { vm.goops.standard_applicability } cached := m.goops_applicability_view(vm, generic, m.arguments(call_base + 1)) or { view.release() return err } if cached.tag != .unspecified { view.release() container_store_validated(mut m.stack, call_base, cached) continue } if !vm.goops_is_applicability_hook(generic, hook) && !vm.goops_is_applicability_hook(generic, vm.globals[vm.goops.effective_binding]) && !vm.goops_is_applicability_hook(generic, vm.globals[vm.goops.specialized_binding]) { view.release() m.prepare_goops_applicability(vm, generic, hook, call_base)! argc = 6 continue } if custom { view = vm.goops_all_methods(generic)! } } methods := view.values if vm.goops.has_redefinitions { obsolete_method := goops_obsolete_method(methods) if obsolete_method.tag != .unspecified { view.release() m.prepare_goops_migration(vm, obsolete_method, call_base)! argc = 3 continue } } method := vm.goops_select_method(methods, m.arguments(call_base + 1)) or { view.release() if err is GoopsNoApplicable { m.prepare_goops_retry(vm, generic.public_value, call_base) argc = 2 continue } return err } needs_next := method.needs_next || method.make_procedure.is_callable() // Next procedures retain an independent method list even if a // reentrant callback rebuilds the extension cache before return. snapshot := if needs_next { methods.clone() } else { []&GoopsMethod{} } view.release() if needs_next { args := m.arguments(call_base + 1).clone() next := goops_next_procedure(vm, generic.public_value, method, snapshot, args) if method.make_procedure.is_callable() && !method.goops_direct_factory() { m.prepare_goops_factory(vm, method, next, call_base) argc = 3 continue } m.goops_pending_next = next } container_store_validated(mut m.stack, call_base, method.procedure) continue } .with_setter, .goops_generic_setter, .goops_accessor { if vm.goops.has_redefinitions && goops_needs_migration(callable) { m.prepare_goops_migration(vm, callable, call_base)! argc = 3 continue } // This cold case belongs after the common call paths in V's // emitted C if-chain. Forward the existing packet to the getter. container_store_validated(mut m.stack, call_base, p.env.slots[0]) continue } .goops_next { obsolete := if vm.goops.has_redefinitions { m.goops_obsolete_argument(call_base, argc) } else { Value{} } if obsolete.tag != .unspecified { m.prepare_goops_migration(vm, obsolete, call_base)! argc = 3 continue } state := p.env.slots[0].goops_next_state() if voidptr(state.owner) != voidptr(vm.owner) { return failure('next-method belongs to another VM') } vm.checked_goops_generic(state.generic)! if vm.goops.has_redefinitions { obsolete_method := goops_obsolete_method(state.methods) if obsolete_method.tag != .unspecified { m.prepare_goops_migration(vm, obsolete_method, call_base)! argc = 3 continue } } method := vm.goops_next_method(state.methods, state.method, state.dispatch_args) or { if err is GoopsNoNext { m.prepare_goops_no_next(vm, state, call_base) argc = 2 continue } return err } if vm.goops.has_redefinitions && goops_needs_migration(goops_method_value(method)) { m.prepare_goops_migration(vm, goops_method_value(method), call_base)! argc = 3 continue } if method.needs_next || method.make_procedure.is_callable() { next := goops_next_procedure(vm, state.generic, method, state.methods, state.dispatch_args) if method.make_procedure.is_callable() && !method.goops_direct_factory() { m.prepare_goops_factory(vm, method, next, call_base) argc = 3 continue } m.goops_pending_next = next } container_store_validated(mut m.stack, call_base, method.procedure) continue } .enumeration_indexer, .enumeration_constructor { value := enumeration_call(p, m.arguments(call_base + 1))! if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .record_constructor, .record_predicate, .record_accessor, .record_mutator { value := record_call(p, m.arguments(call_base + 1))! if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .goops_slot_get, .goops_slot_set, .goops_slot_ref, .goops_slot_set_direct, .goops_slot_bound, .goops_class_slot_ref, .goops_class_slot_set { if vm.goops.has_redefinitions && argc > 0 && goops_needs_migration(m.stack[call_base + 1]) { m.prepare_goops_migration(vm, m.stack[call_base + 1], call_base)! argc = 3 continue } forwarded := m.apply_goops_slot(mut vm, p, call_base, argc, tail)! if forwarded == 0 { return } argc = forwarded continue } .parameter { check_arity('parameter', argc, 0, 1)! if argc == 1 && p.env.slots[1].tag != .unspecified { // Reuse a VM-owned setter bridge, with no per-call procedure or // argument packet. Its converter runs on this same machine. argument := m.stack[call_base + 1] container_store_validated(mut m.stack, call_base, vm.parameter_setter) container_store_validated(mut m.stack, call_base + 1, callable) m.push(argument) argc = 2 continue } value := if argc == 0 { current := m.parameter_value(p) if current.tag == .port_default { vm.default_port(int(current.whole()))! } else { current } } else { m.set_parameter(callable, single_parameter_value(m.stack[call_base + 1])!) unspecified() } if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .case_lambda { container_store_validated(mut m.stack, call_base, p.select_case_clause(argc)!) continue } .call_cc { check_arity('call-with-current-continuation', argc, 1, 1)! receiver := m.stack[call_base + 1] continuation := m.capture(vm.owner, call_base) container_store_validated(mut m.stack, call_base, receiver) container_store_validated(mut m.stack, call_base + 1, procedure_value(&Procedure{ mode: .continuation, name: 'continuation', owner: vm.owner, continuation: continuation })) argc = 1 } .continuation { result := values(m.arguments(call_base + 1)) if !m.transfer(mut vm, p.continuation, result)! { return ContinuationTransfer{ continuation: p.continuation, result: result } } return } .apply { check_arity('apply', argc, 2, -1)! // Replace (apply f prefixes... final-list) in the same operand stack. // Validate before changing state, and retain the tail while clearing slots. list_tail := m.stack.last() extra := list_tail.list_length()! next := m.stack[call_base + 1] for i in 0 .. argc - 2 { container_store_validated(mut m.stack, call_base + 1 + i, m.stack[call_base + 2 + i]) } m.truncate(m.stack.len - 2) container_store_validated(mut m.stack, call_base, next) mut current := list_tail for _ in 0 .. extra { pair := current.pair_pointer() m.push(pair.car) current = pair.cdr } argc = argc - 2 + extra } .values { if allow_values_forward && tail && m.forward_values_to_consumer(vm, call_base, argc) { call_base = m.stack.len - argc - 1 continue } value := values(m.arguments(call_base + 1)) if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .hashtable { check_arity(p.name, argc, p.function.params, p.function.params)! operation := unsafe { HashtableOperation(p.function.instructions[0].a) } table := vm.checked_hashtable(m.stack[call_base + 1])! if operation in [.set, .delete, .update] { vm.check_hashtable_mutation(table)! } if operation == .update { vm.check_hashtable_callback(m.stack[call_base + 3])! } if table.mode == .custom || operation == .update { container_store_validated(mut m.stack, call_base, p.env.slots[0]) continue } value := hashtable_fast(mut vm, operation, table, m.arguments(call_base + 1))! if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .record_seed { value := record_seed_call(mut vm, p, m.arguments(call_base + 1))! if tail { m.finish_call(value) } else { m.truncate(call_base + 1) m.stack[call_base] = value } return } .record_partial { if !m.apply_record_partial(mut vm, p, call_base, argc, tail)! { return } argc = 3 continue } .search { if argc != 2 { check_arity(p.name, argc, 2, 3)! container_store_validated(mut m.stack, call_base, vm.comparison_search(p.primitive == .assoc)) continue } args := m.arguments(call_base + 1) value := if !isnil(vm.owner.bounded_files) { vm.owner.bounded_files.apply_primitive(p.primitive, args, p.name)! } else { data_call(p.primitive, args, p.name)! } if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .port_io { if !isnil(p.env) && argc in [1, 2] && goops_primitive_object(m.stack[call_base + 1]) { container_store_validated(mut m.stack, call_base, p.env.slots[0]) if argc == 1 { m.push(vm.current_output_value()!) argc = 2 } continue } args := m.arguments(call_base + 1) operation := unsafe { PortIoOperation(p.function.instructions[0].a) } if (vm.goops.has_class_printers || !isnil(p.env)) && m.prepare_goops_print(mut vm, p, operation, call_base, args)! { argc = 2 continue } target := m.custom_port_target(operation, args, vm) if target.tag != .unspecified { state := vm.prepare_custom_port_operation(operation, target, args)! if isnil(state) { if tail { m.finish_call(unspecified()) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, unspecified()) } return } m.call_custom_port_bridge(mut vm, p.function, state, call_base, tail)! return } value := p.native(mut vm, args)! if tail { m.finish_call(value) } else { m.truncate(call_base + 1) container_store_validated(mut m.stack, call_base, value) } return } .library_environment { container_store_validated(mut m.stack, call_base, vm.library_environment_driver(m.arguments(call_base + 1), m.source_path())!) m.truncate(call_base + 1) argc = 0 continue } } } } @[inline] fn (mut m Machine) reserve_frame_slot(vm &VM) ! { m.reserve_buffer(vm, .frames, m.frames.len + 1)! } @[inline] fn (mut m Machine) reserve_buffer(vm &VM, buffer MachineBuffer, count int) ! { capacity := match buffer { .stack { m.stack.cap } .frames { m.frames.cap } .bridge_sites { m.bridge_sites.cap } } if count <= capacity { return } if vm.uses_bounded_operations() { vm.owner.bounded_files.reserve_buffer(mut m, buffer, count)! return } match buffer { .stack { m.stack.ensure_cap(count) } .frames { m.frames.ensure_cap(count) } .bridge_sites { m.bridge_sites.ensure_cap(count) } } } @[direct_array_access] fn (mut m Machine) activation(p &Procedure, tail bool) &Environment { return m.activation_for(p.function, p.env, tail) } @[inline] fn (mut m Machine) checked_activation(vm &VM, p &Procedure, tail bool) !&Environment { return m.checked_activation_for(vm, p.function, p.env, tail) } @[inline] fn (mut m Machine) checked_activation_for(vm &VM, function &Function, parent &Environment, tail bool) !&Environment { if vm.uses_bounded_operations() && m.activation_may_allocate(function, parent, tail) { return vm.owner.bounded_files.activate(mut m, function, parent, tail) } return m.activation_for(function, parent, tail) } // Exact-width cached environments already own all their storage. Tail-parent // recycling may add more candidates, but cannot invalidate these matches. fn (m &Machine) activation_may_allocate(function &Function, parent &Environment, tail bool) bool { count := function.slot_count if count == 0 && function.capture_depth == 0 { return false } if tail && !isnil(m.env) && !m.env.escaped && voidptr(m.env) != voidptr(parent) { if m.env.slots.len == count { return false } // With no other spare or released tail parent, the allocator takes this // same header back after caching it. Its capacity can cover a new width. if m.cached == 0 && !m.env.tail_parent && m.env.slots.cap >= count { return false } } if count < m.spares.len { return isnil(m.spares[count]) } mut cursor := EnvironmentRef{m.wide_spares} for !isnil(cursor.value) { if cursor.value.slots.len == count { return false } cursor = EnvironmentRef{cursor.value.parent} } return true } @[direct_array_access] fn (mut m Machine) activation_for(function &Function, parent &Environment, tail bool) &Environment { count := function.slot_count from_tail_scope := tail && !isnil(m.env) && m.env.tail_parent if tail && !isnil(m.env) && m.env.tail_parent { m.release_tail_parents(parent) } // No local slots, outer references, or descendant requiring an outer scope. // The compiler proves this activation needs no environment object at all. if count == 0 && function.capture_depth == 0 { if tail && !isnil(m.env) { m.cache_environment(mut m.env) } return unsafe { nil } } can_reuse := tail && !isnil(m.env) && !m.env.escaped && voidptr(m.env) != voidptr(parent) if can_reuse && m.env.slots.len != count { m.cache_environment(mut m.env) } mut scope := if can_reuse && m.env.slots.len == count { m.env } else if count < m.spares.len && !isnil(m.spares[count]) { available := m.spares[count] m.spares[count] = available.parent m.cached-- available } else { m.take_wide_environment(count, unsafe { nil }) } if isnil(scope) { // Preserve the compiler-owned helper for the next block iteration. Its // released parent (or another spare) can serve a different-width callee. scope = m.take_other_environment(if from_tail_scope { m.env } else { unsafe { &Environment(nil) } }) if isnil(scope) { scope = &Environment{ slots: value_storage(count) } } } // Mutual tail calls can have different local widths. Keep their activation // and its capacity instead of abandoning a fresh allocation on each hop. if scope.slots.len > count { for i in count .. scope.slots.len { container_store_validated(mut scope.slots, i, Value{}) } unsafe { scope.slots.len = count } } else if scope.slots.len < count { previous := scope.slots.len unsafe { scope.slots.grow_len(count - previous) } for i in previous .. count { container_store_validated(mut scope.slots, i, Value{}) } } scope.parent = parent scope.tail_parent = false // Fixed parameters will be overwritten without intervening allocation. Rest // and internal-definition slots must lose old values before initialization. for i in function.params .. count { scope.slots[i] = Value{ tag: .uninitialized } } return scope } // The view exists only during a primitive/native call. Reentry creates another // Machine, so it cannot move this stack. Hosts clone retained containers. fn (m &Machine) arguments(start int) []Value { return unsafe { m.stack[start..] } }