harn-vm 0.10.42

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
//! AST surface that `harn-lint` consumes to enforce `.harn.prompt`
//! drift-prevention rules (#1669).
//!
//! The template parser and AST are otherwise internal — exposing a
//! shallow read-only view through this module keeps the lint crate
//! free of template-engine internals while still giving rules enough
//! structure to walk conditionals, sections, and includes.

use super::ast::{BinOp, Expr, Node, PathSeg};
use super::error::TemplateParseError;
use super::parser::parse as parse_template;
use crate::runtime_limits::RuntimeLimits;

const TEMPLATE_LINT_AST_MAX_DEPTH: usize = RuntimeLimits::DEFAULT.max_template_ast_depth;

/// Parse a template source string into a flat list of lintable
/// constructs (conditionals + sections). Returns `Err` when the
/// template doesn't parse — callers should surface that failure to the
/// user before linting.
pub fn parse(src: &str) -> Result<Vec<LintConstruct>, TemplateParseError> {
    let nodes = parse_template(src).map_err(TemplateParseError::from)?;
    let mut out = Vec::new();
    walk_nodes(&nodes, &mut out, 0)?;
    out.extend(filter_uses(src)?);
    Ok(out)
}

/// One lintable construct. Rules use these to reason about counts
/// (e.g. branch explosion) and individual call sites (e.g. provider-identity
/// comparisons and filter names).
#[derive(Debug, Clone)]
pub enum LintConstruct {
    /// An `{{ if .. }}` / `{{ elif }}` chain. One entry per condition
    /// in the chain (the trailing `{{ else }}` is implicit and not
    /// listed). Conditions are flattened across `elif` to make
    /// branch-count rules straightforward.
    IfChain { branches: Vec<IfBranch> },
    /// A `{{ section "..." }}` block. Sections are themselves
    /// capability-adaptive but never look identity-driven; rules use
    /// this to count capability-aware partials.
    Section {
        name: String,
        line: usize,
        col: usize,
    },
    /// A filter named after `|`, with the exact byte range of its name.
    ///
    /// The parser has already accepted the surrounding expression. This
    /// shallow view lets lint and editor diagnostics validate the name
    /// against the engine's filter registry without exposing the template AST.
    Filter {
        name: String,
        start: usize,
        end: usize,
    },
}

#[derive(Debug, Clone)]
pub struct IfBranch {
    pub line: usize,
    pub col: usize,
    pub condition: ConditionShape,
}

/// Coarse classification of an `{{ if expr }}` condition. The lint
/// rules don't need to evaluate or fully reconstruct expressions —
/// just enough structure to detect the two failure patterns called
/// out in #1669:
///
/// - Identity comparisons (`llm.provider == "..."`).
/// - Capability-flag branches (`llm.capabilities.<flag>`), which the
///   variant-explosion rule counts.
///
/// Conditions outside these shapes resolve to `Other` and don't
/// participate in either rule.
#[derive(Debug, Clone)]
pub enum ConditionShape {
    /// `llm.provider == "..."` / `llm.model == "..."` /
    /// `llm.family == "..."` (or `!=`).
    ProviderIdentity(IdentityField),
    /// Any path-based condition mentioning `llm.capabilities.<flag>`
    /// (including negation and use as a comparison operand). The
    /// variant-explosion rule counts every branch with this shape.
    /// Source position lives on the surrounding [`IfBranch`].
    CapabilityFlag {
        flag: String,
    },
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentityField {
    Provider,
    Model,
    Family,
}

impl IdentityField {
    pub fn as_str(self) -> &'static str {
        match self {
            IdentityField::Provider => "provider",
            IdentityField::Model => "model",
            IdentityField::Family => "family",
        }
    }
}

fn walk_nodes(
    nodes: &[Node],
    out: &mut Vec<LintConstruct>,
    depth: usize,
) -> Result<(), TemplateParseError> {
    for node in nodes {
        walk_node(node, out, depth)?;
    }
    Ok(())
}

