grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/format/xml.rs
// Purpose:   One XML document read into fields, in one pass
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One XML document a record, each field written as it is reached.
//!
//! A name is the path of local element names joined with `.`, the root
//! included, so two documents can write the same name, as two JSON records
//! can. An attribute is `<path>.@<name>`. A name holding `.`, as `<a.b>` or
//! a keyed value can, is written quoted, `["a.b"]`, as [`crate::path`] reads
//! it. An element's own text is one value under its path, written when the
//! element closes. Namespace prefixes and declarations are dropped.
//!
//! What that loses: a repeated element's values and attributes are each
//! written in order, so which attribute went with which value is lost when
//! one repeat lacks either. Text either side of a child element is joined
//! into one value. A carriage return, line feed or tab stays as written,
//! where XML would normalise it.
//!
//! It reads what a log line or a field holds, and is no validating XML
//! parser. Checked: UTF-8, matching end tags, comments, one attribute name
//! an element, one root, nothing but white space outside it, every
//! reference. A `<!DOCTYPE>` is refused, so no entity is ever defined. Not
//! checked: the characters of a name, characters XML forbids in text, and a
//! `<` inside an attribute value.

use std::borrow::Cow;

use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::Reader;
use serde::Deserialize;
use thiserror::Error;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::{canonical, key_part, keys, needs_quotes, push_key};
use crate::strmatch::{Signature, Specificity};
use crate::tier::MatcherTier;

/// Most elements open at once, the root counted.
const MAX_DEPTH: usize = 64;

/// Most attributes on one element.
const MAX_ATTRIBUTES: usize = 256;

/// Name bytes a document may write, as a multiple of its size, and the least
/// that allowance is.
const NAME_FACTOR: usize = 16;
const NAME_FLOOR: usize = 1 << 20;

const BOM: &[u8] = b"\xEF\xBB\xBF";

pub use crate::xml::Keyed;

/// Settings for a configured [`Xml`] parser.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct XmlParserConfig {
    /// Elements named by an attribute's value.
    pub keyed: Vec<Keyed>,
}

/// Why an [`XmlParserConfig`] didn't build.
#[derive(Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum XmlConfigError {
    /// A rule's path or attribute is empty, or its path has an empty part.
    #[error("keyed rule {path:?} by {attribute:?}: a path part or the attribute is empty")]
    Empty {
        /// The rule's path.
        path: String,
        /// The rule's attribute.
        attribute: String,
    },
    /// Two rules for one path.
    #[error("two keyed rules for {0:?}")]
    Twice(String),
    /// The name isn't `xml` or `xml:<instance>`.
    #[error("parser name {0:?} is not `xml` or `xml:<instance>`")]
    Name(String),
}

/// The XML parser, registered as `xml`.
#[derive(Debug, Clone)]
pub struct Xml {
    name: String,
    signature: Signature,
    keyed: Vec<Keyed>,
}

impl Default for Xml {
    fn default() -> Self {
        Self::new()
    }
}

impl Xml {
    /// The parser with no keyed rules.
    ///
    /// # Panics
    ///
    /// Never: the signature's literals are fixed and non-empty.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .anchored([&b"<"[..], b"\xEF\xBB\xBF<"])
            .verify(|span, _| opens_a_document(span))
            .specificity(Specificity::Generic)
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: the XML literals are non-empty"));
        Self {
            name: "xml".to_owned(),
            signature,
            keyed: Vec::new(),
        }
    }

    /// A configured parser, named `xml` or `xml:<instance>`.
    ///
    /// # Errors
    ///
    /// [`XmlConfigError`] for a name of another format or a rule that can't apply.
    pub fn with_config(name: &str, config: &XmlParserConfig) -> Result<Self, XmlConfigError> {
        let format = name.split_once(':').map_or(name, |(format, _)| format);
        if format != "xml" || !crate::parse::valid_parser_name(name) {
            return Err(XmlConfigError::Name(name.to_owned()));
        }
        let mut keyed: Vec<Keyed> = Vec::with_capacity(config.keyed.len());
        for rule in &config.keyed {
            if rule.attribute.is_empty() || keys(&rule.path).any(|k| k.is_empty()) {
                return Err(XmlConfigError::Empty {
                    path: rule.path.clone(),
                    attribute: rule.attribute.clone(),
                });
            }
            let path = canonical(&rule.path).into_owned();
            if keyed.iter().any(|r| r.path == path) {
                return Err(XmlConfigError::Twice(rule.path.clone()));
            }
            keyed.push(Keyed {
                path,
                attribute: rule.attribute.clone(),
            });
        }
        Ok(Self {
            name: name.to_owned(),
            keyed,
            ..Self::new()
        })
    }
}

