| 1 | module scheme |
| 2 | |
| 3 | import reader |
| 4 | |
| 5 | // EvalError is a Scheme runtime failure. Reader/lexer errors retain their own |
| 6 | // types. Source locations are attached by eval; host-only calls have line zero. |
| 7 | pub struct EvalError { |
| 8 | Error |
| 9 | pub: |
| 10 | message string |
| 11 | source_path string |
| 12 | offset int |
| 13 | line int |
| 14 | column int |
| 15 | } |
| 16 | |
| 17 | pub fn (e &EvalError) msg() string { |
| 18 | location := if e.line > 0 { '${e.line}:${e.column}: ${e.message}' } else { e.message } |
| 19 | return if e.source_path != '' { '${e.source_path}:${location}' } else { location } |
| 20 | } |
| 21 | |
| 22 | fn failure(message string) IError { |
| 23 | return EvalError{ message: message } |
| 24 | } |
| 25 | |
| 26 | // Limits apply per eval/call. Zero disables the corresponding limit. Native |
| 27 | // callbacks perform host work outside the Scheme step counter. |
| 28 | // max_open_files instead bounds simultaneously owned file descriptors, including |
| 29 | // transient source readers. None is unlimited; zero forbids acquiring a slot. |
| 30 | pub struct Options { |
| 31 | pub: |
| 32 | max_steps int = 1000000 |
| 33 | max_frames int = 10000 |
| 34 | max_expansions int = 10000 |
| 35 | max_open_files ?int |
| 36 | compile_list_limits ?CompileListLimits |
| 37 | arguments ?[]string |
| 38 | environment ?map[string]string |
| 39 | tai_utc_offset ?f64 |
| 40 | exit_handler ExitFn = request_process_exit |
| 41 | } |
| 42 | |
| 43 | // NativeFn can return a value, propagate a V error, or reenter this VM through |
| 44 | // eval/call. The current evaluation's registers live in its local machine. |
| 45 | pub type NativeFn = fn (mut VM, []Value) !Value |
| 46 | |
| 47 | // Stable identity retained by published runtime and syntax handles. |
| 48 | @[heap] |
| 49 | struct Owner { |
| 50 | token u8 = 1 |
| 51 | mut: |
| 52 | file_budget &FileResourceBudget = unsafe { nil } |
| 53 | bounded_files &BoundedFiles = unsafe { nil } |
| 54 | syntax_domain &SyntaxLexicalDomain = unsafe { nil } |
| 55 | syntax_domain_storage SyntaxLexicalDomain |
| 56 | stdio StandardPorts |
| 57 | // The canonical name/slot table contains no runtime values. VM borrows this |
| 58 | // stable field, so published syntax can resolve later names on any V backend. |
| 59 | syntax_globals map[string]int |
| 60 | report_slots map[int]int |
| 61 | syntax_locations map[string]&SyntaxGlobalLocation |
| 62 | syntax_generation u64 |
| 63 | syntax_tracking bool |
| 64 | } |
| 65 | |
| 66 | @[heap] |
| 67 | struct Environment { |
| 68 | mut: |
| 69 | parent &Environment = unsafe { nil } |
| 70 | slots []Value |
| 71 | escaped bool |
| 72 | // True only when a compiler-owned tail helper replaced this parent. |
| 73 | tail_parent bool |
| 74 | } |
| 75 | |
| 76 | // The ancestor cursor is rebound while each referenced environment stays read-only. |
| 77 | struct EnvironmentRef { |
| 78 | value &Environment |
| 79 | } |
| 80 | |
| 81 | enum ProcedureKind { |
| 82 | closure |
| 83 | native |
| 84 | primitive |
| 85 | apply |
| 86 | values |
| 87 | call_cc |
| 88 | continuation |
| 89 | case_lambda |
| 90 | parameter |
| 91 | search |
| 92 | hashtable |
| 93 | enumeration_indexer |
| 94 | enumeration_constructor |
| 95 | record_constructor |
| 96 | record_predicate |
| 97 | record_accessor |
| 98 | record_mutator |
| 99 | library_environment |
| 100 | record_seed |
| 101 | record_partial |
| 102 | port_io |
| 103 | with_setter |
| 104 | goops_generic_setter |
| 105 | goops_accessor |
| 106 | closure_star |
| 107 | goops_generic |
| 108 | goops_make |
| 109 | goops_method_procedure |
| 110 | goops_method_factory |
| 111 | goops_forward_next |
| 112 | goops_migration_enter |
| 113 | goops_migration_leave |
| 114 | goops_low_get |
| 115 | goops_low_checked_get |
| 116 | goops_low_set |
| 117 | goops_next |
| 118 | goops_slot_get |
| 119 | goops_slot_set |
| 120 | goops_slot_ref |
| 121 | goops_slot_set_direct |
| 122 | goops_slot_bound |
| 123 | goops_class_slot_ref |
| 124 | goops_class_slot_set |
| 125 | } |
| 126 | |
| 127 | @[heap] |
| 128 | struct Procedure { |
| 129 | mode ProcedureKind |
| 130 | name string |
| 131 | owner &Owner = unsafe { nil } |
| 132 | native NativeFn = missing_native |
| 133 | primitive Primitive |
| 134 | function &Function = unsafe { nil } |
| 135 | continuation &Continuation = unsafe { nil } |
| 136 | mut: |
| 137 | env &Environment = unsafe { nil } |
| 138 | } |
| 139 | |
| 140 | // VM owns an independent global environment. Use one VM per thread, or |
| 141 | // synchronize host access. Normal V/Boehm GC handles live values and cycles. |
| 142 | @[heap; nocopy] |
| 143 | pub struct VM { |
| 144 | owner &Owner = unsafe { nil } |
| 145 | allocation_owner voidptr = v_arena_current() |
| 146 | mut: |
| 147 | options Options |
| 148 | compile_list_budget &CompileListBudget = unsafe { nil } |
| 149 | bindings &map[string]int = unsafe { nil } |
| 150 | globals []Value |
| 151 | serial u64 |
| 152 | active []&Machine |
| 153 | active_allocation_owner voidptr = v_arena_current() |
| 154 | spare_machine &Machine = unsafe { nil } |
| 155 | wind_transfer_function &Function = unsafe { nil } |
| 156 | keyword_variables []string |
| 157 | syntax &SyntaxBindings = unsafe { nil } |
| 158 | ports &PortState = unsafe { nil } |
| 159 | evaluation &EvalState = unsafe { nil } |
| 160 | port_storage PortState |
| 161 | evaluation_storage EvalState |
| 162 | record_storage RecordRuntime |
| 163 | standard_count int |
| 164 | standard_original map[int]Value |
| 165 | parameter_setter Value |
| 166 | comparison_searches [2]Value |
| 167 | port_parameters [3]Value |
| 168 | binding_epoch u64 |
| 169 | imported map[string]bool |
| 170 | libraries &LibraryRegistry = unsafe { nil } |
| 171 | environment_constructor Value |
| 172 | feature_list Value |
| 173 | include_paths []string |
| 174 | system &SystemState = unsafe { nil } |
| 175 | system_storage SystemState |
| 176 | goops &GoopsRuntime = unsafe { nil } |
| 177 | goops_slot_bound_bridge Value |
| 178 | // Borrowed only within the native execution host scope. |
| 179 | // Ordinary builds compile out the dispatch hook. |
| 180 | native_execution_scope voidptr = unsafe { nil } |
| 181 | } |
| 182 | |
| 183 | pub fn new() &VM { |
| 184 | return make_vm(Options{}, unsafe { nil }) |
| 185 | } |
| 186 | |
| 187 | pub fn new_with_options(options Options) !&VM { |
| 188 | validate_vm_options(options)! |
| 189 | return make_vm(options, unsafe { nil }) |
| 190 | } |
| 191 | |
| 192 | fn validate_vm_options(options Options) ! { |
| 193 | if options.max_steps < 0 || options.max_frames < 0 || options.max_expansions < 0 { |
| 194 | return failure('runtime limits must be nonnegative') |
| 195 | } |
| 196 | if limit := options.max_open_files { |
| 197 | if limit < 0 { return failure('open file limit must be nonnegative') } |
| 198 | } |
| 199 | validate_system_options(options)! |
| 200 | } |
| 201 | |
| 202 | // Reserve room for the standard bindings and the protocol definitions. |
| 203 | const initial_binding_capacity = 800 |
| 204 | |
| 205 | fn make_vm(options Options, files &BoundedFiles) &VM { |
| 206 | owner := &Owner{ bounded_files: files, file_budget: new_file_resource_budget(options.max_open_files) } |
| 207 | mut vm := &VM{ owner: owner, bindings: &owner.syntax_globals, options: Options{ ...options, arguments: none, environment: none }, system: configured_system(options) } |
| 208 | // Arenas retain earlier map and array buffers when a global table grows. |
| 209 | vm.bindings.reserve(initial_binding_capacity) |
| 210 | vm.globals = []Value{cap: initial_binding_capacity} |
| 211 | vm.install_primitives() |
| 212 | vm.install_control_primitives() |
| 213 | vm.install_port_primitives() |
| 214 | vm.install_eval_primitives() |
| 215 | vm.install_load_primitive() |
| 216 | vm.install_library_primitive() |
| 217 | vm.install_features() |
| 218 | vm.install_system_primitives() |
| 219 | vm.install_enumeration_primitives() |
| 220 | vm.install_hashtable_primitives() |
| 221 | vm.install_arithmetic_primitives() |
| 222 | vm.install_unicode_primitives() |
| 223 | vm.install_record_primitives() |
| 224 | vm.install_bytevector_typed_primitives() |
| 225 | vm.install_transcoder_primitives() |
| 226 | vm.install_procedural_syntax_primitives() |
| 227 | vm.install_memory_port_extensions() |
| 228 | vm.install_selected_file_ports() |
| 229 | vm.install_standard_binary_ports() |
| 230 | vm.install_keyword_primitives() |
| 231 | vm.install_setter_primitives() |
| 232 | vm.install_deferred_goops() |
| 233 | if limits := options.compile_list_limits { |
| 234 | vm.compile_list_budget = &CompileListBudget{ limits: limits } |
| 235 | } |
| 236 | vm.standard_count = vm.globals.len |
| 237 | return vm |
| 238 | } |
| 239 | |
| 240 | fn missing_native(mut _vm VM, _args []Value) !Value { |
| 241 | return failure('uninitialized native procedure') |
| 242 | } |
| 243 | |
| 244 | fn (vm &VM) ready() ! { |
| 245 | if isnil(vm.owner) { return failure('uninitialized VM; use scheme.new()') } |
| 246 | if !isnil(vm.owner.bounded_files) { |
| 247 | if reason := vm.owner.bounded_files.interrupted { return bounded_allocation_request(reason) } |
| 248 | } |
| 249 | if !isnil(vm.goops) && vm.goops.bootstrap_failed && !vm.goops.starting { |
| 250 | return &goops_bootstrap_interrupted |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // eval parses the entire source first, evaluates its forms in order, and |
| 255 | // returns the final value (or unspecified for empty source). Definitions persist. |
| 256 | pub fn (mut vm VM) eval(source string) !Value { |
| 257 | vm.ready()! |
| 258 | vm.check_entry_control()! |
| 259 | // eval borrows its input only for this call. Closures retain our own source |
| 260 | // allocation, including when a V host releases its original input explicitly. |
| 261 | doc := read_source_input(vm, text: source)! |
| 262 | return vm.eval_document(doc, unsafe { nil }, '') |
| 263 | } |
| 264 | |
| 265 | // eval_in evaluates Scheme source in a same-VM environment. The document is |
| 266 | // owned independently of the caller, just as with eval. |
| 267 | pub fn (mut vm VM) eval_in(source string, environment Value) !Value { |
| 268 | vm.ready()! |
| 269 | vm.check_entry_control()! |
| 270 | space := vm.environment_space(environment)! |
| 271 | doc := read_source_input(vm, text: source)! |
| 272 | return vm.eval_document(doc, space, '') |
| 273 | } |
| 274 | |
| 275 | fn (mut vm VM) eval_document(doc reader.Document, space &Namespace, path string) !Value { |
| 276 | context := vm.next_context() |
| 277 | function := vm.new_source_program(doc, context, space, path, false)! |
| 278 | return vm.run_program(function, context) |
| 279 | } |
| 280 | |
| 281 | fn (mut vm VM) run_program(function &Function, context u64) !Value { |
| 282 | if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { |
| 283 | vm.drain_goops_finalizers(false)! |
| 284 | } |
| 285 | parameters := vm.parameter_context() |
| 286 | allocation_owner := v_arena_current() |
| 287 | mut machine := vm.take_entry_machine(context, parameters) |
| 288 | machine.function = function |
| 289 | mut published := false |
| 290 | defer { vm.finish_entry_machine(machine, allocation_owner, published) } |
| 291 | entry := vm.enter_program(mut machine)! |
| 292 | published = true |
| 293 | defer { vm.leave_entry(entry) } |
| 294 | return machine.run(mut vm) |
| 295 | } |
| 296 | |
| 297 | @[inline] |
| 298 | fn (vm &VM) uses_bounded_operations() bool { |
| 299 | // Cold user code needs recoverable reservations too. Only trusted GOOPS |
| 300 | // bootstrap belongs to the handle's outer allocation-failure boundary. |
| 301 | return !isnil(vm.owner.bounded_files) && !isnil(vm.goops) && !vm.goops.starting |
| 302 | } |
| 303 | |
| 304 | @[inline] |
| 305 | fn (mut vm VM) enter_program(mut machine Machine) !ActiveEntry { |
| 306 | if vm.uses_bounded_operations() { |
| 307 | return vm.owner.bounded_files.enter_program(mut vm, mut machine) |
| 308 | } |
| 309 | machine.env = machine.activation_for(machine.function, unsafe { nil }, false) |
| 310 | return vm.enter_context(&machine) |
| 311 | } |
| 312 | |
| 313 | // define sets a global binding. Names use the reader's default folding unless |
| 314 | // fold_case:false is supplied. Primitive bindings can be replaced by the host. |
| 315 | pub fn (mut vm VM) define(name string, value Value, options reader.ReadOptions) ! { |
| 316 | vm.ready()! |
| 317 | key := vm.host_binding_name(name, options)! |
| 318 | vm.bind_global_in(unsafe { nil }, key, value)! |
| 319 | } |
| 320 | |
| 321 | pub fn (vm &VM) lookup(name string, options reader.ReadOptions) !Value { |
| 322 | vm.ready()! |
| 323 | return vm.global_lookup(vm.host_binding_name(name, options)!) |
| 324 | } |
| 325 | |
| 326 | pub fn (mut vm VM) register(name string, callback NativeFn, options reader.ReadOptions) ! { |
| 327 | vm.ready()! |
| 328 | key := vm.host_binding_name(name, options)! |
| 329 | vm.bind_global_in(unsafe { nil }, key, procedure_value(&Procedure{ |
| 330 | mode: .native |
| 331 | name: external_identifier_spelling(key) |
| 332 | owner: vm.owner |
| 333 | native: callback |
| 334 | }))! |
| 335 | } |
| 336 | |
| 337 | // call invokes a Scheme or native procedure without constructing source text. |
| 338 | // Procedures belong to their creating VM; scalar/data values are portable. |
| 339 | pub fn (mut vm VM) call(procedure Value, args []Value) !Value { |
| 340 | vm.ready()! |
| 341 | vm.check_entry_control()! |
| 342 | if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { |
| 343 | vm.drain_goops_finalizers(false)! |
| 344 | } |
| 345 | context := vm.next_context() |
| 346 | parameters := vm.parameter_context() |
| 347 | allocation_owner := v_arena_current() |
| 348 | mut machine := vm.take_entry_machine(context, parameters) |
| 349 | mut published := false |
| 350 | defer { vm.finish_entry_machine(machine, allocation_owner, published) } |
| 351 | entry := if !isnil(vm.owner.bounded_files) { |
| 352 | vm.owner.bounded_files.enter_call(mut vm, mut machine, procedure, args)! |
| 353 | } else { |
| 354 | vm.enter_host_call(mut machine, procedure, args) |
| 355 | } |
| 356 | published = true |
| 357 | defer { vm.leave_entry(entry) } |
| 358 | machine.apply(mut vm, args.len, true) or { |
| 359 | if !machine.accept_transfer(mut vm, err)! { return err } |
| 360 | } |
| 361 | return machine.run(mut vm) |
| 362 | } |
| 363 | |
| 364 | fn (mut vm VM) enter_host_call(mut machine Machine, procedure Value, args []Value) ActiveEntry { |
| 365 | machine.push(procedure) |
| 366 | machine.stack << args |
| 367 | return vm.enter_context(&machine) |
| 368 | } |
| 369 | |
| 370 | // A fixed-arity callback enters the same VM bridge without allocating an |
| 371 | // argument slice. Virtual slots use this synchronous path for one or two args. |
| 372 | fn (mut vm VM) call_small(procedure Value, first Value, second Value, count int) !Value { |
| 373 | vm.ready()! |
| 374 | vm.check_entry_control()! |
| 375 | if !isnil(vm.goops.finalizers) && vm.active.len == 0 && vm.allocation_owner == v_arena_current() { |
| 376 | vm.drain_goops_finalizers(false)! |
| 377 | } |
| 378 | context := vm.next_context() |
| 379 | parameters := vm.parameter_context() |
| 380 | allocation_owner := v_arena_current() |
| 381 | mut machine := vm.take_entry_machine(context, parameters) |
| 382 | mut published := false |
| 383 | defer { vm.finish_entry_machine(machine, allocation_owner, published) } |
| 384 | entry := vm.enter_context(machine) |
| 385 | published = true |
| 386 | defer { vm.leave_entry(entry) } |
| 387 | machine.push(procedure) |
| 388 | machine.push(first) |
| 389 | if count == 2 { machine.push(second) } |
| 390 | machine.apply(mut vm, count, true) or { |
| 391 | if !machine.accept_transfer(mut vm, err)! { return err } |
| 392 | } |
| 393 | return machine.run(mut vm) |
| 394 | } |
| 395 | |
| 396 | fn procedure_value(procedure &Procedure) Value { |
| 397 | return payload_value(.procedure, procedure) |
| 398 | } |
| 399 | |
| 400 | // Cached indices stay valid when globals grow or a binding is redefined. Only |
| 401 | // values move; compiled code never retains a pointer into the growable buffer. |
| 402 | fn (mut vm VM) bind_global(name string, value Value) int { |
| 403 | if !isnil(vm.syntax) && name in vm.syntax.entries { |
| 404 | vm.syntax.entries.delete(name) |
| 405 | vm.binding_epoch++ |
| 406 | } |
| 407 | if special_name(name) && name !in vm.keyword_variables { vm.keyword_variables << name } |
| 408 | if index := (*vm.bindings)[name] { |
| 409 | vm.replace_global(index, value) |
| 410 | vm.note_syntax_location(unsafe { nil }, name, SyntaxBinding{ kind: .global, name: name, global_slot: index }) |
| 411 | return index |
| 412 | } |
| 413 | index := vm.globals.len |
| 414 | vm.globals << value |
| 415 | (*vm.bindings)[name] = index |
| 416 | vm.binding_epoch++ |
| 417 | vm.note_syntax_location(unsafe { nil }, name, SyntaxBinding{ kind: .global, name: name, global_slot: index }) |
| 418 | return index |
| 419 | } |
| 420 | |
| 421 | fn (vm &VM) global_index(name string) !int { |
| 422 | if index := (*vm.bindings)[name] { |
| 423 | if vm.globals[index].tag == .uninitialized { vm.ensure_goops_slot(index) } |
| 424 | return index |
| 425 | } |
| 426 | return failure('unbound variable ${binding_diagnostic_name(name)}') |
| 427 | } |
| 428 | |
| 429 | fn (vm &VM) global_lookup(name string) !Value { |
| 430 | return vm.globals[vm.global_index(name)!] |
| 431 | } |
| 432 | |
| 433 | fn identifier(name string, options reader.ReadOptions) !string { |
| 434 | doc := reader.read_all(name, options)! |
| 435 | if doc.forms.len != 1 { return failure('expected one identifier') } |
| 436 | n := doc.arena.node(doc.forms[0])! |
| 437 | if n.kind != .symbol || n.start != 0 || n.end != name.len { |
| 438 | return failure('expected one identifier') |
| 439 | } |
| 440 | return doc.arena.symbol_name(doc.forms[0]) |
| 441 | } |
| 442 | |
| 443 | fn binding_name(name string, options reader.ReadOptions) !string { |
| 444 | return external_identifier_key(identifier(name, options)!) |
| 445 | } |
| 446 | |
| 447 | fn (vm &VM) host_binding_name(name string, options reader.ReadOptions) !string { |
| 448 | if !isnil(vm.owner.bounded_files) { return vm.owner.bounded_files.binding_name(name, options) } |
| 449 | return binding_name(name, options) |
| 450 | } |
| 451 | |
| 452 | fn special_name(name string) bool { |
| 453 | return name in ['quote', 'if', 'begin', 'lambda', 'lambda*', 'delay', 'delay-force', 'define', |
| 454 | 'define*', 'set!', 'let', 'let*', 'letrec', 'and', 'or', 'cond', 'case', 'do', 'quasiquote', |
| 455 | 'unquote', 'unquote-splicing', 'else', '=>', 'when', 'unless', 'letrec*', 'case-lambda', |
| 456 | 'let-values', 'let*-values', 'define-values', 'parameterize', 'define-record-type', |
| 457 | 'define-class', 'standard-define-class', 'class', 'define-accessor', 'define-extended-generic', |
| 458 | 'define-extended-generics', 'define-generic', 'define-method', 'define-method*', 'method', |
| 459 | 'method*', 'define-enumeration', 'record-type-descriptor', 'record-constructor-descriptor', |
| 460 | 'endianness', 'eol-style', 'error-handling-mode', 'file-options', 'buffer-mode', 'return', |
| 461 | 'break', 'continue', 'vile:statement'] |
| 462 | || name in ['define-library', 'import', 'include', 'include-ci', 'cond-expand'] |
| 463 | || name in ['define-syntax', 'let-syntax', 'letrec-syntax', 'syntax-rules', 'syntax-case', |
| 464 | 'with-syntax', 'syntax', 'quasisyntax', 'unsyntax', 'unsyntax-splicing'] |
| 465 | } |
| 466 | |