ctb_formats_dcdata/format_spec/
ast.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//! Abstract Syntax Tree (AST) definitions for format specifications.
21//!
22//! Provides the data structures representing format composition, conversion,
23//! transmutation, transformation, conjunction, and alternation as outlined in
24//! `docs/file-info.md`.
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use ctb_storage_minimal::shorthand::DcShorthand;
34use serde::{Deserialize, Serialize};
35
36use crate::dc::{
37    DC_TYPE_CONVERSION, DC_TYPE_INTERSECTION, DC_TYPE_TRANSFORMATION,
38    DC_TYPE_TRANSMUTATION, DC_TYPE_UNION, DcChar,
39};
40use crate::syntax::DcRole;
41
42/// Maximum expression recursion depth allowed to prevent stack overflow.
43pub const MAX_FORMAT_EXPR_DEPTH: usize = 32;
44
45/// Maximum number of AST nodes permitted in a single format expression.
46pub const MAX_FORMAT_EXPR_NODES: usize = 256;
47
48/// Operator types for format composition expressions.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub enum FormatOp {
51    /// Format conversion / encoding: `>` (Dc 302).
52    Convert,
53    /// Format transmutation / representation reinterpretation: `!` (Dc 303).
54    Transmute,
55    /// Transformation application: `:` (Dc 301).
56    Transform,
57    /// Type union / conjunction of simultaneous constraints: `&` (Dc 300).
58    Union,
59    /// Type intersection / alternative constraints: `|` (Dc 516).
60    Intersection,
61}
62
63impl FormatOp {
64    /// Returns the `DcChar` constant corresponding to this operator.
65    #[must_use]
66    pub const fn dc_char(self) -> DcChar {
67        match self {
68            Self::Union => DC_TYPE_UNION,
69            Self::Transform => DC_TYPE_TRANSFORMATION,
70            Self::Convert => DC_TYPE_CONVERSION,
71            Self::Transmute => DC_TYPE_TRANSMUTATION,
72            Self::Intersection => DC_TYPE_INTERSECTION,
73        }
74    }
75
76    /// Returns the `DcRole` corresponding to this operator.
77    #[must_use]
78    pub const fn role(self) -> DcRole {
79        match self {
80            Self::Union => DcRole::TypeUnion,
81            Self::Transform => DcRole::TypeTransformation,
82            Self::Convert => DcRole::TypeConversion,
83            Self::Transmute => DcRole::TypeTransmutation,
84            Self::Intersection => DcRole::TypeIntersection,
85        }
86    }
87
88    /// Returns the short Dc ID corresponding to this operator.
89    #[must_use]
90    pub fn dc_id(self) -> u32 {
91        #[expect(
92            clippy::expect_used,
93            reason = "All FormatOp DcChar constants are compile-time short Dcs"
94        )]
95        self.dc_char()
96            .to_short_dc()
97            .expect("FormatOp dc_char is a short Dc")
98    }
99
100    /// Returns the operator corresponding to a short Dc ID, if valid.
101    #[must_use]
102    pub fn from_dc_id(id: u32) -> Option<Self> {
103        let ch = DcChar::from_short(id);
104        [
105            Self::Union,
106            Self::Transform,
107            Self::Convert,
108            Self::Transmute,
109            Self::Intersection,
110        ]
111        .into_iter()
112        .find(|&op| ch == op.dc_char())
113    }
114
115    /// Returns the textual symbol for this operator.
116    #[must_use]
117    pub const fn as_str(self) -> &'static str {
118        match self {
119            Self::Union => "&",
120            Self::Transform => ":",
121            Self::Convert => ">",
122            Self::Transmute => "!",
123            Self::Intersection => "|",
124        }
125    }
126}
127
128/// Typed value in a format parameter binding.
129#[derive(Debug, Clone, PartialEq, Eq, Hash)]
130pub enum ParamValue {
131    /// Integer scalar (e.g. 16 in radix=16).
132    Integer(i64),
133    /// Dc shorthand reference (e.g. f354, or variant format Dcs).
134    Dc(DcShorthand),
135    /// Symbolic identifier.
136    Ident(String),
137    /// Quoted string literal.
138    String(String),
139    /// Nested format specification expression.
140    Expr(Box<FormatExpr>),
141}
142
143/// Key-value binding in a parametric format application.
144#[derive(Debug, Clone, PartialEq, Eq, Hash)]
145pub struct ParamBinding {
146    /// Parameter dimension name (e.g. "radix", "case", "padding").
147    pub name: String,
148    /// Parameter value.
149    pub value: ParamValue,
150}
151
152/// Core expression node in a format specification expression tree.
153#[derive(Debug, Clone, PartialEq, Eq, Hash)]
154pub enum FormatExpr {
155    /// Numeric Document Character shorthand (e.g. `f542`, `l2228766`, `0`, `u0020`).
156    Dc(DcShorthand),
157    /// Explicitly registered stable named type (e.g. `string`, `identifier`, `number`).
158    NamedType(String),
159    /// Format conversion / encoding: `A > B` (Dc 302).
160    Convert(Box<FormatExpr>, Box<FormatExpr>),
161    /// Format transmutation / representation reinterpretation: `A ! B` (Dc 303).
162    Transmute(Box<FormatExpr>, Box<FormatExpr>),
163    /// Transformation application: `A : T` (Dc 301).
164    Transform(Box<FormatExpr>, Box<FormatExpr>),
165    /// Type union / conjunction of simultaneous constraints: `A & B` (Dc 300).
166    Union(Vec<FormatExpr>),
167    /// Type intersection / alternative constraints: `A | B` (Dc 516).
168    Intersection(Vec<FormatExpr>),
169    /// Parametric format application: `target(key=value, ...)` (Dc 535).
170    Apply {
171        /// Application target expression (must resolve to a format Dc shorthand).
172        target: Box<FormatExpr>,
173        /// Bound parameter values.
174        params: Vec<ParamBinding>,
175    },
176}
177
178impl FormatExpr {
179    /// Calculates the maximum tree depth of this expression.
180    #[must_use]
181    pub fn depth(&self) -> usize {
182        match self {
183            Self::Dc(_) | Self::NamedType(_) => 1,
184            Self::Convert(l, r)
185            | Self::Transmute(l, r)
186            | Self::Transform(l, r) => {
187                let max_child = l.depth().max(r.depth());
188                max_child.saturating_add(1)
189            }
190            Self::Union(children) | Self::Intersection(children) => {
191                let mut max_child = 0usize;
192                for child in children {
193                    max_child = max_child.max(child.depth());
194                }
195                max_child.saturating_add(1)
196            }
197            Self::Apply { target, params } => {
198                let mut max_child = target.depth();
199                for param in params {
200                    if let ParamValue::Expr(sub) = &param.value {
201                        max_child = max_child.max(sub.depth());
202                    }
203                }
204                max_child.saturating_add(1)
205            }
206        }
207    }
208
209    /// Calculates the total number of AST nodes in this expression.
210    #[must_use]
211    pub fn node_count(&self) -> usize {
212        match self {
213            Self::Dc(_) | Self::NamedType(_) => 1,
214            Self::Convert(l, r)
215            | Self::Transmute(l, r)
216            | Self::Transform(l, r) => {
217                let left_nodes = l.node_count();
218                let right_nodes = r.node_count();
219                left_nodes.saturating_add(right_nodes).saturating_add(1)
220            }
221            Self::Union(children) | Self::Intersection(children) => {
222                let mut total = 1usize;
223                for child in children {
224                    total = total.saturating_add(child.node_count());
225                }
226                total
227            }
228            Self::Apply { target, params } => {
229                let mut total = target.node_count().saturating_add(1);
230                for param in params {
231                    total = total.saturating_add(1);
232                    if let ParamValue::Expr(sub) = &param.value {
233                        total = total.saturating_add(sub.node_count());
234                    }
235                }
236                total
237            }
238        }
239    }
240
241    /// Returns true if this expression is a leaf node (Dc or `NamedType`).
242    #[must_use]
243    pub const fn is_leaf(&self) -> bool {
244        matches!(self, Self::Dc(_) | Self::NamedType(_))
245    }
246}
247
248impl Serialize for FormatExpr {
249    fn serialize<S>(
250        &self,
251        serializer: S,
252    ) -> std::result::Result<S::Ok, S::Error>
253    where
254        S: serde::Serializer,
255    {
256        serializer.serialize_str(&super::formatter::format_expr(self))
257    }
258}
259
260impl<'de> Deserialize<'de> for FormatExpr {
261    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
262    where
263        D: serde::Deserializer<'de>,
264    {
265        let s = String::deserialize(deserializer)?;
266        super::parser::parse_format_expr(&s).map_err(serde::de::Error::custom)
267    }
268}