/// `<` then a byte that can start a tag, a declaration or a comment, after
/// an optional byte order mark.
fn opens_a_document(span: &[u8]) -> bool {
    let rest = span.strip_prefix(BOM).unwrap_or(span);
    matches!(
        rest,
        [
            b'<',
            b'_' | b':' | b'?' | b'!' | b'a'..=b'z' | b'A'..=b'Z' | 0x80..,
            ..,
        ]
    )
}

impl Parser for Xml {
    fn name(&self) -> &str {
        &self.name
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn hands_on_body(&self) -> bool {
        false
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        if !opens_a_document(input) {
            return Ok(Parsed::NoMatch);
        }
        let text = std::str::from_utf8(input).map_err(|e| ParseError::Malformed {
            offset: e.valid_up_to(),
            reason: "XML that isn't UTF-8",
        })?;
        let skipped = input.len() - input.strip_prefix(BOM).unwrap_or(input).len();
        let mark = out.mark();
        let mut walk = Walk {
            rules: &self.keyed,
            text,
            out,
            stack: Vec::new(),
            path: String::new(),
            pushed: 0,
            names: 0,
            budget: input.len().saturating_mul(NAME_FACTOR).max(NAME_FLOOR),
            prefix_len: 0,
            rooted: false,
        };
        match walk.document(&text[skipped..], skipped) {
            Ok(()) => Ok(Parsed::Done),
            Err(error) => {
                for _ in 0..walk.pushed {
                    walk.out.pop_prefix();
                }
                walk.out.rollback(mark);
                Err(error)
            }
        }
    }
}

/// The text an element holds itself, between and around its children.
#[derive(Debug, Default)]
enum Text<'a> {
    #[default]
    None,
    /// One unbroken run of the input.
    Run(&'a str),
    /// Several runs, or a resolved reference.
    Joined(String),
}

impl<'a> Text<'a> {
    fn push(&mut self, piece: Cow<'a, str>) {
        *self = match (std::mem::take(self), piece) {
            (Self::None, Cow::Borrowed(run)) => Self::Run(run),
            (Self::None, Cow::Owned(made)) => Self::Joined(made),
            (Self::Run(first), piece) => Self::Joined([first, &piece].concat()),
            (Self::Joined(mut all), piece) => {
                all.push_str(&piece);
                Self::Joined(all)
            }
        };
    }

    fn into_value(self) -> FieldValue<'a> {
        match self {
            Self::None => FieldValue::borrowed(b"", Hint::Text),
            Self::Run(run) => FieldValue::borrowed(run.as_bytes(), Hint::Text),
            Self::Joined(all) => FieldValue::owned(all.into_bytes(), Hint::Text),
        }
    }
}

/// An open element.
#[derive(Debug)]
struct Frame<'a> {
    /// The name part it writes under: its local name, or a keyed value.
    name: Cow<'a, str>,
    /// How much of the walk's rule path its own name added.
    path_len: usize,
    text: Text<'a>,
    has_child: bool,
    /// Its text holds more than white space between children.
    counts: bool,
}

struct Walk<'s, 'a, 'o> {
    rules: &'s [Keyed],
    text: &'a str,
    out: &'o mut dyn FieldSink<'a>,
    stack: Vec<Frame<'a>>,
    /// Local names of the open elements as a field name, kept only when
    /// there are keyed rules to match it against.
    path: String,
    /// Prefixes pushed on the sink and not yet popped.
    pushed: usize,
    names: usize,
    budget: usize,
    prefix_len: usize,
    rooted: bool,
}

const fn malformed(offset: usize, reason: &'static str) -> ParseError {
    ParseError::Malformed { offset, reason }
}

/// `piece` as a slice of `text`, when it is one.
fn within<'a>(text: &'a str, piece: &str) -> Option<&'a str> {
    let start = piece.as_ptr().addr().checked_sub(text.as_ptr().addr())?;
    text.get(start..start.checked_add(piece.len())?)
}

/// `piece` borrowed from `text` when it lies in it, copied when it doesn't.
fn kept<'a>(text: &'a str, piece: &str) -> Cow<'a, str> {
    within(text, piece).map_or_else(|| Cow::Owned(piece.to_owned()), Cow::Borrowed)
}

