ctb_formats_dcdata/support/
seed_graph_reconstruct.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//! Offline CSV definition and `SyntaxPattern` AST reconstruction from `SeedGraphIndex`.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::collections::HashMap;
30
31use ctb_storage_minimal::shorthand::DcShorthand;
32use ctb_utilities::format_id::{
33    DC_APPLE_OS_TYPE, DC_COLLECTIVE_TOOLBOX, DC_FILE_EXTENSION,
34    DC_LINE_ENDING_CR, DC_LINE_ENDING_CR_LF, DC_LINE_ENDING_LF,
35    DC_LINE_ENDING_LF_CR, DC_LINE_ENDING_NL, DC_LINE_ENDING_RS, DC_MEDIA_TYPE,
36    DC_UNIFORM_TYPE_IDENTIFIER,
37};
38
39use crate::dc::{
40    DC_ANNOTATION, DC_APPROXIMATE_DECOMPOSITION, DC_BEGIN_ASSOCIATIVITY_GROUP,
41    DC_BEGIN_PARAMETER, DC_BIDIRECTIONAL_CLASS, DC_BOOLEAN_TRUE,
42    DC_CANONICAL_COMBINING_CLASS, DC_CANONICAL_DECOMPOSITION,
43    DC_CANONICAL_NAME, DC_CASE_MAPPING_PARTNER,
44    DC_COMPATIBILITY_DECOMPOSITION, DC_CROSS_REFERENCE, DC_DATA_BYTE_LENGTH,
45    DC_DATA_FORMAT_DESCRIPTION, DC_DC_FORMAT_EXPORT_SUPPORT,
46    DC_DC_FORMAT_IMPORT_SUPPORT, DC_DC_FORMAT_TEST_COVERAGE,
47    DC_DC_FORMAT_VARIATION_NICKNAME, DC_DEFAULT_FORMAT_VARIANT, DC_DESCRIPTION,
48    DC_END_ASSOCIATIVITY_GROUP, DC_ESCAPE, DC_EXCLUSIVE_RANGE_ENDPOINT,
49    DC_FORMAL_ALIAS, DC_FORMAT_PARAM_APPLICATION, DC_FORMAT_VARIATION_ASPECT,
50    DC_GENERAL_FORMAT_EXPORT_SUPPORT, DC_GENERAL_FORMAT_IMPORT_SUPPORT,
51    DC_GENERAL_FORMAT_TEST_COVERAGE, DC_HAS_A,
52    DC_IMPLEMENTATION_SUPPORT_LEVEL, DC_IN_CONTEXT_OF, DC_INFORMAL_ALIAS,
53    DC_IS_ASSOCIATED_WITH,
54    DC_IS_BASED_ON, DC_IS_CLOSING_DELIMITER_FOR, DC_IS_DEPRECATED,
55    DC_IS_INSTANCE_OF, DC_IS_SUBTYPE_OF, DC_MAGIC_SIGNATURE,
56    DC_NEGATED_PATTERN, DC_NICKNAME, DC_OPTIONAL_ABSENT,
57    DC_PATTERN_ALTERNATION, DC_PATTERN_CAPTURE, DC_PATTERN_REPETITION,
58    DC_PATTERN_REPLACEMENT, DC_PROGRAMMATIC_IDENTIFIER, DC_RANGE,
59    DC_REFERENCE_BOUND_VALUE, DC_REFERENCE_NAMED_OBJECT, DC_ROUTINE_INVOCATION,
60    DC_SELF_REFERENCE, DC_SEMANTIC_DECOMPOSITION,
61    DC_START_ENCAPSULATION_BINARY, DC_SUBPATTERN_MATCH, DC_SUPPORT_COMPLETE,
62    DC_SUPPORT_LOSSLESS_ROUNDTRIP, DC_SUPPORT_LOSSLESS_STRICT_VALIDATION,
63    DC_SUPPORT_NOT_APPLICABLE, DC_SUPPORT_PARTIAL, DC_SUPPORT_WORK_IN_PROGRESS,
64    DC_SYNTAX_RULE, DC_TYPE_ATOM_DC, DC_TYPE_CONVERSION, DC_TYPE_INTERSECTION,
65    DC_TYPE_NUMBER, DC_TYPE_ROUTINE, DC_TYPE_TRANSFORMATION,
66    DC_TYPE_TRANSMUTATION, DC_TYPE_UNION, DC_VALUE_RANGE, DcChar,
67};
68use crate::dc_def::{BidiClass, DcDefn, FormatDetails, GeneralCategory};
69use crate::format_spec::{DcToken, FormatExpr, decode_dc_stream};
70use crate::graph_ledger::{NumericBoundValue, SeedEntityKey};
71use crate::seed_graph::SeedGraphIndex;
72use crate::support::syntax_ast::{
73    ActionArg, CharTarget, DcSyntaxRule, NumberSubtypeConstraint, Quantifier,
74    SubtypeConstraint, SyntaxAction, SyntaxElement, SyntaxPattern, SyntaxTerm,
75};
76use crate::support::syntax_parser::format_extension_regex_pattern;
77
78#[must_use]
79fn sh(dc: DcChar) -> DcShorthand {
80    DcShorthand::from_global_id(dc.to_u128())
81}
82
83/// A single stepped element from a `.Semantic:Pattern` `&[DcShorthand]` token slice.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum PatternTokenStep<'a> {
86    /// A leaf term (character ref, range, set, named construct, or rule ref).
87    Term(SyntaxTerm),
88    /// A nested pattern group slice (`298 ... 299`) evaluated recursively as tokens.
89    Group(&'a [DcShorthand]),
90}
91
92/// Named syntax construct reconstructed from the System-block seed graph (`README-named-types.csv`).
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct ReconstructedNamedType {
95    /// System-block seed entity node ID (`586 615 565`).
96    pub seed_id: u128,
97    /// Canonical construct name (`Dc 572` `"Canonical name"`).
98    pub name: String,
99    /// Decoded syntax rule (`Dc 594` `"Syntax rule"`).
100    pub syntax: DcSyntaxRule,
101    /// Optional notes / description (`Dc 573` `"Description"`), or empty string if absent.
102    pub description: String,
103}
104
105struct CommonSubjectDefn {
106    dc_id: u128,
107    name: String,
108    description: String,
109    ident: Option<String>,
110    stable_ident: bool,
111    general_category: GeneralCategory,
112    script: String,
113    category: String,
114    is_deprecated: bool,
115    closes: Option<DcShorthand>,
116    syntax: Option<DcSyntaxRule>,
117    annotations: Vec<String>,
118    magic_names: Vec<String>,
119    cross_references: Vec<String>,
120    decompositions: Vec<String>,
121    implies: Vec<String>,
122    based_on: Vec<String>,
123    os_associations: Vec<String>,
124}
125
126impl SeedGraphIndex {
127    fn get_multi_property_strings(
128        &self,
129        subj: DcShorthand,
130        prop: DcShorthand,
131    ) -> Vec<String> {
132        self.get_multi_properties(subj, prop)
133            .iter()
134            .filter_map(|e| self.get_string(e.value).map(str::to_string))
135            .collect()
136    }
137
138    fn get_joined_multi_property_strings(
139        &self,
140        subj: DcShorthand,
141        prop: DcShorthand,
142    ) -> Option<String> {
143        let items = self.get_multi_property_strings(subj, prop);
144        (!items.is_empty()).then(|| items.join(", "))
145    }
146
147    fn reconstruct_common_subject_defn(
148        &self,
149        subj: DcShorthand,
150        skip_format_expr: bool,
151    ) -> Result<CommonSubjectDefn> {
152        let dc_id = subj.to_global_id()?;
153        // Reason for fallback: subjects were selected from active_single_props by DC_CANONICAL_NAME.
154        let name = self
155            .get_single_property_string(subj, sh(DC_CANONICAL_NAME))
156            .unwrap_or_default()
157            .to_string();
158        // Reason for fallback: subjects without an explicit description default to empty string.
159        let description = self
160            .get_single_property_string(subj, sh(DC_DESCRIPTION))
161            .unwrap_or_default()
162            .to_string();
163        let ident = self
164            .get_single_property_string(subj, sh(DC_PROGRAMMATIC_IDENTIFIER))
165            .map(str::to_string);
166        let stable_ident = self.has_stable_programmatic_identifier(subj);
167
168        let mut general_category = GeneralCategory::NonUnicodeControl;
169        let mut script = String::new();
170        for &obj in self.get_direct_objects(sh(DC_IS_INSTANCE_OF), subj) {
171            if let DcShorthand::Long(seed_id) = obj {
172                match self.get_seed_entity(seed_id) {
173                    Some(SeedEntityKey::GeneralCategory(code)) => {
174                        general_category = code.parse::<GeneralCategory>()?;
175                    }
176                    Some(SeedEntityKey::Script(s)) => {
177                        script.clone_from(s);
178                    }
179                    _ => {}
180                }
181            }
182        }
183
184        let category = category_for_dc_subject(subj, &script);
185        let is_deprecated = self.has_direct_statement(
186            sh(DC_IS_DEPRECATED),
187            subj,
188            sh(DC_BOOLEAN_TRUE),
189        );
190        let closes = self
191            .get_direct_objects(sh(DC_IS_CLOSING_DELIMITER_FOR), subj)
192            .first()
193            .copied();
194        let syntax = self.decode_syntax_rule_for_subject(subj)?;
195        let annotations =
196            self.get_multi_property_strings(subj, sh(DC_ANNOTATION));
197        let magic_names =
198            self.get_multi_property_strings(subj, sh(DC_MAGIC_SIGNATURE));
199        let cross_references = self
200            .get_multi_properties(subj, sh(DC_CROSS_REFERENCE))
201            .iter()
202            .map(|e| {
203                // Reason for fallback: cross-reference targets that have no string literal in the seed graph are formatted as their DcShorthand token.
204                self.get_string(e.value)
205                    .map_or_else(|| e.value.to_string(), str::to_string)
206            })
207            .collect();
208
209        let mut decompositions = Vec::new();
210        for (decomp_dc, tag) in [
211            (DC_CANONICAL_DECOMPOSITION, "equiv"),
212            (DC_APPROXIMATE_DECOMPOSITION, "approx"),
213            (DC_SEMANTIC_DECOMPOSITION, "semantic"),
214            (DC_COMPATIBILITY_DECOMPOSITION, "compat"),
215        ] {
216            for entry in self.get_multi_properties(subj, sh(decomp_dc)) {
217                if let Some(payload) = self.decode_decomposition_payload(
218                    entry.value,
219                    skip_format_expr,
220                ) {
221                    let ctx_objs = self.get_direct_objects(
222                        sh(DC_IN_CONTEXT_OF),
223                        DcShorthand::Long(entry.has_a_id),
224                    );
225                    if ctx_objs.is_empty() {
226                        decompositions.push(format!("<{tag}>{payload}"));
227                    } else {
228                        for &ctx_obj in ctx_objs {
229                            if let Some(ctx_str) = self
230                                .decode_decomposition_payload(
231                                    ctx_obj,
232                                    skip_format_expr,
233                                )
234                            {
235                                decompositions.push(format!(
236                                    "<{tag}@{ctx_str}>{payload}"
237                                ));
238                            }
239                        }
240                    }
241                }
242            }
243        }
244        for &pref_val in self.get_preferred_replacements(subj) {
245            if let Some(payload) =
246                self.decode_decomposition_payload(pref_val, skip_format_expr)
247            {
248                decompositions.push(format!("<prefer>{payload}"));
249            }
250        }
251
252        let implies = self
253            .get_direct_objects(sh(DC_IS_SUBTYPE_OF), subj)
254            .iter()
255            .filter_map(|&obj| {
256                self.decode_relation_target_string(obj, skip_format_expr)
257            })
258            .collect();
259        let based_on = if skip_format_expr {
260            Vec::new()
261        } else {
262            self.get_direct_objects(sh(DC_IS_BASED_ON), subj)
263                .iter()
264                .filter_map(|&obj| {
265                    self.decode_relation_target_string(obj, false)
266                })
267                .collect()
268        };
269        let os_associations = self
270            .get_direct_objects(sh(DC_IS_ASSOCIATED_WITH), subj)
271            .iter()
272            .map(ToString::to_string)
273            .collect();
274
275        Ok(CommonSubjectDefn {
276            dc_id,
277            name,
278            description,
279            ident,
280            stable_ident,
281            general_category,
282            script,
283            category,
284            is_deprecated,
285            closes,
286            syntax,
287            annotations,
288            magic_names,
289            cross_references,
290            decompositions,
291            implies,
292            based_on,
293            os_associations,
294        })
295    }
296
297    /// Reconstructs all Document Character definitions (`DcDefn` for Unicode clarifications and Short Dcs)
298    /// directly from the indexed seed graph, sorted in ascending `dc_id` order.
299    pub fn reconstruct_dc_defns(&self) -> Result<Vec<DcDefn>> {
300        self.reconstruct_dc_defns_inner(false)
301    }
302
303    pub(crate) fn reconstruct_dc_defns_for_resolver(
304        &self,
305    ) -> Result<Vec<DcDefn>> {
306        self.reconstruct_dc_defns_inner(true)
307    }
308
309    fn reconstruct_dc_defns_inner(
310        &self,
311        skip_format_expr: bool,
312    ) -> Result<Vec<DcDefn>> {
313        let sh_name = sh(DC_CANONICAL_NAME);
314        let sh_cc = sh(DC_CANONICAL_COMBINING_CLASS);
315        let sh_bidi = sh(DC_BIDIRECTIONAL_CLASS);
316        let sh_case = sh(DC_CASE_MAPPING_PARTNER);
317
318        let mut subjects: Vec<DcShorthand> = self
319            .active_single_props
320            .keys()
321            .filter_map(|&(subj, prop)| {
322                if prop == sh_name
323                    && matches!(
324                        subj,
325                        DcShorthand::Unicode(_) | DcShorthand::Short(_)
326                    )
327                {
328                    Some(subj)
329                } else {
330                    None
331                }
332            })
333            .collect();
334        subjects.sort_by_key(|s| {
335            // Reason for fallback: Unicode and Short shorthands always have valid global IDs.
336            s.to_global_id().unwrap_or(0)
337        });
338        subjects.dedup();
339
340        let mut defns = Vec::with_capacity(subjects.len());
341        for subj in subjects {
342            let common =
343                self.reconstruct_common_subject_defn(subj, skip_format_expr)?;
344            let short_id = match subj {
345                DcShorthand::Short(sid) => usize::try_from(sid).ok(),
346                _ => None,
347            };
348            // Reason for fallback: characters without a combining class statement have combining class 0.
349            let combining_class = self
350                .get_single_property_integer(subj, sh_cc)
351                .and_then(|v| u8::try_from(v).ok())
352                .unwrap_or(0);
353
354            let bidi_class = if let Some(DcShorthand::Long(seed_id)) =
355                self.get_single_property(subj, sh_bidi)
356            {
357                if let Some(SeedEntityKey::BidiClass(code)) =
358                    self.get_seed_entity(seed_id)
359                {
360                    code.parse::<BidiClass>()?
361                } else {
362                    BidiClass::BN
363                }
364            } else {
365                BidiClass::BN
366            };
367
368            let casing_partner = match self.get_single_property(subj, sh_case) {
369                Some(DcShorthand::Short(partner)) => Some(partner),
370                _ => None,
371            };
372
373            let aliases =
374                self.get_multi_property_strings(subj, sh(DC_INFORMAL_ALIAS));
375            let formal_aliases: Vec<(String, String)> = self
376                .get_multi_property_strings(subj, sh(DC_FORMAL_ALIAS))
377                .into_iter()
378                .map(|s| (String::new(), s))
379                .collect();
380
381            let format_details = if common.script.starts_with(".Formats:")
382                || common.script.starts_with("Formats:")
383            {
384                Some(FormatDetails::default())
385            } else {
386                None
387            };
388
389            let source_file = format!("{}.csv", common.category);
390            defns.push(DcDefn {
391                dc_id: common.dc_id,
392                short_id,
393                ident: common.ident,
394                stable_ident: common.stable_ident,
395                title: None,
396                name: common.name,
397                category: common.category,
398                combining_class,
399                bidi_class,
400                casing_partner,
401                general_category: common.general_category,
402                script: common.script,
403                is_deprecated: common.is_deprecated,
404                decompositions: common.decompositions,
405                aliases,
406                formal_aliases,
407                cross_references: common.cross_references,
408                annotations: common.annotations,
409                implies: common.implies,
410                based_on: common.based_on,
411                os_associations: common.os_associations,
412                magic_names: common.magic_names,
413                syntax: common.syntax,
414                closes: common.closes,
415                description: common.description,
416                format: format_details,
417                source_file,
418                line_number: 0,
419            });
420        }
421
422        Ok(defns)
423    }
424
425    /// Reconstructs all Format definitions (`DcShorthand::Format(_)`) from the active seed graph
426    /// statements, sorted by ascending `dc_id`.
427    pub fn reconstruct_format_defns(&self) -> Result<Vec<DcDefn>> {
428        self.reconstruct_format_defns_inner(false)
429    }
430
431    pub(crate) fn reconstruct_format_defns_for_resolver(
432        &self,
433    ) -> Result<Vec<DcDefn>> {
434        self.reconstruct_format_defns_inner(true)
435    }
436
437    fn reconstruct_format_defns_inner(
438        &self,
439        skip_format_expr: bool,
440    ) -> Result<Vec<DcDefn>> {
441        let sh_name = sh(DC_CANONICAL_NAME);
442        let sh_fmt_desc = sh(DC_DATA_FORMAT_DESCRIPTION);
443        let sh_ext = sh(DC_FILE_EXTENSION);
444        let sh_var_aspect = sh(DC_FORMAT_VARIATION_ASPECT);
445        let sh_var_nick = sh(DC_DC_FORMAT_VARIATION_NICKNAME);
446        let sh_def_variant = sh(DC_DEFAULT_FORMAT_VARIANT);
447        let sh_ctb = sh(DC_COLLECTIVE_TOOLBOX);
448        let sh_supp_level = sh(DC_IMPLEMENTATION_SUPPORT_LEVEL);
449
450        let mut support_by_cap_and_fmt: HashMap<
451            (DcShorthand, DcShorthand),
452            i8,
453        > = HashMap::new();
454        for cap_dc in [
455            DC_GENERAL_FORMAT_IMPORT_SUPPORT,
456            DC_DC_FORMAT_IMPORT_SUPPORT,
457            DC_GENERAL_FORMAT_EXPORT_SUPPORT,
458            DC_DC_FORMAT_EXPORT_SUPPORT,
459            DC_GENERAL_FORMAT_TEST_COVERAGE,
460            DC_DC_FORMAT_TEST_COVERAGE,
461        ] {
462            let cap_sh = sh(cap_dc);
463            for entry in self.get_multi_properties(sh_ctb, cap_sh) {
464                if let Some(level_tok) = self.get_single_property(
465                    DcShorthand::Long(entry.has_a_id),
466                    sh_supp_level,
467                ) {
468                    if let Some(level) = dc_to_support_level(level_tok) {
469                        support_by_cap_and_fmt
470                            .insert((cap_sh, entry.value), level);
471                    }
472                }
473            }
474        }
475
476        let mut subjects: Vec<DcShorthand> = self
477            .active_single_props
478            .keys()
479            .filter_map(|&(subj, prop)| {
480                if prop == sh_name && matches!(subj, DcShorthand::Format(_)) {
481                    Some(subj)
482                } else {
483                    None
484                }
485            })
486            .collect();
487        subjects.sort_by_key(|s| {
488            // Reason for fallback: Format shorthands always have valid global IDs.
489            s.to_global_id().unwrap_or(0)
490        });
491        subjects.dedup();
492
493        let mut defns = Vec::with_capacity(subjects.len());
494        for subj in subjects {
495            let common =
496                self.reconstruct_common_subject_defn(subj, skip_format_expr)?;
497            let short_id = match subj {
498                DcShorthand::Format(sid) => usize::try_from(sid).ok(),
499                _ => None,
500            };
501
502            let aliases = self.get_multi_property_strings(subj, sh(DC_NICKNAME));
503            let title = self
504                .get_multi_property_strings(subj, sh(DC_FORMAL_ALIAS))
505                .into_iter()
506                .next();
507
508            let format_spec = if skip_format_expr {
509                None
510            } else if let Some(DcShorthand::Long(expr_node_id)) =
511                self.get_single_property(subj, sh_fmt_desc)
512            {
513                Some(self.decode_format_expr_node(expr_node_id)?)
514            } else {
515                None
516            };
517
518            let ext_items: Vec<String> = self
519                .get_multi_properties(subj, sh_ext)
520                .iter()
521                .filter_map(|e| {
522                    if let Some(s) = self.get_string(e.value) {
523                        Some(s.to_string())
524                    } else if let DcShorthand::Long(pat_id) = e.value {
525                        self.decode_pattern_node(pat_id).ok().and_then(|r| {
526                            format_extension_regex_pattern(&r.pattern)
527                        })
528                    } else {
529                        None
530                    }
531                })
532                .collect();
533            let extensions = (!ext_items.is_empty()).then(|| ext_items.join(", "));
534            let mime =
535                self.get_joined_multi_property_strings(subj, sh(DC_MEDIA_TYPE));
536            let uti = self.get_joined_multi_property_strings(
537                subj,
538                sh(DC_UNIFORM_TYPE_IDENTIFIER),
539            );
540            let apple_type = self
541                .get_joined_multi_property_strings(subj, sh(DC_APPLE_OS_TYPE));
542            let nicknames = (!aliases.is_empty()).then(|| aliases.join(", "));
543
544            let format_support_pair =
545                |gen_dc: DcChar, dc_dc: DcChar| -> Option<String> {
546                    // Reason for fallback: unannotated capability defaults to support level 0.
547                    let gen_lvl = support_by_cap_and_fmt
548                        .get(&(sh(gen_dc), subj))
549                        .copied()
550                        .unwrap_or(0);
551                    // Reason for fallback: unannotated capability defaults to support level 0.
552                    let dc_lvl = support_by_cap_and_fmt
553                        .get(&(sh(dc_dc), subj))
554                        .copied()
555                        .unwrap_or(0);
556                    if gen_lvl == 0 && dc_lvl == 0 {
557                        None
558                    } else {
559                        Some(format!("{gen_lvl} {dc_lvl}"))
560                    }
561                };
562            let import_support = format_support_pair(
563                DC_GENERAL_FORMAT_IMPORT_SUPPORT,
564                DC_DC_FORMAT_IMPORT_SUPPORT,
565            );
566            let export_support = format_support_pair(
567                DC_GENERAL_FORMAT_EXPORT_SUPPORT,
568                DC_DC_FORMAT_EXPORT_SUPPORT,
569            );
570            let tests = format_support_pair(
571                DC_GENERAL_FORMAT_TEST_COVERAGE,
572                DC_DC_FORMAT_TEST_COVERAGE,
573            );
574
575            let mut varies = Vec::new();
576            let mut variant_type_items = Vec::new();
577            let vary_as = self
578                .get_single_property_string(subj, sh_var_nick)
579                .map(str::to_string);
580            for entry in self.get_multi_properties(subj, sh_var_aspect) {
581                if let DcShorthand::Format(_) = entry.value {
582                    if let Some(nick) = self
583                        .get_single_property_string(entry.value, sh_var_nick)
584                    {
585                        let v_script = format!(".Formats:v:{nick}");
586                        let direct_script = format!(".Formats:{nick}");
587                        if self
588                            .seed_entity_ids
589                            .contains_key(&SeedEntityKey::Script(v_script))
590                            || self.seed_entity_ids.contains_key(
591                                &SeedEntityKey::Script(direct_script),
592                            )
593                        {
594                            variant_type_items.push(nick.to_string());
595                        } else {
596                            varies.push(entry.value);
597                        }
598                    } else {
599                        varies.push(entry.value);
600                    }
601                }
602            }
603            let variant_types = (!variant_type_items.is_empty())
604                .then(|| variant_type_items.join(", "));
605
606            let default_line_ending =
607                match self.get_single_property(subj, sh_def_variant) {
608                    Some(tok) if tok == sh(DC_LINE_ENDING_LF) => {
609                        Some("lf".to_string())
610                    }
611                    Some(tok) if tok == sh(DC_LINE_ENDING_CR) => {
612                        Some("cr".to_string())
613                    }
614                    Some(tok) if tok == sh(DC_LINE_ENDING_CR_LF) => {
615                        Some("crlf".to_string())
616                    }
617                    Some(tok) if tok == sh(DC_LINE_ENDING_LF_CR) => {
618                        Some("lfcr".to_string())
619                    }
620                    Some(tok) if tok == sh(DC_LINE_ENDING_RS) => {
621                        Some("rs".to_string())
622                    }
623                    Some(tok) if tok == sh(DC_LINE_ENDING_NL) => {
624                        Some("nl".to_string())
625                    }
626                    _ => None,
627                };
628
629            let fmt_implies =
630                (!common.implies.is_empty()).then(|| common.implies.join(", "));
631            let fmt_based_on = (!common.based_on.is_empty())
632                .then(|| common.based_on.join(", "));
633
634            let format_details = FormatDetails {
635                implies: fmt_implies,
636                based_on: fmt_based_on,
637                chain: None,
638                format_spec,
639                extensions,
640                mime,
641                uti,
642                apple_type,
643                nicknames,
644                import_support,
645                export_support,
646                tests,
647                variant_types,
648                title: title.clone(),
649                default_line_ending,
650                vary_as,
651                varies,
652            };
653
654            let source_file = format!("{}.csv", common.category);
655            defns.push(DcDefn {
656                dc_id: common.dc_id,
657                short_id,
658                ident: common.ident,
659                stable_ident: common.stable_ident,
660                title,
661                name: common.name,
662                category: common.category,
663                combining_class: 0,
664                bidi_class: BidiClass::BN,
665                casing_partner: None,
666                general_category: GeneralCategory::NonUnicodeControl,
667                script: common.script,
668                is_deprecated: common.is_deprecated,
669                decompositions: common.decompositions,
670                aliases,
671                formal_aliases: Vec::new(),
672                cross_references: common.cross_references,
673                annotations: common.annotations,
674                implies: common.implies,
675                based_on: common.based_on,
676                os_associations: common.os_associations,
677                magic_names: common.magic_names,
678                syntax: common.syntax,
679                closes: common.closes,
680                description: common.description,
681                format: Some(format_details),
682                source_file,
683                line_number: 0,
684            });
685        }
686
687        Ok(defns)
688    }
689
690    /// Reconstructs all active named syntax constructs (`SeedEntityKey::NamedConstruct`)
691    /// that define a `Dc 594` (`Syntax rule`) in the seed graph, ordered by ascending
692    /// entity node ID.
693    pub fn reconstruct_named_types(&self) -> Result<Vec<ReconstructedNamedType>> {
694        let sh_desc = sh(DC_DESCRIPTION);
695        let mut constructs: Vec<(u128, String)> = self
696            .seed_entity_ids
697            .iter()
698            .filter_map(|(key, &seed_id)| match key {
699                SeedEntityKey::NamedConstruct(name) => {
700                    Some((seed_id, name.clone()))
701                }
702                _ => None,
703            })
704            .collect();
705        constructs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
706
707        let mut out = Vec::with_capacity(constructs.len());
708        for (seed_id, name) in constructs {
709            let subj = DcShorthand::Long(seed_id);
710            let Some(syntax) = self.decode_syntax_rule_for_subject(subj)?
711            else {
712                continue;
713            };
714            // Reason for fallback: named constructs without an explicit Dc 573 description default to empty string.
715            let description = self
716                .get_single_property_string(subj, sh_desc)
717                .unwrap_or_default()
718                .to_string();
719            out.push(ReconstructedNamedType {
720                seed_id,
721                name,
722                syntax,
723                description,
724            });
725        }
726        Ok(out)
727    }
728
729    /// Decodes a `FormatExpr` value node by its `node_id`.
730    pub fn decode_format_expr_node(&self, node_id: u128) -> Result<FormatExpr> {
731        let node = self.get_active_node(node_id).with_context(|| {
732            format!("FormatExpr value node l{node_id} not found or inactive in seed graph")
733        })?;
734        let sh_var_nick = sh(DC_DC_FORMAT_VARIATION_NICKNAME);
735        let sh_begin_param = sh(DC_BEGIN_PARAMETER);
736        let mut dc_tokens = Vec::with_capacity(node.tokens.len());
737        let mut prev_tok = None;
738        for &tok in &node.tokens {
739            if prev_tok == Some(sh_begin_param) {
740                if let Some(nick) =
741                    self.get_single_property_string(tok, sh_var_nick)
742                {
743                    dc_tokens.push(DcToken::NamedType(nick.to_string()));
744                    prev_tok = Some(tok);
745                    continue;
746                }
747            }
748            if let DcShorthand::Long(id) = tok {
749                if let Some(SeedEntityKey::NamedConstruct(name)) =
750                    self.get_seed_entity(id)
751                {
752                    dc_tokens.push(DcToken::NamedType(name.clone()));
753                } else if let Some(int_val) = self.get_integer(tok) {
754                    dc_tokens.push(DcToken::NamedType(int_val.to_string()));
755                } else if let Some(str_val) = self.get_string(tok) {
756                    dc_tokens.push(DcToken::NamedType(str_val.to_string()));
757                } else {
758                    dc_tokens.push(DcToken::Dc(tok));
759                }
760            } else {
761                dc_tokens.push(DcToken::Dc(tok));
762            }
763            prev_tok = Some(tok);
764        }
765        decode_dc_stream(&dc_tokens).with_context(|| {
766            format!("Failed to decode FormatExpr tokens in node l{node_id}")
767        })
768    }
769
770    fn node_starts_format_expr(tokens: &[DcShorthand]) -> bool {
771        let is_format_op = |tok: DcShorthand| -> bool {
772            tok == sh(DC_TYPE_UNION)
773                || tok == sh(DC_TYPE_TRANSFORMATION)
774                || tok == sh(DC_TYPE_CONVERSION)
775                || tok == sh(DC_TYPE_TRANSMUTATION)
776                || tok == sh(DC_TYPE_INTERSECTION)
777                || tok == sh(DC_FORMAT_PARAM_APPLICATION)
778        };
779        tokens.first().is_some_and(|&t| {
780            is_format_op(t)
781                || (t == sh(DC_BEGIN_ASSOCIATIVITY_GROUP)
782                    && tokens.get(1).copied().is_some_and(is_format_op))
783        })
784    }
785
786    fn decode_decomposition_payload(
787        &self,
788        val_tok: DcShorthand,
789        skip_format_expr: bool,
790    ) -> Option<String> {
791        if let Some(s) = self.get_string(val_tok) {
792            if skip_format_expr {
793                if s.trim_start().starts_with('(') {
794                    return None;
795                }
796                if !s
797                    .split_whitespace()
798                    .all(|tok| DcShorthand::parse(tok).is_ok())
799                {
800                    let u_tokens: Vec<String> = s
801                        .chars()
802                        .map(|ch| {
803                            DcShorthand::Unicode(u32::from(ch)).to_string()
804                        })
805                        .collect();
806                    return Some(u_tokens.join(" "));
807                }
808            }
809            return Some(s.to_string());
810        }
811        if let DcShorthand::Long(node_id) = val_tok {
812            if let Some(node) = self.get_active_node(node_id) {
813                if Self::node_starts_format_expr(&node.tokens) {
814                    if skip_format_expr {
815                        return None;
816                    }
817                    if let Ok(expr) = self.decode_format_expr_node(node_id) {
818                        return Some(crate::format_spec::format_expr(&expr));
819                    }
820                }
821                let expanded = self.expand_interned_string_nodes(&node.tokens);
822                let parts: Vec<String> =
823                    expanded.iter().map(ToString::to_string).collect();
824                return Some(parts.join(" "));
825            }
826        }
827        Some(val_tok.to_string())
828    }
829
830    fn decode_relation_target_string(
831        &self,
832        obj: DcShorthand,
833        skip_format_expr: bool,
834    ) -> Option<String> {
835        if let Some(s) = self.get_string(obj) {
836            return Some(s.to_string());
837        }
838        if let DcShorthand::Long(node_id) = obj {
839            if let Some(node) = self.get_active_node(node_id)
840                && Self::node_starts_format_expr(&node.tokens)
841            {
842                if skip_format_expr {
843                    return None;
844                }
845                if let Ok(expr) = self.decode_format_expr_node(node_id) {
846                    return Some(crate::format_spec::format_expr(&expr));
847                }
848            }
849            if skip_format_expr {
850                return None;
851            }
852            if let Ok(rule) = self.decode_pattern_node(node_id) {
853                return Some(rule.pattern.format_dsl());
854            }
855        }
856        Some(obj.to_string())
857    }
858
859    /// Decodes a `.Semantic:Pattern` value node by its `node_id` into a `DcSyntaxRule`.
860    pub fn decode_pattern_node(&self, node_id: u128) -> Result<DcSyntaxRule> {
861        let node = self.get_active_node(node_id).with_context(|| {
862            format!("Pattern value node l{node_id} not found or inactive in seed graph")
863        })?;
864        self.decode_syntax_rule_tokens(&node.tokens)
865            .with_context(|| {
866                format!(
867                    "Failed to decode .Semantic:Pattern tokens in node l{node_id}"
868                )
869            })
870    }
871
872    /// Resolves and decodes the active `Dc 594` (`Syntax rule`) property for `subj`, if present.
873    pub fn decode_syntax_rule_for_subject(
874        &self,
875        subj: DcShorthand,
876    ) -> Result<Option<DcSyntaxRule>> {
877        let Some(val_tok) = self.get_single_property(subj, sh(DC_SYNTAX_RULE))
878        else {
879            return Ok(None);
880        };
881        let DcShorthand::Long(node_id) = val_tok else {
882            bail!(
883                "Expected Long node ID for Syntax rule (Dc 594) on {subj}, found {val_tok}"
884            );
885        };
886        self.decode_pattern_node(node_id).map(Some)
887    }
888
889    /// Resolves and decodes the active `SyntaxPattern` for a named syntax construct
890    /// (e.g. `"number"`, `"string"`, `"value"`), if present in the seed graph.
891    pub fn decode_named_construct_pattern(
892        &self,
893        name: &str,
894    ) -> Result<Option<SyntaxPattern>> {
895        let key = SeedEntityKey::NamedConstruct(name.to_string());
896        let Some(seed_id) = self.get_seed_entity_id(&key) else {
897            return Ok(None);
898        };
899        let Some(rule) =
900            self.decode_syntax_rule_for_subject(DcShorthand::Long(seed_id))?
901        else {
902            return Ok(None);
903        };
904        Ok(Some(rule.pattern))
905    }
906
907    /// Decodes a `.Semantic:Pattern` token sequence into a `DcSyntaxRule`.
908    pub fn decode_syntax_rule_tokens(
909        &self,
910        tokens: &[DcShorthand],
911    ) -> Result<DcSyntaxRule> {
912        ensure!(
913            !tokens.is_empty(),
914            "Cannot decode empty .Semantic:Pattern token sequence"
915        );
916        let (pattern_tokens, action) =
917            self.split_trailing_syntax_action(tokens)?;
918        let pattern = self.decode_syntax_pattern_tokens(pattern_tokens)?;
919        let raw = DcSyntaxRule::format_dsl_parts(&pattern, action.as_ref());
920        Ok(DcSyntaxRule {
921            pattern,
922            action,
923            raw,
924        })
925    }
926
927    fn split_trailing_syntax_action<'a>(
928        &self,
929        tokens: &'a [DcShorthand],
930    ) -> Result<(&'a [DcShorthand], Option<SyntaxAction>)> {
931        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
932        let sh_close = sh(DC_END_ASSOCIATIVITY_GROUP);
933        let sh_repl = sh(DC_PATTERN_REPLACEMENT);
934        let sh_invoke = sh(DC_ROUTINE_INVOCATION);
935        let sh_ref_var = sh(DC_REFERENCE_NAMED_OBJECT);
936
937        if tokens.last() != Some(&sh_close) {
938            return Ok((tokens, None));
939        }
940        // Find the matching `298` (`Begin associativity group`) for the final `299`.
941        let mut depth = 0usize;
942        let mut open_idx = None;
943        for (idx, &tok) in tokens.iter().enumerate().rev() {
944            if tok == sh_close {
945                depth = depth.saturating_add(1);
946            } else if tok == sh_open {
947                depth = depth.saturating_sub(1);
948                if depth == 0 {
949                    open_idx = Some(idx);
950                    break;
951                }
952            }
953        }
954        let Some(start) = open_idx else {
955            bail!(
956                "Unbalanced EndAssociativityGroup (299) in pattern token stream"
957            );
958        };
959        let group_slice = tokens
960            .get(start..)
961            .context("Invalid syntax action group token start index")?;
962        if group_slice.get(1) != Some(&sh_repl) {
963            return Ok((tokens, None));
964        }
965        ensure!(
966            group_slice.get(2) == Some(&sh_invoke),
967            "Expected RoutineInvocation (273) after PatternReplacement (607) in syntax action"
968        );
969        let method_tok = *group_slice
970            .get(3)
971            .context("Missing method string node in syntax action")?;
972        let method = self
973            .get_string(method_tok)
974            .with_context(|| {
975                format!(
976                    "Syntax action method token {method_tok} is not a string value node"
977                )
978            })?
979            .to_string();
980
981        let mut args = Vec::new();
982        let mut idx = 4usize;
983        let end_exclusive = group_slice.len().saturating_sub(1);
984        while idx < end_exclusive {
985            let tok = *group_slice
986                .get(idx)
987                .context("Unexpected end of syntax action arguments")?;
988            if tok == sh_ref_var {
989                idx = idx.saturating_add(1);
990                let var_tok = *group_slice.get(idx).context(
991                    "Missing variable name token after ReferenceNamedObject (272)",
992                )?;
993                let var_name = self
994                    .get_string(var_tok)
995                    .with_context(|| {
996                        format!(
997                            "Action variable token {var_tok} is not a string value node"
998                        )
999                    })?
1000                    .to_string();
1001                args.push(ActionArg::Variable(var_name));
1002                idx = idx.saturating_add(1);
1003            } else {
1004                let lit_val = self
1005                    .get_string(tok)
1006                    .with_context(|| {
1007                        format!(
1008                            "Action literal token {tok} is not a string value node"
1009                        )
1010                    })?
1011                    .to_string();
1012                args.push(ActionArg::Literal(lit_val));
1013                idx = idx.saturating_add(1);
1014            }
1015        }
1016
1017        let pattern_slice = tokens
1018            .get(..start)
1019            .context("Invalid token slice preceding syntax action")?;
1020        Ok((pattern_slice, Some(SyntaxAction { method, args })))
1021    }
1022
1023    /// Strips any trailing `298 607 ... 299` (`Pattern replacement`) action group from `tokens`.
1024    pub fn strip_pattern_action_tokens<'a>(
1025        &self,
1026        tokens: &'a [DcShorthand],
1027    ) -> Result<&'a [DcShorthand]> {
1028        let (pattern_slice, _) = self.split_trailing_syntax_action(tokens)?;
1029        Ok(pattern_slice)
1030    }
1031
1032    /// Returns true if the `.Semantic:Pattern` token sequence begins with `Dc 599 "Self reference"`
1033    /// (or an alternation whose first branch begins with `Dc 599 "Self reference"`).
1034    #[must_use]
1035    pub fn pattern_tokens_start_with_self(
1036        &self,
1037        tokens: &[DcShorthand],
1038    ) -> bool {
1039        let sh_self = sh(DC_SELF_REFERENCE);
1040        if tokens.first() == Some(&sh_self) {
1041            return true;
1042        }
1043        if let Ok(Some(branches)) = self.split_alternation_branches(tokens) {
1044            if let Some(first_branch) = branches.first() {
1045                return self.pattern_tokens_start_with_self(first_branch);
1046            }
1047        }
1048        false
1049    }
1050
1051    /// Returns true if the `.Semantic:Pattern` token sequence begins with `Dc 599 "Self reference"`
1052    /// or a character set (`298 604 ...` or `298 602 <non-group> ...`).
1053    #[must_use]
1054    pub fn pattern_tokens_start_with_self_or_charset(
1055        &self,
1056        tokens: &[DcShorthand],
1057    ) -> bool {
1058        let sh_self = sh(DC_SELF_REFERENCE);
1059        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1060        let sh_neg = sh(DC_NEGATED_PATTERN);
1061        let sh_alt = sh(DC_PATTERN_ALTERNATION);
1062        if tokens.first() == Some(&sh_self) {
1063            return true;
1064        }
1065        if tokens.first() == Some(&sh_open) {
1066            if tokens.get(1) == Some(&sh_neg) {
1067                return true;
1068            }
1069            if tokens.get(1) == Some(&sh_alt) && tokens.get(2) != Some(&sh_open)
1070            {
1071                return true;
1072            }
1073        }
1074        if let Ok(Some(branches)) = self.split_alternation_branches(tokens) {
1075            if let Some(first_branch) = branches.first() {
1076                return self
1077                    .pattern_tokens_start_with_self_or_charset(first_branch);
1078            }
1079        }
1080        false
1081    }
1082
1083    /// Returns true if any leading element of `tokens` (accounting for nullable
1084    /// leading elements) explicitly targets a character satisfying `pred`.
1085    #[must_use]
1086    pub fn pattern_tokens_can_start_with_token(
1087        &self,
1088        raw_tokens: &[DcShorthand],
1089        pred: &mut impl FnMut(u128) -> bool,
1090    ) -> bool {
1091        let Ok(tokens) = self.strip_pattern_action_tokens(raw_tokens) else {
1092            return false;
1093        };
1094        if let Ok(Some(branches)) = self.split_alternation_branches(tokens) {
1095            return branches
1096                .iter()
1097                .any(|b| self.pattern_tokens_can_start_with_token(b, pred));
1098        }
1099        let mut idx = 0usize;
1100        while idx < tokens.len() {
1101            let Ok((step, quantifier, after_idx)) =
1102                self.step_pattern_token_slice(tokens, idx)
1103            else {
1104                break;
1105            };
1106            let hit = match step {
1107                PatternTokenStep::Group(inner) => {
1108                    self.pattern_tokens_can_start_with_token(inner, pred)
1109                }
1110                PatternTokenStep::Term(
1111                    SyntaxTerm::CharRef(target)
1112                    | SyntaxTerm::RuleRef { target },
1113                ) => pred(target.to_u128()),
1114                PatternTokenStep::Term(SyntaxTerm::Group(pat)) => {
1115                    pat.can_start_with_token(pred)
1116                }
1117                PatternTokenStep::Term(_) => false,
1118            };
1119            if hit {
1120                return true;
1121            }
1122            if !quantifier.allows_zero() {
1123                break;
1124            }
1125            idx = after_idx;
1126        }
1127        false
1128    }
1129
1130    /// Steps a single quantified element from `tokens` at `idx` without constructing
1131    /// a `SyntaxPattern` AST for nested groups (`298 ... 299`).
1132    pub fn step_pattern_token_slice<'a>(
1133        &self,
1134        tokens: &'a [DcShorthand],
1135        idx: usize,
1136    ) -> Result<(PatternTokenStep<'a>, Quantifier, usize)> {
1137        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1138        let sh_neg = sh(DC_NEGATED_PATTERN);
1139        let sh_alt = sh(DC_PATTERN_ALTERNATION);
1140        let sh_sub = sh(DC_SUBPATTERN_MATCH);
1141
1142        if tokens.get(idx) == Some(&sh_open) {
1143            let close_idx = find_matching_group_close(tokens, idx)?
1144                .context("Unclosed BeginAssociativityGroup (298) in pattern")?;
1145            let inner = tokens
1146                .get(idx.saturating_add(1)..close_idx)
1147                .context("Invalid group token range")?;
1148            let after_group = close_idx.saturating_add(1);
1149            let is_leaf_group = inner.first().is_some_and(|&f| {
1150                f == sh_neg
1151                    || f == sh_sub
1152                    || (f == sh_alt && inner.get(1) != Some(&sh_open))
1153            });
1154            if !is_leaf_group {
1155                let (quantifier, after_quant) =
1156                    self.decode_optional_quantifier_at(tokens, after_group)?;
1157                return Ok((
1158                    PatternTokenStep::Group(inner),
1159                    quantifier,
1160                    after_quant,
1161                ));
1162            }
1163        }
1164
1165        let (term, after_term) = self.decode_syntax_term_at(tokens, idx)?;
1166        let (quantifier, after_quant) =
1167            self.decode_optional_quantifier_at(tokens, after_term)?;
1168        Ok((PatternTokenStep::Term(term), quantifier, after_quant))
1169    }
1170
1171    /// If `tokens` is a top-level `298 602 (branch1) (branch2) ... 299` alternation, returns
1172    /// the inner token slices for each branch without allocating a recursive AST.
1173    pub fn split_alternation_branches<'a>(
1174        &self,
1175        tokens: &'a [DcShorthand],
1176    ) -> Result<Option<Vec<&'a [DcShorthand]>>> {
1177        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1178        let sh_alt = sh(DC_PATTERN_ALTERNATION);
1179
1180        if tokens.first() == Some(&sh_open) && tokens.get(1) == Some(&sh_alt) {
1181            if let Some(close_idx) = find_matching_group_close(tokens, 0)? {
1182                if close_idx.saturating_add(1) == tokens.len() {
1183                    let inner = tokens
1184                        .get(2..close_idx)
1185                        .context("Invalid alternation group bounds")?;
1186                    if inner.first() == Some(&sh_open) {
1187                        let mut branches = Vec::new();
1188                        let mut idx = 0usize;
1189                        while idx < inner.len() {
1190                            ensure!(
1191                                inner.get(idx) == Some(&sh_open),
1192                                "Expected BeginAssociativityGroup (298) for alternation branch at index {idx}"
1193                            );
1194                            let branch_close =
1195                                find_matching_group_close(inner, idx)?
1196                                    .context(
1197                                        "Unclosed alternation branch group",
1198                                    )?;
1199                            let branch_tokens = inner
1200                                .get(idx.saturating_add(1)..branch_close)
1201                                .context(
1202                                    "Invalid alternation branch slice bounds",
1203                                )?;
1204                            branches.push(branch_tokens);
1205                            idx = branch_close.saturating_add(1);
1206                        }
1207                        return Ok(Some(branches));
1208                    }
1209                }
1210            }
1211        }
1212        Ok(None)
1213    }
1214
1215    /// Decodes a single quantified [`SyntaxElement`] at `idx` from a `.Semantic:Pattern` token slice,
1216    /// returning `(element, next_idx)`.
1217    pub fn step_pattern_element_tokens(
1218        &self,
1219        tokens: &[DcShorthand],
1220        idx: usize,
1221    ) -> Result<(SyntaxElement, usize)> {
1222        let (term, after_term) = self.decode_syntax_term_at(tokens, idx)?;
1223        let (quantifier, after_quant) =
1224            self.decode_optional_quantifier_at(tokens, after_term)?;
1225        Ok((SyntaxElement::with_quantifier(term, quantifier), after_quant))
1226    }
1227
1228    fn decode_syntax_pattern_tokens(
1229        &self,
1230        tokens: &[DcShorthand],
1231    ) -> Result<SyntaxPattern> {
1232        if let Some(branch_slices) = self.split_alternation_branches(tokens)? {
1233            let mut branches = Vec::with_capacity(branch_slices.len());
1234            for branch_tokens in branch_slices {
1235                branches
1236                    .push(self.decode_syntax_pattern_tokens(branch_tokens)?);
1237            }
1238            return Ok(SyntaxPattern::Alternation(branches));
1239        }
1240
1241        let mut elements = Vec::new();
1242        let mut idx = 0usize;
1243        while idx < tokens.len() {
1244            let (elem, after_quant) =
1245                self.step_pattern_element_tokens(tokens, idx)?;
1246            elements.push(elem);
1247            idx = after_quant;
1248        }
1249        Ok(SyntaxPattern::Sequence(elements))
1250    }
1251
1252    fn decode_syntax_term_at(
1253        &self,
1254        tokens: &[DcShorthand],
1255        idx: usize,
1256    ) -> Result<(SyntaxTerm, usize)> {
1257        let sh_self = sh(DC_SELF_REFERENCE);
1258        let sh_range = sh(DC_RANGE);
1259        let sh_value_range = sh(DC_VALUE_RANGE);
1260        let sh_atom_dc = sh(DC_TYPE_ATOM_DC);
1261        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1262        let sh_neg = sh(DC_NEGATED_PATTERN);
1263        let sh_alt = sh(DC_PATTERN_ALTERNATION);
1264        let sh_sub = sh(DC_SUBPATTERN_MATCH);
1265        let sh_type_union = sh(DC_TYPE_UNION);
1266        let sh_has_a = sh(DC_HAS_A);
1267        let sh_capture = sh(DC_PATTERN_CAPTURE);
1268
1269        let tok = *tokens
1270            .get(idx)
1271            .context("Unexpected end of pattern token stream")?;
1272
1273        if tok == sh_self {
1274            return Ok((SyntaxTerm::SelfChar, idx.saturating_add(1)));
1275        }
1276
1277        if tok == sh_value_range {
1278            ensure!(
1279                tokens.get(idx.saturating_add(1)) == Some(&sh_atom_dc),
1280                "Expected AtomDc (Dc 640) domain token after Range (Dc 643) in pattern term"
1281            );
1282            let mut next_idx = idx.saturating_add(2);
1283            let start = consume_pattern_char_target(tokens, &mut next_idx)
1284                .context(
1285                    "Missing start token after Range (Dc 643) AtomDc (Dc 640)",
1286                )?;
1287            let end = consume_pattern_char_target(tokens, &mut next_idx)
1288                .context(
1289                    "Missing end token after Range (Dc 643) AtomDc (Dc 640)",
1290                )?;
1291            return Ok((SyntaxTerm::CharRange { start, end }, next_idx));
1292        }
1293
1294        if tok == sh_range {
1295            let mut next_idx = idx.saturating_add(1);
1296            let start = consume_pattern_char_target(tokens, &mut next_idx)
1297                .context("Missing start token after Range (Dc 4)")?;
1298            let end = consume_pattern_char_target(tokens, &mut next_idx)
1299                .context("Missing end token after Range (Dc 4)")?;
1300            return Ok((SyntaxTerm::CharRange { start, end }, next_idx));
1301        }
1302
1303        if tok == sh_open {
1304            let close_idx = find_matching_group_close(tokens, idx)?
1305                .context("Unclosed BeginAssociativityGroup (298) in pattern")?;
1306            let inner = tokens
1307                .get(idx.saturating_add(1)..close_idx)
1308                .context("Invalid group token range")?;
1309            let next_idx = close_idx.saturating_add(1);
1310
1311            let Some(&first_inner) = inner.first() else {
1312                return Ok((
1313                    SyntaxTerm::Group(SyntaxPattern::Sequence(Vec::new())),
1314                    next_idx,
1315                ));
1316            };
1317
1318            if first_inner == sh_neg {
1319                let mut members =
1320                    Vec::with_capacity(inner.len().saturating_sub(1));
1321                let mut m_idx = 1usize;
1322                while m_idx < inner.len() {
1323                    members.push(consume_pattern_char_target(
1324                        inner, &mut m_idx,
1325                    )?);
1326                }
1327                return Ok((
1328                    SyntaxTerm::CharSet {
1329                        negated: true,
1330                        members,
1331                    },
1332                    next_idx,
1333                ));
1334            }
1335
1336            if first_inner == sh_alt && inner.get(1) != Some(&sh_open) {
1337                let mut members =
1338                    Vec::with_capacity(inner.len().saturating_sub(1));
1339                let mut m_idx = 1usize;
1340                while m_idx < inner.len() {
1341                    members.push(consume_pattern_char_target(
1342                        inner, &mut m_idx,
1343                    )?);
1344                }
1345                return Ok((
1346                    SyntaxTerm::CharSet {
1347                        negated: false,
1348                        members,
1349                    },
1350                    next_idx,
1351                ));
1352            }
1353
1354            if first_inner == sh_sub {
1355                let target_tok = *inner.get(1).context(
1356                    "Missing target token after SubpatternMatch (605)",
1357                )?;
1358                if target_tok == sh_type_union {
1359                    let construct_tok = *inner.get(2).context(
1360                        "Missing construct token after TypeUnion (300) in SubpatternMatch (605)",
1361                    )?;
1362                    let DcShorthand::Long(seed_id) = construct_tok else {
1363                        bail!(
1364                            "Expected Long seed entity ID after TypeUnion (300) in SubpatternMatch (605), found {construct_tok}"
1365                        );
1366                    };
1367                    let Some(SeedEntityKey::NamedConstruct(name)) =
1368                        self.get_seed_entity(seed_id)
1369                    else {
1370                        bail!(
1371                            "Expected NamedConstruct seed entity l{seed_id} in SubpatternMatch (605) TypeUnion (300)"
1372                        );
1373                    };
1374                    let (constraint_tokens, rem) = if inner.get(3)
1375                        == Some(&sh_open)
1376                    {
1377                        let group_close = find_matching_group_close(inner, 3)?
1378                            .context(
1379                                "Unclosed nested pattern group in NamedConstruct subtype",
1380                            )?;
1381                        let c_slice = inner
1382                            .get(3..=group_close)
1383                            .context("Invalid nested subtype group bounds")?;
1384                        let r_slice = inner
1385                            .get(group_close.saturating_add(1)..)
1386                            .context("Invalid trailing subtype slice bounds")?;
1387                        (c_slice, r_slice)
1388                    } else if inner.len() >= 5
1389                        && inner.get(inner.len().saturating_sub(2))
1390                            == Some(&sh_capture)
1391                    {
1392                        let split_at = inner.len().saturating_sub(2);
1393                        let c_slice = inner
1394                            .get(3..split_at)
1395                            .context("Invalid subtype token slice")?;
1396                        let r_slice = inner
1397                            .get(split_at..)
1398                            .context("Invalid capture token slice")?;
1399                        (c_slice, r_slice)
1400                    } else {
1401                        let c_slice = inner
1402                            .get(3..)
1403                            .context("Missing subtype constraint tokens")?;
1404                        (c_slice, &[][..])
1405                    };
1406                    let sub_constraint = self
1407                        .decode_named_construct_subtype_tokens(
1408                            name,
1409                            constraint_tokens,
1410                        )?;
1411                    let capture_var = if rem.is_empty() {
1412                        None
1413                    } else {
1414                        ensure!(
1415                            rem.len() == 2 && rem.first() == Some(&sh_capture),
1416                            "Unexpected trailing tokens after NamedConstruct subtype: {rem:?}"
1417                        );
1418                        let var_tok = *rem.get(1).context(
1419                            "Missing capture variable token after PatternCapture (606)",
1420                        )?;
1421                        let var_str = self
1422                            .get_string(var_tok)
1423                            .with_context(|| {
1424                                format!(
1425                                    "NamedConstruct capture variable token {var_tok} is not a string node"
1426                                )
1427                            })?
1428                            .to_string();
1429                        Some(var_str)
1430                    };
1431                    return Ok((
1432                        SyntaxTerm::NamedConstruct {
1433                            name: name.clone(),
1434                            subtype: Some(sub_constraint),
1435                            capture_var,
1436                        },
1437                        next_idx,
1438                    ));
1439                }
1440                if let DcShorthand::Long(seed_id) = target_tok {
1441                    match self.get_seed_entity(seed_id) {
1442                        Some(SeedEntityKey::Script(script_name)) => {
1443                            let mut capture_var = None;
1444                            let mut pos = 2usize;
1445                            while pos < inner.len() {
1446                                let qual = *inner.get(pos).context(
1447                                    "Unexpected end of SubpatternMatch",
1448                                )?;
1449                                if qual == sh_capture {
1450                                    let var_tok = *inner
1451                                        .get(pos.saturating_add(1))
1452                                        .context(
1453                                            "Missing capture variable string node after PatternCapture (606)",
1454                                        )?;
1455                                    let var_str = self
1456                                        .get_string(var_tok)
1457                                        .with_context(|| {
1458                                            format!(
1459                                                "Script capture variable token {var_tok} is not a string node"
1460                                            )
1461                                        })?
1462                                        .to_string();
1463                                    capture_var = Some(var_str);
1464                                    pos = pos.saturating_add(2);
1465                                } else {
1466                                    bail!(
1467                                        "Unexpected qualifier token {qual} in Script SubpatternMatch"
1468                                    );
1469                                }
1470                            }
1471                            return Ok((
1472                                SyntaxTerm::NamedConstruct {
1473                                    name: "script".to_string(),
1474                                    subtype: Some(SubtypeConstraint::Target(
1475                                        script_name.clone(),
1476                                    )),
1477                                    capture_var,
1478                                },
1479                                next_idx,
1480                            ));
1481                        }
1482                        Some(SeedEntityKey::NamedConstruct(name)) => {
1483                            let mut subtype = None;
1484                            let mut capture_var = None;
1485                            let mut pos = 2usize;
1486                            while pos < inner.len() {
1487                                let qual = *inner.get(pos).context(
1488                                    "Unexpected end of SubpatternMatch",
1489                                )?;
1490                                if qual == sh_has_a {
1491                                    let sub_tok = *inner
1492                                        .get(pos.saturating_add(1))
1493                                        .context(
1494                                            "Missing subtype string node after HasA (584)",
1495                                        )?;
1496                                    let sub_str = self
1497                                        .get_string(sub_tok)
1498                                        .with_context(|| {
1499                                            format!(
1500                                                "NamedConstruct subtype token {sub_tok} is not a string node"
1501                                            )
1502                                        })?;
1503                                    subtype = Some(SubtypeConstraint::parse(
1504                                        name, sub_str,
1505                                    )?);
1506                                    pos = pos.saturating_add(2);
1507                                } else if qual == sh_capture {
1508                                    let var_tok = *inner
1509                                        .get(pos.saturating_add(1))
1510                                        .context(
1511                                            "Missing capture variable string node after PatternCapture (606)",
1512                                        )?;
1513                                    let var_str = self
1514                                        .get_string(var_tok)
1515                                        .with_context(|| {
1516                                            format!(
1517                                                "NamedConstruct capture variable token {var_tok} is not a string node"
1518                                            )
1519                                        })?
1520                                        .to_string();
1521                                    capture_var = Some(var_str);
1522                                    pos = pos.saturating_add(2);
1523                                } else {
1524                                    bail!(
1525                                        "Unexpected qualifier token {qual} in NamedConstruct SubpatternMatch"
1526                                    );
1527                                }
1528                            }
1529                            return Ok((
1530                                SyntaxTerm::NamedConstruct {
1531                                    name: name.clone(),
1532                                    subtype,
1533                                    capture_var,
1534                                },
1535                                next_idx,
1536                            ));
1537                        }
1538                        _ => {
1539                            ensure!(
1540                                inner.len() == 2,
1541                                "Unexpected extra tokens in Long SubpatternMatch: {inner:?}"
1542                            );
1543                            let resolved_id = self
1544                                .resolve_latest_node_id(seed_id)
1545                                .with_context(|| {
1546                                    format!(
1547                                        "Referenced subpattern node l{seed_id} not found or inactive in pinned seed graph"
1548                                    )
1549                                })?;
1550                            let sub_pat = if let Some(DcShorthand::Long(
1551                                rule_pat_id,
1552                            )) = self.get_single_property(
1553                                DcShorthand::Long(resolved_id),
1554                                sh(DC_SYNTAX_RULE),
1555                            ) {
1556                                self.decode_pattern_node(rule_pat_id)?
1557                            } else {
1558                                self.decode_pattern_node(resolved_id)?
1559                            };
1560                            return Ok((
1561                                SyntaxTerm::Group(sub_pat.pattern),
1562                                next_idx,
1563                            ));
1564                        }
1565                    }
1566                }
1567                let mut r_idx = 1usize;
1568                let target = consume_pattern_char_target(inner, &mut r_idx)?;
1569                ensure!(
1570                    r_idx == inner.len(),
1571                    "Unexpected extra tokens in RuleRef SubpatternMatch: {inner:?}"
1572                );
1573                return Ok((SyntaxTerm::RuleRef { target }, next_idx));
1574            }
1575
1576            let group_pat = self.decode_syntax_pattern_tokens(inner)?;
1577            return Ok((SyntaxTerm::Group(group_pat), next_idx));
1578        }
1579
1580        ensure!(
1581            tok != sh_alt
1582                && tok != sh(DC_PATTERN_REPETITION)
1583                && tok != sh_neg
1584                && tok != sh_sub
1585                && tok != sh_capture
1586                && tok != sh(DC_PATTERN_REPLACEMENT),
1587            "Unexpected ungrouped .Semantic:Pattern operator {tok} at token index {idx}"
1588        );
1589
1590        let mut next_idx = idx;
1591        let target = consume_pattern_char_target(tokens, &mut next_idx)?;
1592        Ok((SyntaxTerm::CharRef(target), next_idx))
1593    }
1594
1595    fn decode_named_construct_subtype_tokens(
1596        &self,
1597        name: &str,
1598        tokens: &[DcShorthand],
1599    ) -> Result<SubtypeConstraint> {
1600        ensure!(
1601            !tokens.is_empty(),
1602            "Empty subtype constraint token slice for [{name}]"
1603        );
1604        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1605        let sh_close = sh(DC_END_ASSOCIATIVITY_GROUP);
1606        if tokens.first() == Some(&sh_open) {
1607            ensure!(
1608                tokens.last() == Some(&sh_close) && tokens.len() >= 2,
1609                "Unbalanced group in [{name}] nested pattern subtype: {tokens:?}"
1610            );
1611            let inner = tokens
1612                .get(1..tokens.len().saturating_sub(1))
1613                .context("Invalid nested subtype slice")?;
1614            let pat = self.decode_syntax_pattern_tokens(inner)?;
1615            return Ok(SubtypeConstraint::Pattern(Box::new(pat)));
1616        }
1617        if tokens.len() == 2
1618            && tokens.first() == Some(&sh(DC_REFERENCE_BOUND_VALUE))
1619        {
1620            let var_tok = *tokens.get(1).context("Missing bound value token")?;
1621            let var_name = self.get_string(var_tok).with_context(|| {
1622                format!(
1623                    "Bound variable token {var_tok} in [{name}] subtype is not a string node"
1624                )
1625            })?;
1626            return Ok(SubtypeConstraint::BoundVar(var_name.to_string()));
1627        }
1628        if name == "data" {
1629            if tokens.len() == 2
1630                && tokens.first() == Some(&sh(DC_DATA_BYTE_LENGTH))
1631            {
1632                let len_tok =
1633                    *tokens.get(1).context("Missing DataByteLength value")?;
1634                let bytes_u128 = self.get_integer(len_tok).with_context(|| {
1635                    format!(
1636                        "DataByteLength token {len_tok} in [data] subtype is not an integer node"
1637                    )
1638                })?;
1639                let bytes = usize::try_from(bytes_u128).context(
1640                    "DataByteLength in [data] subtype overflows usize",
1641                )?;
1642                return Ok(SubtypeConstraint::Data {
1643                    format: None,
1644                    format_id: None,
1645                    bytes: Some(bytes),
1646                });
1647            }
1648            if tokens.len() == 4
1649                && tokens.first() == Some(&sh(DC_TYPE_UNION))
1650                && tokens.get(2) == Some(&sh(DC_DATA_BYTE_LENGTH))
1651            {
1652                let fmt_tok =
1653                    *tokens.get(1).context("Missing format token in [data]")?;
1654                let len_tok =
1655                    *tokens.get(3).context("Missing DataByteLength value")?;
1656                let bytes_u128 = self.get_integer(len_tok).with_context(|| {
1657                    format!(
1658                        "DataByteLength token {len_tok} in [data] subtype is not an integer node"
1659                    )
1660                })?;
1661                let bytes = usize::try_from(bytes_u128).context(
1662                    "DataByteLength in [data] subtype overflows usize",
1663                )?;
1664                let fmt_str = self.format_stable_or_shorthand_token(fmt_tok);
1665                let format_id = fmt_tok
1666                    .to_global_id()
1667                    .ok()
1668                    .and_then(ctb_utilities::format_id::FormatId::from_dc_id);
1669                return Ok(SubtypeConstraint::Data {
1670                    format: Some(fmt_str),
1671                    format_id,
1672                    bytes: Some(bytes),
1673                });
1674            }
1675            if let [single] = tokens {
1676                let format_id = single
1677                    .to_global_id()
1678                    .ok()
1679                    .and_then(ctb_utilities::format_id::FormatId::from_dc_id);
1680                return Ok(SubtypeConstraint::Data {
1681                    format: Some(self.format_stable_or_shorthand_token(*single)),
1682                    format_id,
1683                    bytes: None,
1684                });
1685            }
1686            bail!(
1687                "Unsupported token sequence for [data:...] subtype: {tokens:?}"
1688            );
1689        }
1690        if name == "number" {
1691            return Ok(SubtypeConstraint::Number(
1692                self.decode_number_subtype_tokens(tokens)?,
1693            ));
1694        }
1695        if tokens.len() == 4
1696            && tokens.first() == Some(&sh(DC_VALUE_RANGE))
1697            && tokens.get(1) == Some(&DcShorthand::Format(200))
1698        {
1699            let min_tok = *tokens.get(2).context("Missing range min token")?;
1700            let max_tok = *tokens.get(3).context("Missing range max token")?;
1701            let min = self.get_integer(min_tok).with_context(|| {
1702                format!(
1703                    "Range min token {min_tok} in [{name}] is not an integer node"
1704                )
1705            })?;
1706            let max = self.get_integer(max_tok).with_context(|| {
1707                format!(
1708                    "Range max token {max_tok} in [{name}] is not an integer node"
1709                )
1710            })?;
1711            return Ok(SubtypeConstraint::LengthRange { min, max });
1712        }
1713        if let [tok] = tokens {
1714            if *tok == sh(DC_TYPE_ROUTINE) {
1715                return Ok(SubtypeConstraint::Target("Routine".to_string()));
1716            }
1717            if let DcShorthand::Long(seed_id) = *tok {
1718                match self.get_seed_entity(seed_id) {
1719                    Some(SeedEntityKey::NamedConstruct(c)) => {
1720                        return Ok(SubtypeConstraint::Target(c.clone()));
1721                    }
1722                    Some(SeedEntityKey::Script(s)) => {
1723                        if name == "format"
1724                            || name == "type"
1725                            || name == "typed_data"
1726                        {
1727                            // Reason for fallback: scripts outside `.Formats:` strip only leading dot.
1728                            return Ok(SubtypeConstraint::Target(
1729                                s.strip_prefix(".Formats:")
1730                                    .or_else(|| s.strip_prefix('.'))
1731                                    .unwrap_or(s)
1732                                    .to_string(),
1733                            ));
1734                        }
1735                        // Reason for fallback: scripts without leading dot are returned as-is.
1736                        return Ok(SubtypeConstraint::Target(
1737                            s.strip_prefix('.').unwrap_or(s).to_string(),
1738                        ));
1739                    }
1740                    other => {
1741                        bail!(
1742                            "Unexpected seed entity {other:?} (l{seed_id}) in [{name}] subtype"
1743                        );
1744                    }
1745                }
1746            }
1747            return Ok(SubtypeConstraint::Target(tok.to_string()));
1748        }
1749        bail!(
1750            "Unsupported subtype constraint tokens for [{name}]: {tokens:?}"
1751        )
1752    }
1753
1754    fn decode_number_subtype_tokens(
1755        &self,
1756        tokens: &[DcShorthand],
1757    ) -> Result<NumberSubtypeConstraint> {
1758        if let [single] = tokens {
1759            ensure!(
1760                matches!(*single, DcShorthand::Format(_)),
1761                "Unexpected single token {single} in [number:...] subtype"
1762            );
1763            let format_id = single
1764                .to_global_id()
1765                .ok()
1766                .and_then(ctb_utilities::format_id::FormatId::from_dc_id);
1767            return Ok(NumberSubtypeConstraint {
1768                format: Some(self.format_stable_or_shorthand_token(*single)),
1769                format_id,
1770                lower_bound: None,
1771                upper_bound: None,
1772            });
1773        }
1774        ensure!(
1775            tokens.first() == Some(&sh(DC_VALUE_RANGE)) && tokens.len() >= 4,
1776            "Expected Range (Dc 643) in [number:...] subtype tokens, found {tokens:?}"
1777        );
1778        let domain_tok = *tokens.get(1).context(
1779            "Missing domain type token in [number:...] Range (Dc 643)",
1780        )?;
1781        let mut idx = 2usize;
1782        let lower_bound = self.consume_number_range_endpoint(tokens, &mut idx)?;
1783        let upper_bound = self.consume_number_range_endpoint(tokens, &mut idx)?;
1784        ensure!(
1785            idx == tokens.len(),
1786            "Unexpected trailing tokens in [number:...] Range (Dc 643): {tokens:?}"
1787        );
1788
1789        let (format, format_id) = match domain_tok {
1790            DcShorthand::Format(_) => (
1791                Some(self.format_stable_or_shorthand_token(domain_tok)),
1792                domain_tok
1793                    .to_global_id()
1794                    .ok()
1795                    .and_then(ctb_utilities::format_id::FormatId::from_dc_id),
1796            ),
1797            tok if tok == sh(DC_TYPE_NUMBER) => (None, None),
1798            other => {
1799                bail!(
1800                    "Unexpected domain type token {other} in [number:...] Range (Dc 643)"
1801                );
1802            }
1803        };
1804        Ok(NumberSubtypeConstraint {
1805            format,
1806            format_id,
1807            lower_bound,
1808            upper_bound,
1809        })
1810    }
1811
1812    fn consume_number_range_endpoint(
1813        &self,
1814        tokens: &[DcShorthand],
1815        idx: &mut usize,
1816    ) -> Result<Option<(bool, NumericBoundValue)>> {
1817        let tok = *tokens
1818            .get(*idx)
1819            .context("Missing range endpoint token in Range (Dc 643)")?;
1820        if tok == sh(DC_OPTIONAL_ABSENT) {
1821            *idx = idx.saturating_add(1);
1822            return Ok(None);
1823        }
1824        let (is_exclusive, val_tok) =
1825            if tok == sh(DC_EXCLUSIVE_RANGE_ENDPOINT) {
1826                let next_tok = *tokens.get(idx.saturating_add(1)).context(
1827                    "Missing endpoint value token after ExclusiveRangeEndpoint (Dc 644)",
1828                )?;
1829                *idx = idx.saturating_add(2);
1830                (true, next_tok)
1831            } else {
1832                *idx = idx.saturating_add(1);
1833                (false, tok)
1834            };
1835        let bound_val = self.decode_numeric_bound_node(val_tok)?;
1836        Ok(Some((is_exclusive, bound_val)))
1837    }
1838
1839    fn decode_numeric_bound_node(
1840        &self,
1841        tok: DcShorthand,
1842    ) -> Result<NumericBoundValue> {
1843        if let Some(val) = self.get_integer(tok) {
1844            return Ok(NumericBoundValue::Unsigned(val));
1845        }
1846        let DcShorthand::Long(node_id) = tok else {
1847            bail!(
1848                "Expected Long value node ID for numeric range bound, found {tok}"
1849            );
1850        };
1851        let node = self.get_active_node(node_id).with_context(|| {
1852            format!("Numeric range bound node l{node_id} not found or inactive in seed graph")
1853        })?;
1854        NumericBoundValue::decode_tokens(&node.tokens).with_context(|| {
1855            format!(
1856                "Failed to decode numeric range bound tokens in node l{node_id}: {:?}",
1857                node.tokens
1858            )
1859        })
1860    }
1861
1862    fn decode_optional_quantifier_at(
1863        &self,
1864        tokens: &[DcShorthand],
1865        idx: usize,
1866    ) -> Result<(Quantifier, usize)> {
1867        let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1868        let sh_rep = sh(DC_PATTERN_REPETITION);
1869        let sh_range = sh(DC_RANGE);
1870        let sh_value_range = sh(DC_VALUE_RANGE);
1871        let sh_absent = sh(DC_OPTIONAL_ABSENT);
1872
1873        if tokens.get(idx) != Some(&sh_open)
1874            || tokens.get(idx.saturating_add(1)) != Some(&sh_rep)
1875        {
1876            return Ok((Quantifier::ExactOne, idx));
1877        }
1878
1879        let close_idx = find_matching_group_close(tokens, idx)?
1880            .context("Unclosed PatternRepetition (603) group")?;
1881        let inner = tokens
1882            .get(idx.saturating_add(1)..close_idx)
1883            .context("Invalid token slice for PatternRepetition (603) group")?;
1884
1885        let (min, max) = if inner.get(1) == Some(&sh_value_range)
1886            && inner.get(2) == Some(&DcShorthand::Format(200))
1887        {
1888            ensure!(
1889                inner.len() == 5,
1890                "Expected 5 tokens in PatternRepetition (603) Range (643) group, found {inner:?}"
1891            );
1892            let min_tok = *inner
1893                .get(3)
1894                .context("Missing minimum bound in PatternRepetition (603)")?;
1895            let min_u128 = self.get_integer(min_tok).with_context(|| {
1896                format!(
1897                    "PatternRepetition min bound token {min_tok} is not an integer value node"
1898                )
1899            })?;
1900            let min = usize::try_from(min_u128)
1901                .context("PatternRepetition min bound overflows usize")?;
1902            let max_tok = *inner
1903                .get(4)
1904                .context("Missing maximum bound in PatternRepetition (603)")?;
1905            let max = if max_tok == sh_absent {
1906                None
1907            } else {
1908                let max_u128 = self.get_integer(max_tok).with_context(|| {
1909                    format!(
1910                        "PatternRepetition max bound token {max_tok} is not an integer value node"
1911                    )
1912                })?;
1913                Some(
1914                    usize::try_from(max_u128).context(
1915                        "PatternRepetition max bound overflows usize",
1916                    )?,
1917                )
1918            };
1919            (min, max)
1920        } else {
1921            ensure!(
1922                inner.get(1) == Some(&sh_range),
1923                "Expected Range (Dc 643 or Dc 4) after PatternRepetition (603)"
1924            );
1925            let min_tok = *inner
1926                .get(2)
1927                .context("Missing minimum bound in PatternRepetition (603)")?;
1928            let min_u128 = self.get_integer(min_tok).with_context(|| {
1929                format!(
1930                    "PatternRepetition min bound token {min_tok} is not an integer value node"
1931                )
1932            })?;
1933            let min = usize::try_from(min_u128)
1934                .context("PatternRepetition min bound overflows usize")?;
1935
1936            let max = if let Some(&max_tok) = inner.get(3) {
1937                ensure!(
1938                    inner.len() == 4,
1939                    "Unexpected extra tokens in PatternRepetition (603): {inner:?}"
1940                );
1941                let max_u128 = self.get_integer(max_tok).with_context(|| {
1942                    format!(
1943                        "PatternRepetition max bound token {max_tok} is not an integer value node"
1944                    )
1945                })?;
1946                Some(
1947                    usize::try_from(max_u128).context(
1948                        "PatternRepetition max bound overflows usize",
1949                    )?,
1950                )
1951            } else {
1952                ensure!(
1953                    inner.len() == 3,
1954                    "Unexpected tokens in PatternRepetition (603): {inner:?}"
1955                );
1956                None
1957            };
1958            (min, max)
1959        };
1960
1961        let quantifier = match (min, max) {
1962            (0, None) => Quantifier::ZeroOrMore,
1963            (1, None) => Quantifier::OneOrMore,
1964            (0, Some(1)) => Quantifier::Optional,
1965            _ => Quantifier::Range { min, max },
1966        };
1967        Ok((quantifier, close_idx.saturating_add(1)))
1968    }
1969}
1970
1971pub(crate) fn find_matching_group_close(
1972    tokens: &[DcShorthand],
1973    open_idx: usize,
1974) -> Result<Option<usize>> {
1975    let sh_open = sh(DC_BEGIN_ASSOCIATIVITY_GROUP);
1976    let sh_close = sh(DC_END_ASSOCIATIVITY_GROUP);
1977    if tokens.get(open_idx) != Some(&sh_open) {
1978        return Ok(None);
1979    }
1980    let mut depth = 0usize;
1981    for (idx, &tok) in tokens.iter().enumerate().skip(open_idx) {
1982        if tok == sh_open {
1983            depth = depth.saturating_add(1);
1984        } else if tok == sh_close {
1985            depth = depth.saturating_sub(1);
1986            if depth == 0 {
1987                return Ok(Some(idx));
1988            }
1989        }
1990    }
1991    bail!(
1992        "Unclosed BeginAssociativityGroup (298) starting at token index {open_idx}"
1993    )
1994}
1995
1996fn consume_pattern_char_target(
1997    tokens: &[DcShorthand],
1998    idx: &mut usize,
1999) -> Result<CharTarget> {
2000    let tok = *tokens
2001        .get(*idx)
2002        .context("Unexpected end of pattern token stream")?;
2003    *idx = idx.saturating_add(1);
2004    if tok == sh(DC_ESCAPE)
2005        && tokens.get(*idx) == Some(&sh(DC_START_ENCAPSULATION_BINARY))
2006    {
2007        let escaped = *tokens
2008            .get(*idx)
2009            .context("Unexpected end of pattern token stream after Dc 255")?;
2010        *idx = idx.saturating_add(1);
2011        return shorthand_to_char_target(escaped);
2012    }
2013    shorthand_to_char_target(tok)
2014}
2015
2016fn shorthand_to_char_target(shorthand: DcShorthand) -> Result<CharTarget> {
2017    let gid = shorthand.to_global_id()?;
2018    CharTarget::from_u128(gid).with_context(|| {
2019        format!(
2020            "Token shorthand '{shorthand}' (GID {gid}) cannot be represented as a CharTarget"
2021        )
2022    })
2023}
2024
2025fn dc_to_support_level(shorthand: DcShorthand) -> Option<i8> {
2026    if shorthand == sh(DC_SUPPORT_NOT_APPLICABLE) {
2027        Some(-1)
2028    } else if shorthand == sh(DC_SUPPORT_WORK_IN_PROGRESS) {
2029        Some(1)
2030    } else if shorthand == sh(DC_SUPPORT_PARTIAL) {
2031        Some(2)
2032    } else if shorthand == sh(DC_SUPPORT_COMPLETE) {
2033        Some(3)
2034    } else if shorthand == sh(DC_SUPPORT_LOSSLESS_ROUNDTRIP) {
2035        Some(4)
2036    } else if shorthand == sh(DC_SUPPORT_LOSSLESS_STRICT_VALIDATION) {
2037        Some(5)
2038    } else {
2039        None
2040    }
2041}
2042
2043fn category_for_dc_subject(subj: DcShorthand, script: &str) -> String {
2044    if matches!(subj, DcShorthand::Unicode(_)) {
2045        return "unicode-clarifications".to_string();
2046    }
2047    if let Some(fmt_cat) = script
2048        .strip_prefix(".Formats:")
2049        .or_else(|| script.strip_prefix("Formats:"))
2050    {
2051        let cat_trimmed = fmt_cat.trim();
2052        if cat_trimmed.starts_with("format_") {
2053            return cat_trimmed.to_string();
2054        }
2055        return format!("format_{cat_trimmed}");
2056    }
2057    if script == ".Semantic" || script.starts_with(".Semantic:") {
2058        return "semantic".to_string();
2059    }
2060    if script == ".EM" || script.starts_with(".EM ") {
2061        return "em".to_string();
2062    }
2063    // Historical snapshot pins use legacy `.EL*` script names mapped to `el.csv`.
2064    if script == ".EL" || script.starts_with(".EL ") {
2065        return "el".to_string();
2066    }
2067    if script == ".DCE" || script.starts_with(".DCE ") {
2068        return "dce".to_string();
2069    }
2070    if script == ".WASM" || script.starts_with(".WASM ") {
2071        return "wasm".to_string();
2072    }
2073    let static_cat = match script {
2074        ".Colors" => "colors",
2075        ".Controls" => "controls",
2076        ".Encapsulation" => "encapsulation",
2077        ".Financial" => "financial",
2078        "Latin" => "latin",
2079        ".Mathematics" => "mathematics",
2080        ".Miscellaneous" => "miscellaneous",
2081        ".Noncharacters" => "noncharacters",
2082        ".Punctuation" => "punctuation",
2083        ".Styling" => "styling",
2084        ".Symbols" | ".Emoji" => "symbols",
2085        ".Variant selectors" => "variant_selectors",
2086        _ => "controls",
2087    };
2088    static_cat.to_string()
2089}