pd-vm 0.23.1

RustScript bytecode compiler and VM
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
418
419
420
421
422
423
424
425
426
427
428
429
#![cfg(feature = "runtime")]
use std::path::Path;

use vm::{
    CallOutcome, FunctionDecl, HostFunction, SourceFlavor, Value, Vm, VmStatus,
    compile_source_file, compile_source_with_flavor,
};

struct PrintFunction;
struct AddOneFunction;

impl HostFunction for PrintFunction {
    fn call(&mut self, _vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, vm::VmError> {
        Ok(CallOutcome::Return(args.to_vec().into()))
    }
}

impl HostFunction for AddOneFunction {
    fn call(&mut self, _vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, vm::VmError> {
        let value = match args.first() {
            Some(Value::Int(value)) => *value,
            _ => return Err(vm::VmError::TypeMismatch("int")),
        };
        Ok(CallOutcome::Return(vec![Value::Int(value + 1)].into()))
    }
}

fn register_functions(vm: &mut Vm, functions: &[FunctionDecl]) {
    for decl in functions {
        match decl.name.as_str() {
            "print" => {
                vm.bind_function("print", Box::new(PrintFunction));
            }
            "add_one" => {
                vm.bind_function("add_one", Box::new(AddOneFunction));
            }
            "runtime::sleep" | "runtime::exit" => {}
            other => panic!("unknown function '{other}'"),
        }
    }
}

fn run_vm_until_halted(vm: &mut Vm) {
    loop {
        match vm.run().expect("vm should run") {
            VmStatus::Halted => break,
            VmStatus::Yielded => continue,
            VmStatus::Waiting(_op_id) => vm
                .wait_for_host_op_blocking()
                .expect("vm should complete host operation"),
        }
    }
}

fn run_compiled_file(path: &Path) -> Vec<Value> {
    let compiled = compile_source_file(path).expect("compile should succeed");
    let mut vm = Vm::new(compiled.program);
    let mut jit_config = *vm.jit_config();
    jit_config.enabled = false;
    vm.set_jit_config(jit_config);
    register_functions(&mut vm, &compiled.functions);
    run_vm_until_halted(&mut vm);
    vm.stack().to_vec()
}

fn run_compiled_source(flavor: SourceFlavor, source: &str) -> Vec<Value> {
    let compiled = compile_source_with_flavor(source, flavor).expect("compile should succeed");
    let mut vm = Vm::new(compiled.program);
    let mut jit_config = *vm.jit_config();
    jit_config.enabled = false;
    vm.set_jit_config(jit_config);
    register_functions(&mut vm, &compiled.functions);
    run_vm_until_halted(&mut vm);
    vm.stack().to_vec()
}

#[test]
fn ifft_math_example_runs() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples");
    let stack = run_compiled_file(&root.join("ifft_math.rss"));
    assert_eq!(
        stack,
        vec![
            Value::Float(1.0),
            Value::Float(2.0),
            Value::Float(3.0),
            Value::Float(4.0),
        ]
    );
}

#[test]
fn rustscript_optional_chain_uses_declared_schema_and_handling_runs() {
    let rss_source = r#"
struct Inner { c: int }
struct Outer { b: Inner }

let present: Outer = { b: { c: 7 } };
let missing: Outer? = null;

present?.b?.c.unwrap_or(0);
missing?.b?.c.unwrap_or(0);
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, rss_source),
        vec![Value::Int(7), Value::Int(0)]
    );
}

#[test]
fn rustscript_optional_chain_handles_declared_array_and_string_indexes() {
    let rss_source = r#"
struct Data {
    arr: [int],
    text: string,
}

let data: Data = { arr: [10, 20], text: "abc" };
data?.arr?.[1].unwrap_or(0);
data?.arr?.[2].unwrap_or(0);
data?.text?.[1].unwrap_or("");
data?.text?.[5].unwrap_or("");
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, rss_source),
        vec![
            Value::Int(20),
            Value::Int(0),
            Value::string("b"),
            Value::string(""),
        ]
    );
}