/// The character a reference names: one of XML's five, or a number for a
/// character XML 1.0 allows.
fn resolve(name: &str) -> Option<char> {
    let code = match name.strip_prefix('#') {
        None => {
            return match name {
                "lt" => Some('<'),
                "gt" => Some('>'),
                "amp" => Some('&'),
                "apos" => Some('\''),
                "quot" => Some('"'),
                _ => None,
            };
        }
        // Digits only: the integer parsers would take a sign.
        Some(number) => match number.strip_prefix('x') {
            Some(hex) if hex.bytes().all(|b| b.is_ascii_hexdigit()) => {
                u32::from_str_radix(hex, 16).ok()?
            }
            None if number.bytes().all(|b| b.is_ascii_digit()) => number.parse().ok()?,
            _ => return None,
        },
    };
    let allowed = matches!(
        code,
        0x9 | 0xA | 0xD | 0x20..=0xD7FF | 0xE000..=0xFFFD | 0x1_0000..
    );
    char::from_u32(code).filter(|_| allowed)
}

/// `raw` with every reference resolved, or `None` for one that doesn't.
fn resolved(raw: &str) -> Option<String> {
    let mut made = String::with_capacity(raw.len());
    let mut rest = raw;
    while let Some(amp) = rest.find('&') {
        made.push_str(&rest[..amp]);
        let end = rest[amp..].find(';')?;
        made.push(resolve(&rest[amp + 1..amp + end])?);
        rest = &rest[amp + end + 1..];
    }
    made.push_str(rest);
    Some(made)
}

