harn-vm 0.8.13

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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Shared option-bag and argument-extraction helpers for stdlib builtins.
//!
//! Before this module landed, every option-bag-accepting builtin had its own
//! hand-rolled chain of `dict.get().map().and_then().ok_or_else()` plus its
//! own near-duplicate `optional_string` / `required_string_arg` /
//! `opts_dict_arg` helpers. Several modules duplicated the same logic under
//! different names with subtly different error shapes (some emitted
//! [`VmError::Runtime`], some [`VmError::Thrown`]). This module is the single
//! canonical home for that logic; builtins pick an [`ErrorKind`] based on
//! whether their failures should bubble out or be catchable from Harn.
//!
//! Conventions:
//! - Function-name strings are `&'static str` so error messages can be
//!   formatted without allocations on the success path.
//! - Optional fields treat both `Nil` and "missing" as None.
//! - String getters trim whitespace and treat trimmed-empty strings as None
//!   (matching the pre-existing helpers).
//! - [`OptionsParser`] tracks consumed keys so callsites with a closed schema
//!   can call [`OptionsParser::finish_strict`] to reject unknown options.
//!
//! Some helpers below are unused by today's callsites and intentionally kept
//! for adoption by future stdlib additions (option-bag parsing is the most
//! common new-builtin shape). `#![allow(dead_code)]` keeps the API surface
//! intact without per-item attributes.
#![allow(dead_code)]

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Display;
use std::rc::Rc;

use crate::value::{VmError, VmValue};

/// Whether an option-parsing failure should bubble as a runtime error or be
/// surfaced as a catchable thrown value.
///
/// Most stdlib builtins use [`ErrorKind::Runtime`]. Session and a handful of
/// other catchable-by-default builtins use [`ErrorKind::Thrown`] so user code
/// can `try` / `recover`.
#[derive(Debug, Clone, Copy)]
pub(crate) enum ErrorKind {
    Runtime,
    Thrown,
}

impl ErrorKind {
    pub(crate) fn err(self, msg: impl Into<String>) -> VmError {
        match self {
            ErrorKind::Runtime => VmError::Runtime(msg.into()),
            ErrorKind::Thrown => VmError::Thrown(VmValue::String(Rc::from(msg.into()))),
        }
    }
}

/// Build a `fn_name: msg` error of the requested kind.
pub(crate) fn fn_err(fn_name: &str, kind: ErrorKind, msg: impl Display) -> VmError {
    kind.err(format!("{fn_name}: {msg}"))
}

/// Require a positional dict argument. Returns the underlying `BTreeMap` by
/// reference to avoid copying.
pub(crate) fn dict_arg<'a>(
    args: &'a [VmValue],
    idx: usize,
    fn_name: &'static str,
    arg_name: &str,
    kind: ErrorKind,
) -> Result<&'a BTreeMap<String, VmValue>, VmError> {
    match args.get(idx) {
        Some(VmValue::Dict(dict)) => Ok(dict.as_ref()),
        Some(value) => Err(fn_err(
            fn_name,
            kind,
            format_args!("`{arg_name}` must be a dict (got {})", value.type_name()),
        )),
        None => Err(fn_err(
            fn_name,
            kind,
            format_args!("`{arg_name}` is required"),
        )),
    }
}

/// Optional positional dict argument. `None`/`Nil` → `None`.
pub(crate) fn optional_dict_arg<'a>(
    args: &'a [VmValue],
    idx: usize,
    fn_name: &'static str,
    arg_name: &str,
    kind: ErrorKind,
) -> Result<Option<&'a BTreeMap<String, VmValue>>, VmError> {
    match args.get(idx) {
        None | Some(VmValue::Nil) => Ok(None),
        Some(VmValue::Dict(dict)) => Ok(Some(dict.as_ref())),
        Some(value) => Err(fn_err(
            fn_name,
            kind,
            format_args!(
                "`{arg_name}` must be a dict or nil (got {})",
                value.type_name()
            ),
        )),
    }
}

