harn-vm 0.8.50

Async bytecode virtual machine for the Harn programming language
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
430
431
432
433
434
435
436
use super::*;
use crate::chunk::{Chunk, Constant};
use harn_lexer::Lexer;
use harn_parser::Parser;

fn compile_source(source: &str) -> Chunk {
    compile_source_with_options(source, CompilerOptions::optimized())
}

fn compile_source_with_options(source: &str, options: CompilerOptions) -> Chunk {
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();
    Compiler::with_options(options).compile(&program).unwrap()
}

fn disasm_opcodes(disasm: &str) -> Vec<&str> {
    disasm
        .lines()
        .filter_map(|line| {
            line.split_once("] ")
                .and_then(|(_, rest)| rest.split_whitespace().next())
        })
        .collect()
}

fn string_constant_count(chunk: &Chunk, value: &str) -> usize {
    chunk
        .constants
        .iter()
        .filter(|constant| matches!(constant, Constant::String(text) if text == value))
        .count()
}

#[test]
fn test_compile_arithmetic() {
    let chunk = compile_source_with_options(
        "pipeline test(task) { let x = 2 + 3 }",
        CompilerOptions::without_optimizations(),
    );
    assert!(!chunk.code.is_empty());
    assert!(chunk.constants.contains(&Constant::Int(2)));
    assert!(chunk.constants.contains(&Constant::Int(3)));
}

#[test]
fn test_compile_typed_int_loop_ops() {
    let chunk = compile_source(
        "pipeline test(task) {
  var i = 0
  var total = 0
  while i < 10 {
    total = total + (i + 3) * 2 - 1
    i = i + 1
  }
}",
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("LESS_INT"));
    assert!(disasm.contains("ADD_INT"));
    assert!(disasm.contains("MUL_INT"));
    assert!(disasm.contains("SUB_INT"));
}

#[test]
fn test_compile_typed_float_ops() {
    let chunk = compile_source(
        "pipeline test(task) {
  let a = 1.0
  let b = 2.0
  let c = a + b
  log(c < 4.0)
}",
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("ADD_FLOAT"));
    assert!(disasm.contains("LESS_FLOAT"));
}

#[test]
fn test_compile_typed_equality_ops() {
    let chunk = compile_source(
        r#"pipeline test(task) {
  let a = true
  let b = false
  let left = "a"
  let right = "b"
  log(a == b)
  log(left != right)
}"#,
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("EQUAL_BOOL"));
    assert!(disasm.contains("NOT_EQUAL_STRING"));
}

#[test]
fn test_compile_generic_ops_for_overloaded_or_mixed_cases() {
    let chunk = compile_source(
        r#"pipeline test(task) {
  let left = "a"
  let right = "b"
  let one = 1
  let two = 2.0
  let xs = [1]
  let ys = [2]
  log(left + right)
  log(one + two)
  log(xs + ys)
}"#,
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("ADD"));
    assert!(!disasm.contains("ADD_INT"));
    assert!(!disasm.contains("ADD_FLOAT"));
}

#[test]
fn test_optimizer_folds_scalar_constants() {
    let chunk = compile_source("pipeline test(task) { log(2 + 3 * 4) }");
    let disasm = chunk.disassemble("test");
    let opcodes = disasm_opcodes(&disasm);

    assert!(chunk.constants.contains(&Constant::Int(14)));
    assert!(!opcodes.contains(&"ADD_INT"));
    assert!(!opcodes.contains(&"MUL_INT"));
    assert!(!opcodes.contains(&"ADD"));
    assert!(!opcodes.contains(&"MUL"));
}

#[test]
fn test_optimizer_escape_hatch_preserves_unoptimized_bytecode() {
    let chunk = compile_source_with_options(
        "pipeline test(task) { log(2 + 3 * 4) }",
        CompilerOptions::without_optimizations(),
    );
    let disasm = chunk.disassemble("test");
    let opcodes = disasm_opcodes(&disasm);

    assert!(chunk.constants.contains(&Constant::Int(2)));
    assert!(chunk.constants.contains(&Constant::Int(3)));
    assert!(chunk.constants.contains(&Constant::Int(4)));
    assert!(opcodes.contains(&"MUL"));
    assert!(opcodes.contains(&"ADD"));
}

#[test]
fn test_optimizer_folds_literal_collections_and_strings() {
    let chunk = compile_source(
        r#"pipeline test(task) {
  log("ha" * 2)
  log([1] + [2, 3])
  log({a: 1} + {b: 2})
}"#,
    );
    let disasm = chunk.disassemble("test");
    let opcodes = disasm_opcodes(&disasm);

    assert!(chunk
        .constants
        .contains(&Constant::String("haha".to_string())));
    assert!(!opcodes.contains(&"ADD"));
    assert!(!opcodes.contains(&"MUL"));
}