impl<'s, 'a> Walk<'s, 'a, '_> {
    /// Add `local` to the rule path: how much it grew by, and the attribute
    /// that names an element there, when a rule says one does.
    fn enter(&mut self, local: &str) -> (usize, Option<&'s str>) {
        let rules: &'s [Keyed] = self.rules;
        if rules.is_empty() {
            return (0, None);
        }
        let before = self.path.len();
        push_key(&mut self.path, local);
        let rule = rules.iter().find(|rule| rule.path == self.path);
        (
            self.path.len() - before,
            rule.map(|rule| rule.attribute.as_str()),
        )
    }

    fn push_prefix(&mut self, prefix: &str) {
        self.out.push_prefix(prefix);
        self.pushed += 1;
        self.prefix_len += prefix.len();
    }

    fn pop_prefix(&mut self, len: usize) {
        self.out.pop_prefix();
        self.pushed -= 1;
        self.prefix_len -= len;
    }

    fn field(&mut self, name: &str, value: FieldValue<'a>) -> Result<(), ParseError> {
        let full = self.prefix_len.saturating_add(name.len());
        self.names = self.names.saturating_add(full);
        if self.names > self.budget {
            return Err(ParseError::Limit {
                what: "XML field name bytes",
            });
        }
        self.out.field(name, value);
        Ok(())
    }

    /// An attribute's value: borrowed when it is the input's own bytes.
    fn value(&self, raw: &str, at: usize) -> Result<Cow<'a, str>, ParseError> {
        if raw.contains('&') {
            let made =
                resolved(raw).ok_or_else(|| malformed(at, "a reference XML doesn't define"))?;
            return Ok(Cow::Owned(made));
        }
        Ok(kept(self.text, raw))
    }

    /// Open an element: its prefix, then its attributes.
    fn open(&mut self, start: &BytesStart<'a>, at: usize) -> Result<(), ParseError> {
        if self.rooted && self.stack.is_empty() {
            return Err(malformed(at, "a second root element"));
        }
        if self.stack.len() == MAX_DEPTH {
            return Err(ParseError::Limit {
                what: "XML nesting depth",
            });
        }
        self.rooted = true;
        if let Some(parent) = self.stack.last_mut() {
            parent.has_child = true;
        }
        let local = start.local_name().into_inner();
        let (path_len, mut key_by) = self.enter(local);
        let unreadable = |_| malformed(at, "an attribute XML can't read");
        let mut name = kept(self.text, local);
        // The qualified name of the attribute that named the element.
        let mut named_by = None;
        if let Some(attribute) = key_by.take() {
            for candidate in start.attributes() {
                let candidate = candidate.map_err(unreadable)?;
                if candidate.key.as_namespace_binding().is_none()
                    && candidate.key.local_name().into_inner() == attribute
                {
                    let key = self.value(&candidate.value, at)?;
                    if !key.trim_ascii().is_empty() {
                        name = key;
                        named_by = Some(candidate.key.into_inner());
                    }
                    break;
                }
            }
        }
        let name = key_part(name);
        self.push_prefix(&name);
        self.push_prefix(".");
        let mut count = 0;
        for attribute in start.attributes() {
            let attribute = attribute.map_err(unreadable)?;
            count += 1;
            if count > MAX_ATTRIBUTES {
                return Err(ParseError::Limit {
                    what: "XML attributes on one element",
                });
            }
            // A declaration's value is checked like any other, then dropped.
            let value = self.value(&attribute.value, at)?;
            let declares = attribute.key.as_namespace_binding().is_some();
            if declares || Some(attribute.key.into_inner()) == named_by {
                continue;
            }
            let local = attribute.key.local_name().into_inner();
            let value = match value {
                Cow::Borrowed(run) => FieldValue::borrowed(run.as_bytes(), Hint::Text),
                Cow::Owned(made) => FieldValue::owned(made.into_bytes(), Hint::Text),
            };
            if needs_quotes(local) {
                let key = key_part(Cow::Owned(format!("@{local}")));
                self.field(&key, value)?;
            } else {
                self.push_prefix("@");
                let wrote = self.field(local, value);
                self.pop_prefix(1);
                wrote?;
            }
        }
        self.stack.push(Frame {
            name,
            path_len,
            text: Text::None,
            has_child: false,
            counts: false,
        });
        Ok(())
    }

    /// Close the innermost element: write its own text under its path.
    fn close(&mut self, at: usize) -> Result<(), ParseError> {
        let frame = self
            .stack
            .pop()
            .ok_or_else(|| malformed(at, "an end tag with no element open"))?;
        self.path.truncate(self.path.len() - frame.path_len);
        self.pop_prefix(1);
        self.pop_prefix(frame.name.len());
        if frame.has_child && !frame.counts {
            return Ok(());
        }
        self.field(&frame.name, frame.text.into_value())
    }

    /// Add `piece` to the open element's text. Outside the root only white
    /// space is allowed, and only as plain text.
    fn text(&mut self, piece: Cow<'a, str>, plain: bool, at: usize) -> Result<(), ParseError> {
        let blank = plain
            && piece
                .bytes()
                .all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'));
        let Some(frame) = self.stack.last_mut() else {
            return if blank {
                Ok(())
            } else {
                Err(malformed(at, "text outside the root element"))
            };
        };
        frame.counts |= !blank;
        frame.text.push(piece);
        Ok(())
    }

    fn document(&mut self, body: &'a str, skipped: usize) -> Result<(), ParseError> {
        let mut reader = Reader::from_str(body);
        reader.config_mut().check_comments = true;
        let mut first = true;
        loop {
            let at = skipped + usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX);
            let event = reader.read_event().map_err(|_| {
                let at = usize::try_from(reader.error_position()).unwrap_or(usize::MAX);
                malformed(skipped.saturating_add(at), "XML that isn't well formed")
            })?;
            match event {
                Event::Decl(decl) => {
                    let version = decl.version().ok();
                    let utf8 = match decl.encoding() {
                        None => true,
                        Some(Ok(name)) => name.eq_ignore_ascii_case("utf-8"),
                        Some(Err(_)) => false,
                    };
                    if !first || version.as_deref() != Some("1.0") || !utf8 {
                        return Err(malformed(at, "an XML declaration this parser doesn't read"));
                    }
                }
                Event::DocType(_) => return Err(malformed(at, "a DOCTYPE, which is refused")),
                Event::PI(_) | Event::Comment(_) => {}
                Event::Start(start) => self.open(&start, at)?,
                Event::Empty(start) => {
                    self.open(&start, at)?;
                    self.close(at)?;
                }
                Event::End(_) => self.close(at)?,
                Event::Text(run) => self.text(run.into_inner(), true, at)?,
                Event::CData(run) => self.text(run.into_inner(), false, at)?,
                Event::GeneralRef(name) => {
                    let named = resolve(&name.into_inner())
                        .ok_or_else(|| malformed(at, "a reference XML doesn't define"))?;
                    self.text(Cow::Owned(named.to_string()), false, at)?;
                }
                Event::Eof if !self.stack.is_empty() => {
                    return Err(malformed(at, "an element that is never closed"));
                }
                Event::Eof if !self.rooted => {
                    return Err(malformed(at, "no root element"));
                }
                Event::Eof => return Ok(()),
            }
            first = false;
        }
    }
}

#[cfg(test)]
mod tests;