1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::syntax_ast::{
30 ActionArg, CharTarget, DcSyntaxRule, Quantifier, SubtypeConstraint,
31 SyntaxAction, SyntaxElement, SyntaxPattern, SyntaxTerm,
32};
33use anyhow::{Context, Result, bail, ensure};
34
35pub fn parse_target_token(token: &str) -> Option<CharTarget> {
40 match ctb_storage_minimal::shorthand::DcShorthand::parse(token).ok()? {
41 ctb_storage_minimal::shorthand::DcShorthand::Short(id) => {
42 Some(CharTarget::Dc(id))
43 }
44 ctb_storage_minimal::shorthand::DcShorthand::Format(id) => {
45 if let Some(fid) =
46 ctb_utilities::format_id::FormatId::from_shorthand(token)
47 {
48 Some(CharTarget::Format(fid))
49 } else if id == ctb_storage_minimal::shorthand::MAX_FORMAT_ID {
50 Some(CharTarget::FormatRegionEnd)
51 } else {
52 None
53 }
54 }
55 ctb_storage_minimal::shorthand::DcShorthand::Unicode(cp) => {
56 Some(CharTarget::Unicode(cp))
57 }
58 ctb_storage_minimal::shorthand::DcShorthand::Long(_)
59 | ctb_storage_minimal::shorthand::DcShorthand::Local(_) => None,
60 }
61}
62
63fn parse_syntax_action(raw: &str) -> Result<SyntaxAction> {
65 let trimmed = raw.trim();
66 let Some(open_idx) = trimmed.find('(') else {
67 bail!(
68 "Action invocation is missing argument list opening '(': '{trimmed}'"
69 );
70 };
71 let Some(close_idx) = trimmed.rfind(')') else {
72 bail!(
73 "Action invocation is missing argument list closing ')': '{trimmed}'"
74 );
75 };
76 ensure!(
77 open_idx < close_idx && close_idx == trimmed.len().saturating_sub(1),
78 "Mismatched parenthesis in action: '{trimmed}'"
79 );
80
81 let method = match trimmed.get(..open_idx) {
82 Some(m) => m.trim().to_string(),
83 None => bail!("Failed to extract action method name"),
84 };
85 ensure!(
86 !method.is_empty()
87 && method.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
88 && method
89 .chars()
90 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.'),
91 "Invalid action method name: '{method}'"
92 );
93
94 let args_str = match trimmed.get(open_idx.saturating_add(1)..close_idx) {
95 Some(a) => a.trim(),
96 None => "",
97 };
98
99 let mut args = Vec::new();
100 if !args_str.is_empty() {
101 for arg in args_str.split(',') {
102 let arg_trim = arg.trim();
103 if arg_trim.is_empty() {
104 continue;
105 }
106 if let Some(var_name) = arg_trim.strip_prefix('$') {
107 args.push(ActionArg::Variable(var_name.trim().to_string()));
108 } else {
109 let clean_literal =
110 arg_trim.trim_matches('"').trim_matches('\'');
111 args.push(ActionArg::Literal(clean_literal.to_string()));
112 }
113 }
114 }
115
116 Ok(SyntaxAction { method, args })
117}
118
119fn parse_bracket_content(content: &str) -> Result<SyntaxElement> {
121 let trimmed = content.trim();
122 ensure!(!trimmed.is_empty(), "Empty bracket construct '[]'");
123
124 if let Some(rest) = trimmed.strip_prefix('^') {
126 let rest_trimmed = rest.trim();
127 let tokens_str = if rest_trimmed.starts_with('(')
128 && rest_trimmed.ends_with(')')
129 {
130 match rest_trimmed.get(1..rest_trimmed.len().saturating_sub(1)) {
131 Some(s) => s.trim(),
132 None => "",
133 }
134 } else if rest_trimmed.contains('|') {
135 bail!(
136 "Alternation '|' in negated set '[{trimmed}]' must be enclosed in parentheses, e.g. '[^({rest_trimmed})]'"
137 );
138 } else {
139 rest_trimmed
140 };
141
142 let mut members = Vec::new();
143 for tok in tokens_str.split(|c: char| c.is_whitespace() || c == '|') {
144 let tok = tok.trim();
145 if tok.is_empty() {
146 continue;
147 }
148 let target = parse_target_token(tok).with_context(|| {
149 format!("Invalid character token in negated set: '{tok}'")
150 })?;
151 members.push(target);
152 }
153 ensure!(
154 !members.is_empty(),
155 "Negated character set '[^]' cannot be empty"
156 );
157 return Ok(SyntaxElement::exact(SyntaxTerm::CharSet {
158 negated: true,
159 members,
160 }));
161 }
162
163 if let Some(rule_tok) = trimmed.strip_suffix(':') {
165 let target = parse_target_token(rule_tok).with_context(|| {
166 format!(
167 "Invalid rule reference target in '[{trimmed}]': '{rule_tok}'"
168 )
169 })?;
170 return Ok(SyntaxElement::exact(SyntaxTerm::RuleRef { target }));
171 }
172
173 if let Some((start_tok, end_tok)) =
175 trimmed.split_once("..").or_else(|| trimmed.split_once('-'))
176 {
177 if let (Some(start), Some(end)) = (
178 parse_target_token(start_tok.trim()),
179 parse_target_token(end_tok.trim()),
180 ) {
181 return Ok(SyntaxElement::exact(SyntaxTerm::CharRange {
182 start,
183 end,
184 }));
185 }
186 }
187
188 let positive_str = if trimmed.starts_with('(') && trimmed.ends_with(')') {
190 match trimmed.get(1..trimmed.len().saturating_sub(1)) {
191 Some(s) => s.trim(),
192 None => "",
193 }
194 } else {
195 trimmed
196 };
197 let tokens: Vec<&str> = positive_str
198 .split(|c: char| c.is_whitespace() || c == '|')
199 .map(str::trim)
200 .filter(|s| !s.is_empty())
201 .collect();
202 if !tokens.is_empty() {
203 let mut targets = Vec::new();
204 let mut all_valid = true;
205 for tok in &tokens {
206 if let Some(target) = parse_target_token(tok) {
207 targets.push(target);
208 } else {
209 all_valid = false;
210 break;
211 }
212 }
213 if all_valid {
214 return Ok(SyntaxElement::exact(SyntaxTerm::CharSet {
215 negated: false,
216 members: targets,
217 }));
218 }
219 }
220
221 let mut top_colon_idx = None;
224 let mut depth_p = 0usize;
225 let mut depth_b = 0usize;
226 for (i, c) in trimmed.char_indices() {
227 match c {
228 '(' => depth_p = depth_p.saturating_add(1),
229 ')' => depth_p = depth_p.saturating_sub(1),
230 '[' => depth_b = depth_b.saturating_add(1),
231 ']' => depth_b = depth_b.saturating_sub(1),
232 ':' if depth_p == 0 && depth_b == 0 => {
233 top_colon_idx = Some(i);
234 break;
235 }
236 _ => {}
237 }
238 }
239
240 if let Some(colon_idx) = top_colon_idx {
241 let name_part_raw = match trimmed.get(..colon_idx) {
242 Some(s) => s,
243 None => bail!(
244 "Invalid name slice bounds in named construct '[{trimmed}]'"
245 ),
246 };
247 let subtype_part_raw = match trimmed.get(colon_idx.saturating_add(1)..)
248 {
249 Some(s) => s,
250 None => bail!(
251 "Invalid subtype slice bounds in named construct '[{trimmed}]'"
252 ),
253 };
254
255 let mut name_words = Vec::new();
256 let mut capture_var = None;
257 let mut elem_quantifier = Quantifier::ExactOne;
258
259 for tok in name_part_raw.split_whitespace() {
260 if let Some(var) = tok.strip_prefix('$') {
261 ensure!(
262 capture_var.is_none(),
263 "Multiple capture variables in named construct '[{trimmed}]'"
264 );
265 let (clean_var, q) =
266 if let Some(stripped) = var.strip_suffix('?') {
267 (stripped, Quantifier::Optional)
268 } else if let Some(stripped) = var.strip_suffix('*') {
269 (stripped, Quantifier::ZeroOrMore)
270 } else if let Some(stripped) = var.strip_suffix('+') {
271 (stripped, Quantifier::OneOrMore)
272 } else {
273 (var, Quantifier::ExactOne)
274 };
275 elem_quantifier = q;
276 capture_var = Some(clean_var.trim().to_string());
277 } else {
278 ensure!(
279 capture_var.is_none(),
280 "Unexpected token after capture variable in named construct name '[{trimmed}]': '{tok}'"
281 );
282 name_words.push(tok);
283 }
284 }
285 let name = name_words.join(" ");
286
287 let mut subtype_str = subtype_part_raw.trim();
288 let mut last_top_whitespace = None;
289 let mut depth_p = 0usize;
290 let mut depth_b = 0usize;
291 for (i, c) in subtype_str.char_indices() {
292 match c {
293 '(' => depth_p = depth_p.saturating_add(1),
294 ')' => depth_p = depth_p.saturating_sub(1),
295 '[' => depth_b = depth_b.saturating_add(1),
296 ']' => depth_b = depth_b.saturating_sub(1),
297 _ if c.is_whitespace() && depth_p == 0 && depth_b == 0 => {
298 last_top_whitespace = Some(i);
299 }
300 _ => {}
301 }
302 }
303 if let Some(ws_idx) = last_top_whitespace {
304 if let Some(candidate_slice) = subtype_str.get(ws_idx..) {
305 let candidate = candidate_slice.trim();
306 if let Some(var) = candidate.strip_prefix('$') {
307 if !var.is_empty() {
308 ensure!(
309 capture_var.is_none(),
310 "Multiple capture variables in named construct '[{trimmed}]'"
311 );
312 capture_var = Some(var.trim().to_string());
313 subtype_str = match subtype_str.get(..ws_idx) {
314 Some(s) => s.trim(),
315 None => subtype_str,
316 };
317 }
318 }
319 }
320 }
321
322 ensure!(
323 !name.is_empty(),
324 "Named construct in brackets must have a name: '[{trimmed}]'"
325 );
326 ensure!(
327 !subtype_str.is_empty(),
328 "Named construct in brackets cannot have an empty subtype: '[{trimmed}]'"
329 );
330 let subtype = SubtypeConstraint::parse(&name, subtype_str)?;
331
332 return Ok(SyntaxElement::with_quantifier(
333 SyntaxTerm::NamedConstruct {
334 name: name.clone(),
335 subtype: Some(subtype),
336 capture_var,
337 },
338 elem_quantifier,
339 ));
340 }
341
342 let mut tokens = Vec::new();
344 let mut current_tok = String::new();
345 let mut depth_p = 0usize;
346 let mut depth_b = 0usize;
347 for c in trimmed.chars() {
348 match c {
349 '(' => {
350 depth_p = depth_p.saturating_add(1);
351 current_tok.push(c);
352 }
353 ')' => {
354 depth_p = depth_p.saturating_sub(1);
355 current_tok.push(c);
356 }
357 '[' => {
358 depth_b = depth_b.saturating_add(1);
359 current_tok.push(c);
360 }
361 ']' => {
362 depth_b = depth_b.saturating_sub(1);
363 current_tok.push(c);
364 }
365 _ if c.is_whitespace() && depth_p == 0 && depth_b == 0 => {
366 if !current_tok.is_empty() {
367 tokens.push(current_tok.clone());
368 current_tok.clear();
369 }
370 }
371 _ => current_tok.push(c),
372 }
373 }
374 if !current_tok.is_empty() {
375 tokens.push(current_tok);
376 }
377
378 let mut name_words: Vec<&str> = Vec::new();
379 let mut capture_var = None;
380 let mut elem_quantifier = Quantifier::ExactOne;
381
382 for tok in &tokens {
383 if let Some(var) = tok.strip_prefix('$') {
384 ensure!(
385 capture_var.is_none(),
386 "Multiple capture variables in named construct '[{trimmed}]'"
387 );
388 let (clean_var, q) = if let Some(stripped) = var.strip_suffix('?') {
389 (stripped, Quantifier::Optional)
390 } else if let Some(stripped) = var.strip_suffix('*') {
391 (stripped, Quantifier::ZeroOrMore)
392 } else if let Some(stripped) = var.strip_suffix('+') {
393 (stripped, Quantifier::OneOrMore)
394 } else {
395 (var, Quantifier::ExactOne)
396 };
397 elem_quantifier = q;
398 capture_var = Some(clean_var.trim().to_string());
399 } else {
400 ensure!(
401 capture_var.is_none(),
402 "Unexpected token after capture variable in named construct '[{trimmed}]': '{tok}'"
403 );
404 name_words.push(tok.as_str());
405 }
406 }
407 let name = name_words.join(" ");
408
409 ensure!(
410 !name.is_empty(),
411 "Named construct in brackets must have a name: '[{trimmed}]'"
412 );
413
414 Ok(SyntaxElement::with_quantifier(
415 SyntaxTerm::NamedConstruct {
416 name,
417 subtype: None,
418 capture_var,
419 },
420 elem_quantifier,
421 ))
422}
423
424fn parse_pattern_expression(raw: &str) -> Result<SyntaxPattern> {
426 let trimmed = raw.trim();
427 if trimmed.is_empty() {
428 return Ok(SyntaxPattern::Sequence(Vec::new()));
429 }
430
431 let mut alt_parts = Vec::new();
433 let mut depth_paren = 0usize;
434 let mut depth_bracket = 0usize;
435 let mut current_segment = String::new();
436
437 for ch in trimmed.chars() {
438 match ch {
439 '(' => {
440 depth_paren = depth_paren.saturating_add(1);
441 current_segment.push(ch);
442 }
443 ')' => {
444 depth_paren = depth_paren.saturating_sub(1);
445 current_segment.push(ch);
446 }
447 '[' => {
448 depth_bracket = depth_bracket.saturating_add(1);
449 current_segment.push(ch);
450 }
451 ']' => {
452 depth_bracket = depth_bracket.saturating_sub(1);
453 current_segment.push(ch);
454 }
455 '|' if depth_paren == 0 && depth_bracket == 0 => {
456 alt_parts.push(current_segment.trim().to_string());
457 current_segment.clear();
458 }
459 _ => {
460 current_segment.push(ch);
461 }
462 }
463 }
464 if !current_segment.trim().is_empty() {
465 alt_parts.push(current_segment.trim().to_string());
466 }
467
468 if alt_parts.len() > 1 {
469 let mut branches = Vec::new();
470 for part in alt_parts {
471 branches.push(parse_pattern_expression(&part)?);
472 }
473 return Ok(SyntaxPattern::Alternation(branches));
474 }
475
476 let mut elements = Vec::new();
478 let chars: Vec<char> = trimmed.chars().collect();
479 let mut idx = 0usize;
480
481 while idx < chars.len() {
482 let Some(&ch) = chars.get(idx) else {
483 break;
484 };
485
486 if ch.is_whitespace() {
487 idx = idx.saturating_add(1);
488 continue;
489 }
490
491 if ch == '~' {
492 idx = idx.saturating_add(1);
493 let (quantifier, next_idx) =
494 parse_trailing_quantifier(&chars, idx)?;
495 idx = next_idx;
496 elements.push(SyntaxElement::with_quantifier(
497 SyntaxTerm::SelfChar,
498 quantifier,
499 ));
500 continue;
501 }
502
503 if ch == '(' {
504 let start = idx.saturating_add(1);
505 let mut depth = 1usize;
506 let mut end = start;
507 while end < chars.len() && depth > 0 {
508 let Some(&c) = chars.get(end) else {
509 break;
510 };
511 if c == '(' {
512 depth = depth.saturating_add(1);
513 } else if c == ')' {
514 depth = depth.saturating_sub(1);
515 }
516 if depth > 0 {
517 end = end.saturating_add(1);
518 }
519 }
520 ensure!(depth == 0, "Unclosed parenthesis in pattern: '{trimmed}'");
521
522 let Some(slice) = chars.get(start..end) else {
523 bail!(
524 "Invalid parenthesis slice bounds in pattern: '{trimmed}'"
525 );
526 };
527 let inner: String = slice.iter().collect();
528 let sub_pattern = parse_pattern_expression(&inner)?;
529 idx = end.saturating_add(1);
530
531 let (quantifier, next_idx) =
532 parse_trailing_quantifier(&chars, idx)?;
533 idx = next_idx;
534
535 elements.push(SyntaxElement::with_quantifier(
536 SyntaxTerm::Group(sub_pattern),
537 quantifier,
538 ));
539 continue;
540 }
541
542 if ch == '[' {
543 let start = idx.saturating_add(1);
544 let mut depth = 1usize;
545 let mut end = start;
546 while end < chars.len() && depth > 0 {
547 let Some(&c) = chars.get(end) else {
548 break;
549 };
550 if c == '[' {
551 depth = depth.saturating_add(1);
552 } else if c == ']' {
553 depth = depth.saturating_sub(1);
554 }
555 if depth > 0 {
556 end = end.saturating_add(1);
557 }
558 }
559 ensure!(depth == 0, "Unclosed bracket in pattern: '{trimmed}'");
560
561 let Some(slice) = chars.get(start..end) else {
562 bail!("Invalid bracket slice bounds in pattern: '{trimmed}'");
563 };
564 let inner: String = slice.iter().collect();
565 let mut element = parse_bracket_content(&inner)?;
566 idx = end.saturating_add(1);
567
568 let (quantifier, next_idx) =
569 parse_trailing_quantifier(&chars, idx)?;
570 idx = next_idx;
571 if quantifier != Quantifier::ExactOne {
572 element.quantifier = quantifier;
573 }
574
575 elements.push(element);
576 continue;
577 }
578
579 let start = idx;
581 while idx < chars.len() {
582 let Some(&c) = chars.get(idx) else {
583 break;
584 };
585 if c.is_whitespace()
586 || c == '('
587 || c == ')'
588 || c == '['
589 || c == ']'
590 || c == '{'
591 || c == '}'
592 || c == '|'
593 {
594 break;
595 }
596 idx = idx.saturating_add(1);
597 }
598
599 let Some(token_slice) = chars.get(start..idx) else {
600 bail!(
601 "Invalid token slice bounds {start}..{idx} in pattern: '{trimmed}'"
602 );
603 };
604 let token_str: String = token_slice.iter().collect();
605 let token_trim = token_str.trim();
606
607 if let Some(target) = parse_target_token(token_trim) {
608 let (quantifier, next_idx) =
609 parse_trailing_quantifier(&chars, idx)?;
610 idx = next_idx;
611 elements.push(SyntaxElement::with_quantifier(
612 SyntaxTerm::CharRef(target),
613 quantifier,
614 ));
615 continue;
616 }
617
618 bail!(
619 "Unrecognized token in syntax pattern: '{token_trim}' in '{trimmed}'"
620 );
621 }
622
623 Ok(SyntaxPattern::Sequence(elements))
624}
625
626fn parse_trailing_quantifier(
628 chars: &[char],
629 idx: usize,
630) -> Result<(Quantifier, usize)> {
631 Ok(if let Some(&q_char) = chars.get(idx) {
632 match q_char {
633 '+' => (Quantifier::OneOrMore, idx.saturating_add(1)),
634 '*' => (Quantifier::ZeroOrMore, idx.saturating_add(1)),
635 '?' => (Quantifier::Optional, idx.saturating_add(1)),
636 '{' => {
637 let start = idx.saturating_add(1);
638 let mut end = start;
639 while end < chars.len() && chars.get(end) != Some(&'}') {
640 end = end.saturating_add(1);
641 }
642 ensure!(
643 end < chars.len(),
644 "Unclosed quantifier at offset {idx}"
645 );
646 let sub = chars
647 .get(start..end)
648 .context("Invalid quantifier bounds")?;
649 let content: String = sub.iter().collect();
650 let trimmed = content.trim();
651 let quantifier = if let Some((min_s, max_s)) =
652 trimmed.split_once("..").or_else(|| trimmed.split_once(','))
653 {
654 let min = if min_s.trim().is_empty() {
655 0
656 } else {
657 min_s.trim().parse::<usize>().with_context(|| {
658 format!(
659 "Invalid minimum in quantifier '{{{content}}}'"
660 )
661 })?
662 };
663 let max = if max_s.trim().is_empty() {
664 None
665 } else {
666 Some(max_s.trim().parse::<usize>().with_context(|| {
667 format!("Invalid maximum in quantifier '{{{content}}}'")
668 })?)
669 };
670 ensure!(
671 max.is_none_or(|max| min <= max),
672 "Reversed bounds in quantifier '{{{content}}}'"
673 );
674 Quantifier::Range { min, max }
675 } else {
676 let count =
677 trimmed.parse::<usize>().with_context(|| {
678 format!(
679 "Invalid count in quantifier '{{{content}}}'"
680 )
681 })?;
682 Quantifier::Range {
683 min: count,
684 max: Some(count),
685 }
686 };
687 (quantifier, end.saturating_add(1))
688 }
689 _ => (Quantifier::ExactOne, idx),
690 }
691 } else {
692 (Quantifier::ExactOne, idx)
693 })
694}
695
696pub fn parse_dc_syntax(raw: &str) -> Result<DcSyntaxRule> {
698 let clean = raw.trim().strip_prefix(':').unwrap_or(raw.trim()).trim();
700 ensure!(!clean.is_empty(), "Empty Dc syntax declaration");
701
702 let mut pattern_str = clean.to_string();
704 let mut action_opt = None;
705
706 let mut depth_paren = 0usize;
707 let mut depth_bracket = 0usize;
708 let chars: Vec<char> = clean.chars().collect();
709
710 for (i, &ch) in chars.iter().enumerate() {
711 match ch {
712 '(' => depth_paren = depth_paren.saturating_add(1),
713 ')' => depth_paren = depth_paren.saturating_sub(1),
714 '[' => depth_bracket = depth_bracket.saturating_add(1),
715 ']' => depth_bracket = depth_bracket.saturating_sub(1),
716 ':' if depth_paren == 0 && depth_bracket == 0 => {
717 let Some(after_slice) = chars.get(i.saturating_add(1)..) else {
719 bail!(
720 "Missing action slice after colon in syntax rule: '{clean}'"
721 );
722 };
723 let after: String = after_slice.iter().collect();
724 if after.contains('(') && after.contains(')') {
725 let Some(before_slice) = chars.get(..i) else {
726 bail!(
727 "Missing pattern slice before colon in syntax rule: '{clean}'"
728 );
729 };
730 let before: String = before_slice.iter().collect();
731 pattern_str = before.trim().to_string();
732 action_opt = Some(parse_syntax_action(&after)?);
733 break;
734 }
735 }
736 _ => {}
737 }
738 }
739
740 let pattern = parse_pattern_expression(&pattern_str)?;
741
742 Ok(DcSyntaxRule {
743 pattern,
744 action: action_opt,
745 raw: raw.trim().to_string(),
746 })
747}
748
749#[must_use]
752pub fn is_extension_regex(entry: &str) -> bool {
753 let trimmed = entry.trim();
754 let trimmed = trimmed.strip_prefix("case:").map_or(trimmed, str::trim);
756 trimmed.starts_with('~') && trimmed.ends_with('~') && trimmed.len() >= 2
757}
758
759pub fn parse_extension_regex(entry: &str) -> Result<DcSyntaxRule> {
765 let raw_trimmed = entry.trim();
766 let body_trimmed = raw_trimmed
768 .strip_prefix("case:")
769 .map_or(raw_trimmed, str::trim);
770
771 let Some(inner) = body_trimmed
772 .strip_prefix('~')
773 .and_then(|s| s.strip_suffix('~'))
774 else {
775 bail!("Extension regex must be enclosed in '~...~': '{raw_trimmed}'");
776 };
777 ensure!(
778 !inner.is_empty(),
779 "Regex extension pattern '~...~' cannot be empty"
780 );
781
782 let chars: Vec<char> = inner.chars().collect();
783 let anchored_start = chars.first() == Some(&'^');
784 let start_idx = usize::from(anchored_start);
785
786 let mut end_idx = chars.len();
788 let mut anchored_end = false;
789 if end_idx > start_idx && chars.get(end_idx.saturating_sub(1)) == Some(&'$')
790 {
791 let mut backslashes = 0usize;
792 let mut scan = end_idx.saturating_sub(1);
793 while scan > start_idx
794 && chars.get(scan.saturating_sub(1)) == Some(&'\\')
795 {
796 backslashes = backslashes.saturating_add(1);
797 scan = scan.saturating_sub(1);
798 }
799 if backslashes.is_multiple_of(2) {
800 anchored_end = true;
801 end_idx = end_idx.saturating_sub(1);
802 }
803 }
804
805 let core_slice = chars
806 .get(start_idx..end_idx)
807 .context("Invalid slice bounds for regex extension body")?;
808 let core_pattern = parse_regex_alternation(core_slice)?;
809
810 let wildcard_short = crate::dc::DC_WILDCARD_PATTERN
811 .to_short()
812 .context("DC_WILDCARD_PATTERN must be a valid short Dc")?;
813 let wildcard_star = SyntaxElement::with_quantifier(
814 SyntaxTerm::CharRef(CharTarget::Dc(wildcard_short)),
815 Quantifier::ZeroOrMore,
816 );
817
818 let pattern = match core_pattern {
819 SyntaxPattern::Sequence(mut elems) => {
820 if !anchored_start {
821 elems.insert(0, wildcard_star.clone());
822 }
823 if !anchored_end {
824 elems.push(wildcard_star);
825 }
826 SyntaxPattern::Sequence(elems)
827 }
828 SyntaxPattern::Alternation(branches) => {
829 if anchored_start && anchored_end {
830 SyntaxPattern::Alternation(branches)
831 } else {
832 let mut elems = Vec::new();
833 if !anchored_start {
834 elems.push(wildcard_star.clone());
835 }
836 elems.push(SyntaxElement::exact(SyntaxTerm::Group(
837 SyntaxPattern::Alternation(branches),
838 )));
839 if !anchored_end {
840 elems.push(wildcard_star);
841 }
842 SyntaxPattern::Sequence(elems)
843 }
844 }
845 };
846
847 Ok(DcSyntaxRule {
848 pattern,
849 action: None,
850 raw: raw_trimmed.to_string(),
851 })
852}
853
854fn parse_regex_alternation(chars: &[char]) -> Result<SyntaxPattern> {
855 let mut branches: Vec<Vec<char>> = Vec::new();
856 let mut current = Vec::new();
857 let mut depth_paren = 0usize;
858 let mut in_bracket = false;
859 let mut idx = 0usize;
860
861 while idx < chars.len() {
862 let Some(&ch) = chars.get(idx) else {
863 break;
864 };
865 if ch == '\\' {
866 current.push(ch);
867 idx = idx.saturating_add(1);
868 let esc = *chars
869 .get(idx)
870 .context("Trailing backslash in regex extension pattern")?;
871 current.push(esc);
872 idx = idx.saturating_add(1);
873 continue;
874 }
875 if in_bracket {
876 if ch == ']' {
877 in_bracket = false;
878 }
879 current.push(ch);
880 idx = idx.saturating_add(1);
881 continue;
882 }
883 match ch {
884 '[' => {
885 in_bracket = true;
886 current.push(ch);
887 }
888 '(' => {
889 depth_paren = depth_paren.saturating_add(1);
890 current.push(ch);
891 }
892 ')' => {
893 ensure!(
894 depth_paren > 0,
895 "Unmatched ')' in regex extension pattern"
896 );
897 depth_paren = depth_paren.saturating_sub(1);
898 current.push(ch);
899 }
900 '|' if depth_paren == 0 => {
901 branches.push(std::mem::take(&mut current));
902 }
903 _ => {
904 current.push(ch);
905 }
906 }
907 idx = idx.saturating_add(1);
908 }
909
910 ensure!(
911 !in_bracket,
912 "Unclosed '[' character class in regex extension pattern"
913 );
914 ensure!(
915 depth_paren == 0,
916 "Unclosed '(' group in regex extension pattern"
917 );
918
919 if branches.is_empty() {
920 parse_regex_sequence(¤t)
921 } else {
922 branches.push(current);
923 let mut parsed_branches = Vec::with_capacity(branches.len());
924 for branch in branches {
925 parsed_branches.push(parse_regex_sequence(&branch)?);
926 }
927 Ok(SyntaxPattern::Alternation(parsed_branches))
928 }
929}
930
931fn parse_regex_sequence(chars: &[char]) -> Result<SyntaxPattern> {
932 let mut elements = Vec::new();
933 let mut idx = 0usize;
934 let wildcard_short = crate::dc::DC_WILDCARD_PATTERN
935 .to_short()
936 .context("DC_WILDCARD_PATTERN must be a valid short Dc")?;
937
938 while idx < chars.len() {
939 let Some(&ch) = chars.get(idx) else {
940 break;
941 };
942 let (term, next_idx) = match ch {
943 '.' => (
944 SyntaxTerm::CharRef(CharTarget::Dc(wildcard_short)),
945 idx.saturating_add(1),
946 ),
947 '\\' => {
948 let esc_idx = idx.saturating_add(1);
949 let &esc = chars
950 .get(esc_idx)
951 .context("Trailing backslash in regex extension pattern")?;
952 let cp = match esc {
953 't' => u32::from('\t'),
954 'n' => u32::from('\n'),
955 'r' => u32::from('\r'),
956 other => u32::from(other),
957 };
958 (
959 SyntaxTerm::CharRef(CharTarget::Unicode(cp)),
960 esc_idx.saturating_add(1),
961 )
962 }
963 '(' => {
964 let mut start = idx.saturating_add(1);
965 let mut depth = 1usize;
966 let mut scan = start;
967 let mut in_bracket = false;
968 while scan < chars.len() && depth > 0 {
969 let Some(&c) = chars.get(scan) else {
970 break;
971 };
972 if c == '\\' {
973 scan = scan.saturating_add(2);
974 continue;
975 }
976 if in_bracket {
977 if c == ']' {
978 in_bracket = false;
979 }
980 scan = scan.saturating_add(1);
981 continue;
982 }
983 if c == '[' {
984 in_bracket = true;
985 } else if c == '(' {
986 depth = depth.saturating_add(1);
987 } else if c == ')' {
988 depth = depth.saturating_sub(1);
989 if depth == 0 {
990 break;
991 }
992 }
993 scan = scan.saturating_add(1);
994 }
995 ensure!(
996 depth == 0,
997 "Unclosed '(' group in regex extension pattern"
998 );
999 if chars.get(start) == Some(&'?')
1001 && chars.get(start.saturating_add(1)) == Some(&':')
1002 {
1003 start = start.saturating_add(2);
1004 }
1005 let inner_slice = chars.get(start..scan).context(
1006 "Invalid group slice in regex extension pattern",
1007 )?;
1008 let inner_pattern = parse_regex_alternation(inner_slice)?;
1009 (SyntaxTerm::Group(inner_pattern), scan.saturating_add(1))
1010 }
1011 '[' => {
1012 let start = idx.saturating_add(1);
1013 let mut scan = start;
1014 while scan < chars.len() {
1015 let Some(&c) = chars.get(scan) else {
1016 break;
1017 };
1018 if c == '\\' {
1019 scan = scan.saturating_add(2);
1020 continue;
1021 }
1022 if c == ']' && scan > start {
1023 break;
1024 }
1025 scan = scan.saturating_add(1);
1026 }
1027 ensure!(
1028 scan < chars.len(),
1029 "Unclosed '[' character class in regex extension pattern"
1030 );
1031 let class_slice = chars.get(start..scan).context(
1032 "Invalid character class slice in regex extension pattern",
1033 )?;
1034 let class_term = parse_regex_char_class(class_slice)?;
1035 (class_term, scan.saturating_add(1))
1036 }
1037 '^' | '$' => {
1038 bail!(
1039 "Unescaped anchor '{ch}' is only supported at pattern boundaries"
1040 );
1041 }
1042 '*' | '+' | '?' | '{' | '}' => {
1043 bail!(
1044 "Unexpected quantifier token '{ch}' without preceding term"
1045 );
1046 }
1047 other => (
1048 SyntaxTerm::CharRef(CharTarget::Unicode(u32::from(other))),
1049 idx.saturating_add(1),
1050 ),
1051 };
1052
1053 let (quantifier, after_q) = parse_trailing_quantifier(chars, next_idx)?;
1054 idx = after_q;
1055 elements.push(SyntaxElement::with_quantifier(term, quantifier));
1056 }
1057
1058 Ok(SyntaxPattern::Sequence(elements))
1059}
1060
1061fn parse_regex_char_class(chars: &[char]) -> Result<SyntaxTerm> {
1062 let negated = chars.first() == Some(&'^');
1063 let mut idx = usize::from(negated);
1064 let mut items: Vec<(u32, Option<u32>)> = Vec::new();
1065
1066 let read_class_char =
1067 |slice: &[char], pos: usize| -> Result<(u32, usize)> {
1068 let &c = slice
1069 .get(pos)
1070 .context("Unexpected end of regex character class")?;
1071 if c == '\\' {
1072 let esc_pos = pos.saturating_add(1);
1073 let &esc = slice
1074 .get(esc_pos)
1075 .context("Trailing backslash in regex character class")?;
1076 let cp = match esc {
1077 't' => u32::from('\t'),
1078 'n' => u32::from('\n'),
1079 'r' => u32::from('\r'),
1080 other => u32::from(other),
1081 };
1082 Ok((cp, esc_pos.saturating_add(1)))
1083 } else {
1084 Ok((u32::from(c), pos.saturating_add(1)))
1085 }
1086 };
1087
1088 while idx < chars.len() {
1089 let (start_cp, next_idx) = read_class_char(chars, idx)?;
1090 if chars.get(next_idx) == Some(&'-')
1091 && next_idx.saturating_add(1) < chars.len()
1092 {
1093 let (end_cp, after_end) =
1094 read_class_char(chars, next_idx.saturating_add(1))?;
1095 ensure!(
1096 start_cp <= end_cp,
1097 "Reversed character range in regex character class"
1098 );
1099 items.push((start_cp, Some(end_cp)));
1100 idx = after_end;
1101 } else {
1102 items.push((start_cp, None));
1103 idx = next_idx;
1104 }
1105 }
1106
1107 ensure!(!items.is_empty(), "Empty regex character class '[]'");
1108
1109 if !negated && items.len() == 1 {
1110 if let Some(&(start_cp, Some(end_cp))) = items.first() {
1111 return Ok(SyntaxTerm::CharRange {
1112 start: CharTarget::Unicode(start_cp),
1113 end: CharTarget::Unicode(end_cp),
1114 });
1115 }
1116 }
1117
1118 let mut members = Vec::new();
1119 for (start_cp, end_opt) in items {
1120 if let Some(end_cp) = end_opt {
1121 for cp in start_cp..=end_cp {
1122 members.push(CharTarget::Unicode(cp));
1123 }
1124 } else {
1125 members.push(CharTarget::Unicode(start_cp));
1126 }
1127 }
1128
1129 Ok(SyntaxTerm::CharSet { negated, members })
1130}
1131
1132#[must_use]
1135pub fn format_extension_regex_pattern(
1136 pattern: &SyntaxPattern,
1137) -> Option<String> {
1138 let wildcard_short = crate::dc::DC_WILDCARD_PATTERN.to_short().ok()?;
1139 let is_wildcard_star = |elem: &SyntaxElement| -> bool {
1140 elem.quantifier == Quantifier::ZeroOrMore
1141 && elem.term == SyntaxTerm::CharRef(CharTarget::Dc(wildcard_short))
1142 };
1143
1144 let (anchored_start, anchored_end, core_slice) = match pattern {
1145 SyntaxPattern::Sequence(elems) => {
1146 if elems.is_empty() {
1147 return None;
1148 }
1149 let unanchored_start = elems.first().is_some_and(is_wildcard_star);
1150 let start = usize::from(unanchored_start);
1151 let unanchored_end = elems.len() > start
1152 && elems.last().is_some_and(is_wildcard_star);
1153 let end = if unanchored_end {
1154 elems.len().saturating_sub(1)
1155 } else {
1156 elems.len()
1157 };
1158 let slice = elems.get(start..end)?;
1159 (!unanchored_start, !unanchored_end, slice)
1160 }
1161 SyntaxPattern::Alternation(_) => {
1162 let mut body = String::from("~^");
1163 body.push_str(&format_regex_inner_pattern(
1164 pattern,
1165 wildcard_short,
1166 )?);
1167 body.push_str("$~");
1168 return Some(body);
1169 }
1170 };
1171
1172 let mut out = String::from("~");
1173 if anchored_start {
1174 out.push('^');
1175 }
1176 for elem in core_slice {
1177 out.push_str(&format_regex_element(elem, wildcard_short)?);
1178 }
1179 if anchored_end {
1180 out.push('$');
1181 }
1182 out.push('~');
1183 Some(out)
1184}
1185
1186fn format_regex_inner_pattern(
1187 pattern: &SyntaxPattern,
1188 wildcard_short: u32,
1189) -> Option<String> {
1190 match pattern {
1191 SyntaxPattern::Sequence(elems) => {
1192 let mut out = String::new();
1193 for elem in elems {
1194 out.push_str(&format_regex_element(elem, wildcard_short)?);
1195 }
1196 Some(out)
1197 }
1198 SyntaxPattern::Alternation(branches) => {
1199 let mut parts = Vec::with_capacity(branches.len());
1200 for b in branches {
1201 parts.push(format_regex_inner_pattern(b, wildcard_short)?);
1202 }
1203 Some(parts.join("|"))
1204 }
1205 }
1206}
1207
1208fn format_regex_element(
1209 elem: &SyntaxElement,
1210 wildcard_short: u32,
1211) -> Option<String> {
1212 let mut s = match &elem.term {
1213 SyntaxTerm::CharRef(CharTarget::Dc(dc)) if *dc == wildcard_short => {
1214 ".".to_string()
1215 }
1216 SyntaxTerm::CharRef(CharTarget::Unicode(cp)) => {
1217 let ch = char::from_u32(*cp)?;
1218 match ch {
1219 '\t' => "\\t".to_string(),
1220 '\n' => "\\n".to_string(),
1221 '\r' => "\\r".to_string(),
1222 '.' | '\\' | '^' | '$' | '*' | '+' | '?' | '(' | ')' | '['
1223 | ']' | '{' | '}' | '|' | '~' => format!("\\{ch}"),
1224 other => other.to_string(),
1225 }
1226 }
1227 SyntaxTerm::Group(inner) => {
1228 format!("({})", format_regex_inner_pattern(inner, wildcard_short)?)
1229 }
1230 SyntaxTerm::CharRange {
1231 start: CharTarget::Unicode(s_cp),
1232 end: CharTarget::Unicode(e_cp),
1233 } => {
1234 let s_ch = char::from_u32(*s_cp)?;
1235 let e_ch = char::from_u32(*e_cp)?;
1236 format!("[{s_ch}-{e_ch}]")
1237 }
1238 SyntaxTerm::CharSet { negated, members } => {
1239 let mut set_str = String::from("[");
1240 if *negated {
1241 set_str.push('^');
1242 }
1243 for m in members {
1244 let CharTarget::Unicode(cp) = m else {
1245 return None;
1246 };
1247 let ch = char::from_u32(*cp)?;
1248 if matches!(ch, '\\' | ']' | '^' | '-') {
1249 set_str.push('\\');
1250 }
1251 set_str.push(ch);
1252 }
1253 set_str.push(']');
1254 set_str
1255 }
1256 _ => return None,
1257 };
1258 match elem.quantifier {
1259 Quantifier::ExactOne => {}
1260 Quantifier::Optional => s.push('?'),
1261 Quantifier::ZeroOrMore => s.push('*'),
1262 Quantifier::OneOrMore => s.push('+'),
1263 Quantifier::Range { min, max } => match max {
1264 Some(m) if m == min => s.push_str(&format!("{{{min}}}")),
1265 Some(m) => s.push_str(&format!("{{{min},{m}}}")),
1266 None => s.push_str(&format!("{{{min},}}")),
1267 },
1268 }
1269 Some(s)
1270}