zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # The guard expression grammar
//!
//! A guard is the one place a Tier-1 flow makes a decision: a step's `when`
//! decides whether the step runs, a finding's `when` decides whether it fires.
//! This module is the guard as syntax, an [`Expr`] tree and the [`parse`]
//! that builds one from the string a flow author wrote. What a parsed guard
//! means against a running flow's variables lives beside the interpreter
//! ([`super::eval`]); the split is the same one the
//! service signatures already keep.
//!
//! ## Shared verbatim with the build
//!
//! Like [`fingerprint::pattern`](crate::fingerprint) and the signature schema,
//! this module carries no dependency on the rest of the crate, only [`std`],
//! so `build.rs` can load it with `#[path]` and reject a malformed guard at
//! build time, with the exact parser the runtime uses. A guard the build
//! accepts is a guard the interpreter can read, because both read this file.
//! Nothing here reaches a network, a clock, or a variable's value: parsing is
//! pure over the text, which is what lets the build do it.
//!
//! ## The grammar
//!
//! Precedence runs `not` over `and` over `or`, with parentheses to override it.
//! A guard is ultimately a boolean; there is no bare-value truthiness, so a lone
//! variable is a parse error rather than a silent "is it non-empty".
//!
//! ```ebnf
//! expr        = or-expr ;
//! or-expr     = and-expr , { "or" , and-expr } ;
//! and-expr    = not-expr , { "and" , not-expr } ;
//! not-expr    = [ "not" ] , primary ;
//! primary     = "(" , expr , ")" | predicate | comparison ;
//! predicate   = "matched" | "bound" "(" ident ")" | "unbound" "(" ident ")" ;
//! comparison  = operand , rel-op , operand ;
//! rel-op      = "==" | "!=" | "<" | "<=" | ">" | ">=" ;
//! operand     = ident | string-literal | int-literal ;
//! ```
//!
//! There is no arithmetic, no function call, and no regex operator
//! (matching is `bind`'s job, run once and its result named): a guard that could
//! compute would be the first inch of a programming language, and the signal
//! that a detection belongs in the compute tier instead.

use std::collections::BTreeSet;
use std::fmt;

/// The deepest a guard may nest parentheses. The grammar recurses once per level,
/// and `eval` re-parses a guard on every evaluation, so an unbounded guard would
/// overflow the stack of the worker running it, which is an abort rather than a
/// catchable error. A real guard nests two or three deep; this leaves generous
/// room under the depth at which the parser's own recursion runs a thread out of
/// stack.
///
/// **Measured, since "generous" is otherwise a hope.** A guard at the deepest
/// this allows parses inside 64 KiB of stack in a release build and 384 KiB in a
/// debug one. Nothing here sets a stack size, so the thread running it has
/// tokio's 2 MiB default: about thirty times the headroom where it matters and
/// five times where the tests run. `a_guard_at_the_bound_parses_well_inside_a_
/// worker_stack` holds the release figure, at a size chosen to pass in either
/// profile.
const MAX_GUARD_DEPTH: usize = 64;

/// A parsed guard expression, the boolean a `when` clause denotes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expr {
    /// `a or b`, true if either side is.
    Or(Box<Expr>, Box<Expr>),
    /// `a and b`, true only if both are.
    And(Box<Expr>, Box<Expr>),
    /// `not a`, the negation.
    Not(Box<Expr>),
    /// `matched`, the enclosing step's combined match result. Meaningful only
    /// where a step result is in scope (a finding's guard), which the build
    /// checks; see [`super::eval`].
    Matched,
    /// `bound(x)`, true if variable `x` has a value.
    Bound(String),
    /// `unbound(x)`, true if variable `x` has none.
    Unbound(String),
    /// `a <op> b`, an equality or ordered comparison of two operands.
    Compare {
        left: Operand,
        op: RelOp,
        right: Operand,
    },
}

