runmat-vm 0.4.4

RunMat virtual machine and bytecode interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::bytecode::{ArgSpec, UserFunction};
use crate::compiler::CompileError;
use runmat_builtins::{Type, Value};
use runmat_hir::{remapping, HirProgram, VarId};
use runmat_runtime::RuntimeError;
use std::collections::HashMap;
use std::future::Future;

pub struct PreparedUserCall {
    pub func: UserFunction,
    pub var_map: HashMap<VarId, VarId>,
    pub func_program: HirProgram,
    pub func_vars: Vec<Value>,
}

pub fn lookup_user_function(
    name: &str,
    functions: &HashMap<String, UserFunction>,
) -> Result<UserFunction, RuntimeError> {
    functions.get(name).cloned().ok_or_else(|| {
        crate::interpreter::errors::mex("UndefinedFunction", &format!("Undefined function: {name}"))
    })
}

pub fn validate_user_function_arity(
    name: &str,
    func: &UserFunction,
    arg_count: usize,
) -> Result<(), RuntimeError> {
    if !func.has_varargin {
        if arg_count < func.params.len() {
            return Err(crate::interpreter::errors::mex(
                "NotEnoughInputs",
                &format!(
                    "Function '{name}' expects {} inputs, got {arg_count}",
                    func.params.len()
                ),
            ));
        }
        if arg_count > func.params.len() {
            return Err(crate::interpreter::errors::mex(
                "TooManyInputs",
                &format!(
                    "Function '{name}' expects {} inputs, got {arg_count}",
                    func.params.len()
                ),
            ));
        }
    } else {
        let min_args = func.params.len().saturating_sub(1);
        if arg_count < min_args {
            return Err(crate::interpreter::errors::mex(
                "NotEnoughInputs",
                &format!("Function '{name}' expects at least {min_args} inputs, got {arg_count}"),
            ));
        }
    }
    Ok(())
}

pub fn prepare_user_call(
    func: UserFunction,
    args: &[Value],
    vars: &[Value],
) -> Result<PreparedUserCall, CompileError> {
    let var_map =
        remapping::create_complete_function_var_map(&func.params, &func.outputs, &func.body);
    let local_var_count = var_map.len();
    let remapped_body = remapping::remap_function_body(&func.body, &var_map);
    let func_vars_count = local_var_count.max(func.params.len());
    let mut func_vars = vec![Value::Num(0.0); func_vars_count];

    if func.has_varargin {
        let fixed = func.params.len().saturating_sub(1);
        for i in 0..fixed {
            if i < args.len() && i < func_vars.len() {
                func_vars[i] = args[i].clone();
            }
        }
        let mut rest: Vec<Value> = if args.len() > fixed {
            args[fixed..].to_vec()
        } else {
            Vec::new()
        };
        let cell = runmat_builtins::CellArray::new(
            std::mem::take(&mut rest),
            1,
            if args.len() > fixed {
                args.len() - fixed
            } else {
                0
            },
        )
        .map_err(|e| CompileError::new(format!("varargin: {e}")))?;
        if fixed < func_vars.len() {
            func_vars[fixed] = Value::Cell(cell);
        }
    } else {
        for (i, _param_id) in func.params.iter().enumerate() {
            if i < args.len() && i < func_vars.len() {
                func_vars[i] = args[i].clone();
            }
        }
    }

    for (original_var_id, local_var_id) in &var_map {
        let local_index = local_var_id.0;
        let global_index = original_var_id.0;
        if local_index < func_vars.len() && global_index < vars.len() {
            let is_parameter = func
                .params
                .iter()
                .any(|param_id| param_id == original_var_id);
            if !is_parameter {
                func_vars[local_index] = vars[global_index].clone();
            }
        }
    }

    if func.has_varargout {
        if let Some(varargout_oid) = func.outputs.last() {
            if let Some(local_id) = var_map.get(varargout_oid) {
                if local_id.0 < func_vars.len() {
                    let empty = runmat_builtins::CellArray::new(vec![], 1, 0)
                        .map_err(|e| CompileError::new(format!("varargout init: {e}")))?;
                    func_vars[local_id.0] = Value::Cell(empty);
                }
            }
        }
    }

    let mut func_var_types = func.var_types.clone();
    if func_var_types.len() < local_var_count {
        func_var_types.resize(local_var_count, Type::Unknown);
    }
    let func_program = HirProgram {
        body: remapped_body,
        var_types: func_var_types,
    };

    Ok(PreparedUserCall {
        func,
        var_map,
        func_program,
        func_vars,
    })
}

