isis-report-lib 0.2.2

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
//! Parser for the `.toon` text format.
//!
//! The grammar is intentionally small and forgiving, matching the Python
//! parser: two spaces per nesting level, `key: value`, `key:` blocks,
//! `key[n]:` arrays, `key[n]{a,b}:` arrays of objects, compact layout fields
//! `key{Label,format,align[,aggregate]}` and the legacy `dados[n]:` alias.

use std::sync::LazyLock;

use indexmap::IndexMap;
use regex::Regex;

use crate::error::{Error, Result};
use crate::pyops;
use crate::value::Value;

const MAX_DEPTH: usize = 256;

static ARRAY_OBJECTS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\w+)\[(\d+)\]\{([^}]+)\}:$").expect("valid toon array-of-objects regex"));
static ARRAY_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\w+)\[(\d+)\]:$").expect("valid toon array regex"));
static FIELD_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\w+)\{([^,]+),([^,]+),([^,}]+)(?:,([^,}]+))?\}$").expect("valid toon field regex"));
static KEY_VALUE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^([^:]+):\s*(.*)$").expect("valid toon key/value regex"));

#[derive(Debug, Clone)]
struct Token {
    level: usize,
    content: String,
}

/// Parser for `.toon` text.
#[derive(Debug, Default, Clone, Copy)]
pub struct ToonParser;

impl ToonParser {
    /// Create a parser.
    pub fn new() -> Self {
        Self
    }

    /// Parse TOON text into a payload value.
    pub fn parse(&self, text: &str) -> Result<Value> {
        let tokens = tokenize(text);
        let mut index = 0usize;
        let result = parse_dict(&tokens, &mut index, 0, 0)?;
        let mut object = result;
        if object.contains_key("dados") && !object.contains_key("data") {
            if let Some(value) = object.shift_remove("dados") {
                object.insert("data".to_string(), value);
            }
        }
        Ok(Value::Object(object))
    }
}

/// Functional shortcut for `ToonParser::new().parse(text)`.
pub fn parse_toon(text: &str) -> Result<Value> {
    ToonParser.parse(text)
}

fn tokenize(text: &str) -> Vec<Token> {
    let mut tokens = Vec::new();
    for line in text.split('\n') {
        let stripped = line.trim_end();
        let content = stripped.trim();
        if content.is_empty() {
            continue;
        }
        let indent = line.chars().take_while(|ch| ch.is_whitespace()).count();
        tokens.push(Token {
            level: indent / 2,
            content: content.to_string(),
        });
    }
    tokens
}

pub(crate) fn convert_value(value: &str) -> Value {
    let trimmed = value.trim();
    if trimmed.eq_ignore_ascii_case("true") {
        return Value::Bool(true);
    }
    if trimmed.eq_ignore_ascii_case("false") {
        return Value::Bool(false);
    }
    if let Ok(value) = pyops::parse_py_int(trimmed) {
        return Value::Int(value);
    }
    if let Ok(value) = pyops::parse_py_float(trimmed) {
        return Value::Float(value);
    }
    Value::String(trimmed.to_string())
}

fn split_fields(value: &str) -> Vec<String> {
    value.split(',').map(|field| field.trim().to_string()).collect()
}

