ctb_formats_dcdata/support/
syntax_validator.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Semantic validator and cross-reference checker for Dc syntax AST trees.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::report::ValidationReport;
30use crate::syntax::ast::{
31    ActionArg, CharTarget, DcSyntaxRule, SubtypeConstraint, SyntaxElement,
32    SyntaxPattern, SyntaxTerm,
33};
34use crate::syntax::parser::parse_target_token;
35use std::collections::{HashMap, HashSet};
36
37/// Format metadata needed to validate format references in syntax rules (e.g. `[data:<format>]`).
38#[derive(Debug, Clone, Default)]
39pub struct FormatValidationInfo {
40    pub short_id: usize,
41    pub ident: Option<String>,
42    pub stable_ident: bool,
43    pub category: String,
44    pub nicknames: Vec<String>,
45    pub has_import_support: bool,
46    pub has_export_support: bool,
47    pub is_deprecated: bool,
48    pub syntax: Option<DcSyntaxRule>,
49    pub closes: Option<ctb_storage_minimal::shorthand::DcShorthand>,
50    pub decompositions: Vec<String>,
51}
52
53/// Registry of format definitions and support levels for syntax validation.
54#[derive(Debug, Clone, Default)]
55pub struct FormatValidationRegistry {
56    pub categories: HashSet<String>,
57    pub formats_by_id: HashMap<usize, FormatValidationInfo>,
58    pub id_by_ident: HashMap<String, usize>,
59    pub id_by_nick: HashMap<String, usize>,
60}
61
62/// Returns `true` when `category_or_script` denotes the `.Formats:transformation`
63/// document-transformation format category.
64#[must_use]
65pub fn is_transformation_format_category(category_or_script: &str) -> bool {
66    let trimmed = category_or_script.trim();
67    // Reason for fallback: Category strings without format prefixes are already normalized.
68    let clean = trimmed
69        .strip_prefix(".Formats:")
70        .or_else(|| trimmed.strip_prefix("Formats:"))
71        .or_else(|| trimmed.strip_prefix("format_"))
72        .unwrap_or(trimmed);
73    clean.eq_ignore_ascii_case("transformation")
74}
75
76impl FormatValidationRegistry {
77    /// Returns `true` if `fid` is registered in this registry and belongs to
78    /// `.Formats:transformation`.
79    #[must_use]
80    pub fn is_transformation_format(&self, fid: usize) -> bool {
81        self.formats_by_id
82            .get(&fid)
83            .is_some_and(|info| is_transformation_format_category(&info.category))
84    }
85
86    /// Creates a new empty format validation registry.
87    #[must_use]
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// Adds a format record to the registry.
93    pub fn add_format(&mut self, info: FormatValidationInfo) {
94        if !info.category.is_empty() {
95            let cat = info.category.trim();
96            // Reason for fallback: Category strings not starting with standard format prefixes are already in normalized form.
97            let clean = cat
98                .strip_prefix(".Formats:")
99                .or_else(|| cat.strip_prefix("Formats:"))
100                .or_else(|| cat.strip_prefix("format_"))
101                .unwrap_or(cat);
102            self.categories.insert(clean.to_string());
103            self.categories.insert(clean.to_ascii_lowercase());
104        }
105        if let Some(ref ident) = info.ident {
106            self.id_by_ident.insert(ident.clone(), info.short_id);
107            self.id_by_ident
108                .insert(ident.to_ascii_lowercase(), info.short_id);
109        }
110        for nick in &info.nicknames {
111            self.id_by_nick.insert(nick.clone(), info.short_id);
112            self.id_by_nick
113                .insert(nick.to_ascii_lowercase(), info.short_id);
114        }
115        self.formats_by_id.insert(info.short_id, info);
116    }
117
118    /// Finds a format by shorthand (`f<N>`), ident, or nickname.
119    #[must_use]
120    pub fn find_format(&self, token: &str) -> Option<&FormatValidationInfo> {
121        let trimmed = token.trim();
122        if let Some(target) = parse_target_token(trimmed) {
123            if let CharTarget::Format(fid) = target {
124                if let Some(id) = fid
125                    .dc_id()
126                    .and_then(|dc| {
127                        dc.checked_sub(
128                            ctb_storage_minimal::global_graph_layout::FORMAT_REGION_START,
129                        )
130                    })
131                    .and_then(|v| usize::try_from(v).ok())
132                {
133                    return self.formats_by_id.get(&id);
134                }
135            }
136        }
137        if let Some(&id) = self.id_by_ident.get(trimmed) {
138            return self.formats_by_id.get(&id);
139        }
140        let lower = trimmed.to_ascii_lowercase();
141        if let Some(&id) = self.id_by_ident.get(&lower) {
142            return self.formats_by_id.get(&id);
143        }
144        if let Some(&id) = self.id_by_nick.get(&lower) {
145            return self.formats_by_id.get(&id);
146        }
147        None
148    }
149}
150
151/// Constructs a `FormatValidationRegistry` from parsed format definitions.
152#[must_use]
153pub fn build_format_validation_registry(
154    format_rows: &[crate::DcDefn],
155) -> FormatValidationRegistry {
156    let mut reg = FormatValidationRegistry::new();
157    for row in format_rows {
158        if let Some(short_id) = row.short_id {
159            let mut nicknames = Vec::new();
160            let mut has_import_support = false;
161            let mut has_export_support = false;
162            if let Some(ref f) = row.format {
163                if let Some(ref n) = f.nicknames {
164                    for nick in n.split(',') {
165                        let t = nick.trim();
166                        if !t.is_empty() {
167                            nicknames.push(t.to_string());
168                        }
169                    }
170                }
171                if let Some(ref imp) = f.import_support {
172                    if let Ok(lvl) = crate::SupportLevel::parse(imp) {
173                        has_import_support = lvl.general > 0 || lvl.dc > 0;
174                    }
175                }
176                if let Some(ref exp) = f.export_support {
177                    if let Ok(lvl) = crate::SupportLevel::parse(exp) {
178                        has_export_support = lvl.general > 0 || lvl.dc > 0;
179                    }
180                }
181            }
182            reg.add_format(FormatValidationInfo {
183                short_id,
184                ident: row.ident.clone(),
185                stable_ident: row.stable_ident,
186                category: row.category.clone(),
187                nicknames,
188                has_import_support,
189                has_export_support,
190                is_deprecated: row.is_deprecated,
191                syntax: row.syntax.clone(),
192                closes: row.closes,
193                decompositions: row.decompositions.clone(),
194            });
195        }
196    }
197    reg
198}
199
200/// Validates a single `CharTarget` against registered datasets.
201fn check_target_reference(
202    target: &CharTarget,
203    source_file: &str,
204    line_no: usize,
205    col_name: &str,
206    known_dc_ids: &HashSet<u32>,
207    known_format_ids: &HashSet<usize>,
208    is_range_endpoint: bool,
209    report: &mut ValidationReport,
210) {
211    match target {
212        CharTarget::Dc(id) => {
213            if is_range_endpoint {
214                // Reason for fallback: SHORT_DC_REGION_END - SHORT_DC_REGION_START is 0xFFFF, which always fits in u32.
215                let max_short_dc = u32::try_from(
216                    ctb_storage_minimal::global_graph_layout::SHORT_DC_REGION_END
217                        .saturating_sub(ctb_storage_minimal::global_graph_layout::SHORT_DC_REGION_START),
218                ).unwrap_or(u32::MAX);
219                if *id > max_short_dc {
220                    report.add_error(
221                        source_file,
222                        Some(line_no),
223                        Some(col_name),
224                        format!("Dc ID '{id}' in syntax rule range exceeds maximum Short Dc ID {max_short_dc}"),
225                        Some("Ensure Dc range is within valid Dc space"),
226                    );
227                }
228            } else if !known_dc_ids.is_empty() && !known_dc_ids.contains(id) {
229                report.add_error(
230                    source_file,
231                    Some(line_no),
232                    Some(col_name),
233                    format!("Referenced Dc ID '{id}' in syntax rule does not exist in Document Characters registry"),
234                    Some("Ensure referenced Dc ID is defined in a Dc category file"),
235                );
236            }
237        }
238        CharTarget::Format(fid) => {
239            let id = fid
240                .dc_id()
241                .and_then(|dc| {
242                    dc.checked_sub(
243                        ctb_storage_minimal::global_graph_layout::FORMAT_REGION_START,
244                    )
245                })
246                .and_then(|v| usize::try_from(v).ok());
247            let shorthand = fid.shorthand();
248            if is_range_endpoint {
249                let max_format_id = match usize::try_from(
250                    ctb_storage_minimal::global_graph_layout::FORMAT_REGION_END
251                        .saturating_sub(ctb_storage_minimal::global_graph_layout::FORMAT_REGION_START),
252                ) {
253                    Ok(m) => m,
254                    Err(_) => usize::MAX,
255                };
256                if id.is_none_or(|id| id > max_format_id) {
257                    report.add_error(
258                        source_file,
259                        Some(line_no),
260                        Some(col_name),
261                        format!("Format ID '{shorthand}' in syntax rule range exceeds maximum format ID f{max_format_id}"),
262                        Some("Ensure format range is within valid format space"),
263                    );
264                }
265            } else if id.is_none_or(|id| !known_format_ids.contains(&id)) {
266                report.add_error(
267                    source_file,
268                    Some(line_no),
269                    Some(col_name),
270                    format!("Format ID '{shorthand}' in syntax rule does not exist in formats registry"),
271                    Some("Ensure referenced format ID is defined in formats category files"),
272                );
273            }
274        }
275        CharTarget::FormatRegionEnd => {
276            if !is_range_endpoint {
277                report.add_error(
278                    source_file,
279                    Some(line_no),
280                    Some(col_name),
281                    format!(
282                        "Format ID 'f{}' in syntax rule does not exist in formats registry",
283                        ctb_storage_minimal::shorthand::MAX_FORMAT_ID
284                    ),
285                    Some("Ensure referenced format ID is defined in formats category files"),
286                );
287            }
288        }
289        CharTarget::Unicode(cp) => {
290            if *cp > 0x0010_FFFF {
291                report.add_error(
292                    source_file,
293                    Some(line_no),
294                    Some(col_name),
295                    format!("Referenced Unicode codepoint 'u{cp:04x}' (U+{cp:04X}) exceeds maximum Unicode codepoint U+10FFFF"),
296                    Some("Ensure referenced Unicode codepoint is <= 0x10FFFF"),
297                );
298            } else if !is_range_endpoint
299                && !ctb_formats_unicode::is_assigned_unicode(*cp)
300            {
301                report.add_error(
302                    source_file,
303                    Some(line_no),
304                    Some(col_name),
305                    format!("Referenced Unicode codepoint 'u{cp:04x}' (U+{cp:04X}) in syntax rule is not an assigned Unicode character"),
306                    Some("Ensure referenced Unicode character exists in Unicode standard"),
307                );
308            }
309        }
310    }
311}
312
313/// Recursively validates pattern terms and accumulates bound capture variables.
314fn validate_pattern_node(
315    pattern: &SyntaxPattern,
316    source_file: &str,
317    line_no: usize,
318    col_name: &str,
319    self_dc_id: u32,
320    known_dc_ids: &HashSet<u32>,
321    known_format_ids: &HashSet<usize>,
322    known_named_types: &HashSet<String>,
323    known_scripts: Option<&HashSet<String>>,
324    known_syntax_targets: &HashSet<CharTarget>,
325    format_registry: Option<&FormatValidationRegistry>,
326    bound_vars: &mut HashSet<String>,
327    report: &mut ValidationReport,
328) {
329    match pattern {
330        SyntaxPattern::Alternation(branches) => {
331            for branch in branches {
332                validate_pattern_node(
333                    branch,
334                    source_file,
335                    line_no,
336                    col_name,
337                    self_dc_id,
338                    known_dc_ids,
339                    known_format_ids,
340                    known_named_types,
341                    known_scripts,
342                    known_syntax_targets,
343                    format_registry,
344                    bound_vars,
345                    report,
346                );
347            }
348        }
349        SyntaxPattern::Sequence(elements) => {
350            for elem in elements {
351                validate_syntax_element(
352                    elem,
353                    source_file,
354                    line_no,
355                    col_name,
356                    self_dc_id,
357                    known_dc_ids,
358                    known_format_ids,
359                    known_named_types,
360                    known_scripts,
361                    known_syntax_targets,
362                    format_registry,
363                    bound_vars,
364                    report,
365                );
366            }
367        }
368    }
369}
370
371/// Validates an individual `SyntaxElement` node.
372fn validate_syntax_element(
373    element: &SyntaxElement,
374    source_file: &str,
375    line_no: usize,
376    col_name: &str,
377    self_dc_id: u32,
378    known_dc_ids: &HashSet<u32>,
379    known_format_ids: &HashSet<usize>,
380    known_named_types: &HashSet<String>,
381    known_scripts: Option<&HashSet<String>>,
382    known_syntax_targets: &HashSet<CharTarget>,
383    format_registry: Option<&FormatValidationRegistry>,
384    bound_vars: &mut HashSet<String>,
385    report: &mut ValidationReport,
386) {
387    if element.quantifier.is_redundant() {
388        report.add_error(
389            source_file,
390            Some(line_no),
391            Some(col_name),
392            "Redundant quantifier '{1}' in syntax rule; matching exactly once is already the default semantics".to_string(),
393            Some("Remove the redundant quantifier"),
394        );
395    }
396
397    match &element.term {
398        SyntaxTerm::SelfChar => {
399            // Self-referential '~' is valid
400        }
401        SyntaxTerm::CharRef(target) => {
402            check_target_reference(
403                target,
404                source_file,
405                line_no,
406                col_name,
407                known_dc_ids,
408                known_format_ids,
409                false,
410                report,
411            );
412        }
413        SyntaxTerm::RuleRef { target } => {
414            check_target_reference(
415                target,
416                source_file,
417                line_no,
418                col_name,
419                known_dc_ids,
420                known_format_ids,
421                false,
422                report,
423            );
424            if target != &CharTarget::Dc(self_dc_id)
425                && !known_syntax_targets.contains(target)
426            {
427                report.add_error(
428                    source_file,
429                    Some(line_no),
430                    Some(col_name),
431                    format!(
432                        "Macro expansion '[{target}:]' references target that does not define its own syntax rule"
433                    ),
434                    Some(
435                        "Define syntax for the referenced character or format before expanding it as a macro rule",
436                    ),
437                );
438            }
439        }
440        SyntaxTerm::CharSet { members, .. } => {
441            for target in members {
442                check_target_reference(
443                    target,
444                    source_file,
445                    line_no,
446                    col_name,
447                    known_dc_ids,
448                    known_format_ids,
449                    false,
450                    report,
451                );
452            }
453        }
454        SyntaxTerm::CharRange { start, end } => {
455            check_target_reference(
456                start,
457                source_file,
458                line_no,
459                col_name,
460                known_dc_ids,
461                known_format_ids,
462                true,
463                report,
464            );
465            check_target_reference(
466                end,
467                source_file,
468                line_no,
469                col_name,
470                known_dc_ids,
471                known_format_ids,
472                true,
473                report,
474            );
475            if start > end {
476                report.add_error(
477                    source_file,
478                    Some(line_no),
479                    Some(col_name),
480                    format!("Invalid character range: start '{start}' is greater than end '{end}'"),
481                    Some("Ensure character range is in ascending order"),
482                );
483            }
484        }
485        SyntaxTerm::NamedConstruct {
486            name,
487            subtype,
488            capture_var,
489        } => {
490            if name.is_empty() {
491                report.add_error(
492                    source_file,
493                    Some(line_no),
494                    Some(col_name),
495                    "Named construct has an empty name".to_string(),
496                    Some("Ensure named construct has a non-empty name e.g. [name]"),
497                );
498            } else if name == "data" {
499                if let Some(sub) = subtype {
500                    let sub_dsl = sub.format_dsl();
501                    let format = match sub {
502                        SubtypeConstraint::Data { format, .. } => {
503                            format.as_deref()
504                        }
505                        _ => {
506                            report.add_error(
507                                source_file,
508                                Some(line_no),
509                                Some(col_name),
510                                format!(
511                                    "Invalid data constraint in '[data:{sub_dsl}]'"
512                                ),
513                                None,
514                            );
515                            return;
516                        }
517                    };
518                    let Some(sub_trimmed) = format else {
519                        return;
520                    };
521                    if sub_trimmed.is_empty() {
522                        report.add_error(
523                            source_file,
524                            Some(line_no),
525                            Some(col_name),
526                            "Named construct '[data:]' is missing a format identifier".to_string(),
527                            Some("Provide a format identifier or use bare '[data]'"),
528                        );
529                    } else if let Some(formats) = format_registry {
530                        // Reason for fallback: Category names without formal prefixes are matched verbatim against known category sets.
531                        let clean_cat = sub_trimmed
532                            .strip_prefix(".Formats:")
533                            .or_else(|| sub_trimmed.strip_prefix("Formats:"))
534                            .or_else(|| sub_trimmed.strip_prefix("format_"))
535                            .unwrap_or(sub_trimmed);
536                        let is_category = formats
537                            .categories
538                            .contains(clean_cat)
539                            || formats
540                                .categories
541                                .contains(&clean_cat.to_ascii_lowercase())
542                            || clean_cat.eq_ignore_ascii_case("hash")
543                            || clean_cat.eq_ignore_ascii_case("compression")
544                            || clean_cat.eq_ignore_ascii_case("container")
545                            || clean_cat.eq_ignore_ascii_case("document")
546                            || clean_cat.eq_ignore_ascii_case("database");
547                        if is_category {
548                            report.add_error(
549                                source_file,
550                                Some(line_no),
551                                Some(col_name),
552                                format!(
553                                    "Construct '[data:{sub_trimmed}]' specifies a format category instead of a specific format identifier"
554                                ),
555                                Some(
556                                    "Specify a specific format identifier with import and export support rather than a category name",
557                                ),
558                            );
559                        } else if let Some(fmt_info) =
560                            formats.find_format(sub_trimmed)
561                        {
562                            if parse_target_token(sub_trimmed)
563                                .is_none()
564                                && !fmt_info.stable_ident
565                            {
566                                report.add_error(
567                                    source_file,
568                                    Some(line_no),
569                                    Some(col_name),
570                                    format!(
571                                        "Format identifier '{sub_trimmed}' in '[data:{sub_dsl}]' is not marked '@stable_ident()'"
572                                    ),
573                                    Some(
574                                        "Use its numeric shorthand 'f<id>' or add '@stable_ident()' to the format definition",
575                                    ),
576                                );
577                            }
578                            if !fmt_info.has_import_support
579                                || !fmt_info.has_export_support
580                            {
581                                // Reason for fallback: Formats lacking a canonical identifier use the subtype string specified in the syntax definition.
582                                let fmt_name = fmt_info
583                                    .ident
584                                    .as_deref()
585                                    .unwrap_or(sub_trimmed);
586                                report.add_error(
587                                    source_file,
588                                    Some(line_no),
589                                    Some(col_name),
590                                    format!(
591                                        "Format '{fmt_name}' referenced in '[data:{sub_trimmed}]' must have both import and export support"
592                                    ),
593                                    Some(
594                                        "Ensure referenced format has both import and export support in its category table",
595                                    ),
596                                );
597                            }
598                        } else {
599                            report.add_error(
600                                source_file,
601                                Some(line_no),
602                                Some(col_name),
603                                format!(
604                                    "Unknown format identifier '{sub_trimmed}' in '[data:{sub_trimmed}]'"
605                                ),
606                                Some(
607                                    "Specify a registered format identifier that has both import and export support",
608                                ),
609                            );
610                        }
611                    }
612                }
613            } else if name == "number" {
614                if let Some(sub) = subtype {
615                    let sub_dsl = sub.format_dsl();
616                    let SubtypeConstraint::Number(num) = sub else {
617                        report.add_error(
618                            source_file,
619                            Some(line_no),
620                            Some(col_name),
621                            format!(
622                                "Invalid number constraint in '[number:{sub_dsl}]'"
623                            ),
624                            None,
625                        );
626                        return;
627                    };
628                    if let (Some(formats), Some(clause)) =
629                        (format_registry, num.format.as_deref())
630                        && !formats.formats_by_id.is_empty()
631                    {
632                        if let Some(target) =
633                            parse_target_token(clause)
634                        {
635                            if matches!(target, CharTarget::Format(_)) {
636                                if formats.find_format(clause).is_none() {
637                                    report.add_error(
638                                        source_file,
639                                        Some(line_no),
640                                        Some(col_name),
641                                        format!(
642                                            "Unknown format ID '{clause}' in '[number:{sub_dsl}]'"
643                                        ),
644                                        Some(
645                                            "Ensure referenced format ID is defined in formats category files",
646                                        ),
647                                    );
648                                }
649                            } else {
650                                report.add_error(
651                                    source_file,
652                                    Some(line_no),
653                                    Some(col_name),
654                                    format!(
655                                        "Invalid target '{clause}' in '[number:{sub_dsl}]'; expected a format shorthand (e.g. 'f351') or '@stable_ident()' format identifier"
656                                    ),
657                                    Some(
658                                        "Use a format shorthand 'f<id>' or a format identifier marked with '@stable_ident()'",
659                                    ),
660                                );
661                            }
662                        } else if let Some(fmt_info) =
663                            formats.find_format(clause)
664                        {
665                            if !fmt_info.stable_ident {
666                                report.add_error(
667                                    source_file,
668                                    Some(line_no),
669                                    Some(col_name),
670                                    format!(
671                                        "Format identifier '{clause}' in '[number:{sub_dsl}]' is not marked '@stable_ident()'"
672                                    ),
673                                    Some(
674                                        "Use its numeric shorthand 'f<id>' or add '@stable_ident()' to the format definition",
675                                    ),
676                                );
677                            }
678                        } else {
679                            report.add_error(
680                                source_file,
681                                Some(line_no),
682                                Some(col_name),
683                                format!(
684                                    "Unknown format identifier '{clause}' in '[number:{sub_dsl}]'"
685                                ),
686                                Some(
687                                    "Use a format shorthand 'f<id>' or a format identifier marked with '@stable_ident()'",
688                                ),
689                            );
690                        }
691                    }
692                }
693            } else if name == "script" {
694                let script_target = subtype
695                    .as_ref()
696                    .and_then(SubtypeConstraint::as_target_str);
697                if script_target.is_none_or(str::is_empty) {
698                    report.add_error(
699                        source_file,
700                        Some(line_no),
701                        Some(col_name),
702                        "Named construct '[script]' requires a non-empty script name (e.g. '[script:.EM Types]')".to_string(),
703                        Some("Specify a valid script name following a colon"),
704                    );
705                } else if let Some(st) = script_target {
706                    let is_valid = if st.starts_with('.') {
707                        if let Some(scripts) = known_scripts {
708                            scripts.contains(st)
709                        } else {
710                            true
711                        }
712                    } else {
713                        ctb_formats_unicode::is_valid_unicode_script(st)
714                    };
715                    if !is_valid {
716                        report.add_error(
717                            source_file,
718                            Some(line_no),
719                            Some(col_name),
720                            format!("Unknown script '[script:{st}]' in syntax rule"),
721                            Some("Must be a registered Dc script or valid Unicode script"),
722                        );
723                    }
724                }
725            } else if !known_named_types.is_empty()
726                && !known_named_types.contains(name)
727            {
728                report.add_error(
729                    source_file,
730                    Some(line_no),
731                    Some(col_name),
732                    format!("Unknown named type construct '[{name}]' in syntax rule"),
733                    Some("Must be a registered named type defined in README-named-types.csv"),
734                );
735            }
736            if let Some(SubtypeConstraint::Pattern(sub_pattern)) = subtype
737            {
738                validate_pattern_node(
739                    sub_pattern,
740                    source_file,
741                    line_no,
742                    col_name,
743                    self_dc_id,
744                    known_dc_ids,
745                    known_format_ids,
746                    known_named_types,
747                    known_scripts,
748                    known_syntax_targets,
749                    format_registry,
750                    bound_vars,
751                    report,
752                );
753            }
754            if let Some(var) = capture_var {
755                bound_vars.insert(var.clone());
756            }
757        }
758        SyntaxTerm::Group(nested_pattern) => {
759            validate_pattern_node(
760                nested_pattern,
761                source_file,
762                line_no,
763                col_name,
764                self_dc_id,
765                known_dc_ids,
766                known_format_ids,
767                known_named_types,
768                known_scripts,
769                known_syntax_targets,
770                format_registry,
771                bound_vars,
772                report,
773            );
774        }
775    }
776}
777
778/// Validates a parsed `DcSyntaxRule` AST against database registries.
779pub fn validate_dc_syntax(
780    rule: &DcSyntaxRule,
781    self_dc_id: u32,
782    known_dc_ids: &HashSet<u32>,
783    known_format_ids: &HashSet<usize>,
784    known_named_types: &HashSet<String>,
785    known_scripts: Option<&HashSet<String>>,
786    known_syntax_targets: &HashSet<CharTarget>,
787    format_registry: Option<&FormatValidationRegistry>,
788    report: &mut ValidationReport,
789    source_file: &str,
790    line_no: usize,
791) {
792    let col_name = "Aliases (syntax)";
793    let mut bound_vars = HashSet::new();
794
795    // 1. Validate Pattern Tree and collect bound variables
796    validate_pattern_node(
797        &rule.pattern,
798        source_file,
799        line_no,
800        col_name,
801        self_dc_id,
802        known_dc_ids,
803        known_format_ids,
804        known_named_types,
805        known_scripts,
806        known_syntax_targets,
807        format_registry,
808        &mut bound_vars,
809        report,
810    );
811
812    // 2. Validate Action Invocation variables
813    if let Some(action) = &rule.action {
814        for arg in &action.args {
815            if let ActionArg::Variable(var_name) = arg {
816                if !bound_vars.contains(var_name) {
817                    report.add_error(
818                        source_file,
819                        Some(line_no),
820                        Some(col_name),
821                        format!(
822                            "Variable '${var_name}' in action invocation '{}' is not bound in syntax pattern",
823                            action.method
824                        ),
825                        Some("Ensure all action parameters correspond to captured variables ($var) in the pattern"),
826                    );
827                }
828            }
829        }
830    }
831}