/// One side of a comparison: a variable to look up, or a literal to compare
/// against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operand {
    /// A bound variable's name, resolved to its value when the guard runs.
    Var(String),
    /// A string literal, written `'…'` or `"…"`.
    Text(String),
    /// An integer literal, the one operand two of which compare numerically.
    Int(i64),
}

/// The six relational operators. `==`/`!=` are total string equalities (numeric
/// only between two integer literals); `<`/`<=`/`>`/`>=` order by
/// [dotted version](crate::version) unless both sides are integers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelOp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
}

// The static-analysis helpers below are consumed by the build-time validator
// (which `#[path]`-loads this file), not by the runtime evaluator, so the plain
// `--lib` build alone sees them as unused.
#[allow(dead_code)]
impl Expr {
    /// The names of every variable this guard reads, the argument of a
    /// `bound`/`unbound`, and any variable operand of a comparison. The build
    /// uses it to prove a guard names only variables an earlier step binds.
    pub fn referenced_vars(&self) -> BTreeSet<String> {
        let mut names = BTreeSet::new();
        self.collect_vars(&mut names);
        names
    }

    fn collect_vars(&self, names: &mut BTreeSet<String>) {
        match self {
            Expr::Or(left, right) | Expr::And(left, right) => {
                left.collect_vars(names);
                right.collect_vars(names);
            }
            Expr::Not(inner) => inner.collect_vars(names),
            Expr::Matched => {}
            Expr::Bound(name) | Expr::Unbound(name) => {
                names.insert(name.clone());
            }
            Expr::Compare { left, right, .. } => {
                if let Operand::Var(name) = left {
                    names.insert(name.clone());
                }
                if let Operand::Var(name) = right {
                    names.insert(name.clone());
                }
            }
        }
    }

    /// Whether this guard reads `matched`. A step's own guard may not, nothing
    /// has matched when the step is gated, so the build rejects one that does.
    pub fn uses_matched(&self) -> bool {
        match self {
            Expr::Matched => true,
            Expr::Or(left, right) | Expr::And(left, right) => {
                left.uses_matched() || right.uses_matched()
            }
            Expr::Not(inner) => inner.uses_matched(),
            Expr::Bound(_) | Expr::Unbound(_) | Expr::Compare { .. } => false,
        }
    }
}

/// Why a guard string is not a valid expression. Its [`Display`](fmt::Display)
/// form is the message the build reports beside the offending flow file.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// The guard is empty or all whitespace.
    Empty,
    /// A character that begins no token, a stray `.`, `&`, or a lone `!`/`=`
    /// that is not part of `!=`/`==`.
    UnexpectedChar(char),
    /// A string literal opened but never closed.
    UnterminatedString,
    /// An integer literal too large for the value it must hold.
    IntOverflow(String),
    /// The parser wanted a specific thing next and did not find it.
    Expected(&'static str),
    /// A complete expression, then more tokens the grammar cannot attach.
    Trailing,
    /// The guard nests parentheses deeper than the parser's bound, which it
    /// refuses rather than recursing into a stack overflow.
    TooDeep,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::Empty => write!(f, "the guard is empty"),
            ParseError::UnexpectedChar(c) => write!(f, "unexpected character {c:?}"),
            ParseError::UnterminatedString => write!(f, "a string literal is not closed"),
            ParseError::IntOverflow(n) => write!(f, "the number {n} is too large"),
            ParseError::Expected(what) => write!(f, "expected {what}"),
            ParseError::Trailing => write!(f, "unexpected trailing input after the expression"),
            ParseError::TooDeep => {
                write!(f, "the guard nests deeper than {MAX_GUARD_DEPTH} levels")
            }
        }
    }
}

impl std::error::Error for ParseError {}