#[test]
fn rustscript_borrowed_map_for_in_iterates_entries_without_keys_array() {
    let source = r#"
let values: map<int> = {a: 1, b: 2, c: 3};
let mut sum: int = 0;
let mut names: string = "";
for (key: string, value: int) in &values {
    names = names + key;
    sum = sum + value;
}
[sum, names.length];
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, source),
        vec![Value::array(vec![Value::Int(6), Value::Int(3)])]
    );
}

#[test]
fn rustscript_borrowed_map_for_in_rejects_mutation() {
    let source = r#"
let mut values: map<int> = {a: 1};
for (key: string, value: int) in &values {
    values["b"] = value;
}
values;
"#;
    let err = match compile_source_with_flavor(source, SourceFlavor::RustScript) {
        Ok(_) => panic!("borrowed map mutation should fail"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("borrowed by a map iterator"));
}

#[test]
fn rustscript_borrowed_map_bindings_do_not_alias_source_or_each_other() {
    // Source alias through the key binding.
    let key_alias = r#"
let values: map<int> = {a: 1};
for (values: string, value: int) in &values {
    value;
}
"#;
    let err = match compile_source_with_flavor(key_alias, SourceFlavor::RustScript) {
        Ok(_) => panic!("map iterator key should not shadow the source"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("shadows the borrowed source"));

    // Source alias through the value binding.
    let value_alias = r#"
let values: map<int> = {a: 1};
for (key: string, values: int) in &values {
    key;
}
"#;
    let err = match compile_source_with_flavor(value_alias, SourceFlavor::RustScript) {
        Ok(_) => panic!("map iterator value should not shadow the source"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("shadows the borrowed source"));

    // Duplicate binding names.
    let duplicate = r#"
let values: map<int> = {a: 1};
for (item: string, item: int) in &values {
    item;
}
"#;
    let err = match compile_source_with_flavor(duplicate, SourceFlavor::RustScript) {
        Ok(_) => panic!("duplicate map iterator bindings should fail"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("duplicate map iterator binding"));
}

#[test]
fn rustscript_borrowed_map_bindings_restore_outer_locals() {
    let source = r#"
let mut key: int = 7;
let values: map<int> = {a: 1};
for (key: string, value: int) in &values {
    let observed: int = value;
}
key = 9;
key;
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, source),
        vec![Value::Int(9)]
    );
}

#[test]
fn rustscript_borrowed_map_for_in_rejects_source_rebinding() {
    let source = r#"
let values: map<int> = {a: 1};
for (key: string, value: int) in &values {
    let values: map<int> = {};
    key;
}
"#;
    let err = match compile_source_with_flavor(source, SourceFlavor::RustScript) {
        Ok(_) => panic!("borrowed map source rebinding should fail"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("borrowed by a map iterator"));
}

#[test]
fn rustscript_borrowed_map_for_in_validates_binding_schemas() {
    let bad_key = r#"
let values: map<int> = {a: 1};
for (key: int, value: int) in &values {
    value;
}
"#;
    let err = match compile_source_with_flavor(bad_key, SourceFlavor::RustScript) {
        Ok(_) => panic!("map iterator keys must be strings"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("map iterator key binding"));

    let bad_value = r#"
let values: map<int> = {a: 1};
for (key: string, value: string) in &values {
    key;
}
"#;
    let err = match compile_source_with_flavor(bad_value, SourceFlavor::RustScript) {
        Ok(_) => panic!("map iterator value schema must match the map"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("map iterator value binding"));
}

#[test]
fn rustscript_borrowed_map_iterator_ids_survive_local_compaction() {
    let source = r#"
let a0: int = 0;
let a1: int = 1;
let a2: int = 2;
let a3: int = 3;
let a4: int = 4;
let a5: int = 5;
let a6: int = 6;
let a7: int = 7;
let a8: int = 8;
let values: map<int> = {a: 1, b: 2};
let mut total: int = 0;
for (key: string, value: int) in &values {
    total += value;
}
total;
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, source),
        vec![Value::Int(3)]
    );

    let nested = r#"
let a0: int = 0;
let a1: int = 1;
let a2: int = 2;
let a3: int = 3;
let a4: int = 4;
let a5: int = 5;
let a6: int = 6;
let a7: int = 7;
let a8: int = 8;
let outer: map<int> = {a: 1, b: 2};
let inner: map<int> = {x: 10, y: 20};
let mut total: int = 0;
for (outer_key: string, outer_value: int) in &outer {
    for (inner_key: string, inner_value: int) in &inner {
        total += outer_value + inner_value;
    }
}
total;
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, nested),
        vec![Value::Int(66)]
    );
}

#[test]
fn rustscript_function_map_iteration_enforces_borrow_and_schema() {
    let rebind = r#"
fn probe() -> int {
    let values: map<int> = {a: 1};
    for (key: string, value: int) in &values {
        let values: map<int> = {};
    }
    values.length
}
probe();
"#;
    let err = match compile_source_with_flavor(rebind, SourceFlavor::RustScript) {
        Ok(_) => panic!("function-local borrowed source rebinding should fail"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("borrowed by a map iterator"));

    let mismatch = r#"
fn probe() -> int {
    let values: map<int> = {a: 1};
    for (key: string, value: string) in &values {}
    values.length
}
probe();
"#;
    let err = match compile_source_with_flavor(mismatch, SourceFlavor::RustScript) {
        Ok(_) => panic!("function-local iterator schema mismatch should fail"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("map iterator value binding"));
}

#[test]
fn rustscript_explicit_iterator_value_schema_requires_typed_source() {
    let source = r#"
let values = {a: 1};
for (key: string, value: int) in &values {}
"#;
    let err = match compile_source_with_flavor(source, SourceFlavor::RustScript) {
        Ok(_) => panic!("explicit iterator schema over an untyped map should fail"),
        Err(err) => err,
    };
    assert!(
        err.to_string()
            .contains("source map has no declared map<T> schema")
    );
}

#[test]
fn rustscript_borrowed_map_iteration_rejects_non_string_keys() {
    let source = r#"
let values: map<int> = {1: 2};
for (key: string, value: int) in &values {}
"#;
    let compiled = compile_source_with_flavor(source, SourceFlavor::RustScript)
        .expect("typed source should compile");
    let mut vm = Vm::new(compiled.program);
    let err = vm
        .run()
        .expect_err("non-string map keys should fail at iterator init");
    assert!(err.to_string().contains("requires string keys"));
}

#[test]
fn rustscript_untyped_rebinding_does_not_reuse_stale_map_schema() {
    let source = r#"
let values: map<int> = {a: 1};
let values = {a: "x"};
for (key: string, value: int) in &values { value; }
"#;
    let err = match compile_source_with_flavor(source, SourceFlavor::RustScript) {
        Ok(_) => panic!("untyped rebinding must clear stale map schema"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("map<T> schema"));
}

#[test]
fn rustscript_function_parameter_map_type_is_visible_to_iterators() {
    let source = r#"
fn sum(values: map<int>) -> int {
    let mut total: int = 0;
    for (key: string, value: int) in &values { total += value; }
    total
}
sum({a: 1, b: 2});
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, source),
        vec![Value::Int(3)]
    );
}

#[test]
fn rustscript_borrowed_map_iterator_propagates_nested_binding_schema() {
    let source = r#"
let groups: map<map<int>> = {first: {a: 1, b: 2}};
let mut total: int = 0;
for (group_key: string, group: map<int>) in &groups {
    for (item_key: string, item: int) in &group { total += item; }
}
total;
"#;
    assert_eq!(
        run_compiled_source(SourceFlavor::RustScript, source),
        vec![Value::Int(3)]
    );
}