grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/format/yaml.rs
// Purpose:   The YAML parser: one document an input into fields
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One YAML document an input, its fields named as `ndjson` names a JSON
//! record's: a nested key joins its parents with `.`, a list writes each
//! element under its key, and `null` writes nothing.
//!
//! YAML is config, read once, so it goes through noyalib rather than one of
//! grippo's own scanners: it doesn't need the speed. noyalib reads YAML 1.2,
//! borrows a string that holds no escape, and bounds the document: 64
//! containers deep, 1,024 expansions of an alias, and its node and event
//! counts. A stream of several documents is split by framing first:
//! `multi_line` with `start: "---"`.

use std::borrow::Cow;

use noyalib::borrowed::{BorrowedValue, from_str_borrowed_with_config};
use noyalib::{ErrorKind, Number, ParserConfig, ParserLimits};

use super::tree::{MAX_DEPTH, Tree};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The YAML parser, registered as `yaml`.
#[derive(Debug, Clone)]
pub struct Yaml {
    signature: Signature,
    config: ParserConfig,
}

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

impl Yaml {
    /// A YAML parser.
    ///
    /// # Panics
    ///
    /// Never: an empty signature always builds.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        let mut limits = ParserLimits::default();
        limits.max_depth = MAX_DEPTH;
        limits.max_documents = 1;
        Self {
            signature,
            config: ParserConfig::new().with_limits(limits),
        }
    }
}

/// Write `value`, the next value in `tree`.
fn walk<'a>(tree: &mut Tree<'_, 'a>, value: BorrowedValue<'a>) -> Result<(), ParseError> {
    match value {
        BorrowedValue::Null => tree.skip(),
        BorrowedValue::Bool(b) => {
            let text: &'static [u8] = if b { b"true" } else { b"false" };
            tree.scalar(FieldValue::borrowed(text, Hint::Bool))?;
        }
        BorrowedValue::Number(n) => tree.scalar(number(&n))?,
        BorrowedValue::String(s) => tree.scalar(text(s))?,
        BorrowedValue::Sequence(items) => {
            tree.open_list()?;
            for item in items {
                walk(tree, item)?;
            }
            tree.close();
        }
        BorrowedValue::Mapping(map) => {
            tree.open_map()?;
            for (key, item) in map {
                tree.key(key);
                walk(tree, item)?;
            }
            tree.close();
        }
    }
    Ok(())
}

/// A number as decimal text: an integer as written in base 10, a float in
/// its shortest form, and an infinity or NaN as text.
fn number(n: &Number) -> FieldValue<'static> {
    match *n {
        Number::Integer(i) => FieldValue::owned(i.to_string().into_bytes(), Hint::Int),
        Number::Float(f) if f.is_finite() => {
            FieldValue::owned(format!("{f:?}").into_bytes(), Hint::Float)
        }
        Number::Float(f) => FieldValue::owned(format!("{f}").into_bytes(), Hint::Text),
        // An unsigned integer, when a crate in the build turns on noyalib's `lossless-u64`.
        _ => FieldValue::owned(n.to_string().into_bytes(), Hint::Int),
    }
}

