| 1 | module scheme |
| 2 | |
| 3 | import arena |
| 4 | import context |
| 5 | |
| 6 | fn dispatch_empty_error(mut _vm VM, _args []Value) !Value { |
| 7 | return IError(none) |
| 8 | } |
| 9 | |
| 10 | // A V Result's failure flag is independent of the dynamic IError payload. |
| 11 | // Neither ordinary nor controlled dispatch may mistake a none payload for success. |
| 12 | fn test_dispatch_preserves_failed_native_result_with_none_error_payload() { |
| 13 | for controlled in [false, true] { |
| 14 | for alt in [false, true] { |
| 15 | mut vm := new() |
| 16 | vm.register('empty-error', dispatch_empty_error) or { panic(err.msg()) } |
| 17 | vm.eval('(define observed #f)') or { panic(err.msg()) } |
| 18 | work := fn [alt] (mut vm VM) !Value { |
| 19 | return if alt { |
| 20 | vm.eval_alt('empty-error()\nobserved = #t') |
| 21 | } else { |
| 22 | vm.eval('(empty-error) (set! observed #t)') |
| 23 | } |
| 24 | } |
| 25 | mut background := context.background() |
| 26 | mut ctx, cancel := context.with_cancel(mut background) |
| 27 | if controlled { |
| 28 | if _ := vm.with_context(mut ctx, work) { |
| 29 | assert false, 'controlled native failure was swallowed: alt=${alt}' |
| 30 | } |
| 31 | } else { |
| 32 | if _ := work(mut vm) { |
| 33 | assert false, 'ordinary native failure was swallowed: alt=${alt}' |
| 34 | } |
| 35 | } |
| 36 | cancel() |
| 37 | assert vm.active.len == 0 |
| 38 | assert !vm.eval('observed') or { panic(err.msg()) }.is_true() |
| 39 | assert (vm.eval('(+ 20 22)') or { panic(err.msg()) }).whole() == 42 |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn test_dispatch_tail_loop_retained_allocation_is_independent_of_instruction_count() { |
| 45 | mut vm := new_with_options(Options{ max_steps: 0, max_frames: 8 }) or { panic(err.msg()) } |
| 46 | vm.eval('(define (allocation-loop n acc) (if (= n 0) acc (allocation-loop (- n 1) (+ acc n))))') or { panic(err.msg()) } |
| 47 | procedure := vm.lookup('allocation-loop') or { panic(err.msg()) } |
| 48 | mut region := arena.new(chunk_size: 1048576) |
| 49 | region.push() |
| 50 | defer { |
| 51 | region.pop() |
| 52 | region.free() |
| 53 | } |
| 54 | vm.call(procedure, [integer(100), integer(0)]) or { panic(err.msg()) } |
| 55 | mut retained := []int{cap: 2} |
| 56 | for count in [1000, 100000] { |
| 57 | args := [integer(count), integer(0)] |
| 58 | before := region.used() |
| 59 | value := vm.call(procedure, args) or { panic(err.msg()) } |
| 60 | retained << region.used() - before |
| 61 | assert value.whole() == i64(count) * (count + 1) / 2 |
| 62 | } |
| 63 | // Entry/frame storage is bounded. Executing 100 times more instructions must |
| 64 | // not allocate an error box (or any other object) on every instruction. |
| 65 | assert retained[0] <= 4096, retained.str() |
| 66 | assert retained[1] <= retained[0] + 512, retained.str() |
| 67 | } |
| 68 | |