harn-vm 0.10.112

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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! The argument contract shared by stdlib builtins.
//!
//! A builtin receives `&[VmValue]` and has to turn it into typed Rust values,
//! rejecting anything that does not fit. That is the same job in every
//! builtin, and before this module each family did it by hand: the stdlib
//! carried well over three hundred one-off `*_arg` / `*_option` helpers, and
//! the same mistake produced four different sentences depending on which one
//! you happened to hit —
//!
//! ```text
//! crypto:     jwt_sign: alg must be a string, got int
//! git:        git_log: path must be a non-empty string, got int
//! bytes:      bytes_slice: expected string at argument 1, got int
//! connectors: connector_call: name is required
//! ```
//!
//! Some of those helpers were not just inconsistent but wrong: several
//! "string" arguments were read with `VmValue::display()`, which stringifies a
//! dict rather than rejecting it, so a mistyped call reached the network
//! instead of the type error.
//!
//! [`Args`] is the one owner. It reads positional arguments, [`Options`]
//! reads dict option bags, and both phrase failures through [`ArgError`] using
//! the [`Expected`] vocabulary, which is built from canonical
//! [`TypeTag`]s rather than free text. The messages a Harn author sees are
//! therefore one shape, and the type names in them are the names `type_of`
//! returns.
//!
//! ```ignore
//! let args = Args::new("jwt_sign", args);
//! let algorithm = args.string(0, "alg")?;      // &str, borrowed
//! let claims = args.dict(1, "claims")?;        // &DictMap
//! let key = args.string(2, "private_key")?;
//! ```
//!
//! Accessors borrow from the argument slice instead of allocating, so the
//! success path of a builtin costs no `String` per argument.
//!
//! The vocabulary is deliberately complete: a reader exists for every shape a
//! builtin may demand, independent of which builtin families a given build
//! compiles. A feature-sliced build (`default-features = false`, as
//! `harn-lsp` and other focused embedders take it) drops the builtins behind
//! `content`, `sqlite`, and the rest, and the readers only those builtins
//! call then have no caller — the contract working as designed, not rot.
//! Gating each reader on its callers' feature families would couple this
//! module to every slice and break again on the next one, so `dead_code` is
//! silenced outside `full` instead. A `full` build still lints normally, so a
//! reader that no builtin calls in any configuration is still a hard error.
#![cfg_attr(not(feature = "full"), allow(dead_code))]

mod options;
mod tag;

#[cfg(test)]
mod drift_tests;
#[cfg(test)]
mod tests;

use std::time::Duration as StdDuration;

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

pub(crate) use options::Options;
#[cfg(test)]
pub(crate) use tag::tag_is_canonical;
pub(crate) use tag::Expected;

/// Whether an argument failure bubbles as a runtime error or as a value the
/// script can `try` / `recover`.
///
/// Most builtins use [`ErrorKind::TypeError`] for a wrong type and let it
/// bubble. Builtins whose failures are part of their normal control flow —
/// sessions, connectors, HTTP — use [`ErrorKind::Thrown`] so scripts can
/// catch them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ErrorKind {
    Runtime,
    TypeError,
    Thrown,
}

impl ErrorKind {
    pub(crate) fn err(self, message: impl Into<String>) -> VmError {
        match self {
            Self::Runtime => VmError::Runtime(message.into()),
            Self::TypeError => VmError::TypeError(message.into()),
            Self::Thrown => VmError::Thrown(VmValue::string(message.into())),
        }
    }
}

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

/// The failure sentences a builtin can produce about one argument.
///
/// Constructing errors through this type rather than `format!` at the call
/// site is what keeps the wording uniform; it is also what lets the
/// vocabulary drift test know where to look.
pub(crate) struct ArgError;

impl ArgError {
    /// `{fn}: `{name}` is required`
    pub(crate) fn required(fn_name: &str, kind: ErrorKind, name: &str) -> VmError {
        fn_err(fn_name, kind, format_args!("`{name}` is required"))
    }

    /// ``{fn}: `{name}` must be a string, got int``
    pub(crate) fn wrong_type(
        fn_name: &str,
        kind: ErrorKind,
        name: &str,
        expected: Expected,
        got: &VmValue,
    ) -> VmError {
        fn_err(
            fn_name,
            kind,
            format_args!(
                "`{name}` must be {expected}, got {}",
                crate::stdlib::args::describe(got)
            ),
        )
    }