fn walk_node(
    node: &Node,
    out: &mut Vec<LintConstruct>,
    depth: usize,
) -> Result<(), TemplateParseError> {
    if depth > TEMPLATE_LINT_AST_MAX_DEPTH {
        return Err(lint_depth_error(node));
    }

    match node {
        Node::Text(_) | Node::Expr { .. } | Node::LegacyBareInterp { .. } => {}
        Node::If {
            branches,
            else_branch,
            line: _,
            col: _,
        } => {
            let mut summary = Vec::with_capacity(branches.len());
            for branch in branches {
                summary.push(IfBranch {
                    line: branch.line,
                    col: branch.col,
                    condition: classify_condition(&branch.cond),
                });
                walk_nodes(&branch.body, out, depth + 1)?;
            }
            out.push(LintConstruct::IfChain { branches: summary });
            if let Some(else_body) = else_branch {
                walk_nodes(else_body, out, depth + 1)?;
            }
        }
        Node::For { body, empty, .. } => {
            walk_nodes(body, out, depth + 1)?;
            if let Some(empty) = empty {
                walk_nodes(empty, out, depth + 1)?;
            }
        }
        Node::Include { .. } => {
            // Include resolution happens at render time. Linting only
            // walks the calling template; the included partial gets
            // linted independently when the linter encounters it.
        }
        Node::Section {
            name,
            body,
            line,
            col,
            ..
        } => {
            out.push(LintConstruct::Section {
                name: name.clone(),
                line: *line,
                col: *col,
            });
            walk_nodes(body, out, depth + 1)?;
        }
    }
    Ok(())
}

fn filter_uses(src: &str) -> Result<Vec<LintConstruct>, TemplateParseError> {
    let tokens = super::lexer::tokenize(src).map_err(TemplateParseError::from)?;
    let mut filters = Vec::new();
    for token in tokens {
        let super::lexer::Token::Directive { start, end, .. } = token else {
            continue;
        };
        scan_directive_filters(src, start, end, &mut filters);
    }
    Ok(filters)
}

fn scan_directive_filters(src: &str, start: usize, end: usize, filters: &mut Vec<LintConstruct>) {
    let bytes = src.as_bytes();
    let mut quote = None;
    let mut cursor = start;
    while cursor < end {
        let byte = bytes[cursor];
        if let Some(delimiter) = quote {
            if byte == b'\\' {
                cursor = (cursor + 2).min(end);
                continue;
            }
            if byte == delimiter {
                quote = None;
            }
            cursor += 1;
            continue;
        }
        if matches!(byte, b'"' | b'\'') {
            quote = Some(byte);
            cursor += 1;
            continue;
        }
        if byte != b'|' {
            cursor += 1;
            continue;
        }
        if bytes.get(cursor + 1) == Some(&b'|') {
            cursor += 2;
            continue;
        }

        cursor += 1;
        while cursor < end && bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }
        let name_start = cursor;
        while cursor < end && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'_') {
            cursor += 1;
        }
        if cursor > name_start {
            filters.push(LintConstruct::Filter {
                name: src[name_start..cursor].to_string(),
                start: name_start,
                end: cursor,
            });
        }
    }
}

fn lint_depth_error(node: &Node) -> TemplateParseError {
    let (line, col) = node_location(node).unwrap_or((1, 1));
    TemplateParseError {
        message: format!("template lint AST depth exceeded ({TEMPLATE_LINT_AST_MAX_DEPTH} levels)"),
        line,
        col,
    }
}

fn node_location(node: &Node) -> Option<(usize, usize)> {
    match node {
        Node::Expr { line, col, .. }
        | Node::If { line, col, .. }
        | Node::For { line, col, .. }
        | Node::Include { line, col, .. }
        | Node::Section { line, col, .. } => Some((*line, *col)),
        Node::Text(_) | Node::LegacyBareInterp { .. } => None,
    }
}

/// Classify the top-level shape of an `{{ if expr }}` condition.
fn classify_condition(expr: &Expr) -> ConditionShape {
    if let Some(identity) = match_identity_compare(expr) {
        return ConditionShape::ProviderIdentity(identity);
    }
    if let Some(capability) = match_capability_path(expr) {
        return capability;
    }
    ConditionShape::Other
}

