vile / scheme / machine.v
1530 lines · 1498 sloc · 52.89 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4import lexer
5
6// Only compiler-produced instruction operands and VM-owned stack indices reach
7// the handlers below. Public calls construct their argument ranges here; vector
8// indices and other user data remain checked inside the primitive procedures.
9// Direct array access avoids generic array_get/array_set calls in that trusted
10// execution machinery. Sanitizer tests cover the stack and capture invariants.
11
12// Return frames contain only execution registers. Arguments and intermediate
13// results share one value stack instead of allocating an array for every call.
14struct CallFrame {
15 function &Function = unsafe { nil }
16 env &Environment = unsafe { nil }
17 ip int
18 base int
19}
20
21@[heap]
22struct Machine {
23mut:
24 context u64
25 logical_context u64
26 wind &WindFrame = unsafe { nil }
27 function &Function = unsafe { nil }
28 env &Environment = unsafe { nil }
29 ip int
30 base int
31 origin reader.NodeId = reader.no_node
32 stack []Value
33 frames []CallFrame
34 bridge_sites []BridgeSite
35 steps int
36 expansions int
37 finished bool
38 spares [8]&Environment
39 wide_spares &Environment = unsafe { nil }
40 cached int
41 parameters &ParameterBinding = unsafe { nil }
42 parameter_base &ParameterBinding = unsafe { nil }
43 library_context &LibraryContext = unsafe { nil }
44 close_failure &CustomCloseFailure = unsafe { nil }
45 // Set only while a selected method enters its closure. The continuation
46 // keeps the resulting lexical slot, not this transient machine field.
47 goops_pending_next Value
48 goops_migrations &GoopsMigrationScope = unsafe { nil }
49 goops_cache_owner voidptr = v_arena_current()
50 goops_borrowed_cache []GoopsBorrowedMethods
51 goops_applicability_cache []GoopsBorrowedApplicability
52}
53
54fn (mut m Machine) charge(limit int) ! {
55 if limit > 0 && m.steps >= limit { return failure('evaluation step limit exceeded') }
56 m.steps++
57}
58
59fn (m &Machine) located(err IError) IError {
60 if is_control_transfer(err) { return err }
61 if err is reader.ReadError || err is lexer.LexError { return err }
62 if err is EvalError {
63 if err.line > 0 || err.source_path != '' { return err }
64 }
65 site := m.error_site()
66 if isnil(site.function) { return err }
67 return site.function.code.source_failure(site.origin, err)
68}
69
70// V array pop/trim keep spare storage. Clear dead handles so conservative GC
71// does not retain returned closures/environments through unused stack capacity.
72@[direct_array_access]
73fn (mut m Machine) truncate(length int) {
74 for i in length .. m.stack.len { container_store_validated(mut m.stack, i, Value{}) }
75 // The stack owns its buffer. Its only slices are borrowed arguments whose
76 // calls have finished before truncation. V's generic trim would copy the
77 // buffer after such a slice; changing only the header is safe here.
78 unsafe { m.stack.len = length }
79}
80
81@[direct_array_access]
82fn (mut m Machine) pop_value() Value {
83 index := m.stack.len - 1
84 value := m.stack[index]
85 m.truncate(index)
86 return value
87}
88
89// This stack owns its buffer; argument views are borrowed only while a native
90// or primitive call runs. Reentry uses another Machine, and snapshots clone the
91// live prefix. Generic array push checks sharing and copies a type-erased value
92// even when spare capacity is already available. Keep that path only for growth.
93@[direct_array_access; inline]
94fn (mut m Machine) push(value Value) {
95 if m.stack.len < m.stack.cap {
96 unsafe {
97 (&Value(m.stack.data))[m.stack.len] = value
98 m.stack.len++
99 }
100 } else {
101 m.stack << value
102 }
103}
104
105// Cached entry has checked spare capacity in this machine's private buffer.
106// Continuation and control snapshots own separate frame buffers.
107@[direct_array_access; inline]
108fn (mut m Machine) append_reserved_frame(frame CallFrame) {
109 unsafe {
110 (&CallFrame(m.frames.data))[m.frames.len] = frame
111 m.frames.len++
112 }
113}
114
115fn (env &Environment) ancestor(depth int) &Environment {
116 mut current := EnvironmentRef{ value: env }
117 for _ in 0 .. depth { current = EnvironmentRef{ value: current.value.parent } }
118 return current.value
119}
120
121@[direct_array_access]
122fn (mut m Machine) finish_call(value Value) {
123 // An unescaped activation cannot be observed after return. Keep a bounded
124 // set of small activations by slot count. While inactive, parent links the
125 // free list; every value slot is cleared before the object enters the cache.
126 if !isnil(m.env) && m.env.tail_parent { m.release_tail_parents(unsafe { nil }) }
127 if !isnil(m.env) { m.cache_environment(mut m.env) }
128 m.truncate(m.base)
129 m.push(value)
130 if m.frames.len == 0 {
131 m.release_bridge_sites(-1)
132 m.finished = true
133 return
134 }
135 index := m.frames.len - 1
136 frame := m.frames[index]
137 container_store_validated(mut m.frames, index, CallFrame{})
138 m.frames.trim(index)
139 m.release_bridge_sites(m.frames.len)
140 m.function = frame.function
141 m.env = frame.env
142 m.ip = frame.ip
143 m.base = frame.base
144}
145
146// One dispatcher source specializes the ordinary loop, the host-controlled
147// loop and the private single-step test entry. Keeping dispatch inside its loop
148// avoids relying on a C compiler's translation-unit inlining budget.
149struct PlainMachineLoop {}
150
151struct ControlledMachineLoop {}
152
153struct SingleMachineStep {}
154
155fn (mut m Machine) run(mut vm VM) !Value {
156 for {
157 value := m.run_once(mut vm) or {
158 // A failed method entry can leave this transient handoff pending.
159 // Managed cleanup must enter its own callbacks without inheriting it.
160 m.goops_pending_next = Value{}
161 m.cleanup_goops_migrations()
162 if is_control_transfer(err) { return m.abandon_process_exit_cleanup(mut vm, err) }
163 if !isnil(m.close_failure) {
164 original := m.close_failure.original
165 // A budget/cancellation failure before a cleanup callback can start must
166 // not rebuild the same queue indefinitely. Existing controls remain live.
167 if !m.close_failure.in_flight {
168 if m.recover_process_exit_cleanup(mut vm, m.close_failure.exit_recovery)! {
169 continue
170 }
171 return m.abandon_process_exit_cleanup(mut vm, original)
172 }
173 if m.begin_custom_close_failure(vm.owner, original) { continue }
174 if m.recover_process_exit_cleanup(mut vm, m.close_failure.exit_recovery)! {
175 continue
176 }
177 return m.abandon_process_exit_cleanup(mut vm, original)
178 }
179 if m.begin_custom_close_failure(vm.owner, err) { continue }
180 if m.recover_process_exit_cleanup(mut vm, unsafe { nil })! { continue }
181 return m.abandon_process_exit_cleanup(mut vm, err)
182 }
183 return value
184 }
185}
186
187fn (mut m Machine) run_once(mut vm VM) !Value {
188 if !isnil(vm.system) && !isnil(vm.system.evaluation) {
189 return m.run_controlled(mut vm, vm.system.evaluation)
190 }
191 return m.dispatch[PlainMachineLoop](mut vm, Instruction{}, unsafe { nil })
192}
193
194fn (mut m Machine) execute(mut vm VM, instruction Instruction) ! {
195 m.dispatch[SingleMachineStep](mut vm, instruction, unsafe { nil })!
196}
197
198@[direct_array_access]
199fn (mut m Machine) dispatch[T](mut vm VM, initial Instruction, control &EvaluationControl) !Value {
200 mut instruction := initial
201 for {
202 $if T is ControlledMachineLoop {
203 control.check_control() or {
204 vm.cleanup_pending_exit_files(m, err)
205 return m.located(err)
206 }
207 }
208 $if T !is SingleMachineStep {
209 if m.finished { break }
210 instruction = m.function.instructions[m.ip]
211 m.ip++
212 m.origin = instruction.origin
213 m.charge(vm.options.max_steps) or {
214 vm.cleanup_pending_exit_files(m, err)
215 return m.located(err)
216 }
217 }
218 mut dispatch_error := IError(unsafe { nil })
219 mut dispatch_failed := false
220 a, b := int(instruction.a), int(instruction.b)
221 match instruction.op {
222 .constant { m.push(m.function.constants[a]) }
223 .local {
224 scope := m.env.ancestor(a)
225 value := scope.slots[b]
226 if value.tag == .uninitialized {
227 dispatch_error = failure('variable used before initialization')
228 dispatch_failed = true
229 } else {
230 m.push(value)
231 }
232 }
233 .global {
234 mut index := m.function.global_slots[a]
235 if index >= 0 {
236 value := vm.read_global(index)
237 $if T is PlainMachineLoop {
238 if isnil(vm.owner.bounded_files)
239 && value.tag == .procedure && m.fuse_primitive_operands(vm, value) {
240 continue
241 }
242 }
243 m.push(value)
244 } else if resolved := vm.global_index_in(m.function.code.namespace, m.function.names[a]) {
245 m.function.global_slots[a] = resolved
246 m.push(vm.read_global(resolved))
247 } else {
248 dispatch_error = err
249 dispatch_failed = true
250 }
251 }
252 .define_local, .assign_local {
253 mut scope := m.env.ancestor(a)
254 scope.slots[b] = m.pop_value()
255 m.push(unspecified())
256 }
257 .closure {
258 mut function := m.function.children[a]
259 if function.capture_depth == 0 {
260 closed := if isnil(function.closed) {
261 function.new_closed_procedure(vm.owner)
262 } else {
263 function.closed
264 }
265 m.push(procedure_value(closed))
266 } else {
267 escape_environment(m.env)
268 m.push(procedure_value(&Procedure{ mode: .closure, owner: vm.owner, function: function, env: m.env }))
269 }
270 }
271 .drop { m.pop_value() }
272 .duplicate { m.push(m.stack.last()) }
273 .swap {
274 last := m.stack.len - 1
275 value := m.stack[last]
276 container_store_validated(mut m.stack, last, m.stack[last - 1])
277 container_store_validated(mut m.stack, last - 1, value)
278 }
279 .jump { m.ip = a }
280 .jump_false {
281 if !m.pop_value().is_true() { m.ip = a }
282 }
283 .and_jump, .or_jump {
284 if m.stack.last().is_true() == (instruction.op == .or_jump) {
285 m.ip = a
286 } else {
287 m.pop_value()
288 }
289 }
290 .case_match {
291 key := m.stack.last()
292 mut matched := false
293 for datum in m.function.constants[b].vector_pointer().items {
294 if eqv(key, datum) {
295 matched = true
296 break
297 }
298 }
299 if matched { m.pop_value() } else { m.ip = a }
300 }
301 .call, .tail_call {
302 mut handled := false
303 if a == 2 && isnil(vm.owner.bounded_files) {
304 base := m.stack.len - 3
305 callable := m.stack[base]
306 if callable.tag == .procedure {
307 p := callable.procedure_pointer()
308 x, y := m.stack[base + 1], m.stack[base + 2]
309 if p.mode == .primitive && isnil(p.env) && voidptr(p.owner) == voidptr(vm.owner) {
310 mut value := Value{}
311 mut ready := false
312 if int(p.primitive) <= int(Primitive.greater_equal)
313 && x.tag == .integer && y.tag == .integer {
314 value = small_integer_call(p.primitive, x.whole(), y.whole())
315 ready = value.tag != .unspecified
316 } else if x.tag == .integer && y.tag == .integer
317 && p.primitive in [.quotient, .remainder, .modulo] {
318 xv, yv := x.whole(), y.whole()
319 // Keep promotion and zero errors on the ordinary path.
320 if yv != 0 && !(p.primitive == .quotient && xv == exact_min && yv == -1) {
321 value = small_integer_division(p.primitive, xv, yv, false, xv < 0, yv < 0) or { unspecified() }
322 ready = value.tag != .unspecified
323 }
324 } else if p.primitive == .vector_ref && x.tag == .vector && y.tag == .integer {
325 index := y.whole()
326 items := x.vector_pointer().items
327 if index >= 0 && index < items.len {
328 value = items[int(index)]
329 ready = true
330 }
331 }
332 if ready {
333 handled = true
334 m.charge(vm.options.max_steps) or {
335 dispatch_error = err
336 dispatch_failed = true
337 }
338 if !dispatch_failed {
339 if instruction.op == .tail_call { m.finish_call(value) } else {
340 m.truncate(base + 1)
341 container_store_validated(mut m.stack, base, value)
342 }
343 }
344 }
345 }
346 }
347 }
348 // A write must charge its application before changing the vector.
349 // Invalid operands and extended primitives retain the full dispatcher.
350 if a == 3 && isnil(vm.owner.bounded_files) {
351 base := m.stack.len - 4
352 callable := m.stack[base]
353 if callable.tag == .procedure {
354 p := callable.procedure_pointer()
355 target, index := m.stack[base + 1], m.stack[base + 2]
356 if p.mode == .primitive && p.primitive == .vector_set && isnil(p.env)
357 && voidptr(p.owner) == voidptr(vm.owner) && target.tag == .vector
358 && !target.read_only && index.tag == .integer {
359 i := index.whole()
360 mut content := target.vector_pointer()
361 if i >= 0 && i < content.items.len {
362 handled = true
363 m.charge(vm.options.max_steps) or {
364 dispatch_error = err
365 dispatch_failed = true
366 }
367 if !dispatch_failed {
368 container_store_validated(mut content.items, int(i), m.stack[base + 3])
369 if instruction.op == .tail_call { m.finish_call(unspecified()) } else {
370 m.truncate(base + 1)
371 container_store_validated(mut m.stack, base, unspecified())
372 }
373 }
374 }
375 }
376 }
377 }
378 if !handled {
379 $if T is PlainMachineLoop {
380 if isnil(vm.owner.bounded_files) && m.enter_cached_closure[T](vm, a, instruction.op == .tail_call) {
381 continue
382 }
383 }
384 $if T is PlainMachineLoop {
385 m.apply_with_values_forward(mut vm, a, instruction.op == .tail_call, true) or {
386 dispatch_error = err
387 dispatch_failed = true
388 }
389 } $else {
390 m.apply(mut vm, a, instruction.op == .tail_call) or {
391 dispatch_error = err
392 dispatch_failed = true
393 }
394 }
395 }
396 }
397 .ret { m.finish_call(m.pop_value()) }
398 else {
399 m.execute_extended(mut vm, instruction) or {
400 dispatch_error = err
401 dispatch_failed = true
402 }
403 }
404 }
405
406 $if T is SingleMachineStep {
407 if dispatch_failed { return dispatch_error }
408 return unspecified()
409 }
410 if dispatch_failed {
411 if m.accept_transfer(mut vm, dispatch_error) or {
412 vm.cleanup_pending_exit_files(m, err)
413 return m.located(err)
414 } {
415 continue
416 }
417 vm.cleanup_pending_exit_files(m, dispatch_error)
418 return m.located(dispatch_error)
419 }
420 }
421 return m.stack[0]
422}
423
424// Keep the cold cache miss outside the hot loop. Only a Procedure born in its
425// compiled Function's allocation owner may become a persistent cached value.
426@[noinline]
427fn (mut function Function) new_closed_procedure(owner &Owner) &Procedure {
428 closed := &Procedure{ mode: if isnil(function.star) { .closure } else { .closure_star }, owner: owner, function: function }
429 if (isnil(function.code) && v_arena_current() == unsafe { nil })
430 || (!isnil(function.code) && v_arena_current() == function.code.allocation_owner) {
431 function.closed = closed
432 }
433 return closed
434}
435
436// Keep compound construction and control setup outside the common dispatch.
437// Otherwise GCC's inlining threshold can turn every instruction into an extra
438// call when a new cold handler is added. This boundary keeps that cost local.
439@[direct_array_access; noinline]
440fn (mut m Machine) execute_extended(mut vm VM, instruction Instruction) ! {
441 a, b := int(instruction.a), int(instruction.b)
442 match instruction.op {
443 .syntax_match { m.match_syntax_case(mut vm, a)! }
444 .syntax_scope_call, .syntax_scope_tail {
445 m.call_syntax_scope(mut vm, instruction.op == .syntax_scope_tail)!
446 }
447 .syntax_accept { m.accept_syntax_clause()! }
448 .syntax_return_call { m.call_syntax_return(mut vm, b)! }
449 .syntax_expand { m.expand_syntax_value(a)! }
450 .implicit_call {
451 if m.stack.last().is_callable() { m.apply(mut vm, 0, a != 0)! }
452 }
453 .exit_mark { m.mark_exit(a) }
454 .early_return { m.return_early(mut vm, a, b)! }
455 .return_call { m.call_return(mut vm, a, b)! }
456 .loop_continue { m.continue_loop(mut vm, a, b)! }
457 .scope_function { m.push(payload_value(.scope_function, m.function.children[a])) }
458 .scope_call, .scope_tail { m.call_scope(mut vm, a, instruction.op == .scope_tail)! }
459 .define_global {
460 slot := vm.bind_global_in(m.function.code.namespace, m.function.names[a], m.pop_value())!
461 m.function.global_slots[a] = slot
462 if b < 0 {
463 vm.bind_global_alias_in(m.function.code.namespace, m.function.names[global_alias_index(instruction.b)], slot)!
464 }
465 m.push(unspecified())
466 }
467 .case_lambda { m.make_case_lambda(vm.owner, a) }
468 .assign_resolved_global {
469 index := m.function.global_slots[a]
470 vm.replace_global(index, m.pop_value())
471 m.push(unspecified())
472 }
473 .enumeration_define {
474 m.push(new_enumeration(m.function.constants[a].enumeration_pointer().enumeration.universe))
475 }
476 .enumeration_select { m.push(enumeration_select(m.pop_value(), m.function.constants[a])!) }
477 .record_define { m.define_record(vm.owner, record_spec_pointer(m.function.constants[a])) }
478 .record_operations {
479 m.record_operations(vm.owner, record_spec_pointer(m.function.constants[a]))
480 }
481 .record_make_type {
482 start := m.stack.len - 6
483 value := record_make_type(mut vm, m.arguments(start))!
484 m.truncate(start)
485 m.push(value)
486 }
487 .record_make_cd {
488 start := m.stack.len - 3
489 if b != 0 && !m.stack[start + 2].is_callable() {
490 return failure('record protocol expression must produce a procedure')
491 }
492 if a != 0 && !m.stack[start + 1].record_false() {
493 return failure('parent-rtd without protocol requires #f parent constructor descriptor')
494 }
495 value := record_make_cd(mut vm, m.arguments(start))!
496 m.truncate(start)
497 m.push(value)
498 }
499 .record_prepare { m.prepare_record(mut vm)! }
500 .record_prepared {
501 value := record_protocol_result(mut vm, m.pop_value())!
502 m.finish_call(value)
503 }
504 .record_parent_prepare { m.prepare_record_parent() }
505 .record_parent_apply { m.apply_record_parent(mut vm)! }
506 .record_factory {
507 argument := m.pop_value()
508 m.push(vm.record_factory_value())
509 m.push(argument)
510 m.apply(mut vm, 1, false)!
511 }
512 .record_default_cd {
513 rtd := record_checked_type(m.pop_value())!
514 m.push(vm.record_default_constructor_descriptor(rtd))
515 }
516 .record_name_define { vm.install_record_name(m.function, a, b)! }
517 .record_auto_uid { m.push(vm.record_auto_uid(m.function.constants[a])) }
518 .global_reference { m.load_global_reference(mut vm, a, instruction)! }
519 .assign_global_reference { m.assign_global_reference(mut vm, a, instruction)! }
520 .unpack_values { m.unpack_values(a, b != 0)! }
521 .source_form { m.enter_source_form(mut vm, reader.NodeId(a), b != 0)! }
522 .load_enter { m.enter_load(mut vm)! }
523 .process_exit_finish { m.finish_process_exit(mut vm, a)! }
524 .sort_init { m.start_sort(unsafe { SortKind(a) })! }
525 .sort_step { m.step_sort(mut vm)! }
526 .sort_collect { m.collect_sort()! }
527 .list_utility_init { m.start_list_utility(unsafe { ListUtilityKind(a) })! }
528 .list_utility_step { m.step_list_utility(mut vm)! }
529 .list_utility_collect { m.collect_list_utility()! }
530 .port_io_enter { m.enter_custom_port_operation()! }
531 .port_io_step { m.step_custom_port_operation(mut vm)! }
532 .port_io_collect { m.collect_custom_port_operation()! }
533 .port_error_close_step { m.step_custom_close_failure(mut vm)! }
534 .port_error_close_collect { m.collect_custom_close_failure() }
535 .hashtable_init { m.start_hashtable(unsafe { HashtableOperation(a) })! }
536 .hashtable_step { m.step_hashtable(mut vm)! }
537 .hashtable_collect { m.collect_hashtable()! }
538 .library_define {
539 vm.register_library(unsafe { &LibraryDeclaration(m.function.constants[a].pointer()) })!
540 m.push(unspecified())
541 }
542 .library_import {
543 request := unsafe { &LibraryImports(m.function.constants[a].pointer()) }
544 m.push(vm.import_driver(request, m.function.code.namespace, m.source_path(), unspecified())!)
545 m.apply(mut vm, 0, false)!
546 }
547 .library_commit {
548 m.push(vm.commit_library_imports(unsafe { &LibraryImportState(m.function.constants[a].pointer()) })!)
549 }
550 .library_complete {
551 vm.complete_library(unsafe { &Library(m.function.constants[a].pointer()) })!
552 m.push(unspecified())
553 }
554 .library_mark_enter {
555 m.enter_library_context(unsafe { &Library(m.function.constants[a].pointer()) })
556 m.push(unspecified())
557 }
558 .library_init_guard {
559 library := unsafe { &Library(m.function.constants[a].pointer()) }
560 match library.status {
561 .ready { m.finish_call(unspecified()) }
562 .registered {}
563 .failed {
564 return failure('library ${library.name.display} initialization previously failed')
565 }
566 .suspended {
567 return failure('library ${library.name.display} initialization is suspended; resume its continuation')
568 }
569 .initializing {
570 return failure('library ${library.name.display} initialization is already in progress')
571 }
572 }
573 }
574 .library_mark_leave {
575 m.leave_library_context(unsafe { &Library(m.function.constants[a].pointer()) })
576 m.push(unspecified())
577 }
578 .define_syntax {
579 definition := m.function.code.syntax_exports[a]
580 vm.bind_syntax_in(m.function.code.namespace, definition.name, definition.transformer)!
581 m.push(unspecified())
582 }
583 .qq_cons, .qq_splice {
584 tail := m.pop_value()
585 head := m.pop_value()
586 value := if instruction.op == .qq_cons {
587 cons(head, tail)
588 } else {
589 splice_onto(head, tail)!
590 }
591 m.push(value)
592 }
593 .qq_prefix {
594 items := m.function.constants[a].vector_pointer().items
595 mut value := m.pop_value()
596 for i := items.len - 1; i >= 0; i-- { value = cons(items[i], value) }
597 m.push(value)
598 }
599 .qq_vector {
600 flags := m.function.constants[a].text()
601 start := m.stack.len - flags.len
602 items := m.arguments(start)
603 value := if b == 0 { vector(items) } else { splice_vector(items, flags)! }
604 m.truncate(start)
605 m.push(value)
606 }
607 .call_values_tail {
608 result := m.pop_value()
609 if result.tag == .multiple {
610 if result.pointer() == unsafe { nil } {
611 m.apply(mut vm, 0, true)!
612 } else {
613 items := result.vector_pointer().items
614 m.stack << items
615 m.apply(mut vm, items.len, true)!
616 }
617 } else {
618 m.push(result)
619 m.apply(mut vm, 1, true)!
620 }
621 }
622 .map_init { m.start_iteration(a != 0)! }
623 .map_step { m.step_iteration(mut vm)! }
624 .map_collect { m.collect_iteration() }
625 .indexed_init { m.start_indexed_iteration(a != 0, b != 0)! }
626 .indexed_step { m.step_indexed_iteration(mut vm)! }
627 .indexed_collect { m.collect_indexed_iteration()! }
628 .search_init { m.start_comparison_search(a != 0)! }
629 .search_step { m.step_comparison_search(mut vm, a != 0)! }
630 .search_collect { m.collect_comparison_search(a != 0)! }
631 .promise {
632 function := m.function.children[a]
633 mut env := if function.capture_depth == 0 {
634 unsafe { &Environment(nil) }
635 } else {
636 m.env
637 }
638 escape_environment(env)
639 m.push(payload_value(.promise, &Promise{ owner: vm.owner, function: function, env: env, lazy: b != 0 }))
640 }
641 .eval_enter { m.enter_eval(mut vm)! }
642 .file_init { m.init_file_control(mut vm, unsafe { FileMode(a) })! }
643 .file_enter { m.enter_file_control(mut vm)! }
644 .file_leave { m.leave_file_control(mut vm)! }
645 .file_return { m.return_file_body(mut vm, a != 0)! }
646 .file_argument { m.push(m.file_extent().file) }
647 .file_parameterize { m.parameterize_file_body(mut vm, a)! }
648 .force_enter { m.enter_force(mut vm)! }
649 .force_finish { m.finish_force(mut vm, a != 0)! }
650 .make_promise {
651 value := m.env.slots[0]
652 m.finish_call(if value.tag == .promise {
653 value
654 } else {
655 payload_value(.promise, &Promise{ owner: vm.owner, ready: true, result: value })
656 })
657 }
658 .wind_init { m.start_wind(mut vm)! }
659 .parameter_create { m.create_parameter(mut vm)! }
660 .parameter_created { m.created_parameter(vm.owner)! }
661 .parameter_set { m.convert_parameter_assignment(mut vm)! }
662 .parameter_assigned { m.assign_parameter()! }
663 .assignment_setter {
664 base := m.stack.len - a - 1
665 getter := m.stack[base]
666 primitive := vm.goops.primitive_setter
667 if !isnil(primitive.procedure_pointer().env) && (getter.tag != .procedure
668 || getter.procedure_pointer().mode !in [.with_setter, .goops_generic_setter, .goops_accessor]) {
669 m.push(primitive.procedure_pointer().env.slots[0])
670 m.push(getter)
671 m.apply(mut vm, 1, false)!
672 } else {
673 setter := vm.setter_for(getter)!
674 container_store_validated(mut m.stack, base, setter)
675 m.ip++
676 }
677 }
678 .assignment_setter_result {
679 setter := m.pop_value()
680 container_store_validated(mut m.stack, m.stack.len - a - 1, setter)
681 }
682 .assignment_finish {
683 container_store_validated(mut m.stack, m.stack.len - 1, unspecified())
684 }
685 .star_bound_skip {
686 if m.env.slots[b].tag != .uninitialized { m.ip = a }
687 }
688 .star_closure {
689 mut function := m.function.children[a]
690 if function.capture_depth == 0 {
691 closed := if isnil(function.closed) {
692 function.new_closed_procedure(vm.owner)
693 } else {
694 function.closed
695 }
696 m.push(procedure_value(closed))
697 } else {
698 escape_environment(m.env)
699 m.push(procedure_value(&Procedure{ mode: .closure_star, owner: vm.owner, function: function, env: m.env }))
700 }
701 }
702 .goops_make_class {
703 vm.ensure_goops()
704 start := m.stack.len - a
705 if vm.goops.protocols_ready {
706 // The evaluated class operands become an ordinary
707 // call, so custom metaclasses share this machine's continuations.
708 m.push(m.stack.last())
709 for index := a; index > 0; index-- {
710 container_store_validated(mut m.stack, start + index, m.stack[start + index - 1])
711 }
712 container_store_validated(mut m.stack, start, vm.goops.class_constructor)
713 m.apply(mut vm, a, false)!
714 } else {
715 value := goops_make_class_native(mut vm, m.arguments(start))!
716 m.truncate(start)
717 m.push(value)
718 }
719 }
720 .goops_top {
721 vm.ensure_goops()
722 m.push(goops_class_value(vm.goops.top))
723 }
724 .goops_define_generic {
725 vm.ensure_goops()
726 start := m.stack.len - 1
727 generic := m.goops_definition_generic(mut vm, a, if b < 0 { -b - 1 } else { b },
728 m.stack[start], b >= 0, b < 0)!
729 m.truncate(start)
730 m.push(if b < 0 { generic } else { unspecified() })
731 }
732 .goops_define_accessor {
733 vm.ensure_goops()
734 start := m.stack.len - 1
735 accessor := m.goops_definition_accessor(mut vm, a, if b < 0 { -b - 1 } else { b }, m.stack[start], b >= 0)!
736 m.truncate(start)
737 m.push(if b < 0 { accessor } else { unspecified() })
738 }
739 .goops_define_method {
740 vm.ensure_goops()
741 start := m.stack.len - 5
742 rest := b < 0
743 slot := if rest { -b - 1 } else { b }
744 method := vm.goops_new_method(m.stack[start + 1], m.stack[start + 2], rest)!
745 mut metadata := method.goops_method_pointer()
746 metadata.formals = m.stack[start + 3]
747 metadata.body = m.stack[start + 4]
748 generic := m.goops_definition_generic(mut vm, a, slot, m.stack[start], false, false)!
749 vm.goops_add_method(generic, method)!
750 m.truncate(start)
751 m.push(unspecified())
752 }
753 .goops_make_method {
754 vm.ensure_goops()
755 start := m.stack.len - 4
756 method := vm.goops_new_method(m.stack[start], m.stack[start + 1], a != 0)!
757 mut metadata := method.goops_method_pointer()
758 metadata.formals = m.stack[start + 2]
759 metadata.body = m.stack[start + 3]
760 m.truncate(start)
761 m.push(method)
762 }
763 .goops_retry_enter { m.enter_goops_retry(mut vm)! }
764 .goops_retry_finish { m.finish_goops_retry(mut vm)! }
765 .goops_factory_apply { m.finish_goops_factory(mut vm)! }
766 .goops_applicability_apply { m.finish_goops_applicability(mut vm)! }
767 .goops_effective_apply { m.finish_goops_effective(mut vm)! }
768 .goops_equal_init { m.start_goops_equal() }
769 .goops_equal_step { m.step_goops_equal(mut vm)! }
770 .goops_equal_resume { m.resume_goops_equal() }
771 .goops_migration_start { m.start_goops_migration(mut vm)! }
772 .goops_migration_retry { m.retry_goops_migration(mut vm)! }
773 .goops_class_redefinition { m.redefine_goops_binding(mut vm, a, b)! }
774 .goops_virtual_read_enter { m.enter_goops_virtual_read(mut vm)! }
775 .goops_virtual_read_finish { m.finish_goops_virtual_read(mut vm)! }
776 .goops_missing_enter { m.enter_goops_missing(mut vm)! }
777 .goops_missing_read_finish { m.finish_goops_missing_read(mut vm)! }
778 .goops_bound_enter {
779 m.push(m.env.slots[0])
780 m.push(m.env.slots[1])
781 m.apply(mut vm, 1, false)!
782 }
783 .goops_bound_finish { m.finish_call(boolean(!vm.goops_unbound(m.pop_value()))) }
784 .parameter_init { m.validate_parameter_bindings(mut vm, a)! }
785 .parameter_convert { m.convert_parameter_binding(mut vm, a)! }
786 .parameter_converted { m.converted_parameter_binding(a)! }
787 .parameter_install { m.install_parameter_bindings(mut vm, a)! }
788 .parameter_finish { m.finish_parameter_bindings(a) }
789 .wind_enter { m.enter_wind(mut vm)! }
790 .wind_leave { m.leave_wind(mut vm)! }
791 .wind_finish { m.finish_wind() }
792 .wind_step { m.step_wind_transfer(mut vm)! }
793 .wind_resume { m.resume_wind_transfer() }
794 .fail { return m.function.failures[a] }
795 else { return failure('invalid extended instruction') }
796 }
797}
798
799// Internal bridges and the independent single-step/control paths retain the
800// original packet protocol. Only the ordinary dispatcher enables forwarding.
801@[inline]
802fn (mut m Machine) apply(mut vm VM, count int, tail bool) ! {
803 return m.apply_with_values_forward(mut vm, count, tail, false)
804}
805
806@[direct_array_access]
807fn (mut m Machine) apply_with_values_forward(mut vm VM, count int, tail bool, allow_values_forward bool) ! {
808 mut argc := count
809 mut call_base := m.stack.len - argc - 1
810 for {
811 m.charge(vm.options.max_steps)!
812 callable := m.stack[call_base]
813 if callable.tag != .procedure {
814 if callable.goops_kind() == .goops_instance {
815 if vm.goops.has_redefinitions && goops_needs_migration(callable) {
816 m.prepare_goops_migration(vm, callable, call_base)!
817 argc = 3
818 continue
819 }
820 container_store_validated(mut m.stack, call_base, vm.goops_resolve_callable(callable)!)
821 continue
822 }
823 return failure('attempt to call a ${callable.tag}')
824 }
825 p := callable.procedure_pointer()
826 if voidptr(p.owner) != voidptr(vm.owner) {
827 return failure('procedure belongs to another VM')
828 }
829 match p.mode {
830 .native, .primitive {
831 // Unary gcd/lcm share abs's extension even if only abs was extended.
832 if argc == 1 && p.primitive in [.gcd, .lcm] && !is_integer_number(m.stack[call_base + 1]) {
833 abs := vm.goops.primitive_abs
834 if abs.tag == .procedure && (!isnil(p.env) || !isnil(abs.procedure_pointer().env)) {
835 container_store_validated(mut m.stack, call_base, abs)
836 continue
837 }
838 }
839 if !isnil(p.env) {
840 forwarded := m.prepare_goops_primitive(vm, p, call_base, argc)!
841 if forwarded >= 0 {
842 argc = forwarded
843 continue
844 }
845 }
846 if p.mode == .native && vm.goops.has_redefinitions {
847 obsolete := m.goops_native_obsolete_argument(mut vm, p, call_base, argc)!
848 if obsolete.tag != .unspecified {
849 m.prepare_goops_migration(vm, obsolete, call_base)!
850 argc = 3
851 continue
852 }
853 }
854 // The application is already charged. Successful scalar reads avoid
855 // slicing arguments and the general primitive/arity dispatchers.
856 mut read := unspecified()
857 if p.mode == .primitive && isnil(p.env) && isnil(vm.owner.bounded_files)
858 && argc > 0 && argc <= 2 && int(p.primitive) > int(Primitive.greater_equal) {
859 read = read_primitive(p.primitive, m.stack[call_base + 1], if argc == 2 { m.stack[call_base + 2] } else { Value{} }, argc)
860 }
861 value := if read.tag != .unspecified {
862 read
863 } else if p.mode == .primitive && !isnil(vm.owner.bounded_files) {
864 vm.owner.bounded_files.apply_primitive(p.primitive, m.arguments(call_base + 1), p.name)!
865 } else if p.mode == .primitive && argc == 2 && int(p.primitive) <= int(Primitive.greater_equal)
866 && m.stack[call_base + 1].tag == .integer && m.stack[call_base + 2].tag == .integer {
867 binary_integer(p.primitive, m.stack[call_base + 1], m.stack[call_base + 2])!
868 } else {
869 args := m.arguments(call_base + 1)
870 if p.mode == .native {
871 result := p.native(mut vm, args)!
872 if !isnil(vm.owner.bounded_files) {
873 if reason := vm.owner.bounded_files.interrupted { return bounded_allocation_request(reason) }
874 }
875 result
876 } else {
877 primitive_call(p.primitive, args, p.name)!
878 }
879 }
880 if tail {
881 m.finish_call(value)
882 } else {
883 // The callable already reserves the result slot. Clear only
884 // arguments, then overwrite it without a pop-and-push cycle.
885 m.truncate(call_base + 1)
886 container_store_validated(mut m.stack, call_base, value)
887 }
888 return
889 }
890 .closure {
891 function := p.function
892 check_arity(if p.name == '' { 'lambda' } else { p.name }, argc, function.params, if function.rest {
893 -1
894 } else {
895 function.params
896 })!
897 if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames {
898 return failure('continuation frame limit exceeded')
899 }
900 $if vile_native ? {
901 if !isnil(vm.native_execution_scope) {
902 if value := m.try_native_execution(mut vm, callable, call_base, argc) {
903 if tail { m.finish_call(value) } else {
904 m.truncate(call_base + 1)
905 container_store_validated(mut m.stack, call_base, value)
906 }
907 return
908 }
909 }
910 }
911 if !tail { m.reserve_frame_slot(vm)! }
912 if isnil(function.code) { m.enter_bridge(vm, tail)! }
913 mut scope := m.checked_activation(vm, p, tail)!
914 for index in 0 .. function.params {
915 scope.slots[index] = m.stack[call_base + 1 + index]
916 }
917 if function.rest {
918 scope.slots[function.params] = m.rest_arguments(vm, call_base, function.params, argc)!
919 }
920 if m.goops_pending_next.tag != .unspecified {
921 m.bind_goops_next(vm, mut scope, function, call_base, argc, argc)!
922 }
923 if !tail {
924 m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base }
925 m.base = call_base
926 }
927 m.truncate(if tail { m.base } else { call_base })
928 m.function = function
929 m.env = scope
930 m.ip = 0
931 return
932 }
933 .closure_star {
934 function := p.function
935 formals := function.star
936 check_arity('lambda*', argc, formals.required, if formals.has_keys || formals.rest_slot >= 0 {
937 -1
938 } else {
939 formals.required + formals.optional
940 })!
941 optional_end := m.validate_star_arguments(formals, call_base, argc)!
942 if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames {
943 return failure('continuation frame limit exceeded')
944 }
945 if !tail { m.reserve_frame_slot(vm)! }
946 if isnil(function.code) { m.enter_bridge(vm, tail)! }
947 mut scope := m.checked_activation(vm, p, tail)!
948 m.bind_star_arguments(vm, mut scope, formals, call_base, argc, optional_end)!
949 if m.goops_pending_next.tag != .unspecified {
950 m.bind_goops_next(vm, mut scope, function, call_base, argc, optional_end)!
951 }
952 if !tail {
953 m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base }
954 m.base = call_base
955 }
956 m.truncate(if tail { m.base } else { call_base })
957 m.function = function
958 m.env = scope
959 m.ip = 0
960 return
961 }
962 .goops_method_factory {
963 check_arity('method factory', argc, 1, 1)!
964 next := m.stack[call_base + 1]
965 if next.is_callable() { vm.check_callable_owner(next)! }
966 value := procedure_value(&Procedure{
967 owner: vm.owner
968 mode: .goops_method_procedure
969 name: 'bound method'
970 env: &Environment{
971 slots: [
972 p.env.slots[0],
973 next,
974 ]
975 escaped: true
976 }
977 })
978 if tail {
979 m.finish_call(value)
980 } else {
981 m.truncate(call_base + 1)
982 container_store_validated(mut m.stack, call_base, value)
983 }
984 return
985 }
986 .goops_migration_enter, .goops_migration_leave {
987 check_arity('migration scope', argc, 0, 0)!
988 state := unsafe { &GoopsMigrationState(p.env.slots[0].pointer()) }
989 if p.mode == .goops_migration_enter {
990 m.enter_goops_migration(vm, state)!
991 } else {
992 m.leave_goops_migration(state)
993 }
994 if tail {
995 m.finish_call(unspecified())
996 } else {
997 m.truncate(call_base + 1)
998 container_store_validated(mut m.stack, call_base, unspecified())
999 }
1000 return
1001 }
1002 .goops_method_procedure {
1003 m.goops_pending_next = p.env.slots[1]
1004 container_store_validated(mut m.stack, call_base, p.env.slots[0])
1005 continue
1006 }
1007 .goops_forward_next {
1008 if argc == 0 {
1009 argc = m.forward_goops_next(p, call_base)!
1010 } else {
1011 container_store_validated(mut m.stack, call_base, p.env.slots[0])
1012 }
1013 continue
1014 }
1015 .goops_make {
1016 value, completed := vm.goops_fast_make(m.arguments(call_base + 1))!
1017 if completed {
1018 if tail {
1019 m.finish_call(value)
1020 } else {
1021 m.truncate(call_base + 1)
1022 container_store_validated(mut m.stack, call_base, value)
1023 }
1024 return
1025 }
1026 container_store_validated(mut m.stack, call_base, p.env.slots[1])
1027 continue
1028 }
1029 .goops_low_get, .goops_low_checked_get, .goops_low_set {
1030 if vm.goops.has_redefinitions && argc > 0 && goops_needs_migration(m.stack[call_base + 1]) {
1031 m.prepare_goops_migration(vm, m.stack[call_base + 1], call_base)!
1032 argc = 3
1033 continue
1034 }
1035 forwarded := m.apply_goops_low(mut vm, p, call_base, argc, tail)!
1036 if forwarded == 0 { return }
1037 argc = forwarded
1038 continue
1039 }
1040 .goops_generic {
1041 if vm.goops.has_redefinitions && goops_needs_migration(callable) {
1042 m.prepare_goops_migration(vm, callable, call_base)!
1043 argc = 3
1044 continue
1045 }
1046 obsolete := if vm.goops.has_redefinitions {
1047 m.goops_obsolete_argument(call_base, argc)
1048 } else {
1049 Value{}
1050 }
1051 if obsolete.tag != .unspecified {
1052 m.prepare_goops_migration(vm, obsolete, call_base)!
1053 argc = 3
1054 continue
1055 }
1056 generic := p.env.slots[0].goops_generic_data_pointer()
1057 if generic.procedure_override.tag != .unspecified && generic.procedure_override.is_true() {
1058 container_store_validated(mut m.stack, call_base, generic.procedure_override)
1059 continue
1060 }
1061 if vm.goops.has_redefinitions {
1062 checking := vm.goops_all_methods(generic)!
1063 obsolete_method := goops_obsolete_method(checking.values)
1064 checking.release()
1065 if obsolete_method.tag != .unspecified {
1066 m.prepare_goops_migration(vm, obsolete_method, call_base)!
1067 argc = 3
1068 continue
1069 }
1070 }
1071 mut view := GoopsMethodsView{}
1072 custom := vm.goops_uses_applicability(generic)
1073 if !custom { view = vm.goops_all_methods(generic)! }
1074 if custom || (vm.goops.protocols_ready && !generic.intrinsic_applicability
1075 && vm.goops_needs_effective_methods(view.values)) {
1076 hook := if custom { vm.globals[vm.goops.applicability_binding] } else { vm.goops.standard_applicability }
1077 cached := m.goops_applicability_view(vm, generic, m.arguments(call_base + 1)) or {
1078 view.release()
1079 return err
1080 }
1081 if cached.tag != .unspecified {
1082 view.release()
1083 container_store_validated(mut m.stack, call_base, cached)
1084 continue
1085 }
1086 if !vm.goops_is_applicability_hook(generic, hook)
1087 && !vm.goops_is_applicability_hook(generic, vm.globals[vm.goops.effective_binding])
1088 && !vm.goops_is_applicability_hook(generic, vm.globals[vm.goops.specialized_binding]) {
1089 view.release()
1090 m.prepare_goops_applicability(vm, generic, hook, call_base)!
1091 argc = 6
1092 continue
1093 }
1094 if custom { view = vm.goops_all_methods(generic)! }
1095 }
1096 methods := view.values
1097 if vm.goops.has_redefinitions {
1098 obsolete_method := goops_obsolete_method(methods)
1099 if obsolete_method.tag != .unspecified {
1100 view.release()
1101 m.prepare_goops_migration(vm, obsolete_method, call_base)!
1102 argc = 3
1103 continue
1104 }
1105 }
1106 method := vm.goops_select_method(methods, m.arguments(call_base + 1)) or {
1107 view.release()
1108 if err is GoopsNoApplicable {
1109 m.prepare_goops_retry(vm, generic.public_value, call_base)
1110 argc = 2
1111 continue
1112 }
1113 return err
1114 }
1115 needs_next := method.needs_next || method.make_procedure.is_callable()
1116 // Next procedures retain an independent method list even if a
1117 // reentrant callback rebuilds the extension cache before return.
1118 snapshot := if needs_next { methods.clone() } else { []&GoopsMethod{} }
1119 view.release()
1120 if needs_next {
1121 args := m.arguments(call_base + 1).clone()
1122 next := goops_next_procedure(vm, generic.public_value, method, snapshot, args)
1123 if method.make_procedure.is_callable() && !method.goops_direct_factory() {
1124 m.prepare_goops_factory(vm, method, next, call_base)
1125 argc = 3
1126 continue
1127 }
1128 m.goops_pending_next = next
1129 }
1130 container_store_validated(mut m.stack, call_base, method.procedure)
1131 continue
1132 }
1133 .with_setter, .goops_generic_setter, .goops_accessor {
1134 if vm.goops.has_redefinitions && goops_needs_migration(callable) {
1135 m.prepare_goops_migration(vm, callable, call_base)!
1136 argc = 3
1137 continue
1138 }
1139 // This cold case belongs after the common call paths in V's
1140 // emitted C if-chain. Forward the existing packet to the getter.
1141 container_store_validated(mut m.stack, call_base, p.env.slots[0])
1142 continue
1143 }
1144 .goops_next {
1145 obsolete := if vm.goops.has_redefinitions {
1146 m.goops_obsolete_argument(call_base, argc)
1147 } else {
1148 Value{}
1149 }
1150 if obsolete.tag != .unspecified {
1151 m.prepare_goops_migration(vm, obsolete, call_base)!
1152 argc = 3
1153 continue
1154 }
1155 state := p.env.slots[0].goops_next_state()
1156 if voidptr(state.owner) != voidptr(vm.owner) {
1157 return failure('next-method belongs to another VM')
1158 }
1159 vm.checked_goops_generic(state.generic)!
1160 if vm.goops.has_redefinitions {
1161 obsolete_method := goops_obsolete_method(state.methods)
1162 if obsolete_method.tag != .unspecified {
1163 m.prepare_goops_migration(vm, obsolete_method, call_base)!
1164 argc = 3
1165 continue
1166 }
1167 }
1168 method := vm.goops_next_method(state.methods, state.method, state.dispatch_args) or {
1169 if err is GoopsNoNext {
1170 m.prepare_goops_no_next(vm, state, call_base)
1171 argc = 2
1172 continue
1173 }
1174 return err
1175 }
1176 if vm.goops.has_redefinitions && goops_needs_migration(goops_method_value(method)) {
1177 m.prepare_goops_migration(vm, goops_method_value(method), call_base)!
1178 argc = 3
1179 continue
1180 }
1181 if method.needs_next || method.make_procedure.is_callable() {
1182 next := goops_next_procedure(vm, state.generic, method, state.methods, state.dispatch_args)
1183 if method.make_procedure.is_callable() && !method.goops_direct_factory() {
1184 m.prepare_goops_factory(vm, method, next, call_base)
1185 argc = 3
1186 continue
1187 }
1188 m.goops_pending_next = next
1189 }
1190 container_store_validated(mut m.stack, call_base, method.procedure)
1191 continue
1192 }
1193 .enumeration_indexer, .enumeration_constructor {
1194 value := enumeration_call(p, m.arguments(call_base + 1))!
1195 if tail {
1196 m.finish_call(value)
1197 } else {
1198 m.truncate(call_base + 1)
1199 container_store_validated(mut m.stack, call_base, value)
1200 }
1201 return
1202 }
1203 .record_constructor, .record_predicate, .record_accessor, .record_mutator {
1204 value := record_call(p, m.arguments(call_base + 1))!
1205 if tail {
1206 m.finish_call(value)
1207 } else {
1208 m.truncate(call_base + 1)
1209 container_store_validated(mut m.stack, call_base, value)
1210 }
1211 return
1212 }
1213 .goops_slot_get, .goops_slot_set, .goops_slot_ref, .goops_slot_set_direct,
1214 .goops_slot_bound, .goops_class_slot_ref, .goops_class_slot_set {
1215 if vm.goops.has_redefinitions && argc > 0 && goops_needs_migration(m.stack[call_base + 1]) {
1216 m.prepare_goops_migration(vm, m.stack[call_base + 1], call_base)!
1217 argc = 3
1218 continue
1219 }
1220 forwarded := m.apply_goops_slot(mut vm, p, call_base, argc, tail)!
1221 if forwarded == 0 { return }
1222 argc = forwarded
1223 continue
1224 }
1225 .parameter {
1226 check_arity('parameter', argc, 0, 1)!
1227 if argc == 1 && p.env.slots[1].tag != .unspecified {
1228 // Reuse a VM-owned setter bridge, with no per-call procedure or
1229 // argument packet. Its converter runs on this same machine.
1230 argument := m.stack[call_base + 1]
1231 container_store_validated(mut m.stack, call_base, vm.parameter_setter)
1232 container_store_validated(mut m.stack, call_base + 1, callable)
1233 m.push(argument)
1234 argc = 2
1235 continue
1236 }
1237 value := if argc == 0 {
1238 current := m.parameter_value(p)
1239 if current.tag == .port_default {
1240 vm.default_port(int(current.whole()))!
1241 } else {
1242 current
1243 }
1244 } else {
1245 m.set_parameter(callable, single_parameter_value(m.stack[call_base + 1])!)
1246 unspecified()
1247 }
1248 if tail {
1249 m.finish_call(value)
1250 } else {
1251 m.truncate(call_base + 1)
1252 container_store_validated(mut m.stack, call_base, value)
1253 }
1254 return
1255 }
1256 .case_lambda {
1257 container_store_validated(mut m.stack, call_base, p.select_case_clause(argc)!)
1258 continue
1259 }
1260 .call_cc {
1261 check_arity('call-with-current-continuation', argc, 1, 1)!
1262 receiver := m.stack[call_base + 1]
1263 continuation := m.capture(vm.owner, call_base)
1264 container_store_validated(mut m.stack, call_base, receiver)
1265 container_store_validated(mut m.stack, call_base + 1, procedure_value(&Procedure{ mode: .continuation, name: 'continuation', owner: vm.owner, continuation: continuation }))
1266 argc = 1
1267 }
1268 .continuation {
1269 result := values(m.arguments(call_base + 1))
1270 if !m.transfer(mut vm, p.continuation, result)! {
1271 return ContinuationTransfer{ continuation: p.continuation, result: result }
1272 }
1273 return
1274 }
1275 .apply {
1276 check_arity('apply', argc, 2, -1)!
1277 // Replace (apply f prefixes... final-list) in the same operand stack.
1278 // Validate before changing state, and retain the tail while clearing slots.
1279 list_tail := m.stack.last()
1280 extra := list_tail.list_length()!
1281 next := m.stack[call_base + 1]
1282 for i in 0 .. argc - 2 {
1283 container_store_validated(mut m.stack, call_base + 1 + i, m.stack[call_base + 2 + i])
1284 }
1285 m.truncate(m.stack.len - 2)
1286 container_store_validated(mut m.stack, call_base, next)
1287 mut current := list_tail
1288 for _ in 0 .. extra {
1289 pair := current.pair_pointer()
1290 m.push(pair.car)
1291 current = pair.cdr
1292 }
1293 argc = argc - 2 + extra
1294 }
1295 .values {
1296 if allow_values_forward && tail && m.forward_values_to_consumer(vm, call_base, argc) {
1297 call_base = m.stack.len - argc - 1
1298 continue
1299 }
1300 value := values(m.arguments(call_base + 1))
1301 if tail {
1302 m.finish_call(value)
1303 } else {
1304 m.truncate(call_base + 1)
1305 container_store_validated(mut m.stack, call_base, value)
1306 }
1307 return
1308 }
1309 .hashtable {
1310 check_arity(p.name, argc, p.function.params, p.function.params)!
1311 operation := unsafe { HashtableOperation(p.function.instructions[0].a) }
1312 table := vm.checked_hashtable(m.stack[call_base + 1])!
1313 if operation in [.set, .delete, .update] { vm.check_hashtable_mutation(table)! }
1314 if operation == .update { vm.check_hashtable_callback(m.stack[call_base + 3])! }
1315 if table.mode == .custom || operation == .update {
1316 container_store_validated(mut m.stack, call_base, p.env.slots[0])
1317 continue
1318 }
1319 value := hashtable_fast(mut vm, operation, table, m.arguments(call_base + 1))!
1320 if tail {
1321 m.finish_call(value)
1322 } else {
1323 m.truncate(call_base + 1)
1324 container_store_validated(mut m.stack, call_base, value)
1325 }
1326 return
1327 }
1328 .record_seed {
1329 value := record_seed_call(mut vm, p, m.arguments(call_base + 1))!
1330 if tail {
1331 m.finish_call(value)
1332 } else {
1333 m.truncate(call_base + 1)
1334 m.stack[call_base] = value
1335 }
1336 return
1337 }
1338 .record_partial {
1339 if !m.apply_record_partial(mut vm, p, call_base, argc, tail)! { return }
1340 argc = 3
1341 continue
1342 }
1343 .search {
1344 if argc != 2 {
1345 check_arity(p.name, argc, 2, 3)!
1346 container_store_validated(mut m.stack, call_base, vm.comparison_search(p.primitive == .assoc))
1347 continue
1348 }
1349 args := m.arguments(call_base + 1)
1350 value := if !isnil(vm.owner.bounded_files) {
1351 vm.owner.bounded_files.apply_primitive(p.primitive, args, p.name)!
1352 } else {
1353 data_call(p.primitive, args, p.name)!
1354 }
1355 if tail {
1356 m.finish_call(value)
1357 } else {
1358 m.truncate(call_base + 1)
1359 container_store_validated(mut m.stack, call_base, value)
1360 }
1361 return
1362 }
1363 .port_io {
1364 if !isnil(p.env) && argc in [1, 2] && goops_primitive_object(m.stack[call_base + 1]) {
1365 container_store_validated(mut m.stack, call_base, p.env.slots[0])
1366 if argc == 1 {
1367 m.push(vm.current_output_value()!)
1368 argc = 2
1369 }
1370 continue
1371 }
1372 args := m.arguments(call_base + 1)
1373 operation := unsafe { PortIoOperation(p.function.instructions[0].a) }
1374 if (vm.goops.has_class_printers || !isnil(p.env)) && m.prepare_goops_print(mut vm, p, operation, call_base, args)! {
1375 argc = 2
1376 continue
1377 }
1378 target := m.custom_port_target(operation, args, vm)
1379 if target.tag != .unspecified {
1380 state := vm.prepare_custom_port_operation(operation, target, args)!
1381 if isnil(state) {
1382 if tail {
1383 m.finish_call(unspecified())
1384 } else {
1385 m.truncate(call_base + 1)
1386 container_store_validated(mut m.stack, call_base, unspecified())
1387 }
1388 return
1389 }
1390 m.call_custom_port_bridge(mut vm, p.function, state, call_base, tail)!
1391 return
1392 }
1393 value := p.native(mut vm, args)!
1394 if tail {
1395 m.finish_call(value)
1396 } else {
1397 m.truncate(call_base + 1)
1398 container_store_validated(mut m.stack, call_base, value)
1399 }
1400 return
1401 }
1402 .library_environment {
1403 container_store_validated(mut m.stack, call_base, vm.library_environment_driver(m.arguments(call_base + 1), m.source_path())!)
1404 m.truncate(call_base + 1)
1405 argc = 0
1406 continue
1407 }
1408 }
1409 }
1410}
1411
1412@[inline]
1413fn (mut m Machine) reserve_frame_slot(vm &VM) ! {
1414 m.reserve_buffer(vm, .frames, m.frames.len + 1)!
1415}
1416
1417@[inline]
1418fn (mut m Machine) reserve_buffer(vm &VM, buffer MachineBuffer, count int) ! {
1419 capacity := match buffer {
1420 .stack { m.stack.cap }
1421 .frames { m.frames.cap }
1422 .bridge_sites { m.bridge_sites.cap }
1423 }
1424 if count <= capacity { return }
1425 if vm.uses_bounded_operations() {
1426 vm.owner.bounded_files.reserve_buffer(mut m, buffer, count)!
1427 return
1428 }
1429 match buffer {
1430 .stack { m.stack.ensure_cap(count) }
1431 .frames { m.frames.ensure_cap(count) }
1432 .bridge_sites { m.bridge_sites.ensure_cap(count) }
1433 }
1434}
1435
1436@[direct_array_access]
1437fn (mut m Machine) activation(p &Procedure, tail bool) &Environment {
1438 return m.activation_for(p.function, p.env, tail)
1439}
1440
1441@[inline]
1442fn (mut m Machine) checked_activation(vm &VM, p &Procedure, tail bool) !&Environment {
1443 return m.checked_activation_for(vm, p.function, p.env, tail)
1444}
1445
1446@[inline]
1447fn (mut m Machine) checked_activation_for(vm &VM, function &Function, parent &Environment, tail bool) !&Environment {
1448 if vm.uses_bounded_operations()
1449 && m.activation_may_allocate(function, parent, tail) {
1450 return vm.owner.bounded_files.activate(mut m, function, parent, tail)
1451 }
1452 return m.activation_for(function, parent, tail)
1453}
1454
1455// Exact-width cached environments already own all their storage. Tail-parent
1456// recycling may add more candidates, but cannot invalidate these matches.
1457fn (m &Machine) activation_may_allocate(function &Function, parent &Environment, tail bool) bool {
1458 count := function.slot_count
1459 if count == 0 && function.capture_depth == 0 { return false }
1460 if tail && !isnil(m.env) && !m.env.escaped && voidptr(m.env) != voidptr(parent) {
1461 if m.env.slots.len == count { return false }
1462 // With no other spare or released tail parent, the allocator takes this
1463 // same header back after caching it. Its capacity can cover a new width.
1464 if m.cached == 0 && !m.env.tail_parent && m.env.slots.cap >= count { return false }
1465 }
1466 if count < m.spares.len { return isnil(m.spares[count]) }
1467 mut cursor := EnvironmentRef{m.wide_spares}
1468 for !isnil(cursor.value) {
1469 if cursor.value.slots.len == count { return false }
1470 cursor = EnvironmentRef{cursor.value.parent}
1471 }
1472 return true
1473}
1474
1475@[direct_array_access]
1476fn (mut m Machine) activation_for(function &Function, parent &Environment, tail bool) &Environment {
1477 count := function.slot_count
1478 from_tail_scope := tail && !isnil(m.env) && m.env.tail_parent
1479 if tail && !isnil(m.env) && m.env.tail_parent { m.release_tail_parents(parent) }
1480 // No local slots, outer references, or descendant requiring an outer scope.
1481 // The compiler proves this activation needs no environment object at all.
1482 if count == 0 && function.capture_depth == 0 {
1483 if tail && !isnil(m.env) { m.cache_environment(mut m.env) }
1484 return unsafe { nil }
1485 }
1486 can_reuse := tail && !isnil(m.env) && !m.env.escaped && voidptr(m.env) != voidptr(parent)
1487 if can_reuse && m.env.slots.len != count { m.cache_environment(mut m.env) }
1488 mut scope := if can_reuse && m.env.slots.len == count {
1489 m.env
1490 } else if count < m.spares.len && !isnil(m.spares[count]) {
1491 available := m.spares[count]
1492 m.spares[count] = available.parent
1493 m.cached--
1494 available
1495 } else {
1496 m.take_wide_environment(count, unsafe { nil })
1497 }
1498 if isnil(scope) {
1499 // Preserve the compiler-owned helper for the next block iteration. Its
1500 // released parent (or another spare) can serve a different-width callee.
1501 scope = m.take_other_environment(if from_tail_scope {
1502 m.env
1503 } else {
1504 unsafe { &Environment(nil) }
1505 })
1506 if isnil(scope) { scope = &Environment{ slots: value_storage(count) } }
1507 }
1508 // Mutual tail calls can have different local widths. Keep their activation
1509 // and its capacity instead of abandoning a fresh allocation on each hop.
1510 if scope.slots.len > count {
1511 for i in count .. scope.slots.len { container_store_validated(mut scope.slots, i, Value{}) }
1512 unsafe { scope.slots.len = count }
1513 } else if scope.slots.len < count {
1514 previous := scope.slots.len
1515 unsafe { scope.slots.grow_len(count - previous) }
1516 for i in previous .. count { container_store_validated(mut scope.slots, i, Value{}) }
1517 }
1518 scope.parent = parent
1519 scope.tail_parent = false
1520 // Fixed parameters will be overwritten without intervening allocation. Rest
1521 // and internal-definition slots must lose old values before initialization.
1522 for i in function.params .. count { scope.slots[i] = Value{ tag: .uninitialized } }
1523 return scope
1524}
1525
1526// The view exists only during a primitive/native call. Reentry creates another
1527// Machine, so it cannot move this stack. Hosts clone retained containers.
1528fn (m &Machine) arguments(start int) []Value {
1529 return unsafe { m.stack[start..] }
1530}
1531