grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/toml.rs
// Purpose:   The TOML parser: one document an input into fields
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One TOML document an input, its fields named as `ndjson` names them.
//!
//! A table's keys join it with `.`, and an array writes each element under its
//! key, so `[[server]]` tables write `server.<key>` once each.
//!
//! TOML is config, read once, so it goes through the `toml` crate rather than
//! one of grippo's own scanners: it doesn't need the speed. A table's keys
//! come out in key order, not file order. A string that holds no escape is
//! borrowed. An integer in hex, octal or binary is written in decimal, a date
//! or time is hinted `Timestamp` as TOML writes it, and `inf` and `nan` are
//! text.

use std::borrow::Cow;

use ::toml::de::{DeInteger, DeTable, DeValue};

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

/// The TOML parser, registered as `toml`.
#[derive(Debug, Clone)]
pub struct Toml {
    signature: Signature,
}

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

impl Toml {
    /// A TOML 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"));
        Self { signature }
    }
}

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

/// An integer in decimal, or its digits as text when it doesn't fit `i64`.
fn integer(n: &DeInteger<'_>) -> FieldValue<'static> {
    i64::from_str_radix(n.as_str(), n.radix()).map_or_else(
        |_| FieldValue::owned(n.to_string().into_bytes(), Hint::Text),
        |i| FieldValue::owned(i.to_string().into_bytes(), Hint::Int),
    )
}

fn walk<'a>(tree: &mut Tree<'_, 'a>, value: DeValue<'a>) -> Result<(), ParseError> {
    match value {
        DeValue::String(s) => tree.scalar(text(s, Hint::Text))?,
        DeValue::Integer(n) if n.radix() == 10 => {
            let digits = n.as_str();
            let value = if digits.parse::<i64>().is_ok() {
                FieldValue::owned(digits.as_bytes().to_vec(), Hint::Int)
            } else {
                integer(&n)
            };
            tree.scalar(value)?;
        }
        DeValue::Integer(n) => tree.scalar(integer(&n))?,
        DeValue::Float(f) => {
            let digits = f.as_str();
            let hint = if digits.ends_with("inf") || digits.ends_with("nan") {
                Hint::Text
            } else {
                Hint::Float
            };
            tree.scalar(FieldValue::owned(digits.as_bytes().to_vec(), hint))?;
        }
        DeValue::Boolean(b) => {
            let text: &'static [u8] = if b { b"true" } else { b"false" };
            tree.scalar(FieldValue::borrowed(text, Hint::Bool))?;
        }
        DeValue::Datetime(d) => {
            tree.scalar(FieldValue::owned(
                d.to_string().into_bytes(),
                Hint::Timestamp,
            ))?;
        }
        DeValue::Array(items) => {
            tree.open_list()?;
            for item in items {
                walk(tree, item.into_inner())?;
            }
            tree.close();
        }
        DeValue::Table(table) => {
            tree.open_map()?;
            entries(tree, table)?;
            tree.close();
        }
    }
    Ok(())
}