fn parse_dict(tokens: &[Token], index: &mut usize, level: usize, depth: usize) -> Result<IndexMap<String, Value>> {
    if depth > MAX_DEPTH {
        return Err(Error::payload("Input is nested too deeply to parse"));
    }
    let mut result = IndexMap::new();
    while *index < tokens.len() {
        let token = &tokens[*index];
        if token.level < level {
            break;
        }
        if token.level > level {
            *index += 1;
            continue;
        }
        if token.content.starts_with("- ") {
            *index += 1;
            continue;
        }

        if let Some(captures) = ARRAY_OBJECTS_RE.captures(&token.content) {
            let key = captures.get(1).map(|m| m.as_str()).unwrap_or_default().to_string();
            let fields = split_fields(captures.get(3).map(|m| m.as_str()).unwrap_or_default());
            let token_level = token.level;
            let mut array = Vec::new();
            *index += 1;
            while *index < tokens.len() && tokens[*index].level > token_level {
                let values: Vec<Value> = tokens[*index].content.split(',').map(convert_value).collect();
                if values.len() != fields.len() {
                    return Err(Error::payload(
                        "Invalid .toon array row: value count does not match the declared fields",
                    ));
                }
                let mut object = IndexMap::new();
                for (field, value) in fields.iter().zip(values) {
                    object.insert(field.clone(), value);
                }
                array.push(Value::Object(object));
                *index += 1;
            }
            result.insert(key, Value::Array(array));
            continue;
        }

        if let Some(captures) = ARRAY_RE.captures(&token.content) {
            let key = captures.get(1).map(|m| m.as_str()).unwrap_or_default().to_string();
            let token_level = token.level;
            *index += 1;
            let array = parse_array(tokens, index, token_level + 1, depth + 1)?;
            result.insert(key, Value::Array(array));
            continue;
        }

        if let Some(captures) = FIELD_RE.captures(&token.content) {
            let key = captures.get(1).map(|m| m.as_str()).unwrap_or_default().to_string();
            let mut field = IndexMap::new();
            field.insert(
                "label".to_string(),
                Value::String(captures.get(2).map(|m| m.as_str()).unwrap_or_default().trim().to_string()),
            );
            field.insert(
                "format_mask".to_string(),
                Value::String(captures.get(3).map(|m| m.as_str()).unwrap_or_default().trim().to_string()),
            );
            field.insert(
                "alignment".to_string(),
                Value::String(captures.get(4).map(|m| m.as_str()).unwrap_or_default().trim().to_string()),
            );
            if let Some(aggregate) = captures.get(5) {
                field.insert("aggregate".to_string(), Value::String(aggregate.as_str().trim().to_string()));
            }
            result.insert(key, Value::Object(field));
            *index += 1;
            continue;
        }

        if let Some(captures) = KEY_VALUE_RE.captures(&token.content) {
            let key = captures.get(1).map(|m| m.as_str()).unwrap_or_default().trim().to_string();
            let value = captures.get(2).map(|m| m.as_str()).unwrap_or_default().trim();
            if !value.is_empty() {
                result.insert(key, convert_value(value));
                *index += 1;
            } else {
                let token_level = token.level;
                if *index + 1 < tokens.len() && tokens[*index + 1].level > token_level {
                    *index += 1;
                    let sub = parse_dict(tokens, index, token_level + 1, depth + 1)?;
                    result.insert(key, Value::Object(sub));
                } else {
                    result.insert(key, Value::Object(IndexMap::new()));
                    *index += 1;
                }
            }
            continue;
        }

        *index += 1;
    }
    Ok(result)
}