/// Match `llm.<provider|model|family> == "..."` or `!= "..."`,
/// returning the LHS identity field that was compared.
fn match_identity_compare(expr: &Expr) -> Option<IdentityField> {
    let Expr::Binary(op, lhs, rhs) = expr else {
        return None;
    };
    if !matches!(op, BinOp::Eq | BinOp::Neq) {
        return None;
    }
    let path = match (lhs.as_ref(), rhs.as_ref()) {
        (Expr::Path(p), Expr::Str(_)) | (Expr::Str(_), Expr::Path(p)) => p,
        _ => return None,
    };
    if !path_starts_with_llm(path) {
        return None;
    }
    match path.get(1) {
        Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "provider" => {
            Some(IdentityField::Provider)
        }
        Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "model" => {
            Some(IdentityField::Model)
        }
        Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "family" => {
            Some(IdentityField::Family)
        }
        _ => None,
    }
}

/// Match `llm.capabilities.<flag>` (possibly negated by `!`) or
/// `llm.capabilities.<flag> == <literal>`, returning the flag name.
fn match_capability_path(expr: &Expr) -> Option<ConditionShape> {
    fn find_capability_path(expr: &Expr) -> Option<String> {
        let mut stack = vec![expr];
        while let Some(expr) = stack.pop() {
            match expr {
                Expr::Path(path) => {
                    if let Some(flag) = capability_flag_from_path(path) {
                        return Some(flag);
                    }
                }
                Expr::Unary(_, inner) => stack.push(inner),
                Expr::Binary(_, lhs, rhs) => {
                    stack.push(rhs);
                    stack.push(lhs);
                }
                Expr::Filter(inner, _, _) => stack.push(inner),
                _ => {}
            }
        }
        None
    }
    let flag = find_capability_path(expr)?;
    Some(ConditionShape::CapabilityFlag { flag })
}

fn capability_flag_from_path(path: &[PathSeg]) -> Option<String> {
    if !path_starts_with_llm(path) {
        return None;
    }
    let Some(PathSeg::Field(name) | PathSeg::Key(name)) = path.get(1) else {
        return None;
    };
    if name != "capabilities" {
        return None;
    }
    let Some(PathSeg::Field(flag) | PathSeg::Key(flag)) = path.get(2) else {
        return None;
    };
    Some(flag.clone())
}

