Skip to main content

vibe/extension_registry/
scalar_compat.rs

1//! Flat-scalar argument marshaling and convenience kernel evaluation for interactive
2//! VibeScript 0.03 programs (`VS03-08`).
3//!
4//! Keeps hot-path marshaling zero-heap using caller-owned stack scratch buffers while
5//! allowing interactive scripts to pass either slice lists (`[a, b, c]`) or flat scalar
6//! arguments (`a, b, c`) to extension functions.
7
8use crate::value::Value;
9use vibescript_abi::{FuncDescriptor, ParamSpec, PrimitiveKind, VibeTrap};
10
11/// Aligns `cursor` up to `align` (power of two).
12#[inline]
13const fn align_up(cursor: usize, align: usize) -> usize {
14    let mask = align - 1;
15    (cursor + mask) & !mask
16}
17
18/// Marshals `effective_args` into `input_scratch` and records `(start, end, kind, elems)`
19/// in `param_offsets` for each parameter in `func.params`.
20pub fn marshal_args_into_scratch(
21    func: &FuncDescriptor,
22    effective_args: &[&Value],
23    input_scratch: &mut [u8],
24    param_offsets: &mut [(usize, usize, PrimitiveKind, usize)],
25) -> Result<(), VibeTrap> {
26    if func.params.len() > param_offsets.len() {
27        return Err(VibeTrap::ArityMismatch);
28    }
29
30    let mut cursor = 0usize;
31
32    // Case 1: Exact 1-to-1 parameter count match
33    if effective_args.len() == func.params.len() {
34        for (idx, (spec, val)) in func.params.iter().zip(effective_args.iter()).enumerate() {
35            cursor = align_up(cursor, spec.kind.elem_align());
36            let start = cursor;
37            let elems = write_value_into_scratch(spec, val, input_scratch, &mut cursor)?;
38            param_offsets[idx] = (start, cursor, spec.kind, elems);
39        }
40        return Ok(());
41    }
42
43    // Case 2: `project_10d_to_3d` called with 10 flat scalar coordinates (default 7D weights)
44    if func.name == "project_10d_to_3d" && effective_args.len() == 10 && func.params.len() == 2 {
45        cursor = align_up(cursor, func.params[0].kind.elem_align());
46        let start0 = cursor;
47        for val in effective_args {
48            write_scalar_into_scratch(func.params[0].kind, val, input_scratch, &mut cursor)?;
49        }
50        param_offsets[0] = (start0, cursor, func.params[0].kind, 10);
51
52        cursor = align_up(cursor, func.params[1].kind.elem_align());
53        let start1 = cursor;
54        const DEFAULT_WEIGHTS_7D: [f32; 7] = [1.0, 0.5, 0.35, 0.25, 0.2, 0.15, 0.1];
55        for w in DEFAULT_WEIGHTS_7D {
56            if cursor + 4 > input_scratch.len() {
57                return Err(VibeTrap::SliceBoundsOverflow);
58            }
59            input_scratch[cursor..cursor + 4].copy_from_slice(&w.to_le_bytes());
60            cursor += 4;
61        }
62        param_offsets[1] = (start1, cursor, func.params[1].kind, 7);
63        return Ok(());
64    }
65
66    // Case 3: Single-slice parameter called with flat scalar arguments
67    if func.params.len() == 1 {
68        let spec = &func.params[0];
69        cursor = align_up(cursor, spec.kind.elem_align());
70        let start = cursor;
71        let mut elems = 0usize;
72        for val in effective_args {
73            elems += write_value_into_scratch(spec, val, input_scratch, &mut cursor)?;
74        }
75        if elems < spec.min_elems as usize || elems > spec.max_elems as usize {
76            return Err(VibeTrap::ArityMismatch);
77        }
78        param_offsets[0] = (start, cursor, spec.kind, elems);
79        return Ok(());
80    }
81
82    // Case 4: Multi-parameter function where flat scalar count equals sum of `min_elems`
83    let total_min: usize = func.params.iter().map(|p| p.min_elems as usize).sum();
84    if total_min == effective_args.len() {
85        let mut arg_idx = 0usize;
86        for (param_idx, spec) in func.params.iter().enumerate() {
87            cursor = align_up(cursor, spec.kind.elem_align());
88            let start = cursor;
89            let count = spec.min_elems as usize;
90            for val in &effective_args[arg_idx..arg_idx + count] {
91                write_scalar_into_scratch(spec.kind, val, input_scratch, &mut cursor)?;
92            }
93            param_offsets[param_idx] = (start, cursor, spec.kind, count);
94            arg_idx += count;
95        }
96        return Ok(());
97    }
98
99    Err(VibeTrap::ArityMismatch)
100}
101
102pub fn write_value_into_scratch(
103    spec: &ParamSpec,
104    val: &Value,
105    scratch: &mut [u8],
106    cursor: &mut usize,
107) -> Result<usize, VibeTrap> {
108    if spec.kind == PrimitiveKind::Utf8Bytes {
109        let bytes = match val {
110            Value::String(s) | Value::Iri(s) | Value::Blank(s) => s.as_bytes(),
111            _ => return Err(VibeTrap::TypeMismatch),
112        };
113        if *cursor + bytes.len() > scratch.len() {
114            return Err(VibeTrap::SliceBoundsOverflow);
115        }
116        scratch[*cursor..*cursor + bytes.len()].copy_from_slice(bytes);
117        *cursor += bytes.len();
118        return Ok(bytes.len());
119    }
120    if spec.kind == PrimitiveKind::NQuin48 {
121        if let Value::List(items) = val {
122            if items.len() == 6 && items.iter().all(|x| !matches!(x, Value::QuinRef(_))) {
123                write_scalar_into_scratch(spec.kind, val, scratch, cursor)?;
124                return Ok(1);
125            }
126            for item in items {
127                write_scalar_into_scratch(spec.kind, item, scratch, cursor)?;
128            }
129            return Ok(items.len());
130        }
131        write_scalar_into_scratch(spec.kind, val, scratch, cursor)?;
132        return Ok(1);
133    }
134    if spec.kind == PrimitiveKind::ResourceHandle {
135        if let Value::List(items) = val {
136            if items.len() == 5 && items.iter().all(|x| !matches!(x, Value::Record(_) | Value::List(_))) {
137                write_scalar_into_scratch(spec.kind, val, scratch, cursor)?;
138                return Ok(1);
139            }
140            for item in items {
141                write_scalar_into_scratch(spec.kind, item, scratch, cursor)?;
142            }
143            return Ok(items.len());
144        }
145        write_scalar_into_scratch(spec.kind, val, scratch, cursor)?;
146        return Ok(1);
147    }
148    match val {
149        Value::List(items) => {
150            for item in items {
151                write_scalar_into_scratch(spec.kind, item, scratch, cursor)?;
152            }
153            Ok(items.len())
154        }
155        scalar => {
156            write_scalar_into_scratch(spec.kind, scalar, scratch, cursor)?;
157            Ok(1)
158        }
159    }
160}
161
162pub fn write_scalar_into_scratch(
163    kind: PrimitiveKind,
164    val: &Value,
165    scratch: &mut [u8],
166    cursor: &mut usize,
167) -> Result<(), VibeTrap> {
168    let need = kind.elem_size();
169    if *cursor + need > scratch.len() {
170        return Err(VibeTrap::SliceBoundsOverflow);
171    }
172    match kind {
173        PrimitiveKind::F64 => {
174            let n = val.as_f64().ok_or(VibeTrap::TypeMismatch)?;
175            scratch[*cursor..*cursor + 8].copy_from_slice(&n.to_le_bytes());
176        }
177        PrimitiveKind::F32 => {
178            let n = val.as_f64().ok_or(VibeTrap::TypeMismatch)? as f32;
179            scratch[*cursor..*cursor + 4].copy_from_slice(&n.to_le_bytes());
180        }
181        PrimitiveKind::I64 => {
182            let n = val.as_i64().ok_or(VibeTrap::TypeMismatch)?;
183            scratch[*cursor..*cursor + 8].copy_from_slice(&n.to_le_bytes());
184        }
185        PrimitiveKind::U64 => {
186            let n = value_to_u64(val).ok_or(VibeTrap::TypeMismatch)?;
187            scratch[*cursor..*cursor + 8].copy_from_slice(&n.to_le_bytes());
188        }
189        PrimitiveKind::U32 => {
190            let n = val.as_i64().ok_or(VibeTrap::TypeMismatch)? as u32;
191            scratch[*cursor..*cursor + 4].copy_from_slice(&n.to_le_bytes());
192        }
193        PrimitiveKind::I32 => {
194            let n = val.as_i64().ok_or(VibeTrap::TypeMismatch)? as i32;
195            scratch[*cursor..*cursor + 4].copy_from_slice(&n.to_le_bytes());
196        }
197        PrimitiveKind::Bool | PrimitiveKind::U8 => {
198            let b = match val {
199                Value::Bool(b) => u8::from(*b),
200                Value::U64(u) => *u as u8,
201                Value::I64(i) => *i as u8,
202                _ => return Err(VibeTrap::TypeMismatch),
203            };
204            scratch[*cursor] = b;
205        }
206        PrimitiveKind::NQuin48 => match val {
207            Value::QuinRef(q) => {
208                let words = q.raw_fields();
209                for (w_idx, word) in words.iter().enumerate() {
210                    let off = *cursor + w_idx * 8;
211                    scratch[off..off + 8].copy_from_slice(&word.to_le_bytes());
212                }
213            }
214            Value::List(xs) if xs.len() == 6 => {
215                for (w_idx, item) in xs.iter().enumerate() {
216                    let word = value_to_u64(item).ok_or(VibeTrap::TypeMismatch)?;
217                    let off = *cursor + w_idx * 8;
218                    scratch[off..off + 8].copy_from_slice(&word.to_le_bytes());
219                }
220            }
221            _ => return Err(VibeTrap::TypeMismatch),
222        },
223        PrimitiveKind::ResourceHandle => match val {
224            Value::Record(rec) => {
225                let owner = rec
226                    .get("owner_provider_hash")
227                    .and_then(value_to_u64)
228                    .ok_or(VibeTrap::TypeMismatch)?;
229                let rk = rec.get("kind").and_then(value_to_u64).unwrap_or(0) as u16;
230                let flags = rec.get("flags").and_then(value_to_u64).unwrap_or(0) as u16;
231                let gen = rec.get("generation").and_then(value_to_u64).unwrap_or(0) as u32;
232                let slot = rec.get("slot").and_then(value_to_u64).unwrap_or(0) as u32;
233                let reserved = rec.get("reserved").and_then(value_to_u64).unwrap_or(0) as u32;
234                scratch[*cursor..*cursor + 8].copy_from_slice(&owner.to_le_bytes());
235                scratch[*cursor + 8..*cursor + 10].copy_from_slice(&rk.to_le_bytes());
236                scratch[*cursor + 10..*cursor + 12].copy_from_slice(&flags.to_le_bytes());
237                scratch[*cursor + 12..*cursor + 16].copy_from_slice(&gen.to_le_bytes());
238                scratch[*cursor + 16..*cursor + 20].copy_from_slice(&slot.to_le_bytes());
239                scratch[*cursor + 20..*cursor + 24].copy_from_slice(&reserved.to_le_bytes());
240            }
241            Value::List(xs) if xs.len() >= 5 => {
242                let owner = value_to_u64(&xs[0]).ok_or(VibeTrap::TypeMismatch)?;
243                let rk = value_to_u64(&xs[1]).ok_or(VibeTrap::TypeMismatch)? as u16;
244                let flags = value_to_u64(&xs[2]).ok_or(VibeTrap::TypeMismatch)? as u16;
245                let gen = value_to_u64(&xs[3]).ok_or(VibeTrap::TypeMismatch)? as u32;
246                let slot = value_to_u64(&xs[4]).ok_or(VibeTrap::TypeMismatch)? as u32;
247                let reserved = xs.get(5).and_then(value_to_u64).unwrap_or(0) as u32;
248                scratch[*cursor..*cursor + 8].copy_from_slice(&owner.to_le_bytes());
249                scratch[*cursor + 8..*cursor + 10].copy_from_slice(&rk.to_le_bytes());
250                scratch[*cursor + 10..*cursor + 12].copy_from_slice(&flags.to_le_bytes());
251                scratch[*cursor + 12..*cursor + 16].copy_from_slice(&gen.to_le_bytes());
252                scratch[*cursor + 16..*cursor + 20].copy_from_slice(&slot.to_le_bytes());
253                scratch[*cursor + 20..*cursor + 24].copy_from_slice(&reserved.to_le_bytes());
254            }
255            _ => return Err(VibeTrap::TypeMismatch),
256        },
257        PrimitiveKind::Utf8Bytes => return Err(VibeTrap::TypeMismatch),
258    }
259    *cursor += need;
260    Ok(())
261}
262
263fn value_to_u64(val: &Value) -> Option<u64> {
264    match val {
265        Value::U64(u) => Some(*u),
266        Value::I64(i) if *i >= 0 => Some(*i as u64),
267        Value::F64(f) if *f >= 0.0 => Some(*f as u64),
268        Value::Bool(b) => Some(u64::from(*b)),
269        Value::List(xs) => xs.first().and_then(value_to_u64),
270        _ => None,
271    }
272}