ctb_formats_dcdata/format_spec/
validator.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//! Semantic validator for format specification expressions.
21//!
22//! Enforces operand constraints:
23//! - Named types must be explicitly registered in `README-named-types.csv`.
24//! - Transformation operands in `A : T` must reference valid transformation entities.
25//! - Rejects unverified nicknames or aliases in persisted expressions.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use anyhow::{Result, bail, ensure};
35use ctb_storage_minimal::shorthand::DcShorthand;
36
37use super::ast::{FormatExpr, MAX_FORMAT_EXPR_DEPTH, MAX_FORMAT_EXPR_NODES};
38use crate::syntax::SyntaxRuleResolver;
39
40/// Validates semantic constraints of a `FormatExpr`.
41///
42/// # Errors
43/// Returns an error if an unregistered named type is encountered, if a transformation
44/// target is invalid, or if tree complexity bounds are exceeded.
45pub fn validate_format_expr(expr: &FormatExpr) -> Result<()> {
46    let depth = expr.depth();
47    ensure!(
48        depth <= MAX_FORMAT_EXPR_DEPTH,
49        "Format expression depth {depth} exceeds maximum allowed depth {MAX_FORMAT_EXPR_DEPTH}"
50    );
51
52    let nodes = expr.node_count();
53    ensure!(
54        nodes <= MAX_FORMAT_EXPR_NODES,
55        "Format expression node count {nodes} exceeds maximum allowed nodes {MAX_FORMAT_EXPR_NODES}"
56    );
57
58    validate_node_recursive(expr)
59}
60
61fn validate_node_recursive(expr: &FormatExpr) -> Result<()> {
62    match expr {
63        FormatExpr::Dc(shorthand) => {
64            validate_shorthand_operand(shorthand)?;
65        }
66        FormatExpr::NamedType(name) => {
67            ensure!(
68                crate::syntax::default_syntax_resolver()
69                    .resolve_named_type(name)
70                    .is_some(),
71                "Unregistered named type '{name}' in format specification; only stable types from the seed graph are permitted"
72            );
73        }
74        FormatExpr::Convert(left, right)
75        | FormatExpr::Transmute(left, right) => {
76            validate_node_recursive(left)?;
77            validate_node_recursive(right)?;
78        }
79        FormatExpr::Transform(left, target) => {
80            validate_node_recursive(left)?;
81            validate_transformation_target(target)?;
82        }
83        FormatExpr::Union(children) | FormatExpr::Intersection(children) => {
84            ensure!(
85                children.len() >= 2,
86                "Conjunction or alternation must have at least 2 children, found {}",
87                children.len()
88            );
89            for child in children {
90                validate_node_recursive(child)?;
91            }
92        }
93        FormatExpr::Apply { target, params } => {
94            ensure!(
95                matches!(
96                    target.as_ref(),
97                    FormatExpr::Dc(
98                        DcShorthand::Format(_) | DcShorthand::Short(9)
99                    )
100                ),
101                "Application target must be a format Dc shorthand (e.g. 'f350'), found '{target}'"
102            );
103            validate_node_recursive(target)?;
104
105            let mut seen_keys = std::collections::HashSet::new();
106            for param in params {
107                ensure!(
108                    !param.name.is_empty(),
109                    "Parameter name cannot be empty in application '{expr}'"
110                );
111                ensure!(
112                    param
113                        .name
114                        .chars()
115                        .all(|c| c.is_ascii_alphanumeric() || c == '_'),
116                    "Parameter name '{}' must be an ASCII identifier in application '{expr}'",
117                    param.name
118                );
119                ensure!(
120                    seen_keys.insert(param.name.clone()),
121                    "Duplicate parameter '{}' in application '{expr}'",
122                    param.name
123                );
124
125                if param.name == "radix" {
126                    match &param.value {
127                        super::ast::ParamValue::Integer(r) => {
128                            ensure!(
129                                *r > 0,
130                                "Radix parameter must be greater than 0, found {r}"
131                            );
132                        }
133                        super::ast::ParamValue::Dc(DcShorthand::Format(
134                            fmt_id,
135                        )) => {
136                            ensure!(
137                                *fmt_id == 354,
138                                "Radix parameter format reference must be f354 (Base), found f{fmt_id}"
139                            );
140                        }
141                        other => {
142                            bail!(
143                                "Invalid radix value '{other:?}': expected positive integer or f354"
144                            );
145                        }
146                    }
147                }
148
149                if let super::ast::ParamValue::Expr(sub) = &param.value {
150                    validate_node_recursive(sub)?;
151                }
152            }
153        }
154    }
155    Ok(())
156}
157
158fn validate_shorthand_operand(shorthand: &DcShorthand) -> Result<()> {
159    match shorthand {
160        DcShorthand::Format(fmt_id) => {
161            ensure!(
162                *fmt_id <= ctb_storage_minimal::shorthand::MAX_FORMAT_ID,
163                "Format ID f{fmt_id} exceeds maximum known format bounds"
164            );
165        }
166        DcShorthand::Short(short_dc) => {
167            ensure!(
168                *short_dc <= ctb_storage_minimal::shorthand::MAX_SHORT_DC,
169                "Short Dc ID {short_dc} exceeds maximum known bounds"
170            );
171        }
172        DcShorthand::Unicode(cp) => {
173            ensure!(
174                *cp <= 0x0010_FFFF,
175                "Unicode codepoint u{cp:x} exceeds maximum 0x10FFFF"
176            );
177        }
178        DcShorthand::Long(_) | DcShorthand::Local(_) => {}
179    }
180    Ok(())
181}
182
183fn validate_transformation_target(target: &FormatExpr) -> Result<()> {
184    match target {
185        FormatExpr::Dc(shorthand @ DcShorthand::Format(fmt_id)) => {
186            let gid = shorthand.to_global_id()?;
187            ensure!(
188                crate::syntax::default_syntax_resolver()
189                    .matches_script("Formats:transformation", gid),
190                "Format f{fmt_id} is not a registered transformation format"
191            );
192            Ok(())
193        }
194        FormatExpr::NamedType(name) => {
195            ensure!(
196                name == "type" || name == "format",
197                "Named type '{name}' is not valid as a transformation target"
198            );
199            Ok(())
200        }
201        other => {
202            bail!(
203                "Invalid transformation target '{other:?}': expected format reference (e.g. f323) or registered transformation"
204            );
205        }
206    }
207}