#[test]
fn test_compiler_reuses_string_constants_within_chunk() {
    let chunk = compile_source(
        r#"pipeline test(task) {
  log("same")
  log("same")
  let row = {status: "same"}
  log(row.status)
}"#,
    );

    assert_eq!(string_constant_count(&chunk, "same"), 1);
    assert_eq!(string_constant_count(&chunk, "status"), 1);
}

#[test]
fn test_compiler_reuses_string_constants_per_nested_chunk() {
    let chunk = compile_source(
        r#"fn inner() {
  log("nested")
  log("nested")
}

pipeline test(task) {
  inner()
}"#,
    );
    let function = chunk
        .functions
        .iter()
        .find(|function| function.name == "inner")
        .expect("inner function should compile");

    assert_eq!(string_constant_count(&function.chunk, "nested"), 1);
}

#[test]
fn test_optimizer_keeps_runtime_erroring_arithmetic_unfolded() {
    let chunk = compile_source("pipeline test(task) { log(1 / 0) }");
    let disasm = chunk.disassemble("test");
    let opcodes = disasm_opcodes(&disasm);

    assert!(opcodes.contains(&"DIV_INT"));
}

#[test]
fn test_optimizer_keeps_large_allocations_unfolded() {
    let chunk = compile_source(r#"pipeline test(task) { log("x" * 1000000) }"#);
    let disasm = chunk.disassemble("test");
    let opcodes = disasm_opcodes(&disasm);

    assert!(opcodes.contains(&"MUL"));
}

#[test]
fn test_compile_function_call() {
    let chunk = compile_source("pipeline test(task) { log(42) }");
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("CALL_BUILTIN"));
    assert!(disasm.contains("\"log\""));
}

#[test]
fn test_compile_if_else() {
    let chunk =
        compile_source(r#"pipeline test(task) { if true { log("yes") } else { log("no") } }"#);
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("JUMP_IF_FALSE"));
    assert!(disasm.contains("JUMP"));
}

#[test]
fn test_compile_while() {
    let chunk = compile_source("pipeline test(task) { var i = 0\n while i < 5 { i = i + 1 } }");
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("JUMP_IF_FALSE"));
    assert!(disasm.contains("JUMP"));
}

#[test]
fn test_compile_locals_to_slots() {
    let chunk = compile_source(
        "pipeline test(task) {
  let a = 1
  var i = 0
  while i < 3 {
    i = i + a
  }
}",
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("DEF_LOCAL_SLOT"));
    assert!(disasm.contains("GET_LOCAL_SLOT"));
    assert!(disasm.contains("SET_LOCAL_SLOT"));
    assert!(!disasm.contains("GET_VAR"));
    assert!(!disasm.contains("SET_VAR"));
}

#[test]
fn test_compile_function_params_to_slots() {
    let chunk = compile_source(
        "pipeline test(task) {
  fn add(a, b = 1) {
    return a + b
  }
  log(add(2))
}",
    );
    let disasm = chunk.functions[0].chunk.disassemble("add");
    assert!(disasm.contains("GET_LOCAL_SLOT"));
    assert!(disasm.contains("DEF_LOCAL_SLOT"));
    assert!(!disasm.contains("GET_VAR"));
}

#[test]
fn test_compile_closure() {
    let chunk = compile_source("pipeline test(task) { let f = { x -> x * 2 } }");
    assert!(!chunk.functions.is_empty());
    assert_eq!(
        chunk.functions[0].param_names().collect::<Vec<_>>(),
        vec!["x"]
    );
}

#[test]
fn test_compile_list() {
    let chunk = compile_source("pipeline test(task) { let a = [1, 2, 3] }");
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("BUILD_LIST"));
}

#[test]
fn test_compile_dict() {
    let chunk = compile_source(r#"pipeline test(task) { let d = {name: "test"} }"#);
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("BUILD_DICT"));
}

#[test]
fn test_disassemble() {
    let chunk = compile_source_with_options(
        "pipeline test(task) { log(2 + 3) }",
        CompilerOptions::without_optimizations(),
    );
    let disasm = chunk.disassemble("test");
    assert!(disasm.contains("CONSTANT"));
    assert!(disasm.contains("ADD"));
    assert!(disasm.contains("CALL"));
}

