instruction-md 0.1.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
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
//! A small regular-expression engine for the specification's patterns (the registry's grammar and attribute patterns)
//! and the reader's line grammar: RE2's syntax subset those use, matched by a Pike VM — leftmost-first like RE2 and
//! ECMAScript, in time linear in the input, so no document can make a pattern backtrack exponentially.
//!
//! Supported: literals and escapes (`\t \n \r \v \f \x{…} \w \d \s` and escaped punctuation), classes (`[a-z]`,
//! `[^…]`), `^` and `$` (the text's start and end), groups (capturing and `(?:…)`), alternation, the quantifiers
//! `* + ? {n} {n,} {n,m}` and their lazy forms, and a leading `(?i)` (ASCII case folding).

use std::fmt;

/// A compiled pattern.
#[derive(Clone)]
pub struct Pattern {
    source: String,
    prog: Vec<Inst>,
    groups: usize,
    fold: bool,
    /// the pattern starts with `^`: it can only match at the text's start
    anchored: bool,
}

impl fmt::Debug for Pattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Pattern({:?})", self.source)
    }
}

impl PartialEq for Pattern {
    fn eq(&self, other: &Self) -> bool {
        self.source == other.source
    }
}

#[derive(Clone, Debug)]
enum Matcher {
    Char(char),
    Class(Vec<(char, char)>, bool),
}

#[derive(Clone, Debug)]
enum Inst {
    Char(Matcher),
    Split(usize, usize),
    Jmp(usize),
    Save(usize),
    Start,
    End,
    Match,
}

#[derive(Clone, Debug)]
enum Ast {
    Empty,
    Char(Matcher),
    Start,
    End,
    Group(Box<Ast>, Option<usize>),
    Concat(Vec<Ast>),
    Alt(Vec<Ast>),
    Repeat(Box<Ast>, u32, Option<u32>, bool),
}

/// The spans a match's groups cover: group 0 is the whole match.
#[derive(Clone, Debug)]
pub struct Captures {
    slots: Vec<Option<usize>>,
}

impl Captures {
    /// The byte span of group `i`, if it took part in the match.
    pub fn span(&self, i: usize) -> Option<(usize, usize)> {
        match (self.slots.get(2 * i).copied().flatten(), self.slots.get(2 * i + 1).copied().flatten()) {
            (Some(a), Some(b)) if a <= b => Some((a, b)),
            _ => None,
        }
    }

    /// The text of group `i` in `text` (the text matched).
    pub fn get<'t>(&self, text: &'t str, i: usize) -> Option<&'t str> {
        self.span(i).and_then(|(a, b)| text.get(a..b))
    }

    /// The whole match's span.
    pub fn whole(&self) -> (usize, usize) {
        self.span(0).unwrap_or((0, 0))
    }
}

struct Parser<'a> {
    chars: Vec<char>,
    i: usize,
    groups: usize,
    fold: bool,
    _src: &'a str,
}

/// An error compiling a pattern.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatternError(pub String);

impl fmt::Display for PatternError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Pattern {
    /// Compiles a pattern.
    pub fn new(source: &str) -> Result<Pattern, PatternError> {
        let mut p = Parser { chars: source.chars().collect(), i: 0, groups: 1, fold: false, _src: source };
        if p.chars.starts_with(&['(', '?', 'i', ')']) {
            p.fold = true;
            p.i = 4;
        }
        let ast = p.alt()?;
        if p.i != p.chars.len() {
            return Err(PatternError(format!("unexpected {:?} in {source}", p.chars[p.i])));
        }
        let mut prog = vec![Inst::Save(0)];
        compile(&ast, &mut prog);
        prog.push(Inst::Save(1));
        prog.push(Inst::Match);
        let anchored = starts_anchored(&ast);
        Ok(Pattern { source: source.to_string(), prog, groups: p.groups, fold: p.fold, anchored })
    }

    /// Compiles a pattern this crate writes itself (the registry's are checked when it loads).
    pub(crate) fn must(source: &str) -> Pattern {
        match Pattern::new(source) {
            Ok(p) => p,
            // the crate's own patterns are fixed text, compiled by the tests: an error here is a bug in this crate
            Err(e) => Pattern::never(&e.0),
        }
    }