fn text(s: Cow<'_, str>) -> FieldValue<'_> {
    match s {
        Cow::Borrowed(s) => FieldValue::borrowed(s.as_bytes(), Hint::Text),
        Cow::Owned(s) => FieldValue::owned(s.into_bytes(), Hint::Text),
    }
}

impl Parser for Yaml {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str {
        "yaml"
    }

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

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

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let doc = std::str::from_utf8(input).map_err(|e| ParseError::Malformed {
            offset: e.valid_up_to(),
            reason: "YAML that isn't UTF-8",
        })?;
        let value = from_str_borrowed_with_config(doc, &self.config).map_err(|e| {
            if e.kind() == ErrorKind::Budget {
                ParseError::Limit {
                    what: "a YAML document past a bound: depth, alias expansions, nodes or documents",
                }
            } else {
                ParseError::Malformed {
                    offset: e.location().map_or(0, |l| l.index().min(input.len())),
                    reason: "YAML that doesn't parse",
                }
            }
        })?;
        match value {
            BorrowedValue::Mapping(_) => {
                let mut tree = Tree::new(out, input.len());
                let walked = walk(&mut tree, value);
                tree.finish(walked)?;
                Ok(Parsed::Done)
            }
            BorrowedValue::Null => Ok(Parsed::Done),
            _ => Ok(Parsed::NoMatch),
        }
    }
}

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

    /// A field as written: name, text, hint, and whether it was borrowed.
    type Row = (String, String, Hint, bool);

    fn read(doc: &str) -> (Result<Parsed, ParseError>, Vec<Row>) {
        let mut out = Fields::new();
        out.field("kept", FieldValue::borrowed(b"1", Hint::Int));
        let got = Yaml::new().parse(doc.as_bytes(), &mut out);
        out.field("after", FieldValue::borrowed(b"1", Hint::Int));
        let rows: Vec<Row> = out
            .as_slice()
            .iter()
            .map(|(n, v)| {
                let borrowed = matches!(v.bytes, Cow::Borrowed(_));
                (
                    n.clone(),
                    String::from_utf8_lossy(&v.bytes).into_owned(),
                    v.hint,
                    borrowed,
                )
            })
            .collect();
        assert_eq!(rows.first().map(|r| r.0.as_str()), Some("kept"));
        assert_eq!(
            rows.last().map(|r| r.0.as_str()),
            Some("after"),
            "prefixes popped"
        );
        (got, rows[1..rows.len() - 1].to_vec())
    }

    #[test]
    fn documents_read_into_fields_or_fail_whole() {
        use Hint::{Bool, Float, Int, Text};
        type Want = Result<&'static [(&'static str, &'static str, Hint)], &'static str>;
        let cases: &[(&str, Want)] = &[
            (
                "host:\n  name: web01\n  ip: [10.0.0.1, 'fe80::1']\nlevel: info\nn: 1.50\nk: 0x1F\nok: true\ngone: ~\nmsg: \"a \\\"q\\\" word\"\n",
                Ok(&[
                    ("host.name", "web01", Text),
                    ("host.ip", "10.0.0.1", Text),
                    ("host.ip", "fe80::1", Text),
                    ("level", "info", Text),
                    ("n", "1.5", Float),
                    ("k", "31", Int),
                    ("ok", "true", Bool),
                    ("msg", "a \"q\" word", Text),
                ]),
            ),
            (
                "a.b: 1\nlist:\n  - {x: 1}\n  - [2, [3]]\n  - !!str 4\nlit: |\n  two\n  lines\n",
                Ok(&[
                    ("[\"a.b\"]", "1", Int),
                    ("list.x", "1", Int),
                    ("list", "2", Int),
                    ("list", "3", Int),
                    ("list", "4", Text),
                    ("lit", "two\nlines\n", Text),
                ]),
            ),
            (
                "base: &b {port: 80}\nweb: *b\ninf: .inf\n",
                Ok(&[
                    ("base.port", "80", Int),
                    ("web.port", "80", Int),
                    ("inf", "inf", Text),
                ]),
            ),
            ("--- \nk: v\n...\n", Ok(&[("k", "v", Text)])),
            ("", Ok(&[])),
            ("# only a comment\n", Ok(&[])),
            ("just text", Err("no match")),
            ("- a\n- b\n", Err("no match")),
            ("k: [1, 2\n", Err("malformed")),
            ("k: v\n  bad: indent\n", Err("malformed")),
            ("a: *nowhere\n", Err("malformed")),
            ("a: 1\n---\nb: 2\n", Err("limit")),
        ];
        for &(doc, want) in cases {
            let (got, rows) = read(doc);
            match (got, want) {
                (Ok(Parsed::Done), Ok(want)) => {
                    let rows: Vec<(&str, &str, Hint)> = rows
                        .iter()
                        .map(|r| (r.0.as_str(), r.1.as_str(), r.2))
                        .collect();
                    assert_eq!(rows, want, "{doc:?}");
                }
                (Ok(Parsed::NoMatch), Err("no match"))
                | (Err(ParseError::Malformed { .. }), Err("malformed"))
                | (Err(ParseError::Limit { .. }), Err("limit")) => {
                    assert!(rows.is_empty(), "{doc:?} wrote {rows:?}");
                }
                (got, want) => panic!("{doc:?}: {got:?}, want {want:?}"),
            }
        }
    }

    #[test]
    fn a_plain_string_is_borrowed() {
        let (got, rows) = read("a: plain\nb: \"esc\\tape\"\n");
        assert!(matches!(got, Ok(Parsed::Done)));
        let borrowed: Vec<bool> = rows.iter().map(|r| r.3).collect();
        assert_eq!(borrowed, [true, false]);
    }

    /// A billion-laughs document and one nested past the bound are limits,
    /// with nothing written.
    #[test]
    fn expansion_and_depth_are_bounded() {
        let mut laughs = String::from("a: &a [x, x, x, x, x, x, x, x, x, x]\n");
        for level in 1..12 {
            let prev = char::from(b'a' + level - 1);
            let name = char::from(b'a' + level);
            let refs = vec![format!("*{prev}"); 10].join(", ");
            laughs.push_str(&[name.to_string(), format!(": &{name} [{refs}]\n")].concat());
        }
        let at = |levels: usize| {
            let mut doc = String::new();
            for i in 0..levels {
                doc.push_str(&"  ".repeat(i));
                doc.push_str("k:\n");
            }
            doc.push_str(&"  ".repeat(levels));
            doc.push_str("v: 1\n");
            doc
        };
        assert!(matches!(read(&at(MAX_DEPTH - 2)).0, Ok(Parsed::Done)));
        for doc in [laughs, at(MAX_DEPTH + 1), at(500)] {
            let (got, rows) = read(&doc);
            assert!(matches!(got, Err(ParseError::Limit { .. })), "{got:?}");
            assert_eq!(rows.len(), 0);
        }
    }

    #[test]
    fn bad_bytes_fail_before_any_field() {
        let mut out = Fields::new();
        let got = Yaml::new().parse(b"k: \xff\n", &mut out);
        assert!(matches!(got, Err(ParseError::Malformed { offset: 3, .. })));
        assert!(out.is_empty());
    }
}