Skip to main content

nmbrs_workload/
op_text.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The pieces of an op field's text.
5//!
6//! Every reader of op-field text divides it the same way, with
7//! [`pieces`]: the bind-point scanner
8//! ([`extract_bind_points`](crate::bindpoints::extract_bind_points)),
9//! the scope resolver that writes phase-constant values into a field,
10//! and the renderers that produce the text an adapter sends. One
11//! division means a brace is a bind point to all of them or to none.
12//!
13//! The rules, in the order they are tried at each position:
14//!
15//! 1. `\{` and `\}` are one literal brace ([`Piece::Brace`]). A
16//!    backslash before anything else is an ordinary character.
17//! 2. `{{ … }}` is an inline expression ([`Piece::Inline`]).
18//! 3. `{` whose next character, after any whitespace, is `'` or `"`
19//!    is a literal brace: the opening of a CQL map or a JSON object.
20//!    The text after it is still scanned, so a bind point inside the
21//!    map is found.
22//! 4. `{ … }` with balanced braces and a body that is not blank is a
23//!    group ([`Piece::Group`]). What a group means is decided by
24//!    [`classify_group`](crate::bindpoints::classify_group).
25//! 5. Any other `{` (no closing brace, or a blank body) is literal.
26//!
27//! A reader that passes text on to a later reader carries
28//! [`Piece::Brace`] as it was written ([`Piece::as_written`]), so the
29//! later reader still sees an escape. The reader that produces final
30//! text writes the brace alone; [`unescape`] does that for a field
31//! that holds no bind points.
32
33use std::borrow::Cow;
34
35/// One piece of an op field's text. See the module documentation for
36/// the rules that divide a text into pieces.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Piece<'a> {
39    /// Text that holds no escape and no bind point.
40    Text(&'a str),
41    /// `\{` or `\}`: the brace it stands for.
42    Brace(char),
43    /// `{{ … }}`: the whole of it as written, and its trimmed body.
44    Inline { raw: &'a str, body: &'a str },
45    /// `{ … }`: the whole of it as written, and its trimmed body.
46    Group { raw: &'a str, body: &'a str },
47}
48
49impl Piece<'_> {
50    /// Append this piece as it was written in the field.
51    pub fn as_written(&self, out: &mut String) {
52        match self {
53            Piece::Text(text) => out.push_str(text),
54            Piece::Brace(brace) => {
55                out.push('\\');
56                out.push(*brace);
57            }
58            Piece::Inline { raw, .. } | Piece::Group { raw, .. } => out.push_str(raw),
59        }
60    }
61}
62
63/// True when `bytes[at..]` starts with `\{` or `\}`.
64fn is_escape(bytes: &[u8], at: usize) -> bool {
65    bytes[at] == b'\\' && matches!(bytes.get(at + 1), Some(b'{') | Some(b'}'))
66}
67
68/// The index of the `}` that closes the `{` at `open`, counting
69/// nested braces and passing over escaped ones.
70fn closing_brace(bytes: &[u8], open: usize) -> Option<usize> {
71    let mut depth = 1u32;
72    let mut at = open + 1;
73    while at < bytes.len() {
74        if is_escape(bytes, at) {
75            at += 2;
76            continue;
77        }
78        match bytes[at] {
79            b'{' => depth += 1,
80            b'}' => {
81                depth -= 1;
82                if depth == 0 {
83                    return Some(at);
84                }
85            }
86            _ => {}
87        }
88        at += 1;
89    }
90    None
91}
92
93/// Divide an op field's text into its pieces.
94///
95/// The pieces, written back with [`Piece::as_written`], are the text.
96pub fn pieces(text: &str) -> Vec<Piece<'_>> {
97    let bytes = text.as_bytes();
98    let end = bytes.len();
99    let mut out = Vec::new();
100    // Where the literal text not yet pushed begins.
101    let mut literal = 0;
102    let mut at = 0;
103    while at < end {
104        if is_escape(bytes, at) {
105            if literal < at {
106                out.push(Piece::Text(&text[literal..at]));
107            }
108            out.push(Piece::Brace(bytes[at + 1] as char));
109            at += 2;
110            literal = at;
111            continue;
112        }
113        if bytes[at] != b'{' {
114            at += 1;
115            continue;
116        }
117        if bytes.get(at + 1) == Some(&b'{') {
118            let Some(close) = text[at + 2..].find("}}").map(|offset| at + 2 + offset) else {
119                // No `}}`: the rest of the text is literal.
120                break;
121            };
122            if literal < at {
123                out.push(Piece::Text(&text[literal..at]));
124            }
125            out.push(Piece::Inline {
126                raw: &text[at..close + 2],
127                body: text[at + 2..close].trim(),
128            });
129            at = close + 2;
130            literal = at;
131            continue;
132        }
133        let next = text[at + 1..].chars().find(|c| !c.is_whitespace());
134        if matches!(next, Some('\'') | Some('"')) {
135            at += 1;
136            continue;
137        }
138        let Some(close) = closing_brace(bytes, at) else {
139            at += 1;
140            continue;
141        };
142        let body = text[at + 1..close].trim();
143        if body.is_empty() {
144            at = close + 1;
145            continue;
146        }
147        if literal < at {
148            out.push(Piece::Text(&text[literal..at]));
149        }
150        out.push(Piece::Group {
151            raw: &text[at..=close],
152            body,
153        });
154        at = close + 1;
155        literal = at;
156    }
157    if literal < end {
158        out.push(Piece::Text(&text[literal..]));
159    }
160    out
161}
162
163/// The final text of a field that holds no bind points: each `\{` and
164/// `\}` becomes the brace alone, and everything else is kept.
165///
166/// For an adapter that reads a field itself instead of rendering it.
167/// A field that does hold bind points is rendered by the adapter's
168/// renderer, which writes the escaped braces the same way.
169pub fn unescape(text: &str) -> Cow<'_, str> {
170    if !text.contains('\\') {
171        return Cow::Borrowed(text);
172    }
173    let pieces = pieces(text);
174    if !pieces.iter().any(|piece| matches!(piece, Piece::Brace(_))) {
175        return Cow::Borrowed(text);
176    }
177    let mut out = String::with_capacity(text.len());
178    for piece in &pieces {
179        match piece {
180            Piece::Brace(brace) => out.push(*brace),
181            other => other.as_written(&mut out),
182        }
183    }
184    Cow::Owned(out)
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    fn written(text: &str) -> String {
192        let mut out = String::new();
193        for piece in pieces(text) {
194            piece.as_written(&mut out);
195        }
196        out
197    }
198
199    #[test]
200    fn the_pieces_written_back_are_the_text() {
201        for text in [
202            "",
203            "plain",
204            "a {name} b {{hash(cycle)}} c",
205            r"^\d\{8\}-{node}\.log$",
206            "WITH compaction = {\n  'class': '{strategy}'\n}",
207            "open { and {} and {  } and {{ unclosed",
208            "{k_{k}_limits}",
209            r"C:\dir\file and \\{name}",
210        ] {
211            assert_eq!(written(text), text);
212        }
213    }
214
215    #[test]
216    fn an_escaped_brace_is_a_brace_and_not_a_group() {
217        assert_eq!(
218            pieces(r"\d\{8\} {node}"),
219            vec![
220                Piece::Text(r"\d"),
221                Piece::Brace('{'),
222                Piece::Text("8"),
223                Piece::Brace('}'),
224                Piece::Text(" "),
225                Piece::Group {
226                    raw: "{node}",
227                    body: "node"
228                },
229            ]
230        );
231    }
232
233    #[test]
234    fn a_backslash_before_anything_else_is_text() {
235        assert_eq!(pieces(r"a\nb\\c"), vec![Piece::Text(r"a\nb\\c")]);
236    }
237
238    #[test]
239    fn an_escaped_brace_inside_a_group_does_not_close_it() {
240        assert_eq!(
241            pieces(r#"{f("\}")}"#),
242            vec![Piece::Group {
243                raw: r#"{f("\}")}"#,
244                body: r#"f("\}")"#
245            }]
246        );
247    }
248
249    #[test]
250    fn a_brace_before_a_quote_is_literal_and_the_map_is_still_scanned() {
251        assert_eq!(
252            pieces("{ 'class': '{strategy}' }"),
253            vec![
254                Piece::Text("{ 'class': '"),
255                Piece::Group {
256                    raw: "{strategy}",
257                    body: "strategy"
258                },
259                Piece::Text("' }"),
260            ]
261        );
262    }
263
264    #[test]
265    fn an_inline_expression_keeps_its_body() {
266        assert_eq!(
267            pieces("v={{ mod(cycle, 10) }}"),
268            vec![
269                Piece::Text("v="),
270                Piece::Inline {
271                    raw: "{{ mod(cycle, 10) }}",
272                    body: "mod(cycle, 10)"
273                },
274            ]
275        );
276    }
277
278    #[test]
279    fn unescape_writes_braces_alone_and_keeps_bind_points() {
280        assert_eq!(unescape(r"^\d\{2,3\}$"), r"^\d{2,3}$");
281        assert_eq!(unescape(r"\{{name}\}"), "{{name}}");
282        assert!(matches!(unescape(r"a\nb"), Cow::Borrowed(_)));
283    }
284}