1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29use serde::{Deserialize, Serialize};
30
31#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub enum CharTarget {
34 Dc(u32),
36 Format(ctb_utilities::format_id::FormatId),
38 FormatRegionEnd,
41 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 #[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 #[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#[derive(
117 Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
118)]
119pub enum Quantifier {
120 #[default]
122 ExactOne,
123 OneOrMore,
125 ZeroOrMore,
127 Optional,
129 Range { min: usize, max: Option<usize> },
131}
132
133impl Quantifier {
134 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
208pub enum NumericBoundValue {
209 Unsigned(u128),
211 Negative(u128),
213 TwoPow128,
215}
216
217impl NumericBoundValue {
218 pub fn parse_dsl_bound(raw: &str) -> Result<Self> {
220 let trimmed = raw.trim();
221 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 #[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 #[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#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
300pub struct NumberSubtypeConstraint {
301 pub format: Option<String>,
303 pub format_id: Option<FormatId>,
305 pub lower_bound: Option<(bool, NumericBoundValue)>,
307 pub upper_bound: Option<(bool, NumericBoundValue)>,
309}
310
311impl NumberSubtypeConstraint {
312 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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373pub enum SubtypeConstraint {
374 Pattern(Box<SyntaxPattern>),
376 Data {
378 format: Option<String>,
379 format_id: Option<FormatId>,
380 bytes: Option<usize>,
381 },
382 Number(NumberSubtypeConstraint),
384 LengthRange { min: u128, max: u128 },
386 BoundVar(String),
388 Target(String),
390}
391
392impl SubtypeConstraint {
393 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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512pub enum SyntaxTerm {
513 SelfChar,
515 CharRef(CharTarget),
517 CharSet {
519 negated: bool,
520 members: Vec<CharTarget>,
521 },
522 CharRange { start: CharTarget, end: CharTarget },
524 RuleRef { target: CharTarget },
526 NamedConstruct {
529 name: String,
530 subtype: Option<SubtypeConstraint>,
531 capture_var: Option<String>,
532 },
533 Group(SyntaxPattern),
535}
536
537impl SyntaxTerm {
538 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
606pub struct SyntaxElement {
607 pub term: SyntaxTerm,
608 pub quantifier: Quantifier,
609}
610
611impl SyntaxElement {
612 #[must_use]
614 pub const fn exact(term: SyntaxTerm) -> Self {
615 Self {
616 term,
617 quantifier: Quantifier::ExactOne,
618 }
619 }
620
621 #[must_use]
623 pub const fn with_quantifier(
624 term: SyntaxTerm,
625 quantifier: Quantifier,
626 ) -> Self {
627 Self { term, quantifier }
628 }
629
630 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
643pub enum SyntaxPattern {
644 Sequence(Vec<SyntaxElement>),
646 Alternation(Vec<SyntaxPattern>),
648}
649
650impl SyntaxPattern {
651 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
780pub enum ActionArg {
781 Variable(String),
783 Literal(String),
785}
786
787#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
789pub struct SyntaxAction {
790 pub method: String,
792 pub args: Vec<ActionArg>,
794}
795
796impl SyntaxAction {
797 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
818pub struct DcSyntaxRule {
819 pub pattern: SyntaxPattern,
821 pub action: Option<SyntaxAction>,
823 pub raw: String,
825}
826
827impl DcSyntaxRule {
828 #[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 #[must_use]
844 pub fn format_dsl(&self) -> String {
845 Self::format_dsl_parts(&self.pattern, self.action.as_ref())
846 }
847}
848
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
851pub struct SyntaxDiagnostic {
852 pub message: String,
854 pub token_offset: u64,
856 pub is_error: bool,
858}
859
860pub 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 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 let canon_self = canonical_map
886 .get(&self_gid)
887 .copied()
888 .unwrap_or(self_gid);
889 let ct_gid = ct.to_u128();
890 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
957pub const MAX_LEGACY_FRAMING_SHORT_DC_ID: u32 = 634;
962
963#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
965pub enum FramingShape {
966 Atom,
968 Paired {
971 closer: u128,
972 has_trailing_after_closer: bool,
973 },
974 Closer { opener: CharTarget },
976 PrefixAtomArity(u8),
979 PrefixArity(u8),
981 PrefixVariableArity,
985 Infix,
988 LegacySourceWhitespace,
990 ValueConstraint,
992}
993
994impl FramingShape {
995 #[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#[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#[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 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#[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}