ctb_formats_dcdata/support/
csv_resolver.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//! CSV-based dataset loading for `DatasetRuleResolver` (used for CSV validation,
21//! codegen, and seed-graph consistency verification).
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::dc_char::{DcChar, DcCharExt};
31use crate::dc_def::DcDefn;
32use crate::support::syntax_validator::build_format_validation_registry;
33use crate::syntax::ast::CharTarget;
34use crate::syntax::parser::parse_dc_syntax;
35use crate::syntax::resolver::{DatasetRuleResolver, detect_container_closer};
36use std::collections::HashMap;
37
38fn parse_prefer_target(decompositions: &[String]) -> Option<CharTarget> {
39    parse_decomposition_target(decompositions, "<prefer>")
40}
41
42fn parse_decomposition_target(
43    decompositions: &[String],
44    marker: &str,
45) -> Option<CharTarget> {
46    for item in decompositions {
47        if let Some(rest) = item.trim().strip_prefix(marker) {
48            let trimmed = rest.trim();
49            if let Ok(shorthand) =
50                ctb_storage_minimal::shorthand::DcShorthand::parse(trimmed)
51            {
52                return match shorthand {
53                    ctb_storage_minimal::shorthand::DcShorthand::Short(id) => {
54                        u32::try_from(id).ok().map(CharTarget::Dc)
55                    }
56                    ctb_storage_minimal::shorthand::DcShorthand::Format(_) => {
57                        ctb_utilities::format_id::FormatId::from_shorthand(
58                            trimmed,
59                        )
60                        .map(CharTarget::Format)
61                    }
62                    ctb_storage_minimal::shorthand::DcShorthand::Unicode(
63                        cp,
64                    ) => Some(CharTarget::Unicode(cp)),
65                    _ => None,
66                };
67            }
68        }
69    }
70    None
71}
72
73impl DatasetRuleResolver {
74    /// Builds a resolver by indexing the CSV fixture dataset
75    /// in `src/formats/dcdata/data-src/`.
76    ///
77    /// Used by the consistency test verifying that the seed graph
78    /// syntax resolver is up to date with the CSV dataset.
79    ///
80    /// # Errors
81    /// Returns an error if the fixture dataset is missing or invalid.
82    pub fn load_from_embedded_dataset() -> Result<Self> {
83        let named_types_csv = crate::get_dc_data_file("README-named-types.csv")
84            .context("Missing README-named-types.csv fixture")?;
85        let named_resolver =
86            Self::load_from_dataset(&[], &[], Some(&named_types_csv))?;
87        let named_types = named_resolver.named_types.keys().cloned().collect();
88        let mut fmt_report = crate::report::ValidationReport::new();
89        let formats_dir = crate::get_formats_categories_dir_path();
90        let mut format_defns =
91            crate::format::validate_all_format_files_from_disk(
92                &formats_dir,
93                None,
94                &mut fmt_report,
95            );
96        fmt_report
97            .ensure_valid()
98            .context("Invalid format dataset for syntax resolution")?;
99        let format_ids = format_defns
100            .iter()
101            .filter_map(|defn| defn.short_id)
102            .collect();
103        let format_syntax_ids = format_defns
104            .iter()
105            .filter(|defn| defn.syntax.is_some())
106            .filter_map(|defn| defn.short_id)
107            .collect();
108        let format_registry = build_format_validation_registry(&format_defns);
109        let categories_dir = crate::get_dc_categories_dir_path();
110        let mut dc_defns = crate::validation::validate_all_dc_files_from_disk(
111            &categories_dir,
112            &format_ids,
113            None,
114            Some(&named_types),
115            None,
116            Some(&format_syntax_ids),
117            Some(&format_registry),
118            &mut fmt_report,
119        );
120        if let Some(data_src_dir) = categories_dir.parent() {
121            let (staged_impls, _) =
122                crate::wat::load_staged_dc_impls(data_src_dir)?;
123            crate::validation::attach_staged_dc_impls_to_defns_with_registry(
124                &staged_impls,
125                &mut dc_defns,
126                Some(&mut format_defns),
127                None,
128                Some(&format_registry),
129                &mut fmt_report,
130            );
131        }
132        fmt_report
133            .ensure_valid()
134            .context("Invalid Dc dataset for syntax resolution")?;
135        dc_defns.sort_by_key(|defn| defn.dc_id);
136        Self::load_from_dataset(
137            &dc_defns,
138            &format_defns,
139            Some(&named_types_csv),
140        )
141    }
142
143    /// Builds a resolver by indexing syntax rules directly from parsed
144    /// dataset definitions.
145    ///
146    /// This is the CSV-driven authoritative indexing path used by
147    /// consistency tests verifying that the seed graph syntax resolver
148    /// matches the CSV dataset. `dc_defns` must be sorted by long ID so
149    /// delimiter precedence is deterministic (matching
150    /// `lookup::get_all_dc_defns`).
151    ///
152    /// # Errors
153    /// Returns an error with CSV row and named type context when a named
154    /// type record or its grammar is invalid.
155    pub fn load_from_dataset(
156        dc_defns: &[DcDefn],
157        format_defns: &[DcDefn],
158        named_types_csv: Option<&[u8]>,
159    ) -> Result<Self> {
160        let mut named_types = Vec::new();
161        if let Some(bytes) = named_types_csv {
162            let mut rdr = csv::ReaderBuilder::new()
163                .has_headers(true)
164                .flexible(true)
165                .from_reader(bytes);
166            for (index, result) in rdr.records().enumerate() {
167                let row = index.saturating_add(2);
168                let record = result.with_context(|| {
169                    format!(
170                        "README-named-types.csv row {row}: invalid CSV record"
171                    )
172                })?;
173                let name = record.get(0).map(str::trim)
174                    .filter(|name| !name.is_empty())
175                    .with_context(|| format!("README-named-types.csv row {row}: missing named type"))?;
176                let syntax_raw = record.get(1).map(str::trim)
177                    .filter(|syntax| !syntax.is_empty())
178                    .with_context(|| format!("README-named-types.csv row {row}: named type '{name}' has no syntax"))?;
179                let rule = parse_dc_syntax(syntax_raw).with_context(|| {
180                    format!("README-named-types.csv row {row}: invalid syntax for named type '{name}': {syntax_raw}")
181                })?;
182                named_types.push((name.to_string(), rule.pattern));
183            }
184        }
185        Self::load_from_definitions(dc_defns, format_defns, named_types)
186    }
187
188    /// Builds a resolver from reconstructed or parsed character, format, and named construct definitions.
189    pub(crate) fn load_from_definitions(
190        dc_defns: &[DcDefn],
191        format_defns: &[DcDefn],
192        named_types: Vec<(String, crate::syntax::ast::SyntaxPattern)>,
193    ) -> Result<Self> {
194        let mut resolver = Self::new();
195
196        let mut explicit_closes_pairs: Vec<(u128, CharTarget)> = Vec::new();
197
198        // 1. Index rules and scripts from Document Character definitions
199        for defn in dc_defns {
200            if let Some(short_id) = defn.short_id {
201                let Ok(sid_u32) = u32::try_from(short_id) else {
202                    continue;
203                };
204                let target = CharTarget::Dc(sid_u32);
205                let sid_u128 = DcChar::from_short(sid_u32).to_u128();
206                if !defn.script.is_empty() {
207                    resolver.add_script_char(defn.script.clone(), sid_u128);
208                }
209                let preferred = parse_prefer_target(&defn.decompositions);
210                if defn.is_deprecated || preferred.is_some() {
211                    resolver.register_deprecated(target.clone(), preferred);
212                }
213                if let Some(ref rule) = defn.syntax {
214                    resolver.add_rule(target, rule.clone());
215                }
216                if let Some(ref closes) = defn.closes {
217                    let opener_target = match closes {
218                        ctb_storage_minimal::shorthand::DcShorthand::Short(id) => {
219                            u32::try_from(*id).ok().map(CharTarget::Dc)
220                        }
221                        ctb_storage_minimal::shorthand::DcShorthand::Format(id) => {
222                            ctb_utilities::format_id::FormatId::from_shorthand(&format!("f{id}"))
223                                .map(CharTarget::Format)
224                        }
225                        ctb_storage_minimal::shorthand::DcShorthand::Unicode(cp) => {
226                            Some(CharTarget::Unicode(*cp))
227                        }
228                        _ => None,
229                    };
230                    if let Some(target) = opener_target {
231                        explicit_closes_pairs.push((sid_u128, target.clone()));
232                        resolver.register_closing_delimiter(sid_u128, target);
233                    }
234                }
235            }
236        }
237
238        // Declared delimiters take precedence: a field ending in a nested
239        // representation's closer does not itself open that representation.
240        for defn in dc_defns {
241            if matches!(defn.script.as_str(), ".EM Routines" | ".EL Routines") {
242                continue;
243            }
244            if let (Some(short_id), Some(rule)) = (defn.short_id, &defn.syntax)
245            {
246                if let (Ok(id), Some(closer)) = (
247                    u32::try_from(short_id),
248                    detect_container_closer(&rule.pattern),
249                ) {
250                    let target = CharTarget::Dc(id);
251                    if !resolver.opener_to_closer.contains_key(&target) {
252                        if !resolver.closing_delimiters.contains_key(&closer) {
253                            resolver.register_closing_delimiter(closer, target);
254                        } else if let crate::syntax::ast::SyntaxPattern::Sequence(
255                            elems,
256                        ) = &rule.pattern
257                            && elems.len() >= 3
258                            && elems
259                                .get(elems.len().saturating_sub(2))
260                                .is_some_and(|el| {
261                                    el.quantifier
262                                        != crate::syntax::ast::Quantifier::ExactOne
263                                })
264                        {
265                            resolver.opener_to_closer.insert(target, closer);
266                        }
267                    }
268                }
269            }
270        }
271
272        // Index formats from formats category files under their script
273        for defn in format_defns {
274            if let Some(short_id) = defn.short_id {
275                if !defn.script.is_empty() {
276                    resolver.add_script_char(defn.script.clone(), defn.dc_id);
277                }
278                let Some(fid) =
279                    ctb_utilities::format_id::FormatId::from_shorthand(
280                        &format!("f{short_id}"),
281                    )
282                    .or_else(|| {
283                        defn.ident.as_deref().and_then(
284                            ctb_utilities::format_id::FormatId::from_ident,
285                        )
286                    })
287                else {
288                    continue;
289                };
290                let target = CharTarget::Format(fid);
291                let preferred = parse_prefer_target(&defn.decompositions);
292                if defn.is_deprecated || preferred.is_some() {
293                    resolver.register_deprecated(target.clone(), preferred);
294                }
295                if let Some(ref rule) = defn.syntax {
296                    resolver.add_rule(target.clone(), rule.clone());
297                    if let Some(closer_tok) =
298                        detect_container_closer(&rule.pattern)
299                    {
300                        if !resolver.opener_to_closer.contains_key(&target)
301                            && !resolver
302                                .closing_delimiters
303                                .contains_key(&closer_tok)
304                        {
305                            resolver
306                                .register_closing_delimiter(closer_tok, target);
307                        }
308                    }
309                }
310            }
311        }
312
313        // 2. Index named types
314        for (name, pattern) in named_types {
315            resolver.add_named_type(name, pattern);
316        }
317
318        for defn in dc_defns.iter().chain(format_defns.iter()) {
319            for imp in &defn.implies {
320                for raw_part in imp.split('&') {
321                    let trimmed = raw_part.trim();
322                    if let Ok(sh) =
323                        ctb_storage_minimal::shorthand::DcShorthand::parse(
324                            trimmed,
325                        )
326                    {
327                        if let Ok(super_gid) = sh.to_global_id() {
328                            resolver.add_subtype(defn.dc_id, super_gid);
329                        }
330                    }
331                }
332            }
333        }
334
335        let equivalents: Vec<_> = dc_defns
336            .iter()
337            .chain(format_defns.iter())
338            .flat_map(|defn| {
339                defn.decompositions.iter().filter_map(move |decomposition| {
340                    parse_decomposition_target(
341                        std::slice::from_ref(decomposition),
342                        "<equiv>",
343                    )
344                    .map(|target| (defn.dc_id, target))
345                })
346            })
347            .collect();
348        let closes_by_id: HashMap<
349            u128,
350            ctb_storage_minimal::shorthand::DcShorthand,
351        > = dc_defns
352            .iter()
353            .chain(format_defns.iter())
354            .filter_map(|d| d.closes.map(|c| (d.dc_id, c)))
355            .collect();
356        let non_routine_short_ids: Vec<u32> = dc_defns
357            .iter()
358            .filter(|d| {
359                !matches!(d.script.as_str(), ".EM Routines" | ".EL Routines")
360                    && d.syntax.is_some()
361            })
362            .filter_map(|d| d.short_id.and_then(|sid| u32::try_from(sid).ok()))
363            .collect();
364
365        resolver.finalize_equivalences_and_derived_tables(
366            &equivalents,
367            &explicit_closes_pairs,
368            &closes_by_id,
369            &non_routine_short_ids,
370        )?;
371        let mut text_decompositions = Vec::new();
372        for defn in dc_defns.iter().chain(format_defns.iter()) {
373            for decomposition in &defn.decompositions {
374                let (payload, approximate) = if let Some(payload) =
375                    decomposition.trim().strip_prefix("<equiv>")
376                {
377                    (payload, false)
378                } else if let Some(payload) =
379                    decomposition.trim().strip_prefix("<approx>")
380                {
381                    (payload, true)
382                } else {
383                    continue;
384                };
385                let targets: Option<Vec<_>> = payload
386                    .split_whitespace()
387                    .map(|token| {
388                        ctb_storage_minimal::shorthand::DcShorthand::parse(
389                            token,
390                        )
391                        .ok()?
392                        .to_global_id()
393                        .ok()
394                    })
395                    .collect();
396                if let Some(targets) = targets
397                    && !targets.is_empty()
398                {
399                    text_decompositions.push((
400                        defn.dc_id,
401                        targets,
402                        approximate,
403                    ));
404                }
405            }
406        }
407        resolver.build_unicode_text_mappings(&text_decompositions);
408        Ok(resolver)
409    }
410}