ctb_formats_dcdata/format_spec/
parser.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Text parser for format specification DSL expressions.
21//!
22//! Enforces strict grouping and disambiguation rules as defined in
23//! `docs/file-info.md`:
24//! - Operational operators (`>`, `!`, `:`) bind left-to-right.
25//! - Conjunction (`&`) and alternation (`|`) cannot be mixed with each other
26//!   without explicit parentheses.
27//! - Conjunction and alternation cannot be mixed with operational operators
28//!   without explicit parentheses.
29//! - Supports `@chain(...)` directive wrapper in source data.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use anyhow::{Context, Result, bail, ensure};
39use ctb_storage_minimal::shorthand::DcShorthand;
40
41use super::ast::{
42    FormatExpr, FormatOp, MAX_FORMAT_EXPR_DEPTH, MAX_FORMAT_EXPR_NODES,
43    ParamBinding, ParamValue,
44};
45use super::dc_stream::{DcToken, decode_dc_stream};
46
47/// Lexical token in the format specification DSL.
48#[derive(Debug, Clone, PartialEq, Eq)]
49enum TokenKind {
50    Ident(String),
51    Gt,
52    Bang,
53    Colon,
54    Amp,
55    Pipe,
56    LParen,
57    RParen,
58    Eq,
59    Comma,
60    Str(String),
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64struct Token {
65    kind: TokenKind,
66    start: usize,
67    end: usize,
68}
69
70impl Token {
71    fn to_dc_token(&self) -> Result<DcToken> {
72        match &self.kind {
73            TokenKind::Gt => Ok(DcToken::Dc(DcShorthand::Short(302))),
74            TokenKind::Bang => Ok(DcToken::Dc(DcShorthand::Short(303))),
75            TokenKind::Colon => Ok(DcToken::Dc(DcShorthand::Short(301))),
76            TokenKind::Amp => Ok(DcToken::Dc(DcShorthand::Short(300))),
77            TokenKind::Pipe => Ok(DcToken::Dc(DcShorthand::Short(516))),
78            TokenKind::LParen => Ok(DcToken::Dc(DcShorthand::Short(298))),
79            TokenKind::RParen => Ok(DcToken::Dc(DcShorthand::Short(299))),
80            TokenKind::Eq => bail!("Unexpected '=' in prefix Dc stream"),
81            TokenKind::Comma => bail!("Unexpected ',' in prefix Dc stream"),
82            TokenKind::Str(s) => Ok(DcToken::NamedType(s.clone())),
83            TokenKind::Ident(ident) => {
84                if let Ok(shorthand) = DcShorthand::parse(ident) {
85                    Ok(DcToken::Dc(shorthand))
86                } else if is_valid_named_type_syntax(ident) {
87                    Ok(DcToken::NamedType(ident.clone()))
88                } else {
89                    bail!("Invalid format specification token '{ident}'");
90                }
91            }
92        }
93    }
94}
95
96/// Tokenizes a format specification string into lexical tokens.
97fn tokenize(input: &str) -> Result<Vec<Token>> {
98    let mut tokens = Vec::new();
99    let mut chars = input.char_indices().peekable();
100
101    while let Some((idx, ch)) = chars.next() {
102        if ch.is_whitespace() {
103            continue;
104        }
105
106        match ch {
107            '>' => tokens.push(Token {
108                kind: TokenKind::Gt,
109                start: idx,
110                end: idx.saturating_add(1),
111            }),
112            '!' => tokens.push(Token {
113                kind: TokenKind::Bang,
114                start: idx,
115                end: idx.saturating_add(1),
116            }),
117            ':' => tokens.push(Token {
118                kind: TokenKind::Colon,
119                start: idx,
120                end: idx.saturating_add(1),
121            }),
122            '&' => tokens.push(Token {
123                kind: TokenKind::Amp,
124                start: idx,
125                end: idx.saturating_add(1),
126            }),
127            '|' => tokens.push(Token {
128                kind: TokenKind::Pipe,
129                start: idx,
130                end: idx.saturating_add(1),
131            }),
132            '(' => tokens.push(Token {
133                kind: TokenKind::LParen,
134                start: idx,
135                end: idx.saturating_add(1),
136            }),
137            ')' => tokens.push(Token {
138                kind: TokenKind::RParen,
139                start: idx,
140                end: idx.saturating_add(1),
141            }),
142            '=' => tokens.push(Token {
143                kind: TokenKind::Eq,
144                start: idx,
145                end: idx.saturating_add(1),
146            }),
147            ',' => tokens.push(Token {
148                kind: TokenKind::Comma,
149                start: idx,
150                end: idx.saturating_add(1),
151            }),
152            '"' => {
153                let start = idx;
154                let mut string_val = String::new();
155                let mut escaped = false;
156                let mut closed = false;
157                let mut end = idx;
158                for (next_idx, next_ch) in chars.by_ref() {
159                    end = next_idx.saturating_add(next_ch.len_utf8());
160                    if escaped {
161                        string_val.push(next_ch);
162                        escaped = false;
163                    } else if next_ch == '\\' {
164                        escaped = true;
165                    } else if next_ch == '"' {
166                        closed = true;
167                        break;
168                    } else {
169                        string_val.push(next_ch);
170                    }
171                }
172                ensure!(
173                    closed,
174                    "Unterminated string literal starting at offset {start}"
175                );
176                tokens.push(Token {
177                    kind: TokenKind::Str(string_val),
178                    start,
179                    end,
180                });
181            }
182            _ if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' => {
183                let start = idx;
184                let mut end = idx.saturating_add(ch.len_utf8());
185                let mut ident = String::new();
186                ident.push(ch);
187
188                while let Some(&(next_idx, next_ch)) = chars.peek() {
189                    if next_ch.is_ascii_alphanumeric()
190                        || next_ch == '_'
191                        || next_ch == '-'
192                    {
193                        ident.push(next_ch);
194                        end = next_idx.saturating_add(next_ch.len_utf8());
195                        chars.next();
196                    } else {
197                        break;
198                    }
199                }
200
201                tokens.push(Token {
202                    kind: TokenKind::Ident(ident),
203                    start,
204                    end,
205                });
206            }
207            _ => {
208                bail!(
209                    "Unexpected character '{ch}' at offset {idx} in format specification"
210                );
211            }
212        }
213    }
214
215    Ok(tokens)
216}
217
218/// Parses a format specification expression from a string slice.
219///
220/// Accepts both infix notation (e.g. `1 & ((2 | 3 | 4) > 5)`) and prefix notation
221/// (e.g. `& 1 > | 2 3 4 ) 5` or `302 303 302 f15 f542 f0 f0`), with optional `@chain(...)`
222/// directive wrapping.
223///
224/// # Errors
225/// Returns an error on syntax errors, ambiguous operator mixtures, exceeding
226/// maximum depth/complexity limits, or invalid token structures.
227pub fn parse_format_expr(input: &str) -> Result<FormatExpr> {
228    let trimmed = input.trim();
229    ensure!(!trimmed.is_empty(), "Empty format specification expression");
230
231    let expr_str = if let Some(stripped) = trimmed.strip_prefix("@chain(") {
232        let Some(inner) = stripped.strip_suffix(')') else {
233            bail!("Malformed '@chain(...)': missing closing parenthesis");
234        };
235        inner.trim()
236    } else if let Some(stripped) = trimmed.strip_prefix("@(") {
237        let Some(inner) = stripped.strip_suffix(')') else {
238            bail!("Malformed '@(...)': missing closing parenthesis");
239        };
240        inner.trim()
241    } else {
242        trimmed
243    };
244
245    ensure!(
246        !expr_str.is_empty(),
247        "Empty format specification inside '@chain(...)' or '@(...)'"
248    );
249
250    let tokens = tokenize(expr_str)?;
251    ensure!(
252        !tokens.is_empty(),
253        "No tokens found in format specification"
254    );
255
256    if is_prefix_token_stream(&tokens) {
257        if let Ok(expr) = parse_prefix_expr(&tokens) {
258            return validate_limits(expr);
259        }
260    }
261
262    match parse_scope(&tokens, 0) {
263        Ok(expr) => validate_limits(expr),
264        Err(infix_err) => {
265            if let Ok(expr) = parse_prefix_expr(&tokens) {
266                validate_limits(expr)
267            } else {
268                Err(infix_err)
269            }
270        }
271    }
272}
273
274fn is_prefix_token_stream(tokens: &[Token]) -> bool {
275    let Some(first) = tokens.first() else {
276        return false;
277    };
278    match &first.kind {
279        TokenKind::Gt
280        | TokenKind::Bang
281        | TokenKind::Colon
282        | TokenKind::Amp
283        | TokenKind::Pipe => true,
284        TokenKind::LParen => {
285            if let Some(second) = tokens.get(1) {
286                matches!(
287                    &second.kind,
288                    TokenKind::Gt
289                        | TokenKind::Bang
290                        | TokenKind::Colon
291                        | TokenKind::Amp
292                        | TokenKind::Pipe
293                ) || is_op_ident(&second.kind)
294            } else {
295                false
296            }
297        }
298        TokenKind::Ident(_) => is_op_ident(&first.kind),
299        TokenKind::RParen
300        | TokenKind::Eq
301        | TokenKind::Comma
302        | TokenKind::Str(_) => false,
303    }
304}
305
306fn is_op_ident(kind: &TokenKind) -> bool {
307    if let TokenKind::Ident(s) = kind {
308        matches!(
309            s.as_str(),
310            "298" | "300" | "301" | "302" | "303" | "516" | "535"
311        )
312    } else {
313        false
314    }
315}
316
317fn parse_prefix_expr(tokens: &[Token]) -> Result<FormatExpr> {
318    let mut dc_tokens = Vec::with_capacity(tokens.len());
319    for tok in tokens {
320        dc_tokens.push(tok.to_dc_token()?);
321    }
322    decode_dc_stream(&dc_tokens)
323}
324
325fn validate_limits(expr: FormatExpr) -> Result<FormatExpr> {
326    let depth = expr.depth();
327    ensure!(
328        depth <= MAX_FORMAT_EXPR_DEPTH,
329        "Format expression depth {depth} exceeds maximum allowed depth {MAX_FORMAT_EXPR_DEPTH}"
330    );
331
332    let nodes = expr.node_count();
333    ensure!(
334        nodes <= MAX_FORMAT_EXPR_NODES,
335        "Format expression node count {nodes} exceeds maximum allowed nodes {MAX_FORMAT_EXPR_NODES}"
336    );
337
338    Ok(expr)
339}
340
341/// Parses a sequence of tokens within a single grouping scope.
342fn parse_scope(tokens: &[Token], current_depth: usize) -> Result<FormatExpr> {
343    ensure!(
344        current_depth <= MAX_FORMAT_EXPR_DEPTH,
345        "Format expression nesting exceeds maximum depth limit of {MAX_FORMAT_EXPR_DEPTH}"
346    );
347    ensure!(!tokens.is_empty(), "Empty expression within parentheses");
348
349    // Partition the token slice at the current scope depth into operands and operators
350    let mut items = Vec::new();
351    let mut operators = Vec::new();
352
353    let mut idx = 0usize;
354    while idx < tokens.len() {
355        let Some(token) = tokens.get(idx) else {
356            break;
357        };
358        match &token.kind {
359            TokenKind::LParen => {
360                let start_idx = idx;
361                let mut paren_depth = 1usize;
362                idx = idx.saturating_add(1);
363
364                while idx < tokens.len() && paren_depth > 0 {
365                    if let Some(t) = tokens.get(idx) {
366                        match &t.kind {
367                            TokenKind::LParen => {
368                                paren_depth = paren_depth.saturating_add(1);
369                            }
370                            TokenKind::RParen => {
371                                paren_depth = paren_depth.saturating_sub(1);
372                            }
373                            _ => {}
374                        }
375                    }
376                    idx = idx.saturating_add(1);
377                }
378
379                ensure!(
380                    paren_depth == 0,
381                    "Unclosed opening parenthesis '(' in format specification"
382                );
383
384                let inner_range =
385                    start_idx.saturating_add(1)..idx.saturating_sub(1);
386                let Some(inner_tokens) = tokens.get(inner_range) else {
387                    bail!("Failed to slice inner parenthesized tokens");
388                };
389                let sub_expr =
390                    parse_scope(inner_tokens, current_depth.saturating_add(1))?;
391                items.push(sub_expr);
392            }
393            TokenKind::RParen => {
394                bail!(
395                    "Unexpected closing parenthesis ')' at offset {}",
396                    token.start
397                );
398            }
399            TokenKind::Ident(ident) => {
400                if let Some(next_tok) = tokens.get(idx.saturating_add(1)) {
401                    if next_tok.kind == TokenKind::LParen {
402                        let Ok(shorthand) = DcShorthand::parse(ident) else {
403                            bail!(
404                                "Identifiers are not permitted as application targets because they are not stable; specify a format Dc shorthand (e.g. 'f350(...)')"
405                            );
406                        };
407                        ensure!(
408                            matches!(shorthand, DcShorthand::Format(_)),
409                            "Target of parametric application must be a format shorthand (e.g. 'f350'), found '{shorthand}'"
410                        );
411
412                        let (params, next_idx) = parse_param_bindings(
413                            tokens,
414                            idx.saturating_add(2),
415                            current_depth,
416                        )?;
417                        let target_expr = Box::new(FormatExpr::Dc(shorthand));
418                        items.push(FormatExpr::Apply {
419                            target: target_expr,
420                            params,
421                        });
422                        idx = next_idx;
423                        continue;
424                    }
425                }
426                let operand = parse_operand(ident)?;
427                items.push(operand);
428                idx = idx.saturating_add(1);
429            }
430            TokenKind::Gt
431            | TokenKind::Bang
432            | TokenKind::Colon
433            | TokenKind::Amp
434            | TokenKind::Pipe => {
435                let op = match &token.kind {
436                    TokenKind::Gt => FormatOp::Convert,
437                    TokenKind::Bang => FormatOp::Transmute,
438                    TokenKind::Colon => FormatOp::Transform,
439                    TokenKind::Amp => FormatOp::Union,
440                    TokenKind::Pipe => FormatOp::Intersection,
441                    _ => unreachable!("Handled by outer match"),
442                };
443                operators.push((op, token.start));
444                idx = idx.saturating_add(1);
445            }
446            TokenKind::Eq | TokenKind::Comma | TokenKind::Str(_) => {
447                bail!(
448                    "Unexpected token {:?} in format specification at offset {}",
449                    token.kind,
450                    token.start
451                );
452            }
453        }
454    }
455
456    ensure!(
457        items.len() == operators.len().saturating_add(1),
458        "Mismatched operators and operands in format specification: found {} operands and {} operators",
459        items.len(),
460        operators.len()
461    );
462
463    if operators.is_empty() {
464        let first = items
465            .pop()
466            .context("Internal parser error: missing operand")?;
467        return Ok(first);
468    }
469
470    // Check operator consistency in this scope
471    let has_union = operators.iter().any(|(op, _)| *op == FormatOp::Union);
472    let has_intersection = operators
473        .iter()
474        .any(|(op, _)| *op == FormatOp::Intersection);
475    let has_operational = operators.iter().any(|(op, _)| {
476        matches!(
477            op,
478            FormatOp::Convert | FormatOp::Transmute | FormatOp::Transform
479        )
480    });
481
482    if (has_union || has_intersection) && has_operational {
483        bail!(
484            "Ambiguous operator mixing: explicit parentheses are required when combining conjunction ('&') or alternation ('|') with operations ('>', '!', ':')"
485        );
486    }
487
488    if has_union && has_intersection {
489        bail!(
490            "Ambiguous operator mixing: neither '&' nor '|' takes precedence over the other; explicit parentheses are required"
491        );
492    }
493
494    if has_union {
495        return Ok(FormatExpr::Union(items));
496    }
497
498    if has_intersection {
499        return Ok(FormatExpr::Intersection(items));
500    }
501
502    // Operational operators: evaluate left-to-right
503    let mut item_iter = items.into_iter();
504    let mut current_expr = item_iter
505        .next()
506        .context("Internal parser error: empty operand list")?;
507
508    for (op, _) in operators {
509        let next_item = item_iter
510            .next()
511            .context("Internal parser error: missing right operand")?;
512        match op {
513            FormatOp::Convert => {
514                current_expr = FormatExpr::Convert(
515                    Box::new(current_expr),
516                    Box::new(next_item),
517                );
518            }
519            FormatOp::Transmute => {
520                current_expr = FormatExpr::Transmute(
521                    Box::new(current_expr),
522                    Box::new(next_item),
523                );
524            }
525            FormatOp::Transform => {
526                current_expr = FormatExpr::Transform(
527                    Box::new(current_expr),
528                    Box::new(next_item),
529                );
530            }
531            FormatOp::Union | FormatOp::Intersection => {
532                unreachable!("Filtered out by consistency checks above");
533            }
534        }
535    }
536
537    Ok(current_expr)
538}
539
540/// Parses a leaf token into a `FormatExpr::Dc` or `FormatExpr::NamedType`.
541fn parse_operand(ident: &str) -> Result<FormatExpr> {
542    if let Ok(shorthand) = DcShorthand::parse(ident) {
543        return Ok(FormatExpr::Dc(shorthand));
544    }
545
546    // Registered named types: lower_snake_case or lowercase
547    if is_valid_named_type_syntax(ident) {
548        return Ok(FormatExpr::NamedType(ident.to_string()));
549    }
550
551    bail!(
552        "Invalid format specification operand '{ident}': expected numeric Dc shorthand (e.g. f542, l2228766, 0) or registered named type"
553    )
554}
555
556/// Validates whether an identifier string adheres to the lexical syntax of named types.
557fn is_valid_named_type_syntax(ident: &str) -> bool {
558    if ident.is_empty() {
559        return false;
560    }
561    ident
562        .chars()
563        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
564}
565
566/// Parses comma-separated parameter bindings inside `(key = value, ...)`.
567fn parse_param_bindings(
568    tokens: &[Token],
569    mut idx: usize,
570    current_depth: usize,
571) -> Result<(Vec<ParamBinding>, usize)> {
572    let mut params = Vec::new();
573
574    if let Some(tok) = tokens.get(idx) {
575        if tok.kind == TokenKind::RParen {
576            return Ok((params, idx.saturating_add(1)));
577        }
578    }
579
580    while idx < tokens.len() {
581        let Some(name_token) = tokens.get(idx) else {
582            bail!(
583                "Unexpected end of tokens in parameter list: expected parameter name"
584            );
585        };
586        let TokenKind::Ident(name) = &name_token.kind else {
587            bail!(
588                "Expected parameter name at offset {}, found {:?}",
589                name_token.start,
590                name_token.kind
591            );
592        };
593        let param_name = name.clone();
594        idx = idx.saturating_add(1);
595
596        let Some(eq_token) = tokens.get(idx) else {
597            bail!("Expected '=' after parameter name '{param_name}'");
598        };
599        ensure!(
600            eq_token.kind == TokenKind::Eq,
601            "Expected '=' after parameter name '{param_name}', found {:?}",
602            eq_token.kind
603        );
604        idx = idx.saturating_add(1);
605
606        let Some(val_token) = tokens.get(idx) else {
607            bail!("Expected value for parameter '{param_name}'");
608        };
609        let (param_value, next_idx) = match &val_token.kind {
610            TokenKind::Str(s) => {
611                (ParamValue::String(s.clone()), idx.saturating_add(1))
612            }
613            TokenKind::Ident(s) => {
614                if let Ok(num) = s.parse::<i64>() {
615                    (ParamValue::Integer(num), idx.saturating_add(1))
616                } else if let Ok(dc) = DcShorthand::parse(s) {
617                    (ParamValue::Dc(dc), idx.saturating_add(1))
618                } else {
619                    (ParamValue::Ident(s.clone()), idx.saturating_add(1))
620                }
621            }
622            TokenKind::LParen => {
623                let start_idx = idx;
624                let mut paren_depth = 1usize;
625                let mut scan_idx = idx.saturating_add(1);
626                while scan_idx < tokens.len() && paren_depth > 0 {
627                    if let Some(t) = tokens.get(scan_idx) {
628                        match &t.kind {
629                            TokenKind::LParen => {
630                                paren_depth = paren_depth.saturating_add(1);
631                            }
632                            TokenKind::RParen => {
633                                paren_depth = paren_depth.saturating_sub(1);
634                            }
635                            _ => {}
636                        }
637                    }
638                    scan_idx = scan_idx.saturating_add(1);
639                }
640                ensure!(
641                    paren_depth == 0,
642                    "Unclosed '(' in parameter value for '{param_name}'"
643                );
644                let inner_tokens = tokens
645                    .get(
646                        start_idx.saturating_add(1)..scan_idx.saturating_sub(1),
647                    )
648                    .context(
649                        "Invalid token slice for parameter value expression",
650                    )?;
651                let sub_expr =
652                    parse_scope(inner_tokens, current_depth.saturating_add(1))?;
653                (ParamValue::Expr(Box::new(sub_expr)), scan_idx)
654            }
655            other => {
656                bail!(
657                    "Unexpected token {other:?} for parameter value '{param_name}'"
658                );
659            }
660        };
661
662        params.push(ParamBinding {
663            name: param_name,
664            value: param_value,
665        });
666        idx = next_idx;
667
668        let Some(sep_token) = tokens.get(idx) else {
669            bail!("Unclosed parameter list: expected ',' or ')'");
670        };
671        match &sep_token.kind {
672            TokenKind::Comma => {
673                idx = idx.saturating_add(1);
674                if let Some(next_tok) = tokens.get(idx) {
675                    if next_tok.kind == TokenKind::RParen {
676                        return Ok((params, idx.saturating_add(1)));
677                    }
678                }
679            }
680            TokenKind::RParen => {
681                idx = idx.saturating_add(1);
682                return Ok((params, idx));
683            }
684            other => {
685                bail!("Expected ',' or ')' in parameter list, found {other:?}");
686            }
687        }
688    }
689
690    bail!("Unclosed parameter list: expected ')'");
691}