/// Require a positional string argument. The string is trimmed and an empty
/// result is rejected, matching the pre-existing helpers across the agent
/// modules.
pub(crate) fn required_string_arg(
    args: &[VmValue],
    idx: usize,
    fn_name: &'static str,
    arg_name: &str,
    kind: ErrorKind,
) -> Result<String, VmError> {
    match args.get(idx) {
        Some(VmValue::String(text)) if !text.trim().is_empty() => Ok(text.to_string()),
        _ => Err(fn_err(
            fn_name,
            kind,
            format_args!("`{arg_name}` must be a non-empty string"),
        )),
    }
}

/// Optional positional string argument. Trims whitespace; empty → `None`.
pub(crate) fn optional_string_arg(
    args: &[VmValue],
    idx: usize,
    fn_name: &'static str,
    arg_name: &str,
    kind: ErrorKind,
) -> Result<Option<String>, VmError> {
    match args.get(idx) {
        None | Some(VmValue::Nil) => Ok(None),
        Some(VmValue::String(s)) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Ok(Some(trimmed.to_string()))
            }
        }
        Some(value) => Err(fn_err(
            fn_name,
            kind,
            format_args!(
                "`{arg_name}` must be a string or nil (got {})",
                value.type_name()
            ),
        )),
    }
}

/// Require a positional int argument.
pub(crate) fn required_int_arg(
    args: &[VmValue],
    idx: usize,
    fn_name: &'static str,
    arg_name: &str,
    kind: ErrorKind,
) -> Result<i64, VmError> {
    args.get(idx)
        .and_then(VmValue::as_int)
        .ok_or_else(|| fn_err(fn_name, kind, format_args!("`{arg_name}` must be an int")))
}

/// Schema-driven parser for an option-bag dict.
///
/// Tracks which keys have been consumed; pair with [`OptionsParser::finish_strict`]
/// to reject unknown keys. For builtins that intentionally forward extras to
/// other layers (e.g. daemon spawn options piped into the agent runtime),
/// either skip the strict check or pass the forwarded keys to
/// [`OptionsParser::allow`] first.
pub(crate) struct OptionsParser<'a> {
    fn_name: &'static str,
    dict: &'a BTreeMap<String, VmValue>,
    seen: BTreeSet<&'static str>,
    kind: ErrorKind,
}

impl<'a> OptionsParser<'a> {
    pub(crate) fn new(
        fn_name: &'static str,
        dict: &'a BTreeMap<String, VmValue>,
        kind: ErrorKind,
    ) -> Self {
        Self {
            fn_name,
            dict,
            seen: BTreeSet::new(),
            kind,
        }
    }

    fn err(&self, msg: impl Display) -> VmError {
        fn_err(self.fn_name, self.kind, msg)
    }

    fn mark(&mut self, key: &'static str) {
        self.seen.insert(key);
    }

    /// Mark `key` as consumed without reading its value. Useful when the
    /// caller will reach into the raw dict separately but still wants
    /// `finish_strict` to consider the key known.
    pub(crate) fn allow(&mut self, key: &'static str) {
        self.mark(key);
    }

