ctb_formats_dcdata/support/
syntax_ast.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//! Abstract Syntax Tree (AST) definitions for the Document Character (Dc)
21//! syntax DSL.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29use serde::{Deserialize, Serialize};
30
31/// Target reference to a character or format entity.
32#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub enum CharTarget {
34    /// Short Document Character (Dc) ID (e.g. 246, 248, 0).
35    Dc(u32),
36    /// Format identifier prefixed with `f` (e.g. `f80`).
37    Format(ctb_utilities::format_id::FormatId),
38    /// Upper bound of the allocated Format Dc block (`f1114111` / `FORMAT_REGION_END`),
39    /// permitted strictly as a syntax range endpoint (e.g. `[f0..f1114111]`).
40    FormatRegionEnd,
41    /// Unicode codepoint prefixed with lowercase `u` (e.g. `u0020`, `u12ab`).
42    Unicode(u32),
43}
44
45impl PartialOrd for CharTarget {
46    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
47        Some(self.cmp(other))
48    }
49}
50
51impl Ord for CharTarget {
52    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
53        self.to_u128().cmp(&other.to_u128())
54    }
55}
56
57impl CharTarget {
58    /// Returns the canonical global graph layout `u128` identifier for this target.
59    #[must_use]
60    pub fn to_u128(&self) -> u128 {
61        match self {
62            Self::Dc(id) => DcChar::from_short(*id).to_u128(),
63            Self::Format(fid) =>
64            {
65                #[expect(
66                    clippy::expect_used,
67                    reason = "Every FormatId variant maps to a known Global Graph Dc ID"
68                )]
69                fid.dc_id().expect(
70                    "FormatId always maps to a valid Global Graph Dc ID",
71                )
72            }
73            Self::FormatRegionEnd => {
74                ctb_storage_minimal::global_graph_layout::FORMAT_REGION_END
75            }
76            Self::Unicode(cp) => u128::from(*cp),
77        }
78    }
79
80    /// Attempts to resolve a global graph layout `u128` identifier into a `CharTarget`.
81    #[must_use]
82    pub fn from_u128(val: u128) -> Option<Self> {
83        let dc = DcChar::from_u128(val);
84        if let Ok(short) = dc.to_short() {
85            Some(Self::Dc(short))
86        } else if let Some(fid) =
87            ctb_utilities::format_id::FormatId::from_dc_id(val)
88        {
89            Some(Self::Format(fid))
90        } else if val
91            == ctb_storage_minimal::global_graph_layout::FORMAT_REGION_END
92        {
93            Some(Self::FormatRegionEnd)
94        } else if let Ok(cp) = dc.to_unicode() {
95            Some(Self::Unicode(cp))
96        } else {
97            None
98        }
99    }
100}
101
102impl std::fmt::Display for CharTarget {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        match self {
105            Self::Dc(id) => write!(f, "{id}"),
106            Self::Format(id) => write!(f, "{}", id.shorthand()),
107            Self::FormatRegionEnd => {
108                write!(f, "f{}", ctb_storage_minimal::shorthand::MAX_FORMAT_ID)
109            }
110            Self::Unicode(cp) => write!(f, "u{cp:04x}"),
111        }
112    }
113}
114
115/// Quantifier applied to a syntax term.
116#[derive(
117    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
118)]
119pub enum Quantifier {
120    /// Exactly one occurrence (default).
121    #[default]
122    ExactOne,
123    /// One or more occurrences (`+`).
124    OneOrMore,
125    /// Zero or more occurrences (`*`).
126    ZeroOrMore,
127    /// Zero or one occurrence (`?` or bracketed optional construct `[...]`).
128    Optional,
129    /// Bounded repetition range (e.g. `{min..max}`, `{min,max}`, `{n}`).
130    Range { min: usize, max: Option<usize> },
131}
132
133impl Quantifier {
134    /// Returns true if matching zero occurrences is permitted.
135    #[must_use]
136    pub const fn allows_zero(self) -> bool {
137        match self {
138            Self::ZeroOrMore | Self::Optional => true,
139            Self::Range { min, .. } => min == 0,
140            _ => false,
141        }
142    }
143
144    /// Returns true if matching multiple occurrences is permitted.
145    #[must_use]
146    pub const fn allows_multiple(self) -> bool {
147        match self {
148            Self::OneOrMore | Self::ZeroOrMore => true,
149            Self::Range { max, .. } => match max {
150                Some(m) => m > 1,
151                None => true,
152            },
153            _ => false,
154        }
155    }
156
157    /// Returns true if the count has reached the maximum permitted occurrences.
158    #[must_use]
159    pub const fn reached_max(self, count: usize) -> bool {
160        match self {
161            Self::ExactOne | Self::Optional => count >= 1,
162            Self::OneOrMore | Self::ZeroOrMore => false,
163            Self::Range { max, .. } => match max {
164                Some(m) => count >= m,
165                None => false,
166            },
167        }
168    }
169
170    /// Returns true if this quantifier explicitly specifies repetition bounds
171    /// matching exactly once (`{1}`, `{1..1}`, or `{1,1}`), which is redundant
172    /// because matching once is already the default semantics of an unquantified term.
173    #[must_use]
174    pub const fn is_redundant(self) -> bool {
175        matches!(
176            self,
177            Self::Range {
178                min: 1,
179                max: Some(1)
180            }
181        )
182    }
183
184    /// Formats this quantifier as its canonical DSL suffix (`""`, `"+"`, `"*"`, `"?"`, or `"{...}"`).
185    #[must_use]
186    pub fn format_dsl_suffix(self) -> String {
187        match self {
188            Self::ExactOne => String::new(),
189            Self::OneOrMore => "+".to_string(),
190            Self::ZeroOrMore => "*".to_string(),
191            Self::Optional => "?".to_string(),
192            Self::Range {
193                min,
194                max: Some(max),
195            } if min == max => format!("{{{min}}}"),
196            Self::Range {
197                min,
198                max: Some(max),
199            } => format!("{{{min}..{max}}}"),
200            Self::Range { min, max: None } => format!("{{{min}..}}"),
201        }
202    }
203}
204
205/// Exact integer endpoint value used in `Dc 643 "Range"` numeric subtype bounds
206/// (`0..=u128::MAX`, negative `-u128`, or `2^128`).
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
208pub enum NumericBoundValue {
209    /// Non-negative integer bound in `0..=u128::MAX`.
210    Unsigned(u128),
211    /// Strictly negative integer bound (`-abs_val`).
212    Negative(u128),
213    /// Exact value `2^128` (`340282366920938463463374607431768211456`).
214    TwoPow128,
215}
216
217impl NumericBoundValue {
218    /// Parses a DSL numeric bound expression (such as `"0"`, `"8"`, `"(2^8)"`, `"(-2^7)"`, or `"(2^128)"`).
219    pub fn parse_dsl_bound(raw: &str) -> Result<Self> {
220        let trimmed = raw.trim();
221        // Reason for fallback: numeric bounds in DSL syntax may be unparenthesized (e.g. "0" or "8"), in which case trimmed is used directly.
222        let inner = trimmed
223            .strip_prefix('(')
224            .and_then(|s| s.strip_suffix(')'))
225            .map_or(trimmed, str::trim);
226        if inner == "2^128" {
227            return Ok(Self::TwoPow128);
228        }
229        if let Some(exp_str) = inner.strip_prefix("2^") {
230            let exp: u32 = exp_str.trim().parse().with_context(|| {
231                format!(
232                    "Invalid power-of-two exponent in numeric bound '{raw}'"
233                )
234            })?;
235            let val = 1u128.checked_shl(exp).with_context(|| {
236                format!("Power-of-two bound '2^{exp}' overflows u128")
237            })?;
238            return Ok(Self::Unsigned(val));
239        }
240        if let Some(exp_str) = inner.strip_prefix("-2^") {
241            let exp: u32 = exp_str.trim().parse().with_context(|| {
242                format!(
243                    "Invalid negative power-of-two exponent in numeric bound '{raw}'"
244                )
245            })?;
246            let abs_val = 1u128.checked_shl(exp).with_context(|| {
247                format!("Negative power-of-two bound '-2^{exp}' overflows u128")
248            })?;
249            return Ok(Self::Negative(abs_val));
250        }
251        if let Some(abs_str) = inner.strip_prefix('-') {
252            let abs_val: u128 = abs_str.trim().parse().with_context(|| {
253                format!("Invalid negative integer bound '{raw}'")
254            })?;
255            return Ok(Self::Negative(abs_val));
256        }
257        let val: u128 = inner.parse().with_context(|| {
258            format!("Invalid unsigned integer bound '{raw}'")
259        })?;
260        Ok(Self::Unsigned(val))
261    }
262
263    /// Returns the human-readable decimal label for `.ctbnodes` comments.
264    #[must_use]
265    pub fn summary_label(self) -> String {
266        match self {
267            Self::Unsigned(val) => val.to_string(),
268            Self::Negative(abs_val) => format!("-{abs_val}"),
269            Self::TwoPow128 => {
270                "340282366920938463463374607431768211456".to_string()
271            }
272        }
273    }
274
275    /// Formats this bound into canonical `[number:...]` DSL syntax (`0`, `8`, `(2^8)`, `(-2^7)`, `(2^128)`).
276    #[must_use]
277    pub fn format_dsl_bound(self) -> String {
278        match self {
279            Self::TwoPow128 => "(2^128)".to_string(),
280            Self::Unsigned(val) => {
281                if val >= 128 && val.is_power_of_two() {
282                    format!("(2^{})", val.trailing_zeros())
283                } else {
284                    val.to_string()
285                }
286            }
287            Self::Negative(abs_val) => {
288                if abs_val >= 128 && abs_val.is_power_of_two() {
289                    format!("(-2^{})", abs_val.trailing_zeros())
290                } else {
291                    format!("-{abs_val}")
292                }
293            }
294        }
295    }
296}
297
298/// Structured numeric format and/or range bound constraint for `[number:...]` constructs.
299#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
300pub struct NumberSubtypeConstraint {
301    /// Optional numeric format shorthand (`f<N>`) or stable format identifier (`Natural0`).
302    pub format: Option<String>,
303    /// Pre-resolved [`FormatId`] corresponding to `format`, if `format` names a known format.
304    pub format_id: Option<FormatId>,
305    /// Optional lower bound `(exclusive, bound)` (`>=` when `exclusive == false`, `>` when `exclusive == true`).
306    pub lower_bound: Option<(bool, NumericBoundValue)>,
307    /// Optional upper bound `(exclusive, bound)` (`<=` when `exclusive == false`, `<` when `exclusive == true`).
308    pub upper_bound: Option<(bool, NumericBoundValue)>,
309}
310
311impl NumberSubtypeConstraint {
312    /// Parses a `[number:...]` subtype constraint string into a [`NumberSubtypeConstraint`].
313    pub fn parse(raw: &str) -> Result<Self> {
314        let clauses = crate::syntax::parse_number_constraint(raw)?;
315        let mut out = Self::default();
316        for clause in clauses {
317            match clause {
318                crate::syntax::NumberConstraintClause::Target(target) => {
319                    ensure!(
320                        out.format.is_none(),
321                        "Duplicate format target '{target}' in [number:{raw}] constraint"
322                    );
323                    out.format_id = FormatId::from_shorthand(target)
324                        .or_else(|| FormatId::from_ident(target));
325                    out.format = Some(target.to_string());
326                }
327                crate::syntax::NumberConstraintClause::LowerBound {
328                    exclusive,
329                    bound,
330                } => {
331                    ensure!(
332                        out.lower_bound.is_none(),
333                        "Duplicate lower bound in [number:{raw}] constraint"
334                    );
335                    out.lower_bound = Some((exclusive, bound));
336                }
337                crate::syntax::NumberConstraintClause::UpperBound {
338                    exclusive,
339                    bound,
340                } => {
341                    ensure!(
342                        out.upper_bound.is_none(),
343                        "Duplicate upper bound in [number:{raw}] constraint"
344                    );
345                    out.upper_bound = Some((exclusive, bound));
346                }
347            }
348        }
349        Ok(out)
350    }
351
352    /// Formats this numeric constraint into canonical `[number:...]` DSL notation.
353    #[must_use]
354    pub fn format_dsl(&self) -> String {
355        let mut parts = Vec::new();
356        if let Some(fmt) = &self.format {
357            parts.push(fmt.clone());
358        }
359        if let Some((excl, lo)) = self.lower_bound {
360            let op = if excl { ">" } else { ">=" };
361            parts.push(format!("{op}{}", lo.format_dsl_bound()));
362        }
363        if let Some((excl, hi)) = self.upper_bound {
364            let op = if excl { "<" } else { "<=" };
365            parts.push(format!("{op}{}", hi.format_dsl_bound()));
366        }
367        parts.join(" & ")
368    }
369}
370
371/// Structured subtype constraint on a [`SyntaxTerm::NamedConstruct`] (`[<name>:<subtype>]`).
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373pub enum SubtypeConstraint {
374    /// Nested syntax pattern constraint (e.g. `[string:[asciiprintable]{4}]` or `[list:([filename] | 513)]`).
375    Pattern(Box<SyntaxPattern>),
376    /// Binary data format and/or byte-length constraint (e.g. `[data:Sha256;bytes=32]`, `[data:bytes=4]`).
377    Data {
378        format: Option<String>,
379        format_id: Option<FormatId>,
380        bytes: Option<usize>,
381    },
382    /// Numeric format and/or range bound constraint (e.g. `[number:Natural0]`, `[number:>=0 & <(2^8)]`).
383    Number(NumberSubtypeConstraint),
384    /// Integer length range constraint (e.g. `[asciilatinletterdigit:1..16]`).
385    LengthRange { min: u128, max: u128 },
386    /// Bound template variable reference (e.g. `$type` in `[type:$type]`).
387    BoundVar(String),
388    /// Named target, script, or format constraint (e.g. `[script:.EM Types]`, `[type:transformation]`, `[list:number]`).
389    Target(String),
390}
391
392impl SubtypeConstraint {
393    /// Parses the `<subtype>` portion of a `[<name>:<subtype>]` named construct into a structured [`SubtypeConstraint`].
394    pub fn parse(name: &str, raw: &str) -> Result<Self> {
395        let trimmed = raw.trim();
396        ensure!(
397            !trimmed.is_empty(),
398            "Empty subtype constraint in '[{name}:{raw}]'"
399        );
400        if let Some(var) = trimmed.strip_prefix('$') {
401            let var_trimmed = var.trim();
402            ensure!(
403                !var_trimmed.is_empty(),
404                "Empty bound variable in '[{name}:{raw}]'"
405            );
406            Ok(Self::BoundVar(var_trimmed.to_string()))
407        } else if name == "data" {
408            let (fmt, bytes) = crate::syntax::parse_data_constraint(trimmed)?;
409            let format_id = fmt.and_then(|s| {
410                FormatId::from_shorthand(s).or_else(|| FormatId::from_ident(s))
411            });
412            Ok(Self::Data {
413                format: fmt.map(str::to_string),
414                format_id,
415                bytes,
416            })
417        } else if name == "number"
418            || (name == "list"
419                && (trimmed.starts_with("<=")
420                    || trimmed.starts_with('<')
421                    || trimmed.starts_with(">=")
422                    || trimmed.starts_with('>')
423                    || trimmed.contains('&')))
424        {
425            Ok(Self::Number(NumberSubtypeConstraint::parse(trimmed)?))
426        } else if name == "string"
427            || trimmed.starts_with('[')
428            || trimmed.starts_with('(')
429        {
430            let rule = crate::syntax::parse_dc_syntax(&format!(":{trimmed}"))?;
431            Ok(Self::Pattern(Box::new(rule.pattern)))
432        } else if let Some((min_s, max_s)) = trimmed.split_once("..") {
433            let min: u128 = min_s.trim().parse().with_context(|| {
434                format!("Invalid min length in '[{name}:{raw}]'")
435            })?;
436            let max: u128 = max_s.trim().parse().with_context(|| {
437                format!("Invalid max length in '[{name}:{raw}]'")
438            })?;
439            Ok(Self::LengthRange { min, max })
440        } else {
441            Ok(Self::Target(trimmed.to_string()))
442        }
443    }
444
445    /// Formats this subtype constraint into canonical Dc syntax DSL notation.
446    #[must_use]
447    pub fn format_dsl(&self) -> String {
448        match self {
449            Self::Pattern(pat) => pat.format_dsl(),
450            Self::Data { format, bytes, .. } => match (format, bytes) {
451                (Some(f), Some(b)) => format!("{f};bytes={b}"),
452                (Some(f), None) => f.clone(),
453                (None, Some(b)) => format!("bytes={b}"),
454                (None, None) => String::new(),
455            },
456            Self::Number(num) => num.format_dsl(),
457            Self::LengthRange { min, max } => format!("{min}..{max}"),
458            Self::BoundVar(v) => format!("${v}"),
459            Self::Target(t) => t.clone(),
460        }
461    }
462
463    /// Returns the pre-resolved [`FormatId`] for this subtype constraint if it specifies a format.
464    #[must_use]
465    pub fn resolved_format_id(&self) -> Option<FormatId> {
466        match self {
467            Self::Data {
468                format_id, format, ..
469            } => format_id.or_else(|| {
470                format.as_deref().and_then(|s| {
471                    FormatId::from_shorthand(s)
472                        .or_else(|| FormatId::from_ident(s))
473                })
474            }),
475            Self::Number(num) => num.format_id.or_else(|| {
476                num.format.as_deref().and_then(|s| {
477                    FormatId::from_shorthand(s)
478                        .or_else(|| FormatId::from_ident(s))
479                })
480            }),
481            Self::Target(s) => {
482                FormatId::from_shorthand(s).or_else(|| FormatId::from_ident(s))
483            }
484            _ => None,
485        }
486    }
487
488    /// Returns the single target identifier string if this constraint represents an unconstrained
489    /// target name, format shorthand, or format identifier (`Target(s)`, format-only `Number`, or format-only `Data`).
490    #[must_use]
491    pub fn as_target_str(&self) -> Option<&str> {
492        match self {
493            Self::Target(s) => Some(s.as_str()),
494            Self::Data {
495                format: Some(s),
496                bytes: None,
497                ..
498            } => Some(s.as_str()),
499            Self::Number(NumberSubtypeConstraint {
500                format: Some(s),
501                lower_bound: None,
502                upper_bound: None,
503                ..
504            }) => Some(s.as_str()),
505            _ => None,
506        }
507    }
508}
509
510/// Syntactic term in a Dc syntax rule.
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512pub enum SyntaxTerm {
513    /// Self character reference (`~`), representing the character defining the rule.
514    SelfChar,
515    /// Direct single reference to a target character (Dc, format, or Unicode).
516    CharRef(CharTarget),
517    /// Bracketed character set (e.g. `[246 247]` or negated `[^248 255]`).
518    CharSet {
519        negated: bool,
520        members: Vec<CharTarget>,
521    },
522    /// Contiguous character range (e.g. `[260-265]`).
523    CharRange { start: CharTarget, end: CharTarget },
524    /// Macro expansion of another character's syntax rule (e.g. `260:` or `[260:]`).
525    RuleRef { target: CharTarget },
526    /// Named syntactic non-terminal construct (e.g. `[identifier $ident]`,
527    /// `[type:transformation]`, `[statement]`).
528    NamedConstruct {
529        name: String,
530        subtype: Option<SubtypeConstraint>,
531        capture_var: Option<String>,
532    },
533    /// Nested parenthesized pattern group `( ... )`.
534    Group(SyntaxPattern),
535}
536
537impl SyntaxTerm {
538    /// Returns a copy of this term with any subtype or list-length constraints removed,
539    /// or `None` if this term is already unconstrained.
540    #[must_use]
541    pub fn unconstrained(&self) -> Option<Self> {
542        match self {
543            Self::NamedConstruct { name, subtype, .. }
544                if name != "script"
545                    && (subtype.is_some() || name.starts_with("list(")) =>
546            {
547                let base_name = if name.starts_with("list(") {
548                    "list".to_owned()
549                } else {
550                    name.clone()
551                };
552                Some(Self::NamedConstruct {
553                    name: base_name,
554                    subtype: None,
555                    capture_var: None,
556                })
557            }
558            Self::Group(pattern) => pattern.unconstrained().map(Self::Group),
559            _ => None,
560        }
561    }
562
563    /// Formats this term into canonical Dc syntax DSL notation.
564    #[must_use]
565    pub fn format_dsl(&self) -> String {
566        match self {
567            Self::SelfChar => "~".to_string(),
568            Self::CharRef(target) => target.to_string(),
569            Self::CharSet { negated, members } => {
570                let prefix = if *negated { "^" } else { "" };
571                let items: Vec<String> =
572                    members.iter().map(ToString::to_string).collect();
573                format!("[{prefix}{}]", items.join(" "))
574            }
575            Self::CharRange { start, end } => format!("[{start}-{end}]"),
576            Self::RuleRef { target } => format!("[{target}:]"),
577            Self::NamedConstruct {
578                name,
579                subtype,
580                capture_var,
581            } => {
582                let mut inner = name.clone();
583                if let Some(sub) = subtype {
584                    inner.push(':');
585                    inner.push_str(&sub.format_dsl());
586                }
587                if let Some(var) = capture_var {
588                    inner.push_str(" $");
589                    inner.push_str(var);
590                }
591                format!("[{inner}]")
592            }
593            Self::Group(pattern) => {
594                if matches!(pattern, SyntaxPattern::Alternation(_)) {
595                    pattern.format_dsl()
596                } else {
597                    format!("({})", pattern.format_dsl())
598                }
599            }
600        }
601    }
602}
603
604/// Quantified element combining a term and its repetition quantifier.
605#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
606pub struct SyntaxElement {
607    pub term: SyntaxTerm,
608    pub quantifier: Quantifier,
609}
610
611impl SyntaxElement {
612    /// Creates a new element with `ExactOne` quantifier.
613    #[must_use]
614    pub const fn exact(term: SyntaxTerm) -> Self {
615        Self {
616            term,
617            quantifier: Quantifier::ExactOne,
618        }
619    }
620
621    /// Creates a new element with the given quantifier.
622    #[must_use]
623    pub const fn with_quantifier(
624        term: SyntaxTerm,
625        quantifier: Quantifier,
626    ) -> Self {
627        Self { term, quantifier }
628    }
629
630    /// Formats this quantified element into canonical Dc syntax DSL notation.
631    #[must_use]
632    pub fn format_dsl(&self) -> String {
633        format!(
634            "{}{}",
635            self.term.format_dsl(),
636            self.quantifier.format_dsl_suffix()
637        )
638    }
639}
640
641/// Pattern grammar combining sequences and alternations.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
643pub enum SyntaxPattern {
644    /// Ordered sequence of syntax elements.
645    Sequence(Vec<SyntaxElement>),
646    /// Alternative patterns separated by `|`.
647    Alternation(Vec<SyntaxPattern>),
648}
649
650impl SyntaxPattern {
651    /// Returns true if every leading branch of this pattern begins with `SyntaxTerm::SelfChar` (`~`).
652    #[must_use]
653    pub fn starts_with_self(&self) -> bool {
654        match self {
655            Self::Sequence(elements) => {
656                elements.first().is_some_and(|element| match &element.term {
657                    SyntaxTerm::SelfChar => true,
658                    SyntaxTerm::Group(pattern) => pattern.starts_with_self(),
659                    _ => false,
660                })
661            }
662            Self::Alternation(branches) => {
663                !branches.is_empty()
664                    && branches.iter().all(Self::starts_with_self)
665            }
666        }
667    }
668
669    /// Returns true if any leading branch of this pattern begins with `SyntaxTerm::SelfChar` (`~`)
670    /// or `SyntaxTerm::CharSet`.
671    #[must_use]
672    pub fn starts_with_self_or_charset(&self) -> bool {
673        match self {
674            Self::Sequence(elems) => {
675                elems.first().is_some_and(|e| match &e.term {
676                    SyntaxTerm::SelfChar | SyntaxTerm::CharSet { .. } => true,
677                    SyntaxTerm::Group(sub) => sub.starts_with_self_or_charset(),
678                    _ => false,
679                })
680            }
681            Self::Alternation(branches) => {
682                branches.iter().any(Self::starts_with_self_or_charset)
683            }
684        }
685    }
686
687    /// Returns true if any leading element of this pattern (accounting for
688    /// nullable leading elements) explicitly targets a character satisfying
689    /// `pred`.
690    #[must_use]
691    pub fn can_start_with_token(
692        &self,
693        pred: &mut impl FnMut(u128) -> bool,
694    ) -> bool {
695        match self {
696            Self::Sequence(elems) => {
697                for elem in elems {
698                    let hit = match &elem.term {
699                        SyntaxTerm::CharRef(target)
700                        | SyntaxTerm::RuleRef { target } => {
701                            pred(target.to_u128())
702                        }
703                        SyntaxTerm::Group(sub) => {
704                            sub.can_start_with_token(pred)
705                        }
706                        _ => false,
707                    };
708                    if hit {
709                        return true;
710                    }
711                    if !elem.quantifier.allows_zero() {
712                        break;
713                    }
714                }
715                false
716            }
717            Self::Alternation(branches) => {
718                branches.iter().any(|b| b.can_start_with_token(pred))
719            }
720        }
721    }
722
723    /// Returns a copy of this pattern with any subtype or list-length constraints removed,
724    /// or `None` if no nested term is constrained.
725    #[must_use]
726    pub fn unconstrained(&self) -> Option<Self> {
727        match self {
728            Self::Sequence(elements) => {
729                let mut changed = false;
730                let mut out = Vec::with_capacity(elements.len());
731                for elem in elements {
732                    if let Some(u_term) = elem.term.unconstrained() {
733                        changed = true;
734                        out.push(SyntaxElement {
735                            term: u_term,
736                            quantifier: elem.quantifier,
737                        });
738                    } else {
739                        out.push(elem.clone());
740                    }
741                }
742                changed.then_some(Self::Sequence(out))
743            }
744            Self::Alternation(branches) => {
745                let mut changed = false;
746                let mut out = Vec::with_capacity(branches.len());
747                for branch in branches {
748                    if let Some(u_branch) = branch.unconstrained() {
749                        changed = true;
750                        out.push(u_branch);
751                    } else {
752                        out.push(branch.clone());
753                    }
754                }
755                changed.then_some(Self::Alternation(out))
756            }
757        }
758    }
759
760    /// Formats this syntax pattern into canonical Dc syntax DSL notation.
761    #[must_use]
762    pub fn format_dsl(&self) -> String {
763        match self {
764            Self::Sequence(elements) => {
765                let parts: Vec<String> =
766                    elements.iter().map(SyntaxElement::format_dsl).collect();
767                parts.join(" ")
768            }
769            Self::Alternation(branches) => {
770                let parts: Vec<String> =
771                    branches.iter().map(Self::format_dsl).collect();
772                format!("({})", parts.join(" | "))
773            }
774        }
775    }
776}
777
778/// Argument passed to an action invocation.
779#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
780pub enum ActionArg {
781    /// Bound variable reference (e.g. `$ident`).
782    Variable(String),
783    /// Literal string argument.
784    Literal(String),
785}
786
787/// Action invocation representing semantic translation or AST emission.
788#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
789pub struct SyntaxAction {
790    /// Qualified action/method identifier (e.g. `lang.assign`).
791    pub method: String,
792    /// Arguments provided to the action invocation.
793    pub args: Vec<ActionArg>,
794}
795
796impl SyntaxAction {
797    /// Formats this syntax action into canonical Dc syntax DSL notation.
798    #[must_use]
799    pub fn format_dsl(&self) -> String {
800        let args: Vec<String> = self
801            .args
802            .iter()
803            .map(|arg| match arg {
804                ActionArg::Variable(var) => format!("${var}"),
805                ActionArg::Literal(lit) => {
806                    let escaped =
807                        lit.replace('\\', "\\\\").replace('"', "\\\"");
808                    format!("\"{escaped}\"")
809                }
810            })
811            .collect();
812        format!("{}({})", self.method, args.join(", "))
813    }
814}
815
816/// Root AST structure for a complete Dc syntax declaration.
817#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
818pub struct DcSyntaxRule {
819    /// Parsed pattern matching specification.
820    pub pattern: SyntaxPattern,
821    /// Optional semantic action declaration following `:`.
822    pub action: Option<SyntaxAction>,
823    /// Original raw source representation.
824    pub raw: String,
825}
826
827impl DcSyntaxRule {
828    /// Formats a `SyntaxPattern` and optional `SyntaxAction` into a canonical `:...` DSL string.
829    #[must_use]
830    pub fn format_dsl_parts(
831        pattern: &SyntaxPattern,
832        action: Option<&SyntaxAction>,
833    ) -> String {
834        let pat_str = pattern.format_dsl();
835        if let Some(act) = action {
836            format!(":{pat_str}: {}", act.format_dsl())
837        } else {
838            format!(":{pat_str}")
839        }
840    }
841
842    /// Formats this syntax rule into a canonical `:...` DSL string.
843    #[must_use]
844    pub fn format_dsl(&self) -> String {
845        Self::format_dsl_parts(&self.pattern, self.action.as_ref())
846    }
847}
848
849/// Diagnostic message emitted during parsing or matching.
850#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
851pub struct SyntaxDiagnostic {
852    /// Explanatory diagnostic message.
853    pub message: String,
854    /// Token or byte offset where the diagnostic occurred.
855    pub token_offset: u64,
856    /// Whether this diagnostic represents a syntax/framing error.
857    pub is_error: bool,
858}
859
860/// Normalizes a syntax pattern by converting explicit references to the defining
861/// character's Short ID (or any equivalent ID) into `SyntaxTerm::SelfChar` (`~`),
862/// and mapping target references to their canonical equivalents under `canonical_map`.
863pub fn normalize_syntax_pattern(
864    pattern: &SyntaxPattern,
865    self_short: Option<u32>,
866    canonical_map: &std::collections::HashMap<u128, u128>,
867) -> SyntaxPattern {
868    let norm_target = |ct: &CharTarget| -> CharTarget {
869        let gid = ct.to_u128();
870        if let Some(&canon_gid) = canonical_map.get(&gid) {
871            // Reason for fallback: unrepresentable canonical GID defaults to original CharTarget.
872            CharTarget::from_u128(canon_gid).unwrap_or_else(|| ct.clone())
873        } else {
874            ct.clone()
875        }
876    };
877
878    let is_self = |ct: &CharTarget| -> bool {
879        match ct {
880            CharTarget::Dc(id) if self_short == Some(*id) => true,
881            _ => {
882                if let Some(self_id) = self_short {
883                    let self_gid = DcChar::from_short(self_id).to_u128();
884                    // Reason for fallback: token not in canonical_map is self-canonical.
885                    let canon_self = canonical_map
886                        .get(&self_gid)
887                        .copied()
888                        .unwrap_or(self_gid);
889                    let ct_gid = ct.to_u128();
890                    // Reason for fallback: token not in canonical_map is self-canonical.
891                    let canon_ct =
892                        canonical_map.get(&ct_gid).copied().unwrap_or(ct_gid);
893                    canon_self == canon_ct
894                } else {
895                    false
896                }
897            }
898        }
899    };
900
901    match pattern {
902        SyntaxPattern::Sequence(elements) => SyntaxPattern::Sequence(
903            elements
904                .iter()
905                .map(|elem| {
906                    let term = match &elem.term {
907                        SyntaxTerm::CharRef(ct) if is_self(ct) => {
908                            SyntaxTerm::SelfChar
909                        }
910                        SyntaxTerm::CharRef(ct) => {
911                            SyntaxTerm::CharRef(norm_target(ct))
912                        }
913                        SyntaxTerm::CharSet { negated, members } => {
914                            let mut norm_members: Vec<CharTarget> =
915                                members.iter().map(norm_target).collect();
916                            norm_members.sort();
917                            norm_members.dedup();
918                            SyntaxTerm::CharSet {
919                                negated: *negated,
920                                members: norm_members,
921                            }
922                        }
923                        SyntaxTerm::CharRange { start, end } => {
924                            SyntaxTerm::CharRange {
925                                start: norm_target(start),
926                                end: norm_target(end),
927                            }
928                        }
929                        SyntaxTerm::RuleRef { target } => SyntaxTerm::RuleRef {
930                            target: norm_target(target),
931                        },
932                        SyntaxTerm::Group(group_pat) => {
933                            SyntaxTerm::Group(normalize_syntax_pattern(
934                                group_pat,
935                                self_short,
936                                canonical_map,
937                            ))
938                        }
939                        other => other.clone(),
940                    };
941                    SyntaxElement {
942                        term,
943                        quantifier: elem.quantifier,
944                    }
945                })
946                .collect(),
947        ),
948        SyntaxPattern::Alternation(branches) => SyntaxPattern::Alternation(
949            branches
950                .iter()
951                .map(|b| normalize_syntax_pattern(b, self_short, canonical_map))
952                .collect(),
953        ),
954    }
955}
956
957/// Highest Short Dc ID permitted to use legacy framing shapes (`PrefixVariableArity`,
958/// `Infix`, or `LegacySourceWhitespace`). Any newly allocated Short Dc (`> 634`)
959/// that defines a syntax rule must use deterministic `Paired`, `Closer`,
960/// `PrefixAtomArity`, or `PrefixArity` framing.
961pub const MAX_LEGACY_FRAMING_SHORT_DC_ID: u32 = 634;
962
963/// Physical framing classification of a Document Character or Format syntax rule.
964#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
965pub enum FramingShape {
966    /// Atomic character with no framing rule (consumes only itself).
967    Atom,
968    /// Paired opening delimiter closed by `closer`, optionally followed by
969    /// trailing elements after the closer (e.g. `543..544 [545:]`).
970    Paired {
971        closer: u128,
972        has_trailing_after_closer: bool,
973    },
974    /// Closing delimiter that terminates a paired block opened by `opener`.
975    Closer { opener: CharTarget },
976    /// Fixed-arity prefix construct `:~ [atom_dc]{N}` where each argument is an
977    /// `[atom_dc]` (either 1 atomic token or `Dc 616` + `[value]`).
978    PrefixAtomArity(u8),
979    /// Fixed-arity prefix construct `:~ <arg_1> ... <arg_N>` consuming `N` child frames.
980    PrefixArity(u8),
981    /// Legacy variable-arity prefix construct (e.g. `Dc 276` optional leading `[type]`,
982    /// `Dc 300`/`516` `([type] [type]) | [list:type]`, `Dc 279` trailing parameter blocks,
983    /// `Dc 407` `(511 [f523:] 512 | [f523:])`, or `Dc 535` `:~ [type] (258 ... 259)+`).
984    PrefixVariableArity,
985    /// Legacy infix operator where `~` is preceded by an LHS construct and followed
986    /// by an RHS construct (`Dc 269`, `Dc 277`).
987    Infix,
988    /// Legacy source whitespace rule (`Dc 267`: `:([statement] ~) | (~ ~) | (~ [statement])`).
989    LegacySourceWhitespace,
990    /// Self-less format value constraint pattern (e.g. `f200`: `:[number:>=0]`).
991    ValueConstraint,
992}
993
994impl FramingShape {
995    /// Returns true if this framing shape is allowed for newly defined Document Characters (`> 634`).
996    #[must_use]
997    pub const fn is_allowed_for_new_dc(&self) -> bool {
998        matches!(
999            self,
1000            Self::Atom
1001                | Self::Paired { .. }
1002                | Self::Closer { .. }
1003                | Self::PrefixAtomArity(_)
1004                | Self::PrefixArity(_)
1005        )
1006    }
1007}
1008
1009fn pattern_contains_self(pattern: &SyntaxPattern) -> bool {
1010    match pattern {
1011        SyntaxPattern::Sequence(elements) => {
1012            elements.iter().any(|el| match &el.term {
1013                SyntaxTerm::SelfChar => true,
1014                SyntaxTerm::Group(sub) => pattern_contains_self(sub),
1015                _ => false,
1016            })
1017        }
1018        SyntaxPattern::Alternation(branches) => {
1019            branches.iter().any(pattern_contains_self)
1020        }
1021    }
1022}
1023
1024fn is_legacy_whitespace_pattern(pattern: &SyntaxPattern) -> bool {
1025    let SyntaxPattern::Alternation(branches) = pattern else {
1026        return false;
1027    };
1028    branches.len() >= 2
1029        && branches.iter().all(|b| {
1030            let SyntaxPattern::Sequence(outer) = b else {
1031                return false;
1032            };
1033            let elems = if let [
1034                SyntaxElement {
1035                    term: SyntaxTerm::Group(SyntaxPattern::Sequence(inner)),
1036                    quantifier: Quantifier::ExactOne,
1037                },
1038            ] = outer.as_slice()
1039            {
1040                inner.as_slice()
1041            } else {
1042                outer.as_slice()
1043            };
1044            elems.len() == 2
1045                && elems.iter().all(|e| {
1046                    e.quantifier == Quantifier::ExactOne
1047                        && (matches!(&e.term, SyntaxTerm::SelfChar)
1048                            || matches!(
1049                                &e.term,
1050                                SyntaxTerm::NamedConstruct { name, .. } if name == "statement"
1051                            ))
1052                })
1053        })
1054}
1055
1056/// Returns true if `rule` is a 1-argument prefix rule (`:~ <1 ExactOne NamedConstruct>`).
1057#[must_use]
1058pub fn is_unary_prefix_rule(rule: &DcSyntaxRule) -> bool {
1059    let SyntaxPattern::Sequence(elems) = &rule.pattern else {
1060        return false;
1061    };
1062    elems.len() == 2
1063        && elems.first().is_some_and(|e| {
1064            e.quantifier == Quantifier::ExactOne
1065                && matches!(e.term, SyntaxTerm::SelfChar)
1066        })
1067        && elems.get(1).is_some_and(|e| {
1068            e.quantifier == Quantifier::ExactOne
1069                && matches!(e.term, SyntaxTerm::NamedConstruct { .. })
1070        })
1071}
1072
1073fn is_inline_paired_subframe<FCloser>(
1074    elements: &[SyntaxElement],
1075    closer_for_opener: &FCloser,
1076) -> bool
1077where
1078    FCloser: Fn(&CharTarget) -> Option<u128>,
1079{
1080    if elements.len() < 2 {
1081        return false;
1082    }
1083    let (Some(first), Some(last)) = (elements.first(), elements.last()) else {
1084        return false;
1085    };
1086    if first.quantifier != Quantifier::ExactOne
1087        || last.quantifier != Quantifier::ExactOne
1088    {
1089        return false;
1090    }
1091    if let (SyntaxTerm::CharRef(opener), SyntaxTerm::CharRef(closer)) =
1092        (&first.term, &last.term)
1093    {
1094        closer_for_opener(opener) == Some(closer.to_u128())
1095    } else {
1096        false
1097    }
1098}
1099
1100fn term_fixed_frame_arity<FCloser, FUnary>(
1101    term: &SyntaxTerm,
1102    closer_for_opener: &FCloser,
1103    is_unary_prefix_target: &FUnary,
1104) -> Option<u8>
1105where
1106    FCloser: Fn(&CharTarget) -> Option<u128>,
1107    FUnary: Fn(&CharTarget) -> bool,
1108{
1109    match term {
1110        SyntaxTerm::NamedConstruct { .. }
1111        | SyntaxTerm::CharRef(_)
1112        | SyntaxTerm::CharSet { .. }
1113        | SyntaxTerm::CharRange { .. }
1114        | SyntaxTerm::RuleRef {
1115            target: CharTarget::Dc(_),
1116        } => Some(1),
1117        SyntaxTerm::Group(SyntaxPattern::Sequence(sub_elems)) => {
1118            sequence_fixed_frame_arity(
1119                sub_elems,
1120                closer_for_opener,
1121                is_unary_prefix_target,
1122            )
1123        }
1124        SyntaxTerm::Group(SyntaxPattern::Alternation(branches)) => {
1125            let first = branches.first()?;
1126            let first_arity = match first {
1127                SyntaxPattern::Sequence(s) => sequence_fixed_frame_arity(
1128                    s,
1129                    closer_for_opener,
1130                    is_unary_prefix_target,
1131                )?,
1132                SyntaxPattern::Alternation(_) => return None,
1133            };
1134            for branch in branches.get(1..)? {
1135                let branch_arity = match branch {
1136                    SyntaxPattern::Sequence(s) => sequence_fixed_frame_arity(
1137                        s,
1138                        closer_for_opener,
1139                        is_unary_prefix_target,
1140                    )?,
1141                    SyntaxPattern::Alternation(_) => return None,
1142                };
1143                if branch_arity != first_arity {
1144                    return None;
1145                }
1146            }
1147            Some(first_arity)
1148        }
1149        SyntaxTerm::SelfChar | SyntaxTerm::RuleRef { .. } => None,
1150    }
1151}
1152
1153fn sequence_fixed_frame_arity<FCloser, FUnary>(
1154    elements: &[SyntaxElement],
1155    closer_for_opener: &FCloser,
1156    is_unary_prefix_target: &FUnary,
1157) -> Option<u8>
1158where
1159    FCloser: Fn(&CharTarget) -> Option<u128>,
1160    FUnary: Fn(&CharTarget) -> bool,
1161{
1162    if elements.is_empty() {
1163        return Some(0);
1164    }
1165    if is_inline_paired_subframe(elements, closer_for_opener) {
1166        return Some(1);
1167    }
1168    let mut total = 0u8;
1169    let mut idx = 0usize;
1170    while idx < elements.len() {
1171        if let (Some(e0), Some(e1), Some(e2)) = (
1172            elements.get(idx),
1173            elements.get(idx.saturating_add(1)),
1174            elements.get(idx.saturating_add(2)),
1175        ) {
1176            if e0.quantifier == Quantifier::ExactOne
1177                && e1.quantifier == Quantifier::ExactOne
1178                && e2.quantifier == Quantifier::ExactOne
1179                && let (
1180                    SyntaxTerm::CharRef(opener),
1181                    SyntaxTerm::CharRef(closer),
1182                ) = (&e0.term, &e2.term)
1183                && closer_for_opener(opener) == Some(closer.to_u128())
1184            {
1185                total = total.checked_add(1)?;
1186                idx = idx.saturating_add(3);
1187                continue;
1188            }
1189        }
1190        if let (Some(e0), Some(e1)) =
1191            (elements.get(idx), elements.get(idx.saturating_add(1)))
1192        {
1193            if e0.quantifier == Quantifier::ExactOne
1194                && e1.quantifier == Quantifier::ExactOne
1195                && let SyntaxTerm::CharRef(sub_op) = &e0.term
1196                && is_unary_prefix_target(sub_op)
1197                && matches!(e1.term, SyntaxTerm::NamedConstruct { .. })
1198            {
1199                total = total.checked_add(1)?;
1200                idx = idx.saturating_add(2);
1201                continue;
1202            }
1203        }
1204        let el = elements.get(idx)?;
1205        if el.quantifier != Quantifier::ExactOne {
1206            return None;
1207        }
1208        let term_arity = term_fixed_frame_arity(
1209            &el.term,
1210            closer_for_opener,
1211            is_unary_prefix_target,
1212        )?;
1213        total = total.checked_add(term_arity)?;
1214        idx = idx.saturating_add(1);
1215    }
1216    Some(total)
1217}
1218
1219/// Classifies the physical framing shape of a Document Character or Format rule,
1220/// using `closer_for_opener` and `is_unary_prefix_target` to identify inline subframes.
1221///
1222/// Returns `None` if `rule` does not conform to any recognized framing shape.
1223#[must_use]
1224pub fn classify_rule_framing_shape_with<FCloser, FUnary>(
1225    target: &CharTarget,
1226    rule: Option<&DcSyntaxRule>,
1227    closer: Option<u128>,
1228    has_trailing_after_closer: bool,
1229    closing_opener: Option<CharTarget>,
1230    closer_for_opener: FCloser,
1231    is_unary_prefix_target: FUnary,
1232) -> Option<FramingShape>
1233where
1234    FCloser: Fn(&CharTarget) -> Option<u128>,
1235    FUnary: Fn(&CharTarget) -> bool,
1236{
1237    if let Some(closer) = closer {
1238        return Some(FramingShape::Paired {
1239            closer,
1240            has_trailing_after_closer,
1241        });
1242    }
1243    if let Some(opener) = closing_opener {
1244        return Some(FramingShape::Closer { opener });
1245    }
1246    let Some(rule) = rule else {
1247        return Some(FramingShape::Atom);
1248    };
1249
1250    if is_legacy_whitespace_pattern(&rule.pattern) {
1251        return Some(FramingShape::LegacySourceWhitespace);
1252    }
1253
1254    if let SyntaxPattern::Sequence(elements) = &rule.pattern {
1255        if let Some(self_idx) = elements
1256            .iter()
1257            .position(|el| matches!(el.term, SyntaxTerm::SelfChar))
1258        {
1259            if self_idx > 0 && self_idx.saturating_add(1) < elements.len() {
1260                return Some(FramingShape::Infix);
1261            }
1262            if self_idx > 0
1263                && self_idx.saturating_add(1) == elements.len()
1264                && elements
1265                    .last()
1266                    .is_some_and(|el| el.quantifier == Quantifier::ExactOne)
1267            {
1268                if let Some(first) = elements.first() {
1269                    if first.quantifier == Quantifier::ExactOne {
1270                        match &first.term {
1271                            SyntaxTerm::CharRef(opener) => {
1272                                return Some(FramingShape::Closer {
1273                                    opener: opener.clone(),
1274                                });
1275                            }
1276                            SyntaxTerm::CharSet {
1277                                negated: false,
1278                                members,
1279                            } => {
1280                                if let Some(opener) = members.first() {
1281                                    return Some(FramingShape::Closer {
1282                                        opener: opener.clone(),
1283                                    });
1284                                }
1285                            }
1286                            _ => {}
1287                        }
1288                    }
1289                }
1290            }
1291        }
1292    }
1293
1294    match &rule.pattern {
1295        SyntaxPattern::Sequence(elements)
1296            if elements.first().is_some_and(|el| {
1297                el.quantifier == Quantifier::ExactOne
1298                    && matches!(el.term, SyntaxTerm::SelfChar)
1299            }) =>
1300        {
1301            let tail = elements.get(1..)?;
1302            if tail.is_empty() {
1303                return Some(FramingShape::PrefixArity(0));
1304            }
1305            if tail.iter().all(|el| {
1306                el.quantifier == Quantifier::ExactOne
1307                    && matches!(
1308                        &el.term,
1309                        SyntaxTerm::NamedConstruct {
1310                            name,
1311                            subtype: None,
1312                            ..
1313                        } if name == "atom_dc"
1314                    )
1315            }) {
1316                let arity = u8::try_from(tail.len()).ok()?;
1317                return Some(FramingShape::PrefixAtomArity(arity));
1318            }
1319            if let Some(arity) = sequence_fixed_frame_arity(
1320                tail,
1321                &closer_for_opener,
1322                &is_unary_prefix_target,
1323            ) {
1324                return Some(FramingShape::PrefixArity(arity));
1325            }
1326            return Some(FramingShape::PrefixVariableArity);
1327        }
1328        SyntaxPattern::Alternation(branches)
1329            if branches
1330                .first()
1331                .is_some_and(SyntaxPattern::starts_with_self) =>
1332        {
1333            let mut common_arity: Option<u8> = None;
1334            for branch in branches {
1335                let SyntaxPattern::Sequence(elems) = branch else {
1336                    return Some(FramingShape::PrefixVariableArity);
1337                };
1338                let branch_tail = if elems
1339                    .first()
1340                    .is_some_and(|e| matches!(e.term, SyntaxTerm::SelfChar))
1341                {
1342                    elems.get(1..)?
1343                } else {
1344                    elems.as_slice()
1345                };
1346                let Some(branch_arity) = sequence_fixed_frame_arity(
1347                    branch_tail,
1348                    &closer_for_opener,
1349                    &is_unary_prefix_target,
1350                ) else {
1351                    return Some(FramingShape::PrefixVariableArity);
1352                };
1353                if let Some(prev) = common_arity {
1354                    if prev != branch_arity {
1355                        return Some(FramingShape::PrefixVariableArity);
1356                    }
1357                } else {
1358                    common_arity = Some(branch_arity);
1359                }
1360            }
1361            // Reason for fallback: when no branch was evaluated (e.g. empty choice list), prefix variable arity is assumed.
1362            return Some(common_arity.map_or(
1363                FramingShape::PrefixVariableArity,
1364                FramingShape::PrefixArity,
1365            ));
1366        }
1367        _ => {}
1368    }
1369
1370    if matches!(target, CharTarget::Format(_))
1371        && !pattern_contains_self(&rule.pattern)
1372    {
1373        return Some(FramingShape::ValueConstraint);
1374    }
1375
1376    None
1377}
1378
1379/// Classifies the physical framing shape of a Document Character or Format rule
1380/// without external subframe lookups.
1381#[must_use]
1382pub fn classify_rule_framing_shape(
1383    target: &CharTarget,
1384    rule: Option<&DcSyntaxRule>,
1385    closer: Option<u128>,
1386    has_trailing_after_closer: bool,
1387    closing_opener: Option<CharTarget>,
1388) -> Option<FramingShape> {
1389    classify_rule_framing_shape_with(
1390        target,
1391        rule,
1392        closer,
1393        has_trailing_after_closer,
1394        closing_opener,
1395        |_| None,
1396        |_| false,
1397    )
1398}