pub fn first_output_value(
    func: &UserFunction,
    var_map: &HashMap<VarId, VarId>,
    func_result_vars: &[Value],
) -> Value {
    if func.outputs.is_empty() {
        return Value::Num(0.0);
    }
    if func.has_varargout {
        let total_named = func.outputs.len().saturating_sub(1);
        if total_named > 0 {
            if let Some(oid) = func.outputs.first() {
                if let Some(local_id) = var_map.get(oid) {
                    if let Some(value) = func_result_vars.get(local_id.0) {
                        return value.clone();
                    }
                }
            }
        }
        if let Some(varargout_oid) = func.outputs.last() {
            if let Some(local_id) = var_map.get(varargout_oid) {
                if let Some(Value::Cell(ca)) = func_result_vars.get(local_id.0) {
                    if let Some(first) = ca.data.first() {
                        return (**first).clone();
                    }
                }
            }
        }
        return Value::Num(0.0);
    }
    let Some(output_id) = func.outputs.first() else {
        return Value::Num(0.0);
    };
    let Some(local_id) = var_map.get(output_id) else {
        return Value::Num(0.0);
    };
    func_result_vars
        .get(local_id.0)
        .cloned()
        .unwrap_or(Value::Num(0.0))
}

pub fn collect_multi_outputs(
    name: &str,
    func: &UserFunction,
    var_map: &HashMap<VarId, VarId>,
    func_result_vars: &[Value],
    out_count: usize,
) -> Result<Vec<Value>, RuntimeError> {
    let mut outputs = Vec::with_capacity(out_count);
    if func.has_varargout {
        let total_named = func.outputs.len().saturating_sub(1);
        let mut pushed = 0usize;
        for i in 0..total_named.min(out_count) {
            if let Some(oid) = func.outputs.get(i) {
                if let Some(local_id) = var_map.get(oid) {
                    let idx = local_id.0;
                    let v = func_result_vars
                        .get(idx)
                        .cloned()
                        .unwrap_or(Value::Num(0.0));
                    outputs.push(v);
                    pushed += 1;
                }
            }
        }
        if pushed < out_count {
            if let Some(varargout_oid) = func.outputs.last() {
                if let Some(local_id) = var_map.get(varargout_oid) {
                    if let Some(Value::Cell(ca)) = func_result_vars.get(local_id.0) {
                        let available = ca.data.len();
                        let need = out_count - pushed;
                        if need > available {
                            return Err(crate::interpreter::errors::mex(
                                "VarargoutMismatch",
                                &format!(
                                    "Function '{name}' returned {available} varargout values, {need} requested"
                                ),
                            ));
                        }
                        for vi in 0..need {
                            outputs.push((*ca.data[vi]).clone());
                        }
                    }
                }
            }
        }
    } else {
        let defined = func.outputs.len();
        if out_count > defined {
            return Err(crate::interpreter::errors::mex(
                "TooManyOutputs",
                &format!("Function '{name}' defines {defined} outputs, {out_count} requested"),
            ));
        }
        for i in 0..out_count {
            let v = func
                .outputs
                .get(i)
                .and_then(|oid| var_map.get(oid))
                .map(|lid| lid.0)
                .and_then(|idx| func_result_vars.get(idx))
                .cloned()
                .unwrap_or(Value::Num(0.0));
            outputs.push(v);
        }
    }
    Ok(outputs)
}

pub fn expand_cell_indices(
    cell: &runmat_builtins::CellArray,
    indices: &[Value],
) -> Result<Vec<Value>, RuntimeError> {
    match indices.len() {
        1 => match &indices[0] {
            Value::Num(n) => {
                let idx = *n as usize;
                if idx == 0 || idx > cell.data.len() {
                    return Err(crate::interpreter::errors::mex(
                        "CellIndexOutOfBounds",
                        "Cell index out of bounds",
                    ));
                }
                Ok(vec![(*cell.data[idx - 1]).clone()])
            }
            Value::Int(i) => {
                let idx = i.to_i64() as usize;
                if idx == 0 || idx > cell.data.len() {
                    return Err(crate::interpreter::errors::mex(
                        "CellIndexOutOfBounds",
                        "Cell index out of bounds",
                    ));
                }
                Ok(vec![(*cell.data[idx - 1]).clone()])
            }
            Value::Tensor(t) => {
                let mut out = Vec::with_capacity(t.data.len());
                for &val in &t.data {
                    let idx = val as usize;
                    if idx == 0 || idx > cell.data.len() {
                        return Err(crate::interpreter::errors::mex(
                            "CellIndexOutOfBounds",
                            "Cell index out of bounds",
                        ));
                    }
                    out.push((*cell.data[idx - 1]).clone());
                }
                Ok(out)
            }
            _ => Err(crate::interpreter::errors::mex(
                "CellIndexType",
                "Unsupported cell index type",
            )),
        },
        2 => {
            let r: f64 = (&indices[0]).try_into()?;
            let c: f64 = (&indices[1]).try_into()?;
            let (ir, ic) = (r as usize, c as usize);
            if ir == 0 || ir > cell.rows || ic == 0 || ic > cell.cols {
                return Err(crate::interpreter::errors::mex(
                    "CellSubscriptOutOfBounds",
                    "Cell subscript out of bounds",
                ));
            }
            Ok(vec![(*cell.data[(ir - 1) * cell.cols + (ic - 1)]).clone()])
        }
        _ => Err(crate::interpreter::errors::mex(
            "CellIndexType",
            "Unsupported cell index type",
        )),
    }
}