    /// ``{fn}: `{name}` must be a string or nil, got int``
    pub(crate) fn wrong_type_optional(
        fn_name: &str,
        kind: ErrorKind,
        name: &str,
        expected: Expected,
        got: &VmValue,
    ) -> VmError {
        fn_err(
            fn_name,
            kind,
            format_args!(
                "`{name}` must be {expected} or nil, got {}",
                crate::stdlib::args::describe(got)
            ),
        )
    }

    /// ``{fn}: `{name}` must not be empty``
    pub(crate) fn empty(fn_name: &str, kind: ErrorKind, name: &str) -> VmError {
        fn_err(fn_name, kind, format_args!("`{name}` must not be empty"))
    }

    /// ``{fn}: `{name}` must be one of `a`, `b`; got `c` ``
    pub(crate) fn not_one_of(
        fn_name: &str,
        kind: ErrorKind,
        name: &str,
        allowed: &[&str],
        got: &str,
    ) -> VmError {
        let allowed = allowed
            .iter()
            .map(|value| format!("`{value}`"))
            .collect::<Vec<_>>()
            .join(", ");
        fn_err(
            fn_name,
            kind,
            format_args!("`{name}` must be one of {allowed}; got `{got}`"),
        )
    }

    /// ``{fn}: `{name}` {constraint}`` — for range and shape rules a type
    /// alone cannot express, e.g. `must be >= 0`.
    pub(crate) fn constraint(
        fn_name: &str,
        kind: ErrorKind,
        name: &str,
        constraint: impl std::fmt::Display,
    ) -> VmError {
        fn_err(fn_name, kind, format_args!("`{name}` {constraint}"))
    }
}

/// The type name to show for a value that failed a check.
///
/// This is `VmValue::type_name` for every ordinary value; it exists as a seam
/// so the "got …" half of a message can never be spelled by hand.
fn describe(value: &VmValue) -> &'static str {
    value.type_name()
}

/// Positional-argument reader for one builtin call.
///
/// Cheap to construct (two words plus a slice reference), so build one at the
/// top of a builtin and read through it rather than indexing `args` directly.
/// The builtin name and the argument slice carry separate lifetimes: the
/// name only has to live long enough to format an error, while the values
/// back every borrowed accessor result. Tying them together would force a
/// caller that takes `builtin: &str` to leak that lifetime into what it
/// returns.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Args<'name, 'a> {
    fn_name: &'name str,
    values: &'a [VmValue],
    kind: ErrorKind,
}

impl<'name, 'a> Args<'name, 'a> {
    /// A reader whose failures bubble as `VmError::TypeError`.
    pub(crate) fn new(fn_name: &'name str, values: &'a [VmValue]) -> Self {
        Self {
            fn_name,
            values,
            kind: ErrorKind::TypeError,
        }
    }

    /// A reader whose failures are catchable by `try` / `recover`.
    pub(crate) fn thrown(fn_name: &'name str, values: &'a [VmValue]) -> Self {
        Self {
            fn_name,
            values,
            kind: ErrorKind::Thrown,
        }
    }

    /// A reader whose failures bubble as `VmError::Runtime`.
    pub(crate) fn runtime(fn_name: &'name str, values: &'a [VmValue]) -> Self {
        Self {
            fn_name,
            values,
            kind: ErrorKind::Runtime,
        }
    }

    /// An [`Options`] reader over a bag already in hand, for the parsers
    /// that receive `Option<&DictMap>` rather than the raw argument slice.
    pub(crate) fn runtime_options(
        fn_name: &'name str,
        dict: Option<&'a DictMap>,
    ) -> Options<'name, 'a> {
        Options::new(fn_name, ErrorKind::Runtime, dict)
    }

    /// Read one value already in hand as if it were argument 0.
    ///
    /// Some builtins pull a value out of a dict or an event before checking
    /// it. They get the same vocabulary as a positional read rather than a
    /// parallel set of value-level helpers. `None` reads as a missing
    /// argument, so a caller holding an `Option` does not need its own
    /// guard clause before every check.
    pub(crate) fn single(fn_name: &'name str, kind: ErrorKind, value: Option<&'a VmValue>) -> Self {
        Self {
            fn_name,
            values: value.map_or(&[], std::slice::from_ref),
            kind,
        }
    }

