module scheme import reader // EvalError is a Scheme runtime failure. Reader/lexer errors retain their own // types. Source locations are attached by eval; host-only calls have line zero. pub struct EvalError { Error pub: message string source_path string offset int line int column int } pub fn (e &EvalError) msg() string { location := if e.line > 0 { '${e.line}:${e.column}: ${e.message}' } else { e.message } return if e.source_path != '' { '${e.source_path}:${location}' } else { location } } fn failure(message string) IError { return EvalError{ message: message } } // Limits apply per eval/call. Zero disables the corresponding limit. Native // callbacks perform host work outside the Scheme step counter. // max_open_files instead bounds simultaneously owned file descriptors, including // transient source readers. None is unlimited; zero forbids acquiring a slot. pub struct Options { pub: max_steps int = 1000000 max_frames int = 10000 max_expansions int = 10000 max_open_files ?int compile_list_limits ?CompileListLimits arguments ?[]string environment ?map[string]string tai_utc_offset ?f64 exit_handler ExitFn = request_process_exit } // NativeFn can return a value, propagate a V error, or reenter this VM through // eval/call. The current evaluation's registers live in its local machine. pub type NativeFn = fn (mut VM, []Value) !Value // Stable identity retained by published runtime and syntax handles. @[heap] struct Owner { token u8 = 1 mut: file_budget &FileResourceBudget = unsafe { nil } bounded_files &BoundedFiles = unsafe { nil } syntax_domain &SyntaxLexicalDomain = unsafe { nil } syntax_domain_storage SyntaxLexicalDomain stdio StandardPorts // The canonical name/slot table contains no runtime values. VM borrows this // stable field, so published syntax can resolve later names on any V backend. syntax_globals map[string]int report_slots map[int]int syntax_locations map[string]&SyntaxGlobalLocation syntax_generation u64 syntax_tracking bool } @[heap] struct Environment { mut: parent &Environment = unsafe { nil } slots []Value escaped bool // True only when a compiler-owned tail helper replaced this parent. tail_parent bool } // The ancestor cursor is rebound while each referenced environment stays read-only. struct EnvironmentRef { value &Environment } enum ProcedureKind { closure native primitive apply values call_cc continuation case_lambda parameter search hashtable enumeration_indexer enumeration_constructor record_constructor record_predicate record_accessor record_mutator library_environment record_seed record_partial port_io with_setter goops_generic_setter goops_accessor closure_star goops_generic goops_make goops_method_procedure goops_method_factory goops_forward_next goops_migration_enter goops_migration_leave goops_low_get goops_low_checked_get goops_low_set goops_next goops_slot_get goops_slot_set goops_slot_ref goops_slot_set_direct goops_slot_bound goops_class_slot_ref goops_class_slot_set } @[heap] struct Procedure { mode ProcedureKind name string owner &Owner = unsafe { nil } native NativeFn = missing_native primitive Primitive function &Function = unsafe { nil } continuation &Continuation = unsafe { nil } mut: env &Environment = unsafe { nil } } // VM owns an independent global environment. Use one VM per thread, or // synchronize host access. Normal V/Boehm GC handles live values and cycles. @[heap; nocopy] pub struct VM { owner &Owner = unsafe { nil } allocation_owner voidptr = v_arena_current() mut: options Options compile_list_budget &CompileListBudget = unsafe { nil } bindings &map[string]int = unsafe { nil } globals []Value serial u64 active []&Machine active_allocation_owner voidptr = v_arena_current() spare_machine &Machine = unsafe { nil } wind_transfer_function &Function = unsafe { nil } keyword_variables []string syntax &SyntaxBindings = unsafe { nil } ports &PortState = unsafe { nil } evaluation &EvalState = unsafe { nil } port_storage PortState evaluation_storage EvalState record_storage RecordRuntime standard_count int standard_original map[int]Value parameter_setter Value comparison_searches [2]Value port_parameters [3]Value binding_epoch u64 imported map[string]bool libraries &LibraryRegistry = unsafe { nil } environment_constructor Value feature_list Value include_paths []string system &SystemState = unsafe { nil } system_storage SystemState goops &GoopsRuntime = unsafe { nil } goops_slot_bound_bridge Value // Borrowed only within the native execution host scope. // Ordinary builds compile out the dispatch hook. native_execution_scope voidptr = unsafe { nil } } pub fn new() &VM { return make_vm(Options{}, unsafe { nil }) } pub fn new_with_options(options Options) !&VM { validate_vm_options(options)! return make_vm(options, unsafe { nil }) } fn validate_vm_options(options Options) ! { if options.max_steps < 0 || options.max_frames < 0 || options.max_expansions < 0 { return failure('runtime limits must be nonnegative') } if limit := options.max_open_files { if limit < 0 { return failure('open file limit must be nonnegative') } } validate_system_options(options)! } // Reserve room for the standard bindings and the protocol definitions. const initial_binding_capacity = 800 fn make_vm(options Options, files &BoundedFiles) &VM { owner := &Owner{ bounded_files: files, file_budget: new_file_resource_budget(options.max_open_files) } mut vm := &VM{ owner: owner, bindings: &owner.syntax_globals, options: Options{ ...options, arguments: none, environment: none }, system: configured_system(options) } // Arenas retain earlier map and array buffers when a global table grows. vm.bindings.reserve(initial_binding_capacity) vm.globals = []Value{cap: initial_binding_capacity} vm.install_primitives() vm.install_control_primitives() vm.install_port_primitives() vm.install_eval_primitives() vm.install_load_primitive() vm.install_library_primitive() vm.install_features() vm.install_system_primitives() vm.install_enumeration_primitives() vm.install_hashtable_primitives() vm.install_arithmetic_primitives() vm.install_unicode_primitives() vm.install_record_primitives() vm.install_bytevector_typed_primitives() vm.install_transcoder_primitives() vm.install_procedural_syntax_primitives() vm.install_memory_port_extensions() vm.install_selected_file_ports() vm.install_standard_binary_ports() vm.install_keyword_primitives() vm.install_setter_primitives() vm.install_deferred_goops() if limits := options.compile_list_limits { vm.compile_list_budget = &CompileListBudget{ limits: limits } } vm.standard_count = vm.globals.len return vm } fn missing_native(mut _vm VM, _args []Value) !Value { return failure('uninitialized native procedure') } fn (vm &VM) ready() ! { if isnil(vm.owner) { return failure('uninitialized VM; use scheme.new()') } if !isnil(vm.owner.bounded_files) { if reason := vm.owner.bounded_files.interrupted { return bounded_allocation_request(reason) } } if !isnil(vm.goops) && vm.goops.bootstrap_failed && !vm.goops.starting { return &goops_bootstrap_interrupted } } // eval parses the entire source first, evaluates its forms in order, and // returns the final value (or unspecified for empty source). Definitions persist. pub fn (mut vm VM) eval(source string) !Value { vm.ready()! vm.check_entry_control()! // eval borrows its input only for this call. Closures retain our own source // allocation, including when a V host releases its original input explicitly. doc := read_source_input(vm, text: source)! return vm.eval_document(doc, unsafe { nil }, '') } // eval_in evaluates Scheme source in a same-VM environment. The document is // owned independently of the caller, just as with eval. pub fn (mut vm VM) eval_in(source string, environment Value) !Value { vm.ready()! vm.check_entry_control()! space := vm.environment_space(environment)! doc := read_source_input(vm, text: source)! return vm.eval_document(doc, space, '') } fn (mut vm VM) eval_document(doc reader.Document, space &Namespace, path string) !Value { context := vm.next_context() function := vm.new_source_program(doc, context, space, path, false)! return vm.run_program(function, context) } fn (mut vm VM) run_program(function &Function, context u64) !Value { if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { vm.drain_goops_finalizers(false)! } parameters := vm.parameter_context() allocation_owner := v_arena_current() mut machine := vm.take_entry_machine(context, parameters) machine.function = function mut published := false defer { vm.finish_entry_machine(machine, allocation_owner, published) } entry := vm.enter_program(mut machine)! published = true defer { vm.leave_entry(entry) } return machine.run(mut vm) } @[inline] fn (vm &VM) uses_bounded_operations() bool { // Cold user code needs recoverable reservations too. Only trusted GOOPS // bootstrap belongs to the handle's outer allocation-failure boundary. return !isnil(vm.owner.bounded_files) && !isnil(vm.goops) && !vm.goops.starting } @[inline] fn (mut vm VM) enter_program(mut machine Machine) !ActiveEntry { if vm.uses_bounded_operations() { return vm.owner.bounded_files.enter_program(mut vm, mut machine) } machine.env = machine.activation_for(machine.function, unsafe { nil }, false) return vm.enter_context(&machine) } // define sets a global binding. Names use the reader's default folding unless // fold_case:false is supplied. Primitive bindings can be replaced by the host. pub fn (mut vm VM) define(name string, value Value, options reader.ReadOptions) ! { vm.ready()! key := vm.host_binding_name(name, options)! vm.bind_global_in(unsafe { nil }, key, value)! } pub fn (vm &VM) lookup(name string, options reader.ReadOptions) !Value { vm.ready()! return vm.global_lookup(vm.host_binding_name(name, options)!) } pub fn (mut vm VM) register(name string, callback NativeFn, options reader.ReadOptions) ! { vm.ready()! key := vm.host_binding_name(name, options)! vm.bind_global_in(unsafe { nil }, key, procedure_value(&Procedure{ mode: .native name: external_identifier_spelling(key) owner: vm.owner native: callback }))! } // call invokes a Scheme or native procedure without constructing source text. // Procedures belong to their creating VM; scalar/data values are portable. pub fn (mut vm VM) call(procedure Value, args []Value) !Value { vm.ready()! vm.check_entry_control()! if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { vm.drain_goops_finalizers(false)! } context := vm.next_context() parameters := vm.parameter_context() allocation_owner := v_arena_current() mut machine := vm.take_entry_machine(context, parameters) mut published := false defer { vm.finish_entry_machine(machine, allocation_owner, published) } entry := if !isnil(vm.owner.bounded_files) { vm.owner.bounded_files.enter_call(mut vm, mut machine, procedure, args)! } else { vm.enter_host_call(mut machine, procedure, args) } published = true defer { vm.leave_entry(entry) } machine.apply(mut vm, args.len, true) or { if !machine.accept_transfer(mut vm, err)! { return err } } return machine.run(mut vm) } fn (mut vm VM) enter_host_call(mut machine Machine, procedure Value, args []Value) ActiveEntry { machine.push(procedure) machine.stack << args return vm.enter_context(&machine) } // A fixed-arity callback enters the same VM bridge without allocating an // argument slice. Virtual slots use this synchronous path for one or two args. fn (mut vm VM) call_small(procedure Value, first Value, second Value, count int) !Value { vm.ready()! vm.check_entry_control()! if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { vm.drain_goops_finalizers(false)! } context := vm.next_context() parameters := vm.parameter_context() allocation_owner := v_arena_current() mut machine := vm.take_entry_machine(context, parameters) mut published := false defer { vm.finish_entry_machine(machine, allocation_owner, published) } entry := vm.enter_context(machine) published = true defer { vm.leave_entry(entry) } machine.push(procedure) machine.push(first) if count == 2 { machine.push(second) } machine.apply(mut vm, count, true) or { if !machine.accept_transfer(mut vm, err)! { return err } } return machine.run(mut vm) } fn procedure_value(procedure &Procedure) Value { return payload_value(.procedure, procedure) } // Cached indices stay valid when globals grow or a binding is redefined. Only // values move; compiled code never retains a pointer into the growable buffer. fn (mut vm VM) bind_global(name string, value Value) int { if !isnil(vm.syntax) && name in vm.syntax.entries { vm.syntax.entries.delete(name) vm.binding_epoch++ } if special_name(name) && name !in vm.keyword_variables { vm.keyword_variables << name } if index := (*vm.bindings)[name] { vm.replace_global(index, value) vm.note_syntax_location(unsafe { nil }, name, SyntaxBinding{ kind: .global, name: name, global_slot: index }) return index } index := vm.globals.len vm.globals << value (*vm.bindings)[name] = index vm.binding_epoch++ vm.note_syntax_location(unsafe { nil }, name, SyntaxBinding{ kind: .global, name: name, global_slot: index }) return index } fn (vm &VM) global_index(name string) !int { if index := (*vm.bindings)[name] { if vm.globals[index].tag == .uninitialized { vm.ensure_goops_slot(index) } return index } return failure('unbound variable ${binding_diagnostic_name(name)}') } fn (vm &VM) global_lookup(name string) !Value { return vm.globals[vm.global_index(name)!] } fn identifier(name string, options reader.ReadOptions) !string { doc := reader.read_all(name, options)! if doc.forms.len != 1 { return failure('expected one identifier') } n := doc.arena.node(doc.forms[0])! if n.kind != .symbol || n.start != 0 || n.end != name.len { return failure('expected one identifier') } return doc.arena.symbol_name(doc.forms[0]) } fn binding_name(name string, options reader.ReadOptions) !string { return external_identifier_key(identifier(name, options)!) } fn (vm &VM) host_binding_name(name string, options reader.ReadOptions) !string { if !isnil(vm.owner.bounded_files) { return vm.owner.bounded_files.binding_name(name, options) } return binding_name(name, options) } fn special_name(name string) bool { return name in ['quote', 'if', 'begin', 'lambda', 'lambda*', 'delay', 'delay-force', 'define', 'define*', 'set!', 'let', 'let*', 'letrec', 'and', 'or', 'cond', 'case', 'do', 'quasiquote', 'unquote', 'unquote-splicing', 'else', '=>', 'when', 'unless', 'letrec*', 'case-lambda', 'let-values', 'let*-values', 'define-values', 'parameterize', 'define-record-type', 'define-class', 'standard-define-class', 'class', 'define-accessor', 'define-extended-generic', 'define-extended-generics', 'define-generic', 'define-method', 'define-method*', 'method', 'method*', 'define-enumeration', 'record-type-descriptor', 'record-constructor-descriptor', 'endianness', 'eol-style', 'error-handling-mode', 'file-options', 'buffer-mode', 'return', 'break', 'continue', 'vile:statement'] || name in ['define-library', 'import', 'include', 'include-ci', 'cond-expand'] || name in ['define-syntax', 'let-syntax', 'letrec-syntax', 'syntax-rules', 'syntax-case', 'with-syntax', 'syntax', 'quasisyntax', 'unsyntax', 'unsyntax-splicing'] }