harn-vm 0.10.49

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
use crate::stdlib::macros::{harn_builtin, VmBuiltinDef};
use crate::value::{string_char_count, VmError, VmValue};
use crate::vm::Vm;

const I64_FLOAT_UPPER_BOUND_EXCLUSIVE: f64 = 9_223_372_036_854_775_808.0;

pub(crate) fn register_type_builtins(vm: &mut Vm) {
    for def in MODULE_BUILTINS {
        vm.register_builtin_def(def);
    }
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "type_of(...args: any) -> string", category = "types"
)]
fn type_of_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    Ok(VmValue::String(arcstr::ArcStr::from(val.type_name())))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "to_string(...args: any) -> string", category = "types"
)]
fn to_string_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    Ok(VmValue::String(arcstr::ArcStr::from(val.display())))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "to_int(...args: any) -> int", category = "types"
)]
fn to_int_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    match val {
        VmValue::Int(n) => Ok(VmValue::Int(*n)),
        VmValue::Float(n) => Ok(float_to_int(*n).map(VmValue::Int).unwrap_or(VmValue::Nil)),
        // Truncates toward zero, like the float path.
        VmValue::Decimal(d) => {
            use rust_decimal::prelude::ToPrimitive;
            Ok(d.trunc().to_i64().map(VmValue::Int).unwrap_or(VmValue::Nil))
        }
        VmValue::Bool(value) => Ok(VmValue::Int(i64::from(*value))),
        // Trim surrounding whitespace before parsing, matching `decimal(...)`
        // and Python's `int(" 42 ")`/JS `Number(" 42 ")`. A string is exactly
        // the case `std/coerce` exists for (numbers rendered by an LLM/JSON),
        // and a stray newline should not silently produce `nil`.
        VmValue::String(s) => Ok(s
            .trim()
            .parse::<i64>()
            .map(VmValue::Int)
            .unwrap_or(VmValue::Nil)),
        _ => Ok(VmValue::Nil),
    }
}

fn float_to_int(value: f64) -> Option<i64> {
    if !value.is_finite() || value < i64::MIN as f64 || value >= I64_FLOAT_UPPER_BOUND_EXCLUSIVE {
        return None;
    }
    Some(value as i64)
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "to_float(...args: any) -> float", category = "types"
)]
fn to_float_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    match val {
        VmValue::Float(n) => Ok(VmValue::Float(*n)),
        VmValue::Int(n) => Ok(VmValue::Float(*n as f64)),
        // Lossy: a 96-bit decimal may not be exactly representable as f64.
        VmValue::Decimal(d) => {
            use rust_decimal::prelude::ToPrimitive;
            Ok(d.to_f64().map(VmValue::Float).unwrap_or(VmValue::Nil))
        }
        VmValue::String(s) => Ok(s
            .trim()
            .parse::<f64>()
            .map(VmValue::Float)
            .unwrap_or(VmValue::Nil)),
        _ => Ok(VmValue::Nil),
    }
}

/// Construct an exact decimal. Unlike `to_int`/`to_float` (which return `nil`
/// on a bad value), `decimal` THROWS on un-parseable input, because silently
/// dropping a money value to `nil` is dangerous. Accepts a string (exact
/// parse), an int (exact), a float (explicit opt-in to the lossy binary→decimal
/// conversion), or a decimal (identity).
#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "decimal(value: string | int | float | decimal) -> decimal",
    category = "types"
)]
fn decimal_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    fn throw(message: String) -> VmError {
        VmError::Thrown(VmValue::String(arcstr::ArcStr::from(message)))
    }
    let val = args.first().unwrap_or(&VmValue::Nil);
    match val {
        VmValue::Decimal(d) => Ok(VmValue::decimal(**d)),
        VmValue::Int(n) => Ok(VmValue::decimal(rust_decimal::Decimal::from(*n))),
        VmValue::String(s) => s
            .trim()
            .parse::<rust_decimal::Decimal>()
            .map(VmValue::decimal)
            .map_err(|_| throw(format!("decimal: cannot parse {s:?} as a decimal"))),
        VmValue::Float(f) => rust_decimal::Decimal::from_f64_retain(*f)
            .map(VmValue::decimal)
            .ok_or_else(|| throw(format!("decimal: cannot represent {f} as a decimal"))),
        other => Err(throw(format!(
            "decimal: cannot convert {} to a decimal",
            other.type_name()
        ))),
    }
}