/// Parses a guard string into an [`Expr`], or reports why it is not one.
///
/// Pure over the text: it reads no variable's value and touches nothing outside
/// the string, so the build can call it to validate a guard without running the
/// flow.
pub fn parse(input: &str) -> Result<Expr, ParseError> {
    let tokens = lex(input)?;
    if tokens.is_empty() {
        return Err(ParseError::Empty);
    }
    let mut parser = Parser {
        tokens,
        pos: 0,
        depth: 0,
    };
    let expr = parser.or_expr()?;
    if parser.pos != parser.tokens.len() {
        return Err(ParseError::Trailing);
    }
    Ok(expr)
}

/// A lexical token, the parser's alphabet, one step up from characters.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Token {
    And,
    Or,
    Not,
    Matched,
    Bound,
    Unbound,
    LParen,
    RParen,
    Op(RelOp),
    Ident(String),
    Text(String),
    Int(i64),
}

/// Splits a guard string into tokens, or reports the first character that
/// begins none.
fn lex(input: &str) -> Result<Vec<Token>, ParseError> {
    let mut tokens = Vec::new();
    let chars: Vec<char> = input.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];
        match c {
            c if c.is_whitespace() => i += 1,
            '(' => {
                tokens.push(Token::LParen);
                i += 1;
            }
            ')' => {
                tokens.push(Token::RParen);
                i += 1;
            }
            '<' | '>' | '=' | '!' => {
                let two = chars.get(i + 1) == Some(&'=');
                let op = match (c, two) {
                    ('<', true) => RelOp::Le,
                    ('<', false) => RelOp::Lt,
                    ('>', true) => RelOp::Ge,
                    ('>', false) => RelOp::Gt,
                    ('=', true) => RelOp::Eq,
                    ('!', true) => RelOp::Ne,
                    // A lone `=` or `!` is not an operator this grammar has.
                    _ => return Err(ParseError::UnexpectedChar(c)),
                };
                tokens.push(Token::Op(op));
                i += if two { 2 } else { 1 };
            }
            '\'' | '"' => {
                let quote = c;
                let start = i + 1;
                let mut j = start;
                while j < chars.len() && chars[j] != quote {
                    j += 1;
                }
                if j >= chars.len() {
                    return Err(ParseError::UnterminatedString);
                }
                tokens.push(Token::Text(chars[start..j].iter().collect()));
                i = j + 1;
            }
            c if c.is_ascii_digit() => {
                let start = i;
                while i < chars.len() && chars[i].is_ascii_digit() {
                    i += 1;
                }
                let digits: String = chars[start..i].iter().collect();
                let value = digits
                    .parse()
                    .map_err(|_| ParseError::IntOverflow(digits))?;
                tokens.push(Token::Int(value));
            }
            c if c.is_ascii_alphabetic() || c == '_' => {
                let start = i;
                while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                let word: String = chars[start..i].iter().collect();
                tokens.push(keyword(word));
            }
            _ => return Err(ParseError::UnexpectedChar(c)),
        }
    }
    Ok(tokens)
}

/// A bare word is one of the grammar's keywords or, failing that, an identifier.
/// The keywords are reserved: a flow cannot bind a variable named `matched` or
/// `and`, which is why they are spelled out here rather than left ambiguous.
fn keyword(word: String) -> Token {
    match word.as_str() {
        "and" => Token::And,
        "or" => Token::Or,
        "not" => Token::Not,
        "matched" => Token::Matched,
        "bound" => Token::Bound,
        "unbound" => Token::Unbound,
        _ => Token::Ident(word),
    }
}

/// A recursive-descent parser over the token stream. One pass, no backtracking:
/// each rule consumes exactly the tokens it recognises and hands the rest on.
struct Parser {
    tokens: Vec<Token>,
    pos: usize,
    /// The parenthesis-nesting depth of the expression currently being parsed,
    /// bounded by [`MAX_GUARD_DEPTH`] so the recursion cannot overflow the stack.
    depth: usize,
}

impl Parser {
    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<Token> {
        let token = self.tokens.get(self.pos).cloned();
        if token.is_some() {
            self.pos += 1;
        }
        token
    }