fn entries<'a>(tree: &mut Tree<'_, 'a>, table: DeTable<'a>) -> Result<(), ParseError> {
    for (key, value) in table {
        tree.key(key.into_inner());
        walk(tree, value.into_inner())?;
    }
    Ok(())
}

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

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

    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: "TOML that isn't UTF-8",
        })?;
        let table = DeTable::parse(doc).map_err(|e| ParseError::Malformed {
            offset: e.span().map_or(0, |s| s.start.min(input.len())),
            reason: "TOML that doesn't parse",
        })?;
        let mut tree = Tree::new(out, input.len());
        let walked = tree
            .open_map()
            .and_then(|()| entries(&mut tree, table.into_inner()));
        tree.finish(walked)?;
        Ok(Parsed::Done)
    }
}

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

    fn read(doc: &str) -> (Result<Parsed, ParseError>, Vec<(String, String, Hint)>) {
        let mut out = Fields::new();
        out.push_prefix("outer.");
        let got = Toml::new().parse(doc.as_bytes(), &mut out);
        out.pop_prefix();
        out.field("after", FieldValue::borrowed(b"1", Hint::Int));
        let mut rows: Vec<(String, String, Hint)> = out
            .as_slice()
            .iter()
            .map(|(n, v)| {
                (
                    n.clone(),
                    String::from_utf8_lossy(&v.bytes).into_owned(),
                    v.hint,
                )
            })
            .collect();
        assert_eq!(
            rows.pop().map(|r| r.0),
            Some("after".to_owned()),
            "prefixes popped"
        );
        (got, rows)
    }

    #[test]
    fn documents_read_into_fields_or_fail_whole() {
        use Hint::{Bool, Float, Int, Text, Timestamp};
        type Want = Result<&'static [(&'static str, &'static str, Hint)], &'static str>;
        let cases: &[(&str, Want)] = &[
            (
                "title = \"web\"\nport = 8_080\nhex = 0x1F\nratio = 1.50\nup = true\nwhen = 1979-05-27T07:32:00Z\n\n[server]\nhost = 'h\\1'\nips = [\"10.0.0.1\", \"fe80::1\"]\n\n[server.\"a.b\"]\nk = -1\n",
                Ok(&[
                    ("outer.hex", "31", Int),
                    ("outer.port", "8080", Int),
                    ("outer.ratio", "1.50", Float),
                    ("outer.server[\"a.b\"].k", "-1", Int),
                    ("outer.server.host", "h\\1", Text),
                    ("outer.server.ips", "10.0.0.1", Text),
                    ("outer.server.ips", "fe80::1", Text),
                    ("outer.title", "web", Text),
                    ("outer.up", "true", Bool),
                    ("outer.when", "1979-05-27T07:32:00Z", Timestamp),
                ]),
            ),
            (
                "[[srv]]\nn = 1\n[[srv]]\nn = 2\nt = { a = [[1], {b = 'x'}] }\nf = inf\nbig = 0xFFFFFFFFFFFFFFFF\n",
                Ok(&[
                    ("outer.srv.n", "1", Int),
                    ("outer.srv.big", "0xFFFFFFFFFFFFFFFF", Text),
                    ("outer.srv.f", "inf", Text),
                    ("outer.srv.n", "2", Int),
                    ("outer.srv.t.a", "1", Int),
                    ("outer.srv.t.a.b", "x", Text),
                ]),
            ),
            ("", Ok(&[])),
            ("# just a comment\n", Ok(&[])),
            ("k = \n", Err("malformed")),
            ("k = 1\nk = 2\n", Err("malformed")),
            ("[a\nk=1\n", Err("malformed")),
            ("just text", Err("malformed")),
        ];
        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:?}");
                }
                (Err(ParseError::Malformed { offset, .. }), Err("malformed")) => {
                    assert!(offset <= doc.len());
                    assert!(rows.is_empty(), "{doc:?} wrote {rows:?}");
                }
                (got, want) => panic!("{doc:?}: {got:?}, want {want:?}"),
            }
        }
    }

    #[test]
    fn a_plain_string_is_borrowed_and_nesting_is_bounded() {
        let mut out = Fields::new();
        Toml::new()
            .parse(b"a = 'x'\nb = \"e\\tx\"\n", &mut out)
            .unwrap();
        let borrowed: Vec<bool> = out
            .as_slice()
            .iter()
            .map(|(_, v)| matches!(v.bytes, Cow::Borrowed(_)))
            .collect();
        assert_eq!(borrowed, [true, false]);
        let deep = format!("a = {}1{}\n", "[".repeat(70), "]".repeat(70));
        let mut out = Fields::new();
        let got = Toml::new().parse(deep.as_bytes(), &mut out);
        assert!(
            matches!(
                got,
                Err(ParseError::Limit { .. } | ParseError::Malformed { .. })
            ),
            "{got:?}"
        );
        assert!(out.is_empty());
    }
}