#[harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "Ok(value?: any) -> any",
    runtime_only = true,
    category = "types"
)]
fn ok_ctor_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().cloned().unwrap_or(VmValue::Nil);
    Ok(VmValue::enum_variant("Result", "Ok", vec![val]))
}

#[harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "Err(value?: any) -> any",
    runtime_only = true,
    category = "types"
)]
fn err_ctor_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().cloned().unwrap_or(VmValue::Nil);
    Ok(VmValue::enum_variant("Result", "Err", vec![val]))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "is_ok(value: any) -> bool", category = "types"
)]
fn is_ok_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    Ok(VmValue::Bool(matches!(
        val,
        VmValue::EnumVariant(enum_variant)
        if enum_variant.is_variant("Result", "Ok")
    )))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "is_err(value: any) -> bool", category = "types"
)]
fn is_err_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    Ok(VmValue::Bool(matches!(
        val,
        VmValue::EnumVariant(enum_variant)
        if enum_variant.is_variant("Result", "Err")
    )))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "unwrap(...args: any) -> any", category = "types"
)]
fn unwrap_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    match val {
        VmValue::EnumVariant(enum_variant) if enum_variant.is_variant("Result", "Ok") => {
            Ok(enum_variant.fields.first().cloned().unwrap_or(VmValue::Nil))
        }
        VmValue::EnumVariant(enum_variant) if enum_variant.is_variant("Result", "Err") => {
            let msg = enum_variant
                .fields
                .first()
                .map(|f| f.display())
                .unwrap_or_default();
            Err(VmError::Runtime(format!("unwrap called on Err: {msg}")))
        }
        _ => Ok(val.clone()),
    }
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "unwrap_or(...args: any) -> any", category = "types"
)]
fn unwrap_or_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    let default = args.get(1).cloned().unwrap_or(VmValue::Nil);
    match val {
        VmValue::EnumVariant(enum_variant) if enum_variant.is_variant("Result", "Ok") => {
            Ok(enum_variant.fields.first().cloned().unwrap_or(VmValue::Nil))
        }
        VmValue::EnumVariant(enum_variant) if enum_variant.is_variant("Result", "Err") => {
            Ok(default)
        }
        _ => Ok(val.clone()),
    }
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "unwrap_err(...args: any) -> any", category = "types"
)]
fn unwrap_err_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let val = args.first().unwrap_or(&VmValue::Nil);
    match val {
        VmValue::EnumVariant(enum_variant) if enum_variant.is_variant("Result", "Err") => {
            Ok(enum_variant.fields.first().cloned().unwrap_or(VmValue::Nil))
        }
        _ => Err(VmError::Runtime("unwrap_err called on non-Err".into())),
    }
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "unreachable(...args: any) -> never", category = "types"
)]
fn unreachable_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let msg = match args.first() {
        Some(val) => format!("unreachable code was reached: {}", val.display()),
        None => "unreachable code was reached".to_string(),
    };
    Err(VmError::Runtime(msg))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "to_list(...args: any) -> list", category = "types"
)]
fn to_list_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Set(s) => Ok(VmValue::List(s.shared_items())),
        VmValue::List(l) => Ok(VmValue::List(l.clone())),
        other => Ok(VmValue::List(std::sync::Arc::new(vec![other.clone()]))),
    }
}

/// Construct a fixed-arity positional value.
///
/// The runtime representation is deliberately the canonical Harn list value;
/// `tuple<T0, ...>` is a checked static/runtime-boundary refinement, not a
/// second collection hierarchy.
#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "tuple(...items: any) -> list",
    category = "types"
)]
fn tuple_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    Ok(VmValue::List(std::sync::Arc::new(args.to_vec())))
}

#[harn_builtin(
    exposure = "pure",
    effects = [],
    sig = "len(value: string | bytes | list | dict | set | range | nil) -> int",
    category = "types"
)]
fn len_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::String(s) => Ok(VmValue::Int(string_char_count(s) as i64)),
        VmValue::Bytes(bytes) => Ok(VmValue::Int(bytes.len() as i64)),
        VmValue::List(items) => Ok(VmValue::Int(items.len() as i64)),
        VmValue::Dict(map) => Ok(VmValue::Int(map.len() as i64)),
        VmValue::Set(s) => Ok(VmValue::Int(s.len() as i64)),
        VmValue::Range(r) => Ok(VmValue::Int(r.len())),
        _ => Ok(VmValue::Int(0)),
    }
}