    /// A pattern that matches nothing (the fallback for one that does not compile).
    fn never(source: &str) -> Pattern {
        Pattern {
            source: source.to_string(),
            prog: vec![Inst::Char(Matcher::Class(Vec::new(), false)), Inst::Match],
            groups: 1,
            fold: false,
            anchored: false,
        }
    }

    /// The pattern as written.
    pub fn as_str(&self) -> &str {
        &self.source
    }

    /// Does the pattern match anywhere in the text?
    pub fn is_match(&self, text: &str) -> bool {
        self.run(text, 0, 0, true).is_some()
    }

    /// The leftmost match's span.
    pub fn find(&self, text: &str) -> Option<(usize, usize)> {
        self.captures_at(text, 0).map(|c| c.whole())
    }

    /// The leftmost match's text.
    pub fn find_str<'t>(&self, text: &'t str) -> Option<&'t str> {
        self.find(text).and_then(|(a, b)| text.get(a..b))
    }

    /// The leftmost match and its groups.
    pub fn captures(&self, text: &str) -> Option<Captures> {
        self.captures_at(text, 0)
    }

    /// Every non-overlapping match's span, left to right.
    pub fn find_iter(&self, text: &str) -> Vec<(usize, usize)> {
        self.captures_iter(text).iter().map(Captures::whole).collect()
    }

    /// Every non-overlapping match, left to right.
    pub fn captures_iter(&self, text: &str) -> Vec<Captures> {
        let mut out = Vec::new();
        let mut at = 0;
        while at <= text.len() {
            let Some(c) = self.captures_at(text, at) else { break };
            let (a, b) = c.whole();
            out.push(c);
            at = if b > a {
                b
            } else {
                match text[b..].chars().next() {
                    Some(ch) => b + ch.len_utf8(),
                    None => break,
                }
            };
        }
        out
    }

    /// The text with every match replaced by what `f` makes of it.
    pub fn replace_all(&self, text: &str, mut f: impl FnMut(&Captures) -> String) -> String {
        let mut out = String::with_capacity(text.len());
        let mut last = 0;
        for c in self.captures_iter(text) {
            let (a, b) = c.whole();
            out.push_str(&text[last..a]);
            out.push_str(&f(&c));
            last = b;
        }
        out.push_str(&text[last..]);
        out
    }

    /// The leftmost match starting at or after `start` (a char boundary), with its groups.
    pub fn captures_at(&self, text: &str, start: usize) -> Option<Captures> {
        self.run(text, start, self.groups * 2, false).map(|slots| Captures { slots })
    }

    /// The Pike VM: threads in priority order, one step per character. `slots` are the capture slots kept (none for
    /// a yes-or-no answer); `any`: stop at the first match found, leftmost-first or not.
    fn run(&self, text: &str, start: usize, slots: usize, any: bool) -> Option<Vec<Option<usize>>> {
        if start > text.len() || !text.is_char_boundary(start) || self.anchored && start > 0 {
            return None;
        }
        let n = self.prog.len();
        let mut clist = Threads::new(n);
        let mut nlist = Threads::new(n);
        let mut matched: Option<Vec<Option<usize>>> = None;
        let mut pos = start;
        loop {
            if matched.is_none() && (!self.anchored || pos == 0) {
                self.add(&mut clist, 0, pos, text, vec![None; slots]);
            }
            if clist.list.is_empty() {
                break;
            }
            let ch = text[pos..].chars().next();
            let next = pos + ch.map_or(0, char::len_utf8);
            nlist.clear();
            let threads = std::mem::take(&mut clist.list);
            for (pc, caps) in threads {
                match &self.prog[pc] {
                    Inst::Char(m) => {
                        if let Some(c) = ch
                            && self.matches(m, c)
                        {
                            self.add(&mut nlist, pc + 1, next, text, caps);
                        }
                    }
                    Inst::Match => {
                        matched = Some(caps);
                        if any {
                            return matched;
                        }
                        break;
                    }
                    _ => {}
                }
            }
            std::mem::swap(&mut clist, &mut nlist);
            if ch.is_none() {
                break;
            }
            pos = next;
        }
        matched
    }

    fn matches(&self, m: &Matcher, c: char) -> bool {
        let fold = self.fold;
        match m {
            Matcher::Char(x) => *x == c || fold && x.eq_ignore_ascii_case(&c),
            Matcher::Class(ranges, negated) => {
                let hit = |c: char| ranges.iter().any(|&(a, b)| a <= c && c <= b);
                let mut found = hit(c);
                if !found && fold && c.is_ascii_alphabetic() {
                    found = hit(c.to_ascii_lowercase()) || hit(c.to_ascii_uppercase());
                }
                found != *negated
            }
        }
    }

    /// Adds a thread at pc, following the instructions that consume nothing.
    fn add(&self, list: &mut Threads, pc: usize, pos: usize, text: &str, mut caps: Vec<Option<usize>>) {
        let mut stack: Vec<(usize, Restore)> = vec![(pc, None)];
        // (an explicit stack: a restore entry puts a slot back once its branch is followed)
        while let Some((pc, restore)) = stack.pop() {
            if let Some((slot, old)) = restore {
                caps[slot] = old;
                continue;
            }
            if list.seen[pc] == list.generation {
                continue;
            }
            list.seen[pc] = list.generation;
            match &self.prog[pc] {
                Inst::Jmp(t) => stack.push((*t, None)),
                Inst::Split(a, b) => {
                    stack.push((*b, None));
                    stack.push((*a, None));
                }
                Inst::Save(slot) => {
                    if *slot < caps.len() {
                        let old = caps[*slot];
                        caps[*slot] = Some(pos);
                        stack.push((0, Some((*slot, old))));
                        stack.push((pc + 1, None));
                    } else {
                        stack.push((pc + 1, None));
                    }
                }
                Inst::Start => {
                    if pos == 0 {
                        stack.push((pc + 1, None));
                    }
                }
                Inst::End => {
                    if pos == text.len() {
                        stack.push((pc + 1, None));
                    }
                }
                Inst::Char(_) | Inst::Match => list.list.push((pc, caps.clone())),
            }
        }
    }
}