fn path_starts_with_llm(path: &[PathSeg]) -> bool {
    matches!(
        path.first(),
        Some(PathSeg::Field(name)) if name == "llm",
    )
}

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

    fn parse_ok(src: &str) -> Vec<LintConstruct> {
        parse(src).expect("template should parse")
    }

    fn filters(src: &str) -> Vec<(String, usize, usize)> {
        parse_ok(src)
            .into_iter()
            .filter_map(|construct| match construct {
                LintConstruct::Filter { name, start, end } => Some((name, start, end)),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn filter_uses_carry_exact_name_ranges() {
        let source = "{{ name | uppr | default: \"| not_a_filter\" }}";
        let found = filters(source);
        assert_eq!(
            found
                .iter()
                .map(|(name, _, _)| name.as_str())
                .collect::<Vec<_>>(),
            ["uppr", "default"]
        );
        for (name, start, end) in found {
            assert_eq!(&source[start..end], name);
        }
    }

    #[test]
    fn logical_or_comments_and_raw_text_are_not_filters() {
        let source = concat!(
            "{{ if a || b }}x{{ end }}\n",
            "{{# ignored | nope #}}\n",
            "{{ raw }}{{ value | nope }}{{ endraw }}\n",
        );
        assert!(filters(source).is_empty());
    }

    fn first_if(constructs: &[LintConstruct]) -> &[IfBranch] {
        match constructs
            .iter()
            .find(|c| matches!(c, LintConstruct::IfChain { .. }))
            .expect("if chain present")
        {
            LintConstruct::IfChain { branches } => branches.as_slice(),
            _ => unreachable!(),
        }
    }

    #[test]
    fn provider_identity_eq_detected() {
        let constructs = parse_ok("{{ if llm.provider == \"anthropic\" }}x{{ else }}y{{ end }}");
        let branches = first_if(&constructs);
        assert_eq!(branches.len(), 1);
        assert!(matches!(
            branches[0].condition,
            ConditionShape::ProviderIdentity(IdentityField::Provider)
        ));
    }

    #[test]
    fn model_identity_neq_detected() {
        let constructs = parse_ok("{{ if llm.model != \"gpt-5\" }}x{{ end }}");
        let branches = first_if(&constructs);
        assert!(matches!(
            branches[0].condition,
            ConditionShape::ProviderIdentity(IdentityField::Model)
        ));
    }

    #[test]
    fn capability_flag_detected_in_negation_and_filter() {
        let constructs = parse_ok(
            "{{ if !llm.capabilities.native_tools }}x{{ end }}\
             {{ if llm.capabilities.prefers_xml_scaffolding | default: false }}y{{ end }}",
        );
        let if_chains: Vec<_> = constructs
            .iter()
            .filter_map(|c| match c {
                LintConstruct::IfChain { branches } => Some(branches.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(if_chains.len(), 2);
        assert!(matches!(
            if_chains[0][0].condition,
            ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
        ));
        assert!(matches!(
            if_chains[1][0].condition,
            ConditionShape::CapabilityFlag { ref flag, .. } if flag == "prefers_xml_scaffolding"
        ));
    }

    #[test]
    fn capability_flag_detection_handles_wide_binary_expression() {
        let mut terms = (0..300).map(|idx| format!("flag{idx}")).collect::<Vec<_>>();
        terms.push("llm.capabilities.native_tools".to_string());
        let src = format!("{{{{ if {} }}}}x{{{{ end }}}}", terms.join(" or "));

        let constructs = parse_ok(&src);
        let branches = first_if(&constructs);

        assert!(matches!(
            branches[0].condition,
            ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
        ));
    }

    #[test]
    fn parse_reports_template_control_depth_limit() {
        let depth = RuntimeLimits::DEFAULT.max_template_ast_depth + 1;
        let mut src = String::new();
        for _ in 0..depth {
            src.push_str("{{ if true }}");
        }
        src.push('x');
        for _ in 0..depth {
            src.push_str("{{ end }}");
        }

        let err = parse(&src).expect_err("depth limit");

        assert!(err.message.contains("template nesting depth exceeded"));
        assert!(err.message.contains(&format!(
            "({} levels)",
            RuntimeLimits::DEFAULT.max_template_ast_depth
        )));
    }

    #[test]
    fn parse_reports_template_expression_depth_limit() {
        let depth = RuntimeLimits::DEFAULT.max_template_ast_depth + 1;
        let condition = format!("{}llm.capabilities.native_tools", "!".repeat(depth));
        let src = format!("{{{{ if {condition} }}}}x{{{{ end }}}}");

        let err = parse(&src).expect_err("depth limit");

        assert!(err.message.contains("template expression depth exceeded"));
        assert!(err.message.contains(&format!(
            "({} levels)",
            RuntimeLimits::DEFAULT.max_template_ast_depth
        )));
    }

    #[test]
    fn elif_chain_lifts_per_branch_condition() {
        let constructs = parse_ok(
            "{{ if llm.provider == \"openai\" }}a\
             {{ elif llm.capabilities.native_tools }}b\
             {{ else }}c{{ end }}",
        );
        let branches = first_if(&constructs);
        assert_eq!(branches.len(), 2);
        assert!(matches!(
            branches[0].condition,
            ConditionShape::ProviderIdentity(IdentityField::Provider)
        ));
        assert!(matches!(
            branches[1].condition,
            ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
        ));
    }

    #[test]
    fn unrelated_condition_falls_through_to_other() {
        let constructs = parse_ok("{{ if score > 0.5 }}a{{ end }}");
        let branches = first_if(&constructs);
        assert!(matches!(branches[0].condition, ConditionShape::Other));
    }

    #[test]
    fn sections_listed_in_source_order() {
        let constructs = parse_ok(
            "{{ section \"task\" }}t{{ endsection }}\
             {{ section \"output_format\" }}o{{ endsection }}",
        );
        let names: Vec<_> = constructs
            .iter()
            .filter_map(|c| match c {
                LintConstruct::Section { name, .. } => Some(name.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(names, vec!["task", "output_format"]);
    }
}