| 1 | module scheme |
| 2 | |
| 3 | // Share the generated-C private pair type rather than aliasing a VM Pair. |
| 4 | // Host pairs use a negative marker only while preparing an entry; C never sees it. |
| 5 | const native_host_pair = i64(-1) |
| 6 | const native_pair_capacity = 4096 |
| 7 | |
| 8 | @[typedef] |
| 9 | struct C.VileNativePair { |
| 10 | mut: |
| 11 | car i64 |
| 12 | cdr &C.VileNativePair = unsafe { nil } |
| 13 | } |
| 14 | |
| 15 | struct NativePairInput { |
| 16 | cells &C.VileNativePair |
| 17 | mut: |
| 18 | used int |
| 19 | visited u64 |
| 20 | } |
| 21 | |
| 22 | fn native_input_scalar(value Value) ?NativeScalar { |
| 23 | if value.tag == .pair { |
| 24 | return NativeScalar{x: i64(u64(value.pointer())), k: native_host_pair} |
| 25 | } |
| 26 | scalar := native_scalar(value) |
| 27 | if scalar.k == 0 { return none } |
| 28 | return scalar |
| 29 | } |
| 30 | |
| 31 | // A failed import changes no VM state. Capacity bounds cycles and long lists; |
| 32 | // rejecting further pair imports for this plan prevents quadratic VM replay. |
| 33 | @[direct_array_access] |
| 34 | fn (mut input NativePairInput) import_list(value C.VileNativeValue) ?C.VileNativeValue { |
| 35 | if value.k != native_host_pair { return value } |
| 36 | start := input.used |
| 37 | mut current := Value{tag: .pair, bits: ValueBits{payload: unsafe { voidptr(value.x) }}} |
| 38 | for current.tag == .pair { |
| 39 | if input.used >= native_pair_capacity { return none } |
| 40 | input.visited++ |
| 41 | pair := current.pair_pointer() |
| 42 | if pair.car.tag != .integer { return none } |
| 43 | unsafe { |
| 44 | input.cells[input.used] = C.VileNativePair{car: pair.car.whole()} |
| 45 | if input.used > start { input.cells[input.used - 1].cdr = &input.cells[input.used] } |
| 46 | } |
| 47 | input.used++ |
| 48 | current = pair.cdr |
| 49 | } |
| 50 | if current.tag != .nil { return none } |
| 51 | return C.VileNativeValue{x: i64(u64(unsafe { &input.cells[start] })), k: 3} |
| 52 | } |
| 53 | |
| 54 | fn (mut scope NativeScope) import_pair_inputs(mut plan NativePlan, args &C.VileNativeValue, argc int, pool voidptr) ?int { |
| 55 | mut input := NativePairInput{cells: unsafe { &C.VileNativePair(pool) }} |
| 56 | defer { scope.pair_nodes_visited += input.visited } |
| 57 | for i in 0 .. argc { |
| 58 | value := input.import_list(unsafe { args[i] }) or { |
| 59 | plan.pair_inputs_rejected = true |
| 60 | scope.pair_input_rejections++ |
| 61 | return none |
| 62 | } |
| 63 | unsafe { args[i] = value } |
| 64 | } |
| 65 | for i, capture in plan.captures { |
| 66 | if capture.alias < i { |
| 67 | scope.capture_values[i] = scope.capture_values[capture.alias] |
| 68 | continue |
| 69 | } |
| 70 | scope.capture_values[i] = input.import_list(scope.capture_values[i]) or { |
| 71 | plan.pair_inputs_rejected = true |
| 72 | scope.pair_input_rejections++ |
| 73 | return none |
| 74 | } |
| 75 | } |
| 76 | return input.used |
| 77 | } |
| 78 | |