    pub(crate) fn fn_name(&self) -> &'name str {
        self.fn_name
    }

    pub(crate) fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Build an error in this reader's kind, prefixed with the builtin name.
    pub(crate) fn err(&self, message: impl std::fmt::Display) -> VmError {
        fn_err(self.fn_name, self.kind, message)
    }

    /// The raw value at `index`, treating `Nil` as absent.
    pub(crate) fn get(&self, index: usize) -> Option<&'a VmValue> {
        match self.values.get(index) {
            None | Some(VmValue::Nil) => None,
            Some(value) => Some(value),
        }
    }

    /// The raw value at `index`, distinguishing an explicit `Nil` from a
    /// missing argument. Only needed by builtins where `nil` means something.
    pub(crate) fn raw(&self, index: usize) -> Option<&'a VmValue> {
        self.values.get(index)
    }

    /// Reject a call outside `min..=max` arguments before reading anything.
    pub(crate) fn arity(&self, min: usize, max: usize) -> Result<(), VmError> {
        let count = self.values.len();
        if count >= min && count <= max {
            return Ok(());
        }
        let expected = if min == max {
            format!("{min}")
        } else {
            format!("{min}-{max}")
        };
        Err(self.err(format_args!("expected {expected} argument(s), got {count}")))
    }

    /// Reject a call with fewer than `min` arguments, for builtins that take
    /// a variable number.
    pub(crate) fn min_arity(&self, min: usize) -> Result<(), VmError> {
        let count = self.values.len();
        if count >= min {
            return Ok(());
        }
        Err(self.err(format_args!(
            "expected at least {min} argument(s), got {count}"
        )))
    }

    fn required_at(&self, index: usize, name: &str) -> Result<&'a VmValue, VmError> {
        self.get(index)
            .ok_or_else(|| ArgError::required(self.fn_name, self.kind, name))
    }

    fn wrong(&self, name: &str, expected: Expected, got: &VmValue) -> VmError {
        ArgError::wrong_type(self.fn_name, self.kind, name, expected, got)
    }

    fn wrong_optional(&self, name: &str, expected: Expected, got: &VmValue) -> VmError {
        ArgError::wrong_type_optional(self.fn_name, self.kind, name, expected, got)
    }

    // ---- strings ----------------------------------------------------------

    /// A required string, borrowed. Empty strings are allowed; use
    /// [`Args::non_empty_string`] when they are not.
    pub(crate) fn string(&self, index: usize, name: &str) -> Result<&'a str, VmError> {
        match self.required_at(index, name)? {
            VmValue::String(text) => Ok(text.as_str()),
            other => Err(self.wrong(name, Expected::STRING, other)),
        }
    }

    /// A required string that must have non-whitespace content. The returned
    /// slice is trimmed.
    pub(crate) fn non_empty_string(&self, index: usize, name: &str) -> Result<&'a str, VmError> {
        let text = self.string(index, name)?.trim();
        if text.is_empty() {
            return Err(ArgError::empty(self.fn_name, self.kind, name));
        }
        Ok(text)
    }

    /// An optional string. Missing and `nil` both read as `None`.
    pub(crate) fn opt_string(&self, index: usize, name: &str) -> Result<Option<&'a str>, VmError> {
        match self.get(index) {
            None => Ok(None),
            Some(VmValue::String(text)) => Ok(Some(text.as_str())),
            Some(other) => Err(self.wrong_optional(name, Expected::STRING, other)),
        }
    }

    // ---- numbers ----------------------------------------------------------

    /// A required int. Floats are rejected; use [`Args::number`] where a
    /// float is genuinely acceptable.
    pub(crate) fn int(&self, index: usize, name: &str) -> Result<i64, VmError> {
        match self.required_at(index, name)? {
            VmValue::Int(value) => Ok(*value),
            other => Err(self.wrong(name, Expected::INT, other)),
        }
    }

    pub(crate) fn opt_int(&self, index: usize, name: &str) -> Result<Option<i64>, VmError> {
        match self.get(index) {
            None => Ok(None),
            Some(VmValue::Int(value)) => Ok(Some(*value)),
            Some(other) => Err(self.wrong_optional(name, Expected::INT, other)),
        }
    }

    // ---- bools ------------------------------------------------------------

    /// A required int, also accepting a float that has no fractional part.
    ///
    /// JSON has one number type, so a dict that came from `json_parse` or an
    /// LLM response carries `3` as `Float(3.0)`. Builtins that read such
    /// dicts use this; builtins whose argument is written directly in Harn
    /// source use [`Args::int`], which rejects `3.0` and says so.
    pub(crate) fn whole_int(&self, index: usize, name: &str) -> Result<i64, VmError> {
        match self.required_at(index, name)? {
            VmValue::Int(value) => Ok(*value),
            VmValue::Float(value) if value.fract() == 0.0 => Ok(*value as i64),
            other => Err(self.wrong(name, Expected::INT_OR_FLOAT, other)),
        }
    }

    /// A required string restricted to a closed set of spellings.
    pub(crate) fn enum_string(
        &self,
        index: usize,
        name: &str,
        allowed: &[&str],
    ) -> Result<&'a str, VmError> {
        let text = self.string(index, name)?;
        if allowed.contains(&text) {
            return Ok(text);
        }
        Err(ArgError::not_one_of(
            self.fn_name,
            self.kind,
            name,
            allowed,
            text,
        ))
    }

    pub(crate) fn bool(&self, index: usize, name: &str) -> Result<bool, VmError> {
        match self.required_at(index, name)? {
            VmValue::Bool(value) => Ok(*value),
            other => Err(self.wrong(name, Expected::BOOL, other)),
        }
    }

    pub(crate) fn opt_bool(&self, index: usize, name: &str) -> Result<Option<bool>, VmError> {
        match self.get(index) {
            None => Ok(None),
            Some(VmValue::Bool(value)) => Ok(Some(*value)),
            Some(other) => Err(self.wrong_optional(name, Expected::BOOL, other)),
        }
    }

    pub(crate) fn bool_or(&self, index: usize, name: &str, default: bool) -> Result<bool, VmError> {
        Ok(self.opt_bool(index, name)?.unwrap_or(default))
    }

    pub(crate) fn float(&self, index: usize, name: &str) -> Result<f64, VmError> {
        match self.required_at(index, name)? {
            VmValue::Float(value) => Ok(*value),
            other => Err(self.wrong(name, Expected::FLOAT, other)),
        }
    }

    // ---- containers -------------------------------------------------------

    pub(crate) fn dict(&self, index: usize, name: &str) -> Result<&'a DictMap, VmError> {
        match self.required_at(index, name)? {
            VmValue::Dict(dict) => Ok(dict.as_ref()),
            other => Err(self.wrong(name, Expected::DICT, other)),
        }
    }

    pub(crate) fn opt_dict(
        &self,
        index: usize,
        name: &str,
    ) -> Result<Option<&'a DictMap>, VmError> {
        match self.get(index) {
            None => Ok(None),
            Some(VmValue::Dict(dict)) => Ok(Some(dict.as_ref())),
            Some(other) => Err(self.wrong_optional(name, Expected::DICT, other)),
        }
    }

    pub(crate) fn list(&self, index: usize, name: &str) -> Result<&'a [VmValue], VmError> {
        match self.required_at(index, name)? {
            VmValue::List(list) => Ok(list.as_slice()),
            other => Err(self.wrong(name, Expected::LIST, other)),
        }
    }

    /// A required list as the shared handle rather than a slice, for callers
    /// that pass the list along without copying it.
    pub(crate) fn list_shared(
        &self,
        index: usize,
        name: &str,
    ) -> Result<&'a std::sync::Arc<Vec<VmValue>>, VmError> {
        match self.required_at(index, name)? {
            VmValue::List(list) => Ok(list),
            other => Err(self.wrong(name, Expected::LIST, other)),
        }
    }

    pub(crate) fn opt_list(
        &self,
        index: usize,
        name: &str,
    ) -> Result<Option<&'a [VmValue]>, VmError> {
        match self.get(index) {
            None => Ok(None),
            Some(VmValue::List(list)) => Ok(Some(list.as_slice())),
            Some(other) => Err(self.wrong_optional(name, Expected::LIST, other)),
        }
    }

    /// A required list whose every element is a string.
    ///
    /// The element type is checked here rather than by the caller, so a
    /// `["a", 3]` argument fails at the boundary with the element's own type
    /// named instead of silently stringifying.
    pub(crate) fn string_list(&self, index: usize, name: &str) -> Result<Vec<&'a str>, VmError> {
        self.collect_string_list(self.list(index, name)?, name)
    }

    pub(crate) fn opt_string_list(
        &self,
        index: usize,
        name: &str,
    ) -> Result<Option<Vec<&'a str>>, VmError> {
        let Some(list) = self.opt_list(index, name)? else {
            return Ok(None);
        };
        self.collect_string_list(list, name).map(Some)
    }

    fn collect_string_list(
        &self,
        list: &'a [VmValue],
        name: &str,
    ) -> Result<Vec<&'a str>, VmError> {
        list.iter()
            .map(|value| match value {
                VmValue::String(text) => Ok(text.as_str()),
                other => Err(self.wrong(name, Expected::STRING_LIST, other)),
            })
            .collect()
    }

    // ---- bytes ------------------------------------------------------------

    pub(crate) fn bytes(&self, index: usize, name: &str) -> Result<&'a [u8], VmError> {
        match self.required_at(index, name)? {
            VmValue::Bytes(bytes) => Ok(bytes.as_slice()),
            other => Err(self.wrong(name, Expected::BYTES, other)),
        }
    }

    /// Bytes, or a string taken as its UTF-8 bytes.
    pub(crate) fn bytes_or_string(&self, index: usize, name: &str) -> Result<&'a [u8], VmError> {
        match self.required_at(index, name)? {
            VmValue::Bytes(bytes) => Ok(bytes.as_slice()),
            VmValue::String(text) => Ok(text.as_bytes()),
            other => Err(self.wrong(name, Expected::BYTES_OR_STRING, other)),
        }
    }

    // ---- closures ---------------------------------------------------------

    pub(crate) fn closure(&self, index: usize, name: &str) -> Result<&'a VmClosure, VmError> {
        match self.required_at(index, name)? {
            VmValue::Closure(closure) => Ok(closure.as_ref()),
            other => Err(self.wrong(name, Expected::CLOSURE, other)),
        }
    }

    // ---- durations --------------------------------------------------------

    /// A non-negative millisecond count, from a `duration`, an int, or a
    /// finite float.
    ///
    /// Waitpoints, monitors, HITL, and the storage connectors all accept this
    /// trio; keeping the edge cases (negative, infinite, out-of-range float)
    /// in one place is why they agree.
    pub(crate) fn millis(&self, index: usize, name: &str) -> Result<u64, VmError> {
        let value = self.required_at(index, name)?;
        self.millis_from(value, name)
    }

    pub(crate) fn duration(&self, index: usize, name: &str) -> Result<StdDuration, VmError> {
        self.millis(index, name).map(StdDuration::from_millis)
    }

    fn millis_from(&self, value: &VmValue, name: &str) -> Result<u64, VmError> {
        match value {
            VmValue::Duration(millis) | VmValue::Int(millis) if *millis >= 0 => Ok(*millis as u64),
            VmValue::Duration(_) | VmValue::Int(_) => Err(ArgError::constraint(
                self.fn_name,
                self.kind,
                name,
                "must be >= 0",
            )),
            VmValue::Float(millis)
                if millis.is_finite() && *millis >= 0.0 && *millis <= u64::MAX as f64 =>
            {
                Ok(*millis as u64)
            }
            VmValue::Float(_) => Err(ArgError::constraint(
                self.fn_name,
                self.kind,
                name,
                "must be a finite millisecond count >= 0",
            )),
            other => Err(self.wrong(name, Expected::DURATION_OR_INT, other)),
        }
    }

    // ---- json -------------------------------------------------------------

    /// A dict argument, converted to a JSON object. Missing or `nil` yields
    /// an empty object, which is what the observability and timing builtins
    /// want from an absent attribute bag.
    pub(crate) fn json_object(
        &self,
        index: usize,
        name: &str,
    ) -> Result<serde_json::Map<String, serde_json::Value>, VmError> {
        let Some(value) = self.get(index) else {
            return Ok(serde_json::Map::new());
        };
        match value {
            VmValue::Dict(_) => match crate::llm::helpers::vm_value_to_json(value) {
                serde_json::Value::Object(map) => Ok(map),
                other => unreachable!("a dict converts to a JSON object, got {other:?}"),
            },
            other => Err(self.wrong_optional(name, Expected::DICT, other)),
        }
    }

    // ---- option bags ------------------------------------------------------

    /// Read a trailing option-bag argument. A missing or `nil` argument
    /// yields an empty bag, so callers need no separate absent case.
    pub(crate) fn options(&self, index: usize, name: &str) -> Result<Options<'name, 'a>, VmError> {
        Ok(Options::new(
            self.fn_name,
            self.kind,
            self.opt_dict(index, name)?,
        ))
    }
}