harn-vm 0.8.95

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
//! JUnit XML parsing builtin.
//!
//! `parse_junit_xml(text_or_bytes)` returns a list of test-case dicts.
//! Accepts a `string` or `bytes` argument and is intentionally lenient:
//! malformed input yields fewer records, never an exception. JUnit XML is
//! the de facto interchange format emitted by GTest (`--gtest_output=xml`),
//! Maven Surefire / Gradle, xUnit, pytest, vitest, and cargo-nextest's
//! JUnit dialect, so a single parser covers most compiled-language runners.
//!
//! A second copy of this parser lives at
//! `crates/harn-hostlib/src/tools/test_parsers.rs`, where it serves the
//! `inspect_test_results` host capability. The two implementations are
//! deliberately independent — the format is small and stable, and consoli-
//! dating later is straightforward if drift becomes a real problem.

use std::collections::BTreeMap;
use std::time::Duration;

use crate::stdlib::macros::{harn_builtin, VmBuiltinDef};
use crate::value::{VmError, VmValue};
use crate::vm::Vm;

const MAX_DURATION_MS: u64 = i64::MAX as u64;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    Passed,
    Failed,
    Skipped,
    Errored,
}

impl Status {
    fn as_str(self) -> &'static str {
        match self {
            Status::Passed => "passed",
            Status::Failed => "failed",
            Status::Skipped => "skipped",
            Status::Errored => "errored",
        }
    }
}

#[derive(Debug, Clone)]
struct TestRecord {
    name: String,
    status: Status,
    duration_ms: u64,
    message: Option<String>,
    stdout: Option<String>,
    stderr: Option<String>,
}

impl TestRecord {
    fn new(name: impl Into<String>, status: Status) -> Self {
        Self {
            name: name.into(),
            status,
            duration_ms: 0,
            message: None,
            stdout: None,
            stderr: None,
        }
    }
}

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

pub(crate) const MODULE_BUILTINS: &[&VmBuiltinDef] = &[&PARSE_JUNIT_XML_IMPL_DEF];

#[harn_builtin(
    sig = "parse_junit_xml(input: string | bytes | nil) -> list",
    category = "junit"
)]
fn parse_junit_xml_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let bytes: Vec<u8> = match args.first() {
        Some(VmValue::String(s)) => s.as_bytes().to_vec(),
        Some(VmValue::Bytes(b)) => (**b).clone(),
        Some(VmValue::Nil) | None => Vec::new(),
        Some(other) => {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                format!(
                    "parse_junit_xml: expected string or bytes, got {}",
                    other.type_name()
                ),
            ))));
        }
    };
    let records = parse_junit_xml(&bytes);
    let list: Vec<VmValue> = records.into_iter().map(record_to_value).collect();
    Ok(VmValue::List(std::sync::Arc::new(list)))
}

fn record_to_value(record: TestRecord) -> VmValue {
    let mut map: BTreeMap<String, VmValue> = BTreeMap::new();
    map.insert(
        "name".to_string(),
        VmValue::String(std::sync::Arc::from(record.name.as_str())),
    );
    map.insert(
        "status".to_string(),
        VmValue::String(std::sync::Arc::from(record.status.as_str())),
    );
    map.insert(
        "duration_ms".to_string(),
        VmValue::Int(record.duration_ms as i64),
    );
    map.insert(
        "message".to_string(),
        record
            .message
            .map(|s| VmValue::String(std::sync::Arc::from(s)))
            .unwrap_or(VmValue::Nil),
    );
    map.insert(
        "stdout".to_string(),
        record
            .stdout
            .map(|s| VmValue::String(std::sync::Arc::from(s)))
            .unwrap_or(VmValue::Nil),
    );
    map.insert(
        "stderr".to_string(),
        record
            .stderr
            .map(|s| VmValue::String(std::sync::Arc::from(s)))
            .unwrap_or(VmValue::Nil),
    );
    VmValue::Dict(std::sync::Arc::new(map))
}

