ctb_formats_dcdata/support/
shared.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//! Shared validation primitives for identifiers, MIME types, extensions, and schema constraints.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::report::ValidationReport;
30use std::collections::HashMap;
31
32pub use crate::dc_def::{BidiClass, GeneralCategory, SupportLevel};
33
34const RUST_KEYWORDS: &[&str] = &[
35    "as", "break", "const", "continue", "crate", "else", "enum", "extern",
36    "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
37    "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct",
38    "super", "trait", "true", "type", "unsafe", "use", "where", "while",
39    "async", "await", "dyn", "abstract", "become", "box", "do", "final",
40    "macro", "override", "priv", "typeof", "unsized", "virtual", "yield",
41    "try",
42];
43
44/// Validates that a string is a syntactically valid Rust identifier and not a keyword.
45pub fn validate_rust_identifier(ident: &str) -> Result<()> {
46    if ident.is_empty() {
47        bail!("Identifier cannot be empty");
48    }
49
50    let mut chars = ident.chars();
51    let Some(first) = chars.next() else {
52        bail!("Identifier cannot be empty");
53    };
54
55    if !first.is_ascii_alphabetic() && first != '_' {
56        bail!(
57            "Identifier '{ident}' must start with an ASCII letter or underscore"
58        );
59    }
60
61    for ch in chars {
62        if !ch.is_ascii_alphanumeric() && ch != '_' {
63            bail!(
64                "Identifier '{ident}' contains invalid character '{ch}' (must be alphanumeric or '_')"
65            );
66        }
67    }
68
69    if RUST_KEYWORDS.contains(&ident) {
70        bail!("Identifier '{ident}' is a reserved Rust keyword");
71    }
72
73    Ok(())
74}
75
76/// Splits a comma-separated string while respecting parentheses and brackets.
77pub fn split_comma_separated_items(raw: &str) -> Vec<String> {
78    let mut items = Vec::new();
79    let mut depth_paren = 0usize;
80    let mut depth_bracket = 0usize;
81    let mut current = String::new();
82
83    for ch in raw.chars() {
84        match ch {
85            '(' => {
86                depth_paren = depth_paren.saturating_add(1);
87                current.push(ch);
88            }
89            ')' => {
90                depth_paren = depth_paren.saturating_sub(1);
91                current.push(ch);
92            }
93            '[' => {
94                depth_bracket = depth_bracket.saturating_add(1);
95                current.push(ch);
96            }
97            ']' => {
98                depth_bracket = depth_bracket.saturating_sub(1);
99                current.push(ch);
100            }
101            ',' if depth_paren == 0 && depth_bracket == 0 => {
102                let trimmed = current.trim();
103                if !trimmed.is_empty() {
104                    items.push(trimmed.to_string());
105                }
106                current.clear();
107            }
108            _ => {
109                current.push(ch);
110            }
111        }
112    }
113    let trimmed = current.trim();
114    if !trimmed.is_empty() {
115        items.push(trimmed.to_string());
116    }
117    items
118}
119
120/// Validates a single extension entry or regex-delimited pattern (`~...~`).
121pub fn validate_extension_entry(entry: &str) -> Result<()> {
122    let trimmed = entry.trim();
123    if trimmed.is_empty() {
124        bail!("Extension entry cannot be blank");
125    }
126
127    let trimmed = if let Some(stripped) = trimmed.strip_prefix("case:") {
128        stripped.trim()
129    } else {
130        trimmed
131    };
132
133    if trimmed.is_empty() {
134        bail!("Extension entry cannot be blank after case prefix");
135    }
136
137    if trimmed.starts_with('~') && trimmed.ends_with('~') && trimmed.len() >= 2
138    {
139        let pattern = if let Some(stripped) =
140            trimmed.strip_prefix('~').and_then(|s| s.strip_suffix('~'))
141        {
142            stripped
143        } else {
144            trimmed
145        };
146        if pattern.is_empty() {
147            bail!("Regex extension pattern '~...~' cannot be empty");
148        }
149        regex::Regex::new(pattern).with_context(|| {
150            format!("Invalid regex pattern in extension rule: '{trimmed}'")
151        })?;
152        crate::syntax::parse_extension_regex(trimmed).with_context(|| {
153            format!(
154                "Extension regex pattern '{trimmed}' cannot be compiled to a Dc pattern rule"
155            )
156        })?;
157        return Ok(());
158    }
159
160    if !trimmed.starts_with('.') {
161        bail!(
162            "Extension '{trimmed}' must start with a leading dot '.' or be a regex enclosed in '~...~'"
163        );
164    }
165
166    Ok(())
167}
168
169/// Validates a comma-separated list of extensions or regex patterns.
170pub fn validate_extensions_field(field: &str) -> Result<()> {
171    let trimmed = field.trim();
172    if trimmed.is_empty() {
173        return Ok(());
174    }
175
176    for item in trimmed.split(',') {
177        let item_trimmed = item.trim();
178        if item_trimmed.is_empty() {
179            continue;
180        }
181        validate_extension_entry(item_trimmed)?;
182    }
183    Ok(())
184}
185
186/// Validates a comma-separated list of MIME types (e.g. `text/plain, text/plain;charset=utf-8`).
187pub fn validate_mime_field(field: &str) -> Result<()> {
188    let trimmed = field.trim();
189    if trimmed.is_empty() {
190        return Ok(());
191    }
192
193    for item in trimmed.split(',') {
194        let item_trimmed = item.trim();
195        if item_trimmed.is_empty() {
196            continue;
197        }
198        let mime_base = match item_trimmed.split(';').next() {
199            Some(base) => base.trim(),
200            None => item_trimmed,
201        };
202        let Some((typ, subtyp)) = mime_base.split_once('/') else {
203            bail!(
204                "MIME type '{item_trimmed}' missing '/' separator (expected 'type/subtype')"
205            );
206        };
207        if typ.trim().is_empty() || subtyp.trim().is_empty() {
208            bail!("MIME type '{item_trimmed}' has empty type or subtype");
209        }
210    }
211    Ok(())
212}
213
214/// Validates support level values: blank or two space-separated levels `<general> <dc>` in `-1..=5`.
215///
216/// Scale for each component:
217/// - `-1`: N/A (e.g. reverse transformation for one-way functions, or non-Dc formats)
218/// - `0`: None / unsupported
219/// - `1`: WIP
220/// - `2`: Basic / stream / partial format support
221/// - `3`: Full general format support / complete semantic roundtripping to Dc syntax
222/// - `4`: Lossless and roundtrippable (for Dc: unambiguous bit-for-bit reconstruction)
223/// - `5`: Level 4 + optional strict validation
224pub fn validate_support_level(val: &str) -> Result<()> {
225    SupportLevel::parse(val).map(|_| ())
226}
227
228/// Validates Unicode General Category code (e.g. `Cc`, `Sm`, `!Cx`).
229pub fn validate_general_category(cat: &str) -> Result<GeneralCategory> {
230    cat.parse::<GeneralCategory>()
231}
232
233/// Validates Unicode Bidi class code (e.g. `L`, `BN`, `ON`).
234pub fn validate_bidi_class(bidi: &str) -> Result<BidiClass> {
235    bidi.parse::<BidiClass>()
236}
237
238/// Validates Canonical Combining Class integer (`0..=254`).
239pub fn validate_combining_class(cls: &str) -> Result<u8> {
240    let trimmed = cls.trim();
241    if trimmed.is_empty() {
242        return Ok(0);
243    }
244    let val = trimmed.parse::<u8>().with_context(|| {
245        format!("Invalid combining class integer '{trimmed}'")
246    })?;
247    if val > 254 {
248        bail!("Combining class {val} out of valid Unicode range (0..=254)");
249    }
250    Ok(val)
251}
252
253/// Validates that format labels and Dc names are unique across all records.
254pub fn validate_cross_table_uniqueness(
255    dc_names: &[(usize, &str, &str)], // (short_id, name, file_path)
256    format_labels: &[(usize, &str, &str)], // (short_id, label, file_path)
257    report: &mut ValidationReport,
258) {
259    let mut dc_name_map: HashMap<String, (usize, String)> = HashMap::new();
260    for &(short_id, raw_name, file_path) in dc_names {
261        let clean_name = if let Some(stripped) = raw_name.strip_prefix('!') {
262            stripped.trim()
263        } else {
264            raw_name.trim()
265        };
266        if clean_name.is_empty() {
267            continue;
268        }
269        let key = clean_name.to_lowercase();
270        if let Some((prev_id, prev_file)) = dc_name_map.get(&key) {
271            report.add_error(
272                file_path,
273                None,
274                Some("Name"),
275                format!(
276                    "Duplicate Dc name '{clean_name}' (Short ID {short_id}) already defined in {prev_file} (Short ID {prev_id})"
277                ),
278                Some("Ensure all Dc names are distinct"),
279            );
280        } else {
281            dc_name_map.insert(key, (short_id, file_path.to_string()));
282        }
283
284        if !file_path.contains("unicode-clarifications.csv")
285            && ctb_formats_unicode::is_known_unicode_name(clean_name)
286        {
287            report.add_error(
288                file_path,
289                None,
290                Some("Name"),
291                format!(
292                    "Dc name '{clean_name}' (Short ID {short_id}) collides with official Unicode character name"
293                ),
294                Some("Disambiguate name, or do not add Dc as duplicate"),
295            );
296        }
297    }
298
299    let mut fmt_label_map: HashMap<String, (usize, String)> = HashMap::new();
300    for &(short_id, raw_label, file_path) in format_labels {
301        let clean_label = raw_label.trim();
302        if clean_label.is_empty() {
303            continue;
304        }
305        let key = clean_label.to_lowercase();
306        if let Some((prev_id, prev_file)) = fmt_label_map.get(&key) {
307            report.add_error(
308                file_path,
309                None,
310                Some("Label"),
311                format!(
312                    "Duplicate Format label '{clean_label}' (Format ID {short_id}) already defined in {prev_file} (Format ID {prev_id})"
313                ),
314                Some("Ensure all Format labels are distinct"),
315            );
316        } else {
317            fmt_label_map
318                .insert(key.clone(), (short_id, file_path.to_string()));
319        }
320
321        // Cross-table check: Format label cannot collide with a Dc name
322        if let Some((dc_id, dc_file)) = dc_name_map.get(&key) {
323            report.add_error(
324                file_path,
325                None,
326                Some("Label"),
327                format!(
328                    "Format label '{clean_label}' (Format ID {short_id}) collides with Dc name in {dc_file} (Dc ID {dc_id})"
329                ),
330                Some("Rename format label or Dc name to resolve collision"),
331            );
332        }
333
334        // Cross-table check: Format label cannot collide with a Unicode character name
335        if ctb_formats_unicode::is_known_unicode_name(clean_label) {
336            report.add_error(
337                file_path,
338                None,
339                Some("Label"),
340                format!(
341                    "Format label '{clean_label}' (Format ID {short_id}) collides with official Unicode character name"
342                ),
343                Some("Rename format label to avoid colliding with Unicode character"),
344            );
345        }
346    }
347}