pub fn expand_all_cell(cell: &runmat_builtins::CellArray) -> Vec<Value> {
    cell.data.iter().map(|p| (*(*p)).clone()).collect()
}

pub fn subsref_paren_index_cell(indices: &[Value]) -> Result<Value, RuntimeError> {
    Ok(Value::Cell(
        runmat_builtins::CellArray::new(indices.to_vec(), 1, indices.len())
            .map_err(|e| CompileError::new(format!("subsref build error: {e}")))?,
    ))
}

pub fn subsref_brace_index_cell_raw(indices: &[Value]) -> Result<Value, RuntimeError> {
    Ok(Value::Cell(
        runmat_builtins::CellArray::new(indices.to_vec(), 1, indices.len())
            .map_err(|e| CompileError::new(format!("subsref build error: {e}")))?,
    ))
}

pub fn subsref_brace_numeric_index_values(indices: &[Value]) -> Vec<Value> {
    indices
        .iter()
        .map(|v| Value::Num((v).try_into().unwrap_or(0.0)))
        .collect()
}

pub fn subsref_empty_brace_cell() -> Result<Value, RuntimeError> {
    Ok(Value::Cell(
        runmat_builtins::CellArray::new(vec![], 1, 0)
            .map_err(|e| CompileError::new(format!("subsref build error: {e}")))?,
    ))
}

pub async fn build_expanded_args_from_specs<ExpandObjectAll, ExpandObjectIndices, FutAll, FutIdx>(
    stack: &mut Vec<Value>,
    specs: &[ArgSpec],
    invalid_expand_all_msg: &str,
    invalid_expand_msg: &str,
    mut expand_object_all: ExpandObjectAll,
    mut expand_object_indices: ExpandObjectIndices,
) -> Result<Vec<Value>, RuntimeError>
where
    ExpandObjectAll: FnMut(Value) -> FutAll,
    ExpandObjectIndices: FnMut(Value, Vec<Value>) -> FutIdx,
    FutAll: Future<Output = Result<Vec<Value>, RuntimeError>>,
    FutIdx: Future<Output = Result<Vec<Value>, RuntimeError>>,
{
    let mut temp: Vec<Value> = Vec::new();
    for spec in specs.iter().rev() {
        if spec.is_expand {
            let mut indices = Vec::with_capacity(spec.num_indices);
            for _ in 0..spec.num_indices {
                indices.push(stack.pop().ok_or_else(|| {
                    crate::interpreter::errors::mex("StackUnderflow", "stack underflow")
                })?);
            }
            indices.reverse();
            let base = stack.pop().ok_or_else(|| {
                crate::interpreter::errors::mex("StackUnderflow", "stack underflow")
            })?;

            let expanded = if spec.expand_all {
                match base {
                    Value::Cell(ca) => expand_all_cell(&ca),
                    other @ Value::Object(_) => expand_object_all(other).await?,
                    _ => {
                        return Err(crate::interpreter::errors::mex(
                            "InvalidExpandAllTarget",
                            invalid_expand_all_msg,
                        ))
                    }
                }
            } else {
                match (base, indices.len()) {
                    (Value::Cell(ca), 1) | (Value::Cell(ca), 2) => {
                        expand_cell_indices(&ca, &indices)?
                    }
                    (other @ Value::Object(_), _) => expand_object_indices(other, indices).await?,
                    _ => {
                        return Err(crate::interpreter::errors::mex(
                            "ExpandError",
                            invalid_expand_msg,
                        ))
                    }
                }
            };
            temp.extend(expanded);
        } else {
            temp.push(stack.pop().ok_or_else(|| {
                crate::interpreter::errors::mex("StackUnderflow", "stack underflow")
            })?);
        }
    }
    temp.reverse();
    Ok(temp)
}