ctb_formats_dcdata/
syntax.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//! Document Character (Dc) syntax Domain Specific Language (DSL) module.
21//!
22//! Provides AST definitions, lexer/parser, semantic and cross-reference validators,
23//! and resilient tag-soup pattern matchers for evaluating and processing DcText documents.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32use std::sync::{Arc, LazyLock};
33
34pub mod resolver;
35#[rustfmt::skip]
36#[path = "syntax/role.generated.rs"]
37pub mod role;
38pub use crate::support::data_constraint;
39pub use crate::support::seed_graph_reconstruct::PatternTokenStep;
40pub use crate::support::syntax_ast as ast;
41pub use crate::support::syntax_parser as parser;
42pub use crate::support::syntax_validator as validator;
43
44pub use ast::SyntaxPattern as DcSyntaxExpr;
45pub use ast::{
46    ActionArg, CharTarget, DcSyntaxRule, FramingShape,
47    MAX_LEGACY_FRAMING_SHORT_DC_ID, NumberSubtypeConstraint, NumericBoundValue,
48    Quantifier, SubtypeConstraint, SyntaxAction, SyntaxDiagnostic,
49    SyntaxElement, SyntaxPattern, SyntaxTerm, classify_rule_framing_shape,
50    classify_rule_framing_shape_with, is_unary_prefix_rule,
51    normalize_syntax_pattern,
52};
53pub use data_constraint::{
54    NumberConstraintClause, parse_data_constraint, parse_number_constraint,
55};
56pub use parser::{
57    format_extension_regex_pattern, is_extension_regex, parse_dc_syntax,
58    parse_extension_regex, parse_target_token,
59};
60pub use resolver::{
61    DatasetRuleResolver, StarterSet, SyntaxRuleResolver,
62    detect_container_closer, extract_container_header_elements,
63    extract_trailing_after_closer,
64};
65pub use role::DcRole;
66pub use validator::{
67    FormatValidationInfo, FormatValidationRegistry,
68    build_format_validation_registry, is_transformation_format_category,
69    validate_dc_syntax,
70};
71
72impl DatasetRuleResolver {
73    /// Loads the authoritative resolver state from the bundled runtime seed graph
74    /// (`data/graph/85899_34592.ctbnbdl` via `SeedGraphIndex::shared()`).
75    #[must_use]
76    pub fn load() -> Self {
77        #[expect(
78            clippy::expect_used,
79            reason = "Bundled runtime seed graph (data/graph/85899_34592.ctbnbdl) is validated at build time and must load"
80        )]
81        Self::load_from_seed_graph()
82            .expect("Bundled runtime seed graph syntax resolver must load")
83    }
84}
85
86static DEFAULT_RESOLVER: LazyLock<Arc<DatasetRuleResolver>> =
87    LazyLock::new(|| Arc::new(DatasetRuleResolver::load()));
88
89static HISTORICAL_RESOLVER_CACHE: LazyLock<
90    std::sync::Mutex<
91        std::collections::HashMap<u128, Arc<DatasetRuleResolver>>,
92    >,
93> = LazyLock::new(|| {
94    std::sync::Mutex::new(std::collections::HashMap::new())
95});
96
97/// Returns the lazily loaded shared default syntax resolver instance.
98#[must_use]
99pub fn default_syntax_resolver() -> &'static Arc<DatasetRuleResolver> {
100    &DEFAULT_RESOLVER
101}
102
103/// Registers a pre-built [`DatasetRuleResolver`] in the historical resolver cache
104/// for `most_recent_node_id` (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`).
105pub fn register_historical_syntax_resolver(
106    most_recent_node_id: u128,
107    resolver: Arc<DatasetRuleResolver>,
108) {
109    if let Ok(mut cache) = HISTORICAL_RESOLVER_CACHE.lock() {
110        if cache.len() >= 64 {
111            cache.clear();
112        }
113        cache.insert(most_recent_node_id, resolver);
114    }
115}
116
117/// Returns a shared syntax resolver reflecting the System-block graph state as of
118/// `most_recent_node_id` (`Dc 641` `"Global graph system block most recent node ID at time of document creation"`).
119///
120/// When `most_recent_node_id` matches the current `HEAD` System-block most recent node ID,
121/// returns [`default_syntax_resolver()`] without rebuilding. When `most_recent_node_id`
122/// exceeds `HEAD` (and is not explicitly registered in the resolver cache), returns an error
123/// rather than silently substituting `HEAD`.
124pub fn syntax_resolver_at_most_recent(
125    most_recent_node_id: u128,
126) -> Result<Arc<DatasetRuleResolver>> {
127    if let Ok(cache) = HISTORICAL_RESOLVER_CACHE.lock()
128        && let Some(existing) = cache.get(&most_recent_node_id)
129    {
130        return Ok(Arc::clone(existing));
131    }
132    let shared_graph = crate::seed_graph::SeedGraphIndex::shared()?;
133    let head_id = shared_graph.system_block_most_recent_node_id();
134    if head_id == Some(most_recent_node_id) {
135        return Ok(Arc::clone(default_syntax_resolver()));
136    }
137    let built = Arc::new(DatasetRuleResolver::load_at_most_recent(
138        most_recent_node_id,
139    )?);
140    if let Ok(mut cache) = HISTORICAL_RESOLVER_CACHE.lock() {
141        if cache.len() >= 64 {
142            cache.clear();
143        }
144        cache.insert(most_recent_node_id, Arc::clone(&built));
145    }
146    Ok(built)
147}