#[test]
fn test_compile_discard_bindings_do_not_define_underscore() {
    let chunk = compile_source(
        r#"
pipeline test(task) {
  let _ = 1
  let [_, keep, _] = [10, 20, 30]
  let {drop: _, keep_dict} = {drop: 1, keep_dict: 2}
  for (_, value) in [pair("left", "right")] {
    log(value)
  }
  log(keep)
  log(keep_dict)
}
"#,
    );

    assert!(
        !chunk.constants.contains(&Constant::String("_".to_string())),
        "discard bindings should not emit a named `_` slot: {:?}",
        chunk.constants
    );
}

/// Regression: an attribute on a top-level declaration must not add a
/// module-level `Op::Pop` in script mode (a file with `fn main`). The
/// script-mode top-level loop pops after any item whose `produces_value`
/// is true; before the fix, a `Node::AttributedDecl` wrapping a `FnDecl`
/// fell through `produces_value`'s `_ => true` catch-all and emitted a
/// `Pop` against an empty operand stack — surfacing only at runtime as
/// "Stack underflow", which broke every `@route`-decorated handler in
/// `harn serve site`.
///
/// `@deprecated` emits no registration bytecode of its own, so the
/// attributed program's module-level op stream must match the bare one
/// exactly. Function bodies live in separate chunks (stored as
/// constants), so the top chunk's disassembly is purely module-level.
#[test]
fn attributed_top_level_fn_does_not_emit_spurious_pop() {
    let bare = compile_source(
        "fn f(x: int) -> int { return x + 1 }\nfn main(harness: Harness) { let _ = 1 }",
    );
    let attributed = compile_source(
        "@deprecated\nfn f(x: int) -> int { return x + 1 }\nfn main(harness: Harness) { let _ = 1 }",
    );

    let pop_count = |chunk: &Chunk| {
        disasm_opcodes(&chunk.disassemble("module"))
            .into_iter()
            .filter(|op| *op == "Pop")
            .count()
    };

    assert_eq!(
        pop_count(&attributed),
        pop_count(&bare),
        "an attributed top-level fn must not add a module-level Pop\n\
         bare:\n{}\nattributed:\n{}",
        bare.disassemble("module"),
        attributed.disassemble("module"),
    );
}

/// #2622: the debug-build balance model classifies straight-line statements
/// exactly. A bare `Op::Closure` leaves one value (`Some(1)`); pairing it
/// with the matching bind (`Op::DefVar`) nets zero (`Some(0)`); and emitting
/// a branch taints the span so the model declines to judge it (`None`).
#[test]
fn balance_model_tracks_straight_line_and_declines_branches() {
    let mut chunk = Chunk::new();

    let push_probe = chunk.balance_probe();
    chunk.emit_u16(Op::Closure, 0, 1);
    assert_eq!(chunk.balance_delta_since(push_probe), Some(1));

    // Closure + matching bind is the shape every top-level `fn`/`struct`
    // declaration lowers to — it must net zero.
    let decl_probe = chunk.balance_probe();
    chunk.emit_u16(Op::Closure, 0, 1);
    chunk.emit_u16(Op::DefVar, 0, 1);
    assert_eq!(chunk.balance_delta_since(decl_probe), Some(0));

    // A jump is non-linear: the running sum can't be trusted across it, so
    // the model reports `None` rather than risk a false assertion.
    let branch_probe = chunk.balance_probe();
    let _ = chunk.emit_jump(Op::JumpIfFalse, 1);
    assert_eq!(chunk.balance_delta_since(branch_probe), None);
}

/// #2622: a `produces_value` gap must fail loudly at compile time. We force
/// the value-discarding classification to lie (`true` for a top-level `fn`,
/// which emits a balanced `Closure; DefVar` and leaves nothing to pop) and
/// confirm the balance assertion panics instead of letting the compiler emit
/// the unbalanced `Op::Pop` that #2610 only caught as a runtime underflow.
#[test]
fn miswired_produces_value_trips_balance_assertion() {
    struct ResetGuard;
    impl Drop for ResetGuard {
        fn drop(&mut self) {
            super::state::FORCE_DISCARDED_PRODUCES_VALUE.with(|c| c.set(None));
        }
    }

    let _guard = ResetGuard;
    super::state::FORCE_DISCARDED_PRODUCES_VALUE.with(|c| c.set(Some(true)));

    // Swallow the expected panic's backtrace so it doesn't clutter test output.
    let prior_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        compile_source("fn f() -> int { return 1 }\nfn main(harness: Harness) { let _ = 1 }")
    }));
    std::panic::set_hook(prior_hook);

    assert!(
        result.is_err(),
        "miswiring produces_value to `true` for a balanced top-level decl \
         must trip the #2622 stack-balance assertion",
    );
}