fn parse_array(tokens: &[Token], index: &mut usize, level: usize, depth: usize) -> Result<Vec<Value>> {
    if depth > MAX_DEPTH {
        return Err(Error::payload("Input is nested too deeply to parse"));
    }
    let mut result = Vec::new();
    while *index < tokens.len() {
        let token = &tokens[*index];
        if token.level < level {
            break;
        }
        if token.level > level {
            *index += 1;
            continue;
        }
        if !token.content.starts_with("- ") {
            *index += 1;
            continue;
        }
        let item_text = token.content[2..].trim();
        let token_level = token.level;
        let mut item: Value;
        if let Some(captures) = KEY_VALUE_RE.captures(item_text) {
            let key = captures.get(1).map(|m| m.as_str()).unwrap_or_default().trim().to_string();
            let value = captures.get(2).map(|m| m.as_str()).unwrap_or_default().trim();
            let mut object = IndexMap::new();
            if !value.is_empty() {
                object.insert(key, convert_value(value));
            } else {
                let mut sub = IndexMap::new();
                if *index + 1 < tokens.len() && tokens[*index + 1].level > token_level {
                    *index += 1;
                    sub = parse_dict(tokens, index, token_level + 1, depth + 1)?;
                }
                object.insert(key, Value::Object(sub));
            }
            item = Value::Object(object);
        } else {
            *index += 1;
            result.push(convert_value(item_text));
            continue;
        }

        *index += 1;
        if *index < tokens.len() && tokens[*index].level == token_level + 1 {
            let extra = parse_dict(tokens, index, token_level + 1, depth + 1)?;
            if let Value::Object(object) = &mut item {
                for (key, value) in extra {
                    object.insert(key, value);
                }
            }
        }
        result.push(item);
    }
    Ok(result)
}

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

    fn parse(text: &str) -> serde_json::Value {
        parse_toon(text).unwrap().to_json()
    }

    #[test]
    fn simple_key_value_and_coercion() {
        assert_eq!(
            parse("a: 1\nb: 2.5\nc: true\nd: false\ne: text"),
            json!({"a": 1, "b": 2.5, "c": true, "d": false, "e": "text"})
        );
    }

    #[test]
    fn compact_layout_field() {
        assert_eq!(
            parse("layout:\n  product{Product,str,left}"),
            json!({"layout": {"product": {"label": "Product", "format_mask": "str", "alignment": "left"}}})
        );
        assert_eq!(
            parse("layout:\n  total{Total,float,right,sum}"),
            json!({"layout": {"total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"}}})
        );
    }

    #[test]
    fn array_of_objects() {
        assert_eq!(
            parse("items[2]{qty,price}:\n  1,1500\n  2,1000"),
            json!({"items": [{"qty": 1, "price": 1500}, {"qty": 2, "price": 1000}]})
        );
    }

    #[test]
    fn arrays_and_data_alias() {
        assert_eq!(parse("data[1]:\n  - product: Pen"), json!({"data": [{"product": "Pen"}]}));
        assert_eq!(parse("dados[1]:\n  - produto: Caneta"), json!({"data": [{"produto": "Caneta"}]}));
        assert_eq!(parse("a[2]:\n  - x: 1\n  - y: 2\nb: 3"), json!({"a": [{"x": 1}, {"y": 2}], "b": 3}));
        assert_eq!(
            parse("items[1]:\n  - address:\n    city: Rome"),
            json!({"items": [{"address": {"city": "Rome"}}]})
        );
        assert_eq!(parse("nums[2]:\n  - 42\n  - 7"), json!({"nums": [42, 7]}));
    }

    #[test]
    fn tolerant_input() {
        assert_eq!(parse("a: 1\n    stray deep\nb: 2"), json!({"a": 1, "b": 2}));
        assert_eq!(parse("a: 1\n- orphan\nb: 2"), json!({"a": 1, "b": 2}));
        assert_eq!(parse("a: 1\n???\nb: 2"), json!({"a": 1, "b": 2}));
        assert_eq!(parse("a: 1\nempty:"), json!({"a": 1, "empty": {}}));
        assert_eq!(
            parse("a[1]:\n  - x: 1\n      deep: junk\n  - y: 2"),
            json!({"a": [{"x": 1}, {"y": 2}]})
        );
        assert_eq!(parse("a[1]:\n  - x: 1\n  trailing: x"), json!({"a": [{"x": 1}]}));
    }

    #[test]
    fn deeply_nested_input_fails_closed() {
        let deep: String = (0..5000).map(|index| format!("{}level{index}:\n", "  ".repeat(index))).collect();
        let error = parse_toon(&deep).unwrap_err();
        assert!(error.to_string().contains("nested too deeply"));
    }

    #[test]
    fn full_example_file() {
        let text = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../..")
                .join("isis-report-lib")
                .join("examples")
                .join("sales_order.toon"),
        );
        // The example lives in the Python reference checkout; this test is
        // ignored when the fixture is not present.
        if let Ok(text) = text {
            let value = parse_toon(&text).unwrap();
            assert_eq!(
                value.get("meta").and_then(|m| m.get("title")).and_then(Value::as_str),
                Some("Sales Order")
            );
            assert!(value.get("data").is_some());
        }
    }
}