    /// Return the raw VmValue for `key` if present. Marks the key consumed.
    pub(crate) fn raw(&mut self, key: &'static str) -> Option<&'a VmValue> {
        self.mark(key);
        self.dict.get(key)
    }

    pub(crate) fn required_string(&mut self, key: &'static str) -> Result<String, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            Some(VmValue::String(s)) if !s.trim().is_empty() => Ok(s.to_string()),
            Some(VmValue::String(_)) => {
                Err(self.err(format_args!("`{key}` must be a non-empty string")))
            }
            None | Some(VmValue::Nil) => Err(self.err(format_args!("`{key}` is required"))),
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a string (got {})",
                value.type_name()
            ))),
        }
    }

    pub(crate) fn optional_string(&mut self, key: &'static str) -> Result<Option<String>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(VmValue::String(s)) => {
                let trimmed = s.trim();
                if trimmed.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(trimmed.to_string()))
                }
            }
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a string or nil (got {})",
                value.type_name()
            ))),
        }
    }

    /// Optional string field that preserves the value exactly. Use this for
    /// fields where leading/trailing whitespace is part of the public contract.
    pub(crate) fn optional_string_raw(
        &mut self,
        key: &'static str,
    ) -> Result<Option<String>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(VmValue::String(s)) => Ok(Some(s.to_string())),
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a string or nil (got {})",
                value.type_name()
            ))),
        }
    }

    pub(crate) fn optional_bool(&mut self, key: &'static str) -> Result<Option<bool>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(VmValue::Bool(b)) => Ok(Some(*b)),
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a bool or nil (got {})",
                value.type_name()
            ))),
        }
    }

    pub(crate) fn bool_or(&mut self, key: &'static str, default: bool) -> Result<bool, VmError> {
        Ok(self.optional_bool(key)?.unwrap_or(default))
    }

    pub(crate) fn optional_int(&mut self, key: &'static str) -> Result<Option<i64>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(value) => match value.as_int() {
                Some(v) => Ok(Some(v)),
                None => Err(self.err(format_args!(
                    "`{key}` must be an int or nil (got {})",
                    value.type_name()
                ))),
            },
        }
    }

    pub(crate) fn optional_usize(&mut self, key: &'static str) -> Result<Option<usize>, VmError> {
        let Some(raw) = self.optional_int(key)? else {
            return Ok(None);
        };
        if raw < 0 {
            return Err(self.err(format_args!("`{key}` must be >= 0")));
        }
        Ok(Some(raw as usize))
    }

    pub(crate) fn optional_list(
        &mut self,
        key: &'static str,
    ) -> Result<Option<&'a [VmValue]>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(VmValue::List(list)) => Ok(Some(list.as_slice())),
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a list or nil (got {})",
                value.type_name()
            ))),
        }
    }

    pub(crate) fn optional_dict(
        &mut self,
        key: &'static str,
    ) -> Result<Option<&'a BTreeMap<String, VmValue>>, VmError> {
        self.mark(key);
        match self.dict.get(key) {
            None | Some(VmValue::Nil) => Ok(None),
            Some(VmValue::Dict(d)) => Ok(Some(d.as_ref())),
            Some(value) => Err(self.err(format_args!(
                "`{key}` must be a dict or nil (got {})",
                value.type_name()
            ))),
        }
    }

    /// Reject any keys not yet marked consumed (and not in `extra_known`).
    /// Use this on closed-schema option bags. For bags that forward extras,
    /// either skip this call or pre-mark them with [`OptionsParser::allow`].
    pub(crate) fn finish_strict(self, extra_known: &[&'static str]) -> Result<(), VmError> {
        let mut unknown: Vec<&str> = self
            .dict
            .keys()
            .filter(|key| !self.seen.contains(key.as_str()))
            .filter(|key| !extra_known.contains(&key.as_str()))
            .map(|s| s.as_str())
            .collect();
        if unknown.is_empty() {
            return Ok(());
        }
        unknown.sort();
        Err(fn_err(
            self.fn_name,
            self.kind,
            format!("unknown option(s): {}", unknown.join(", ")),
        ))
    }
}

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

    fn dict(pairs: &[(&str, VmValue)]) -> BTreeMap<String, VmValue> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), v.clone()))
            .collect()
    }

    #[test]
    fn parser_required_string_present() {
        let d = dict(&[("task", VmValue::String(Rc::from("do it")))]);
        let mut p = OptionsParser::new("daemon_spawn", &d, ErrorKind::Runtime);
        assert_eq!(p.required_string("task").unwrap(), "do it");
    }

    #[test]
    fn parser_required_string_missing() {
        let d = dict(&[]);
        let mut p = OptionsParser::new("daemon_spawn", &d, ErrorKind::Runtime);
        let err = p.required_string("task").unwrap_err();
        match err {
            VmError::Runtime(msg) => {
                assert!(msg.contains("daemon_spawn:"));
                assert!(msg.contains("`task`"));
            }
            other => panic!("expected Runtime error, got {other:?}"),
        }
    }

    #[test]
    fn parser_required_string_empty() {
        let d = dict(&[("task", VmValue::String(Rc::from("   ")))]);
        let mut p = OptionsParser::new("daemon_spawn", &d, ErrorKind::Runtime);
        assert!(p.required_string("task").is_err());
    }

    #[test]
    fn parser_optional_string_trims() {
        let d = dict(&[("name", VmValue::String(Rc::from("  joe  ")))]);
        let mut p = OptionsParser::new("agent", &d, ErrorKind::Runtime);
        assert_eq!(p.optional_string("name").unwrap().as_deref(), Some("joe"));
    }

    #[test]
    fn parser_optional_string_raw_preserves_whitespace() {
        let d = dict(&[("prompt", VmValue::String(Rc::from("  >  ")))]);
        let mut p = OptionsParser::new("std/io.read_line", &d, ErrorKind::Runtime);
        assert_eq!(
            p.optional_string_raw("prompt").unwrap().as_deref(),
            Some("  >  ")
        );
    }

    #[test]
    fn parser_optional_string_raw_accepts_empty_string() {
        let d = dict(&[("prompt", VmValue::String(Rc::from("")))]);
        let mut p = OptionsParser::new("std/io.read_line", &d, ErrorKind::Runtime);
        assert_eq!(
            p.optional_string_raw("prompt").unwrap().as_deref(),
            Some("")
        );
    }

    #[test]
    fn parser_optional_bool_default() {
        let d = dict(&[]);
        let mut p = OptionsParser::new("agent", &d, ErrorKind::Runtime);
        assert!(!p.bool_or("wait", false).unwrap());
        let d2 = dict(&[("wait", VmValue::Bool(true))]);
        let mut p2 = OptionsParser::new("agent", &d2, ErrorKind::Runtime);
        assert!(p2.bool_or("wait", false).unwrap());
    }

    #[test]
    fn parser_thrown_kind_wraps_in_thrown_string() {
        let d = dict(&[]);
        let mut p = OptionsParser::new("agent_session_open", &d, ErrorKind::Thrown);
        let err = p.required_string("id").unwrap_err();
        match err {
            VmError::Thrown(VmValue::String(s)) => assert!(s.contains("agent_session_open:")),
            other => panic!("expected Thrown(String), got {other:?}"),
        }
    }

    #[test]
    fn parser_finish_strict_rejects_unknown() {
        let d = dict(&[
            ("name", VmValue::String(Rc::from("a"))),
            ("typo_key", VmValue::Bool(true)),
        ]);
        let mut p = OptionsParser::new("agent", &d, ErrorKind::Runtime);
        p.optional_string("name").unwrap();
        let err = p.finish_strict(&[]).unwrap_err();
        match err {
            VmError::Runtime(msg) => assert!(msg.contains("typo_key"), "got: {msg}"),
            other => panic!("expected Runtime, got {other:?}"),
        }
    }

    #[test]
    fn parser_finish_strict_allows_extra_known() {
        let d = dict(&[("forwarded", VmValue::Bool(true))]);
        let p = OptionsParser::new("daemon_spawn", &d, ErrorKind::Runtime);
        p.finish_strict(&["forwarded"]).unwrap();
    }

    #[test]
    fn dict_arg_extracts() {
        let v = VmValue::Dict(Rc::new(dict(&[("a", VmValue::Bool(true))])));
        let args = vec![v];
        let got = dict_arg(&args, 0, "fn", "config", ErrorKind::Runtime).unwrap();
        assert_eq!(got.len(), 1);
    }

    #[test]
    fn dict_arg_rejects_non_dict() {
        let args = vec![VmValue::Int(3)];
        let err = dict_arg(&args, 0, "fn", "config", ErrorKind::Runtime).unwrap_err();
        assert!(matches!(err, VmError::Runtime(_)));
    }
}