// `==` is structural. `is_same` is identity (Arc::ptr_eq for heap values);
// for primitive scalars it reduces to structural equality.
#[harn_builtin(
    exposure = "capability_arg:0",
    effects = ["state.observe@arg0"],
    sig = "is_same(a: any, b: any) -> bool", category = "types"
)]
fn is_same_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let a = args.first().unwrap_or(&VmValue::Nil);
    let b = args.get(1).unwrap_or(&VmValue::Nil);
    Ok(VmValue::Bool(crate::value::values_identical(a, b)))
}

// Stable identity key — differs iff two values live at different heap
// allocations. For hashing by identity rather than structure; primitives
// return their display() text.
#[harn_builtin(
    exposure = "capability_arg:0",
    effects = ["state.observe@arg0"],
    sig = "addr_of(value: any) -> string", category = "types"
)]
fn addr_of_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let v = args.first().unwrap_or(&VmValue::Nil);
    Ok(VmValue::String(arcstr::ArcStr::from(
        crate::value::value_identity_key(v),
    )))
}

// `drop(handle)` — close a stdlib handle deterministically. Dispatch is by
// runtime value tag: each handle variant maps to its existing close verb
// (`Channel` → mark closed, `SyncPermit` → release). Non-drop values are a
// silent no-op so callers can hand `drop` any value without guarding.
// `owned<T>` bindings call this implicitly at scope exit via a synthetic
// `defer { drop(<binding>) }`.
#[harn_builtin(
    exposure = "capability_arg:0",
    effects = ["state.mutate@arg0"],
    sig = "drop(handle: any) -> nil", category = "types"
)]
fn drop_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let v = args.first().unwrap_or(&VmValue::Nil);
    match v {
        VmValue::Channel(ch) => {
            ch.close();
        }
        VmValue::SyncPermit(permit) => {
            permit.release();
        }
        VmValue::ResourceGuard(guard) => {
            guard.release()?;
        }
        _ => {}
    }
    Ok(VmValue::Nil)
}

pub(crate) const MODULE_BUILTINS: &[&VmBuiltinDef] = &[
    &TYPE_OF_IMPL_DEF,
    &TO_STRING_IMPL_DEF,
    &TO_INT_IMPL_DEF,
    &TO_FLOAT_IMPL_DEF,
    &DECIMAL_IMPL_DEF,
    &TUPLE_IMPL_DEF,
    &OK_CTOR_IMPL_DEF,
    &ERR_CTOR_IMPL_DEF,
    &IS_OK_IMPL_DEF,
    &IS_ERR_IMPL_DEF,
    &UNWRAP_IMPL_DEF,
    &UNWRAP_OR_IMPL_DEF,
    &UNWRAP_ERR_IMPL_DEF,
    &UNREACHABLE_IMPL_DEF,
    &TO_LIST_IMPL_DEF,
    &LEN_IMPL_DEF,
    &IS_SAME_IMPL_DEF,
    &ADDR_OF_IMPL_DEF,
    &DROP_IMPL_DEF,
];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn to_int_converts_bools() {
        assert_eq!(
            to_int_impl(&[VmValue::Bool(true)], &mut String::new())
                .unwrap()
                .as_int(),
            Some(1)
        );
        assert_eq!(
            to_int_impl(&[VmValue::Bool(false)], &mut String::new())
                .unwrap()
                .as_int(),
            Some(0)
        );
    }

    #[test]
    fn to_int_rejects_non_finite_and_out_of_range_floats() {
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1.0e30] {
            let converted = to_int_impl(&[VmValue::Float(value)], &mut String::new()).unwrap();
            assert!(matches!(converted, VmValue::Nil));
        }
    }

    #[test]
    fn to_int_and_to_float_trim_surrounding_whitespace() {
        let s = |text: &str| VmValue::String(arcstr::ArcStr::from(text));
        assert!(matches!(
            to_int_impl(&[s("  42  ")], &mut String::new()).unwrap(),
            VmValue::Int(42)
        ));
        assert!(matches!(
            to_int_impl(&[s("42\n")], &mut String::new()).unwrap(),
            VmValue::Int(42)
        ));
        match to_float_impl(&[s("  1.5  ")], &mut String::new()).unwrap() {
            VmValue::Float(f) => assert!((f - 1.5).abs() < 1e-9),
            other => panic!("expected 1.5, got {other:?}"),
        }
        // Non-numeric strings still return nil.
        assert!(matches!(
            to_int_impl(&[s("nope")], &mut String::new()).unwrap(),
            VmValue::Nil
        ));
    }
}