nmbrs-workload 0.7.3

Uniform workload specification parsing and processing for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The pieces of an op field's text.
//!
//! Every reader of op-field text divides it the same way, with
//! [`pieces`]: the bind-point scanner
//! ([`extract_bind_points`](crate::bindpoints::extract_bind_points)),
//! the scope resolver that writes phase-constant values into a field,
//! and the renderers that produce the text an adapter sends. One
//! division means a brace is a bind point to all of them or to none.
//!
//! The rules, in the order they are tried at each position:
//!
//! 1. `\{` and `\}` are one literal brace ([`Piece::Brace`]). A
//!    backslash before anything else is an ordinary character.
//! 2. `{{ … }}` is an inline expression ([`Piece::Inline`]).
//! 3. `{` whose next character, after any whitespace, is `'` or `"`
//!    is a literal brace: the opening of a CQL map or a JSON object.
//!    The text after it is still scanned, so a bind point inside the
//!    map is found.
//! 4. `{ … }` with balanced braces and a body that is not blank is a
//!    group ([`Piece::Group`]). What a group means is decided by
//!    [`classify_group`](crate::bindpoints::classify_group).
//! 5. Any other `{` (no closing brace, or a blank body) is literal.
//!
//! A reader that passes text on to a later reader carries
//! [`Piece::Brace`] as it was written ([`Piece::as_written`]), so the
//! later reader still sees an escape. The reader that produces final
//! text writes the brace alone; [`unescape`] does that for a field
//! that holds no bind points.

use std::borrow::Cow;

/// One piece of an op field's text. See the module documentation for
/// the rules that divide a text into pieces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Piece<'a> {
    /// Text that holds no escape and no bind point.
    Text(&'a str),
    /// `\{` or `\}`: the brace it stands for.
    Brace(char),
    /// `{{ … }}`: the whole of it as written, and its trimmed body.
    Inline { raw: &'a str, body: &'a str },
    /// `{ … }`: the whole of it as written, and its trimmed body.
    Group { raw: &'a str, body: &'a str },
}

impl Piece<'_> {
    /// Append this piece as it was written in the field.
    pub fn as_written(&self, out: &mut String) {
        match self {
            Piece::Text(text) => out.push_str(text),
            Piece::Brace(brace) => {
                out.push('\\');
                out.push(*brace);
            }
            Piece::Inline { raw, .. } | Piece::Group { raw, .. } => out.push_str(raw),
        }
    }
}

/// True when `bytes[at..]` starts with `\{` or `\}`.
fn is_escape(bytes: &[u8], at: usize) -> bool {
    bytes[at] == b'\\' && matches!(bytes.get(at + 1), Some(b'{') | Some(b'}'))
}

/// The index of the `}` that closes the `{` at `open`, counting
/// nested braces and passing over escaped ones.
fn closing_brace(bytes: &[u8], open: usize) -> Option<usize> {
    let mut depth = 1u32;
    let mut at = open + 1;
    while at < bytes.len() {
        if is_escape(bytes, at) {
            at += 2;
            continue;
        }
        match bytes[at] {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(at);
                }
            }
            _ => {}
        }
        at += 1;
    }
    None
}

/// Divide an op field's text into its pieces.
///
/// The pieces, written back with [`Piece::as_written`], are the text.
pub fn pieces(text: &str) -> Vec<Piece<'_>> {
    let bytes = text.as_bytes();
    let end = bytes.len();
    let mut out = Vec::new();
    // Where the literal text not yet pushed begins.
    let mut literal = 0;
    let mut at = 0;
    while at < end {
        if is_escape(bytes, at) {
            if literal < at {
                out.push(Piece::Text(&text[literal..at]));
            }
            out.push(Piece::Brace(bytes[at + 1] as char));
            at += 2;
            literal = at;
            continue;
        }
        if bytes[at] != b'{' {
            at += 1;
            continue;
        }
        if bytes.get(at + 1) == Some(&b'{') {
            let Some(close) = text[at + 2..].find("}}").map(|offset| at + 2 + offset) else {
                // No `}}`: the rest of the text is literal.
                break;
            };
            if literal < at {
                out.push(Piece::Text(&text[literal..at]));
            }
            out.push(Piece::Inline {
                raw: &text[at..close + 2],
                body: text[at + 2..close].trim(),
            });
            at = close + 2;
            literal = at;
            continue;
        }
        let next = text[at + 1..].chars().find(|c| !c.is_whitespace());
        if matches!(next, Some('\'') | Some('"')) {
            at += 1;
            continue;
        }
        let Some(close) = closing_brace(bytes, at) else {
            at += 1;
            continue;
        };
        let body = text[at + 1..close].trim();
        if body.is_empty() {
            at = close + 1;
            continue;
        }
        if literal < at {
            out.push(Piece::Text(&text[literal..at]));
        }
        out.push(Piece::Group {
            raw: &text[at..=close],
            body,
        });
        at = close + 1;
        literal = at;
    }
    if literal < end {
        out.push(Piece::Text(&text[literal..]));
    }
    out
}