/// A slot to put back once a branch has been followed: (the slot, its value before).
type Restore = Option<(usize, Option<usize>)>;

struct Threads {
    /// the generation a pc was last added in (a list is cleared by moving to the next generation)
    seen: Vec<u32>,
    generation: u32,
    list: Vec<(usize, Vec<Option<usize>>)>,
}

impl Threads {
    fn new(n: usize) -> Threads {
        Threads { seen: vec![0; n], generation: 1, list: Vec::new() }
    }
    fn clear(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        if self.generation == 0 {
            self.seen.iter_mut().for_each(|s| *s = 0);
            self.generation = 1;
        }
        self.list.clear();
    }
}

/// Does every match have to start at the text's start (a leading `^` on every branch)?
fn starts_anchored(ast: &Ast) -> bool {
    match ast {
        Ast::Start => true,
        Ast::Concat(items) => items.first().is_some_and(starts_anchored),
        Ast::Group(inner, _) => starts_anchored(inner),
        Ast::Alt(items) => !items.is_empty() && items.iter().all(starts_anchored),
        _ => false,
    }
}

fn compile(ast: &Ast, prog: &mut Vec<Inst>) {
    match ast {
        Ast::Empty => {}
        Ast::Char(m) => prog.push(Inst::Char(m.clone())),
        Ast::Start => prog.push(Inst::Start),
        Ast::End => prog.push(Inst::End),
        Ast::Group(inner, index) => {
            if let Some(i) = index {
                prog.push(Inst::Save(2 * i));
                compile(inner, prog);
                prog.push(Inst::Save(2 * i + 1));
            } else {
                compile(inner, prog);
            }
        }
        Ast::Concat(items) => items.iter().for_each(|a| compile(a, prog)),
        Ast::Alt(items) => {
            let mut jumps = Vec::new();
            for (k, item) in items.iter().enumerate() {
                if k + 1 < items.len() {
                    let split = prog.len();
                    prog.push(Inst::Split(split + 1, 0));
                    compile(item, prog);
                    jumps.push(prog.len());
                    prog.push(Inst::Jmp(0));
                    let next = prog.len();
                    prog[split] = Inst::Split(split + 1, next);
                } else {
                    compile(item, prog);
                }
            }
            let end = prog.len();
            for j in jumps {
                prog[j] = Inst::Jmp(end);
            }
        }
        Ast::Repeat(inner, min, max, greedy) => {
            for _ in 0..*min {
                compile(inner, prog);
            }
            match max {
                None => {
                    let split = prog.len();
                    prog.push(Inst::Split(0, 0));
                    compile(inner, prog);
                    prog.push(Inst::Jmp(split));
                    let out = prog.len();
                    prog[split] = if *greedy { Inst::Split(split + 1, out) } else { Inst::Split(out, split + 1) };
                }
                Some(max) => {
                    let mut splits = Vec::new();
                    for _ in *min..*max {
                        splits.push(prog.len());
                        prog.push(Inst::Split(0, 0));
                        compile(inner, prog);
                    }
                    let out = prog.len();
                    for s in splits {
                        prog[s] = if *greedy { Inst::Split(s + 1, out) } else { Inst::Split(out, s + 1) };
                    }
                }
            }
        }
    }
}