    /// Consumes the next token if it equals `expected`, else reports `what`.
    fn eat(&mut self, expected: &Token, what: &'static str) -> Result<(), ParseError> {
        if self.peek() == Some(expected) {
            self.pos += 1;
            Ok(())
        } else {
            Err(ParseError::Expected(what))
        }
    }

    /// `or-expr = and-expr , { "or" , and-expr }`, the loosest binding.
    ///
    /// Every nesting cycle passes through here, since a parenthesised primary
    /// re-enters it, so the parenthesis-depth guard lives here. It counts nesting
    /// rather than total work, so a flat guard with many `or` clauses is fine and
    /// only genuine parenthesis nesting is bounded.
    fn or_expr(&mut self) -> Result<Expr, ParseError> {
        self.depth += 1;
        if self.depth > MAX_GUARD_DEPTH {
            return Err(ParseError::TooDeep);
        }
        let mut left = self.and_expr()?;
        while self.peek() == Some(&Token::Or) {
            self.pos += 1;
            let right = self.and_expr()?;
            left = Expr::Or(Box::new(left), Box::new(right));
        }
        self.depth -= 1;
        Ok(left)
    }

    /// `and-expr = not-expr , { "and" , not-expr }`.
    fn and_expr(&mut self) -> Result<Expr, ParseError> {
        let mut left = self.not_expr()?;
        while self.peek() == Some(&Token::And) {
            self.pos += 1;
            let right = self.not_expr()?;
            left = Expr::And(Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    /// `not-expr = [ "not" ] , primary`, one optional negation, binding tighter
    /// than `and`, so `not a and b` is `(not a) and b`.
    fn not_expr(&mut self) -> Result<Expr, ParseError> {
        if self.peek() == Some(&Token::Not) {
            self.pos += 1;
            Ok(Expr::Not(Box::new(self.primary()?)))
        } else {
            self.primary()
        }
    }

    /// `primary = "(" , expr , ")" | predicate | comparison`.
    fn primary(&mut self) -> Result<Expr, ParseError> {
        match self.peek() {
            Some(Token::LParen) => {
                self.pos += 1;
                let inner = self.or_expr()?;
                self.eat(&Token::RParen, "a closing ')'")?;
                Ok(inner)
            }
            Some(Token::Matched) => {
                self.pos += 1;
                Ok(Expr::Matched)
            }
            Some(Token::Bound) => {
                self.pos += 1;
                Ok(Expr::Bound(self.predicate_arg()?))
            }
            Some(Token::Unbound) => {
                self.pos += 1;
                Ok(Expr::Unbound(self.predicate_arg()?))
            }
            _ => self.comparison(),
        }
    }

    /// The `( ident )` a `bound`/`unbound` predicate wraps.
    fn predicate_arg(&mut self) -> Result<String, ParseError> {
        self.eat(&Token::LParen, "'(' after the predicate")?;
        let name = match self.advance() {
            Some(Token::Ident(name)) => name,
            _ => return Err(ParseError::Expected("a variable name")),
        };
        self.eat(&Token::RParen, "a closing ')'")?;
        Ok(name)
    }

    /// `comparison = operand , rel-op , operand`.
    fn comparison(&mut self) -> Result<Expr, ParseError> {
        let left = self.operand()?;
        let op = match self.advance() {
            Some(Token::Op(op)) => op,
            _ => return Err(ParseError::Expected("a comparison operator")),
        };
        let right = self.operand()?;
        Ok(Expr::Compare { left, op, right })
    }

    /// `operand = ident | string-literal | int-literal`.
    fn operand(&mut self) -> Result<Operand, ParseError> {
        match self.advance() {
            Some(Token::Ident(name)) => Ok(Operand::Var(name)),
            Some(Token::Text(text)) => Ok(Operand::Text(text)),
            Some(Token::Int(value)) => Ok(Operand::Int(value)),
            _ => Err(ParseError::Expected("a variable, string, or number")),
        }
    }
}

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

    fn ok(input: &str) -> Expr {
        parse(input).expect("a valid guard")
    }

    fn var(name: &str) -> Operand {
        Operand::Var(name.to_string())
    }

    fn text(value: &str) -> Operand {
        Operand::Text(value.to_string())
    }

    #[test]
    fn a_bare_predicate_parses() {
        assert_eq!(ok("matched"), Expr::Matched);
        assert_eq!(ok("bound(version)"), Expr::Bound("version".to_string()));
        assert_eq!(ok("unbound(version)"), Expr::Unbound("version".to_string()));
    }

    #[test]
    fn every_relational_operator_parses() {
        for (src, op) in [
            ("v == '1'", RelOp::Eq),
            ("v != '1'", RelOp::Ne),
            ("v < '1'", RelOp::Lt),
            ("v <= '1'", RelOp::Le),
            ("v > '1'", RelOp::Gt),
            ("v >= '1'", RelOp::Ge),
        ] {
            assert_eq!(
                ok(src),
                Expr::Compare {
                    left: var("v"),
                    op,
                    right: text("1"),
                },
                "{src}"
            );
        }
    }

    #[test]
    fn operands_may_be_variables_strings_or_integers() {
        assert_eq!(
            ok("count == 3"),
            Expr::Compare {
                left: var("count"),
                op: RelOp::Eq,
                right: Operand::Int(3),
            }
        );
        // Double quotes read the same as single ones.
        assert_eq!(
            ok(r#"name == "nginx""#),
            Expr::Compare {
                left: var("name"),
                op: RelOp::Eq,
                right: text("nginx"),
            }
        );
    }

    #[test]
    fn precedence_is_not_over_and_over_or() {
        // `a and b or c` groups as `(a and b) or c`.
        let expr = ok("bound(a) and bound(b) or bound(c)");
        assert_eq!(
            expr,
            Expr::Or(
                Box::new(Expr::And(
                    Box::new(Expr::Bound("a".to_string())),
                    Box::new(Expr::Bound("b".to_string())),
                )),
                Box::new(Expr::Bound("c".to_string())),
            )
        );

        // `not a and b` groups as `(not a) and b`, not `not (a and b)`.
        let expr = ok("not matched and bound(v)");
        assert_eq!(
            expr,
            Expr::And(
                Box::new(Expr::Not(Box::new(Expr::Matched))),
                Box::new(Expr::Bound("v".to_string())),
            )
        );
    }

    #[test]
    fn parentheses_override_precedence() {
        // The parens force the `or` under the `and`.
        let expr = ok("bound(a) and (bound(b) or bound(c))");
        assert_eq!(
            expr,
            Expr::And(
                Box::new(Expr::Bound("a".to_string())),
                Box::new(Expr::Or(
                    Box::new(Expr::Bound("b".to_string())),
                    Box::new(Expr::Bound("c".to_string())),
                )),
            )
        );
    }

    #[test]
    fn the_grafana_guard_parses_as_written() {
        // The design's worked conditional-step guard, verbatim.
        let expr = ok("bound(version) and version < '8.3.1'");
        assert_eq!(
            expr,
            Expr::And(
                Box::new(Expr::Bound("version".to_string())),
                Box::new(Expr::Compare {
                    left: var("version"),
                    op: RelOp::Lt,
                    right: text("8.3.1"),
                }),
            )
        );
    }

    #[test]
    fn referenced_vars_and_uses_matched_walk_the_whole_tree() {
        let expr = ok("bound(a) and (version < '2' or unbound(b)) and not matched");
        assert_eq!(
            expr.referenced_vars(),
            ["a", "b", "version"]
                .iter()
                .map(|s| s.to_string())
                .collect()
        );
        assert!(expr.uses_matched());

        // A comparison of two literals references nothing, and a guard with no
        // `matched` anywhere reports none.
        let literals = ok("3 < 4 and bound(x)");
        assert_eq!(
            literals.referenced_vars(),
            ["x"].iter().map(|s| s.to_string()).collect()
        );
        assert!(!literals.uses_matched());
    }

    #[test]
    fn an_empty_or_whitespace_guard_is_rejected() {
        assert_eq!(parse(""), Err(ParseError::Empty));
        assert_eq!(parse("   "), Err(ParseError::Empty));
    }

    #[test]
    fn a_bare_operand_is_not_a_guard() {
        // No bare-value truthiness, a lone variable wants a comparison.
        assert_eq!(
            parse("version"),
            Err(ParseError::Expected("a comparison operator"))
        );
    }

    #[test]
    fn malformed_predicates_and_parens_are_rejected() {
        assert!(matches!(
            parse("bound version"),
            Err(ParseError::Expected(_))
        ));
        assert!(matches!(parse("bound()"), Err(ParseError::Expected(_))));
        assert!(matches!(parse("(matched"), Err(ParseError::Expected(_))));
        // A complete expression with leftover tokens.
        assert_eq!(parse("matched matched"), Err(ParseError::Trailing));
    }

    #[test]
    fn lexical_errors_name_their_cause() {
        assert_eq!(parse("v = '1'"), Err(ParseError::UnexpectedChar('=')));
        assert_eq!(parse("v & w"), Err(ParseError::UnexpectedChar('&')));
        assert_eq!(parse("v == 'open"), Err(ParseError::UnterminatedString));
        // An unquoted dotted version is not an integer and not a string, so its
        // stray '.' is the unexpected character, versions must be quoted.
        assert_eq!(parse("v < 8.3.1"), Err(ParseError::UnexpectedChar('.')));
    }

    #[test]
    fn a_guard_nested_past_the_bound_is_refused_rather_than_overflowing_the_stack() {
        // `eval` re-parses a guard on every evaluation and this runs on a worker
        // thread, so an unbounded parenthesis nest would abort the process rather
        // than fail. The bound turns that into an ordinary parse error.
        let over = MAX_GUARD_DEPTH + 5;
        let deep = format!("{}matched{}", "(".repeat(over), ")".repeat(over));
        assert_eq!(parse(&deep), Err(ParseError::TooDeep));

        // A guard nested the handful of levels a real one reaches still parses.
        let shallow = format!("{}matched{}", "(".repeat(4), ")".repeat(4));
        assert!(parse(&shallow).is_ok());
    }

    /// **The bound sits a long way under the cliff, not just under it.**
    ///
    /// [`MAX_GUARD_DEPTH`]'s documentation claims generous room, and a bound
    /// whose margin nobody has measured is a bound nobody knows the size of. The
    /// failure it prevents is an abort rather than an error, so the margin is
    /// the whole of the safety.
    ///
    /// 512 KiB is chosen to pass in either profile: a debug build needs a little
    /// under 384 KiB for this and a release build a little under 64 KiB, against
    /// the 2 MiB a tokio worker gets by default.
    #[test]
    fn a_guard_at_the_bound_parses_well_inside_a_worker_stack() {
        let parsed = std::thread::Builder::new()
            .stack_size(512 * 1024)
            .spawn(|| {
                let levels = MAX_GUARD_DEPTH - 1;
                let source = format!("{}matched{}", "(".repeat(levels), ")".repeat(levels));
                parse(&source).is_ok()
            })
            .expect("the thread spawns")
            .join()
            .expect("it did not overflow");

        assert!(
            parsed,
            "the deepest allowed guard has to parse inside a small stack, not merely not crash"
        );
    }

    /// And nesting far past the bound is still an ordinary error rather than an
    /// abort, however far past.
    #[test]
    fn nesting_far_past_the_bound_is_still_only_an_error() {
        for levels in [1_000usize, 100_000] {
            let source = format!("{}matched{}", "(".repeat(levels), ")".repeat(levels));
            assert_eq!(parse(&source), Err(ParseError::TooDeep), "{levels} levels");
        }
    }
}