/// The final text of a field that holds no bind points: each `\{` and
/// `\}` becomes the brace alone, and everything else is kept.
///
/// For an adapter that reads a field itself instead of rendering it.
/// A field that does hold bind points is rendered by the adapter's
/// renderer, which writes the escaped braces the same way.
pub fn unescape(text: &str) -> Cow<'_, str> {
    if !text.contains('\\') {
        return Cow::Borrowed(text);
    }
    let pieces = pieces(text);
    if !pieces.iter().any(|piece| matches!(piece, Piece::Brace(_))) {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len());
    for piece in &pieces {
        match piece {
            Piece::Brace(brace) => out.push(*brace),
            other => other.as_written(&mut out),
        }
    }
    Cow::Owned(out)
}

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

    fn written(text: &str) -> String {
        let mut out = String::new();
        for piece in pieces(text) {
            piece.as_written(&mut out);
        }
        out
    }

    #[test]
    fn the_pieces_written_back_are_the_text() {
        for text in [
            "",
            "plain",
            "a {name} b {{hash(cycle)}} c",
            r"^\d\{8\}-{node}\.log$",
            "WITH compaction = {\n  'class': '{strategy}'\n}",
            "open { and {} and {  } and {{ unclosed",
            "{k_{k}_limits}",
            r"C:\dir\file and \\{name}",
        ] {
            assert_eq!(written(text), text);
        }
    }

    #[test]
    fn an_escaped_brace_is_a_brace_and_not_a_group() {
        assert_eq!(
            pieces(r"\d\{8\} {node}"),
            vec![
                Piece::Text(r"\d"),
                Piece::Brace('{'),
                Piece::Text("8"),
                Piece::Brace('}'),
                Piece::Text(" "),
                Piece::Group {
                    raw: "{node}",
                    body: "node"
                },
            ]
        );
    }

    #[test]
    fn a_backslash_before_anything_else_is_text() {
        assert_eq!(pieces(r"a\nb\\c"), vec![Piece::Text(r"a\nb\\c")]);
    }

    #[test]
    fn an_escaped_brace_inside_a_group_does_not_close_it() {
        assert_eq!(
            pieces(r#"{f("\}")}"#),
            vec![Piece::Group {
                raw: r#"{f("\}")}"#,
                body: r#"f("\}")"#
            }]
        );
    }

    #[test]
    fn a_brace_before_a_quote_is_literal_and_the_map_is_still_scanned() {
        assert_eq!(
            pieces("{ 'class': '{strategy}' }"),
            vec![
                Piece::Text("{ 'class': '"),
                Piece::Group {
                    raw: "{strategy}",
                    body: "strategy"
                },
                Piece::Text("' }"),
            ]
        );
    }

    #[test]
    fn an_inline_expression_keeps_its_body() {
        assert_eq!(
            pieces("v={{ mod(cycle, 10) }}"),
            vec![
                Piece::Text("v="),
                Piece::Inline {
                    raw: "{{ mod(cycle, 10) }}",
                    body: "mod(cycle, 10)"
                },
            ]
        );
    }

    #[test]
    fn unescape_writes_braces_alone_and_keeps_bind_points() {
        assert_eq!(unescape(r"^\d\{2,3\}$"), r"^\d{2,3}$");
        assert_eq!(unescape(r"\{{name}\}"), "{{name}}");
        assert!(matches!(unescape(r"a\nb"), Cow::Borrowed(_)));
    }
}