impl Parser<'_> {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.i).copied()
    }

    fn err<T>(&self, what: &str) -> Result<T, PatternError> {
        Err(PatternError(format!("{what} at {}", self.i)))
    }

    fn alt(&mut self) -> Result<Ast, PatternError> {
        let mut items = vec![self.concat()?];
        while self.peek() == Some('|') {
            self.i += 1;
            items.push(self.concat()?);
        }
        Ok(if items.len() == 1 { items.pop().unwrap_or(Ast::Empty) } else { Ast::Alt(items) })
    }

    fn concat(&mut self) -> Result<Ast, PatternError> {
        let mut items = Vec::new();
        while let Some(c) = self.peek() {
            if c == '|' || c == ')' {
                break;
            }
            let atom = self.atom()?;
            let atom = self.quantified(atom)?;
            items.push(atom);
        }
        Ok(Ast::Concat(items))
    }

    fn quantified(&mut self, atom: Ast) -> Result<Ast, PatternError> {
        let (min, max) = match self.peek() {
            Some('*') => {
                self.i += 1;
                (0, None)
            }
            Some('+') => {
                self.i += 1;
                (1, None)
            }
            Some('?') => {
                self.i += 1;
                (0, Some(1))
            }
            Some('{') => {
                let save = self.i;
                self.i += 1;
                let Some(min) = self.number() else {
                    self.i = save;
                    return Ok(atom);
                };
                let max = if self.peek() == Some(',') {
                    self.i += 1;
                    if self.peek() == Some('}') { None } else { self.number() }
                } else {
                    Some(min)
                };
                if self.peek() != Some('}') {
                    return self.err("bad repetition");
                }
                self.i += 1;
                if max.is_some_and(|m| m < min) || min > 1000 || max.is_some_and(|m| m > 1000) {
                    return self.err("bad repetition");
                }
                (min, max)
            }
            _ => return Ok(atom),
        };
        let greedy = if self.peek() == Some('?') {
            self.i += 1;
            false
        } else {
            true
        };
        Ok(Ast::Repeat(Box::new(atom), min, max, greedy))
    }

    fn number(&mut self) -> Option<u32> {
        let start = self.i;
        let mut n: u32 = 0;
        while let Some(c) = self.peek().filter(char::is_ascii_digit) {
            n = n.saturating_mul(10).saturating_add(c as u32 - '0' as u32);
            self.i += 1;
        }
        (self.i > start).then_some(n)
    }

    fn atom(&mut self) -> Result<Ast, PatternError> {
        let Some(c) = self.peek() else { return self.err("unexpected end") };
        self.i += 1;
        match c {
            '^' => Ok(Ast::Start),
            '$' => Ok(Ast::End),
            '.' => Ok(Ast::Char(Matcher::Class(vec![('\n', '\n')], true))),
            '(' => {
                let index = if self.chars[self.i..].starts_with(&['?', ':']) {
                    self.i += 2;
                    None
                } else {
                    let g = self.groups;
                    self.groups += 1;
                    Some(g)
                };
                let inner = self.alt()?;
                if self.peek() != Some(')') {
                    return self.err("unclosed group");
                }
                self.i += 1;
                Ok(Ast::Group(Box::new(inner), index))
            }
            '[' => self.class(),
            '\\' => {
                let ranges = self.escape()?;
                Ok(Ast::Char(ranges))
            }
            '*' | '+' | '?' => self.err("nothing to repeat"),
            c => Ok(Ast::Char(Matcher::Char(c))),
        }
    }

    /// An escape after its backslash: one character, or a class (\w, \d, \s).
    fn escape(&mut self) -> Result<Matcher, PatternError> {
        let Some(c) = self.peek() else { return self.err("trailing backslash") };
        self.i += 1;
        Ok(match c {
            't' => Matcher::Char('\t'),
            'n' => Matcher::Char('\n'),
            'r' => Matcher::Char('\r'),
            'v' => Matcher::Char('\u{b}'),
            'f' => Matcher::Char('\u{c}'),
            'w' => Matcher::Class(vec![('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z')], false),
            'd' => Matcher::Class(vec![('0', '9')], false),
            's' => Matcher::Class(vec![('\t', '\n'), ('\u{c}', '\r'), (' ', ' ')], false),
            'x' => {
                if self.peek() != Some('{') {
                    return self.err("bad \\x");
                }
                self.i += 1;
                let mut v: u32 = 0;
                while let Some(d) = self.peek().and_then(|d| d.to_digit(16)) {
                    v = v.saturating_mul(16).saturating_add(d);
                    self.i += 1;
                }
                if self.peek() != Some('}') {
                    return self.err("bad \\x");
                }
                self.i += 1;
                match char::from_u32(v) {
                    Some(ch) => Matcher::Char(ch),
                    None => return self.err("bad \\x"),
                }
            }
            c if c.is_ascii_punctuation() => Matcher::Char(c),
            _ => return self.err("unknown escape"),
        })
    }

    fn class(&mut self) -> Result<Ast, PatternError> {
        let negated = self.peek() == Some('^');
        if negated {
            self.i += 1;
        }
        let mut ranges = Vec::new();
        let mut first = true;
        loop {
            let Some(c) = self.peek() else { return self.err("unclosed class") };
            if c == ']' && !first {
                self.i += 1;
                break;
            }
            first = false;
            self.i += 1;
            let lo = if c == '\\' {
                match self.escape()? {
                    Matcher::Char(ch) => ch,
                    Matcher::Class(rs, _) => {
                        ranges.extend(rs);
                        continue;
                    }
                }
            } else {
                c
            };
            if self.peek() == Some('-') && self.chars.get(self.i + 1).is_some_and(|&n| n != ']') {
                self.i += 1;
                let Some(h) = self.peek() else { return self.err("unclosed class") };
                self.i += 1;
                let hi = if h == '\\' {
                    match self.escape()? {
                        Matcher::Char(ch) => ch,
                        Matcher::Class(..) => return self.err("bad range"),
                    }
                } else {
                    h
                };
                if hi < lo {
                    return self.err("bad range");
                }
                ranges.push((lo, hi));
            } else {
                ranges.push((lo, lo));
            }
        }
        Ok(Ast::Char(Matcher::Class(ranges, negated)))
    }
}

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

    #[test]
    fn matches_like_re2() {
        let p = Pattern::must(r"^(\*\*)?(MUST NOT|MUST)(?:\[([^\]\s]*)\])?:(\*\*)?[ \t]+(\S.*)$".replace(r"\S", r"[^\s]").as_str());
        let c = p.captures("**MUST NOT[x]:** go").unwrap();
        assert_eq!(c.get("**MUST NOT[x]:** go", 2), Some("MUST NOT"));
        assert_eq!(c.get("**MUST NOT[x]:** go", 3), Some("x"));
        assert_eq!(c.get("**MUST NOT[x]:** go", 5), Some("go"));
        assert!(Pattern::must("^sha256:[0-9a-f]{64}$").is_match(&format!("sha256:{}", "a".repeat(64))));
        assert!(!Pattern::must("^sha256:[0-9a-f]{64}$").is_match(&format!("sha256:{}", "a".repeat(63))));
        let lazy = Pattern::must(r"^#{1,6}[ \t].*?[ \t](\{[^{}]*\})[ \t]*$");
        assert_eq!(lazy.captures("## A {x} b {#id}").and_then(|c| c.get("## A {x} b {#id}", 1).map(String::from)), Some("{#id}".into()));
        assert_eq!(Pattern::must("`+").find_iter("a `` b ` c"), vec![(2, 4), (7, 8)]);
        assert!(Pattern::must("(?i)^https?://x$").is_match("HTTPS://X"));
        let nested = Pattern::must(r"^(?:/(?:[^~]|~[01])*)*$");
        assert!(!nested.is_match(&format!("{}~x", "/".repeat(5000))));
        assert_eq!(Pattern::must("a|ab").find("ab"), Some((0, 1)));
    }
}