fn parse_junit_xml(bytes: &[u8]) -> Vec<TestRecord> {
    let Ok(text) = std::str::from_utf8(bytes) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    let mut cursor = 0;
    while let Some(rel_open) = text[cursor..].find("<testcase") {
        let open_start = cursor + rel_open;
        let header_end = match text[open_start..].find('>') {
            Some(idx) => open_start + idx,
            None => break,
        };
        let header = &text[open_start..header_end];
        let self_closing = header.ends_with('/');
        let name = attr(header, "name").unwrap_or_default();
        let classname = attr(header, "classname");
        let time_seconds = attr(header, "time")
            .and_then(|s| s.parse::<f64>().ok())
            .unwrap_or(0.0);

        let qualified = match (&classname, name.is_empty()) {
            (Some(cls), false) if !cls.is_empty() => format!("{cls}::{name}"),
            (_, _) => name.clone(),
        };

        let mut record = TestRecord::new(qualified, Status::Passed);
        record.duration_ms = duration_seconds_to_ms(time_seconds);

        if !self_closing {
            let close_idx = match text[header_end..].find("</testcase>") {
                Some(idx) => header_end + idx,
                None => break,
            };
            let body = &text[header_end + 1..close_idx];
            apply_body(&mut record, body);
            cursor = close_idx + "</testcase>".len();
        } else {
            cursor = header_end + 1;
        }

        out.push(record);
    }
    out
}

fn apply_body(record: &mut TestRecord, body: &str) {
    if let Some((message, body_text)) = first_child_with_message(body, "failure") {
        record.status = Status::Failed;
        record.message = Some(combined_message(message, body_text));
    } else if let Some((message, body_text)) = first_child_with_message(body, "error") {
        record.status = Status::Errored;
        record.message = Some(combined_message(message, body_text));
    } else if body.contains("<skipped") {
        record.status = Status::Skipped;
    }

    if let Some(text) = first_child_text(body, "system-out") {
        record.stdout = Some(text);
    }
    if let Some(text) = first_child_text(body, "system-err") {
        record.stderr = Some(text);
    }
}

fn first_child_with_message(body: &str, tag: &str) -> Option<(Option<String>, String)> {
    let open = format!("<{tag}");
    let close_open = format!("</{tag}>");
    let pos = body.find(open.as_str())?;
    let header_end = body[pos..].find('>').map(|i| pos + i)?;
    let header = &body[pos..header_end];
    let message = attr(header, "message");
    let self_closing = header.ends_with('/');
    let body_text = if self_closing {
        String::new()
    } else {
        let close_pos = body[header_end..]
            .find(&close_open)
            .map(|i| header_end + i)?;
        unescape_xml(body[header_end + 1..close_pos].trim())
    };
    Some((message, body_text))
}

fn first_child_text(body: &str, tag: &str) -> Option<String> {
    let open = format!("<{tag}");
    let close = format!("</{tag}>");
    let pos = body.find(open.as_str())?;
    let header_end = body[pos..].find('>').map(|i| pos + i)?;
    let close_pos = body[header_end..].find(&close).map(|i| header_end + i)?;
    Some(unescape_xml(body[header_end + 1..close_pos].trim()))
}

fn combined_message(message: Option<String>, body_text: String) -> String {
    match (message, body_text.is_empty()) {
        (Some(m), true) => m,
        (Some(m), false) => format!("{m}\n{body_text}"),
        (None, _) => body_text,
    }
}

fn attr(header: &str, key: &str) -> Option<String> {
    let bytes = header.as_bytes();
    let mut idx = 0;
    while idx < bytes.len() {
        while idx < bytes.len() && bytes[idx].is_ascii_whitespace() {
            idx += 1;
        }
        if idx >= bytes.len() {
            break;
        }
        if bytes[idx] == b'<' || bytes[idx] == b'/' {
            idx += 1;
            continue;
        }
        let name_start = idx;
        while idx < bytes.len()
            && (bytes[idx].is_ascii_alphanumeric()
                || matches!(bytes[idx], b'_' | b'-' | b':' | b'.'))
        {
            idx += 1;
        }
        let name = &header[name_start..idx];
        while idx < bytes.len() && bytes[idx].is_ascii_whitespace() {
            idx += 1;
        }
        if idx >= bytes.len() || bytes[idx] != b'=' {
            if idx == name_start || idx >= bytes.len() || matches!(bytes[idx], b'>' | b'/') {
                idx += 1;
            }
            continue;
        }
        idx += 1;
        while idx < bytes.len() && bytes[idx].is_ascii_whitespace() {
            idx += 1;
        }
        if idx >= bytes.len() || !matches!(bytes[idx], b'"' | b'\'') {
            continue;
        }
        let quote = bytes[idx];
        idx += 1;
        let value_start = idx;
        while idx < bytes.len() && bytes[idx] != quote {
            idx += 1;
        }
        if idx >= bytes.len() {
            break;
        }
        if name == key {
            return Some(unescape_xml(&header[value_start..idx]));
        }
        idx += 1;
    }
    None
}

fn unescape_xml(text: &str) -> String {
    text.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

fn duration_seconds_to_ms(seconds: f64) -> u64 {
    if !seconds.is_finite() || seconds < 0.0 {
        return 0;
    }
    Duration::try_from_secs_f64(seconds)
        .map(|duration| duration.as_millis().min(u128::from(MAX_DURATION_MS)) as u64)
        .unwrap_or(MAX_DURATION_MS)
}

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

    #[test]
    fn parses_pass_fail_skip() {
        let xml = r#"<?xml version="1.0"?>
<testsuites>
  <testsuite name="suite">
    <testcase classname="C" name="passes" time="0.001"/>
    <testcase classname="C" name="fails" time="0.002">
      <failure message="boom">stack trace here</failure>
    </testcase>
    <testcase classname="C" name="skipped"><skipped/></testcase>
  </testsuite>
</testsuites>"#;
        let records = parse_junit_xml(xml.as_bytes());
        assert_eq!(records.len(), 3);
        assert_eq!(records[0].status, Status::Passed);
        assert_eq!(records[0].name, "C::passes");
        assert_eq!(records[0].duration_ms, 1);
        assert_eq!(records[1].status, Status::Failed);
        assert!(records[1].message.as_deref().unwrap().contains("boom"));
        assert!(records[1]
            .message
            .as_deref()
            .unwrap()
            .contains("stack trace"));
        assert_eq!(records[2].status, Status::Skipped);
    }

    #[test]
    fn parses_error_and_streams() {
        let xml = r#"<testsuite>
  <testcase name="errors">
    <error message="segfault">core dumped</error>
    <system-out>hello</system-out>
    <system-err>warn: x</system-err>
  </testcase>
</testsuite>"#;
        let records = parse_junit_xml(xml.as_bytes());
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].status, Status::Errored);
        assert_eq!(records[0].name, "errors");
        assert_eq!(records[0].stdout.as_deref(), Some("hello"));
        assert_eq!(records[0].stderr.as_deref(), Some("warn: x"));
    }

    #[test]
    fn unescapes_entities_in_messages() {
        let xml = r#"<testsuite>
  <testcase name="t">
    <failure message="a &amp; b">left &lt; right</failure>
  </testcase>
</testsuite>"#;
        let records = parse_junit_xml(xml.as_bytes());
        let msg = records[0].message.as_deref().unwrap();
        assert!(msg.contains("a & b"));
        assert!(msg.contains("left < right"));
    }

    #[test]
    fn malformed_xml_yields_empty() {
        let records = parse_junit_xml(b"not xml at all");
        assert!(records.is_empty());
    }

    #[test]
    fn classname_does_not_shadow_name_attribute() {
        let xml = r#"<testsuite>
  <testcase classname="pkg.Suite" name="actual" time="0"/>
</testsuite>"#;
        let records = parse_junit_xml(xml.as_bytes());
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].name, "pkg.Suite::actual");
    }

    #[test]
    fn huge_duration_saturates_instead_of_panicking() {
        let xml = r#"<testsuite>
  <testcase name="slow" time="1e308"/>
</testsuite>"#;
        let records = parse_junit_xml(xml.as_bytes());
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].duration_ms, MAX_DURATION_MS);
    }

    #[test]
    fn parses_single_quoted_and_spaced_attributes() {
        let xml = r"<testsuite>
  <testcase classname = 'pkg.Suite' name = 'actual' time = '0.003'>
    <failure message = 'a &amp; b'>left &lt; right</failure>
  </testcase>
</testsuite>";
        let records = parse_junit_xml(xml.as_bytes());
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].name, "pkg.Suite::actual");
        assert_eq!(records[0].duration_ms, 3);
        assert_eq!(records[0].status, Status::Failed);
        let message = records[0].message.as_deref().unwrap();
        assert!(message.contains("a & b"));
        assert!(message.contains("left < right"));
    }
}