1mod char_set;
2mod commands;
3mod lexer;
4mod lexical;
5mod sections;
6
7use char_set::{has_case, lower_char_set, negate_expr, with_case_variants};
8use commands::{apply_retypes, command_channel, command_type};
9use lexer::{Lexer, Token, TokenKind};
10
11use super::{GrammarImportError, parse_error, unsupported_error};
12use crate::grammar::feature::{FeatureExpr, FeatureForm, FieldValue, class_expression};
13use crate::grammar::feature_runtime::lexical_kernel;
14use crate::grammar::{
15 Grammar, GrammarExpr, GrammarFormat, GrammarRule, RuleAttributes, RuleKind, UnicodeClassItem,
16};
17
18const FORMAT: GrammarFormat = GrammarFormat::Antlr;
19
20pub fn import_antlr(text: &str) -> Result<Grammar, GrammarImportError> {
36 Parser::new(Lexer::new(text).tokenize()?).parse_grammar()
37}
38
39#[derive(Clone, Debug)]
40struct Parser {
41 tokens: Vec<Token>,
42 cursor: usize,
43 pending_comments: Vec<String>,
44 case_insensitive: bool,
47 rule_case_insensitive: bool,
48 syntactic_production: bool,
49 sections: Vec<lexical::Section>,
50 section: Option<usize>,
51 mode: Option<String>,
52 lexical_facts: Vec<lexical::RuleFacts>,
53 obligations: Vec<lexical::Obligation>,
54}
55
56impl Parser {
57 const fn new(tokens: Vec<Token>) -> Self {
58 Self {
59 tokens,
60 cursor: 0,
61 pending_comments: Vec::new(),
62 case_insensitive: false,
63 rule_case_insensitive: false,
64 syntactic_production: false,
65 sections: Vec::new(),
66 section: None,
67 mode: None,
68 lexical_facts: Vec::new(),
69 obligations: Vec::new(),
70 }
71 }
72
73 fn parse_grammar(&mut self) -> Result<Grammar, GrammarImportError> {
74 let mut grammar = Grammar::new().with_source_format(FORMAT);
75 let mut rules = Vec::new();
76 while !self.is_end() {
77 self.collect_comments();
78 if self.is_end() {
79 break;
80 }
81 if self.parse_header()? || self.parse_skipped_directive()? {
82 continue;
83 }
84 rules.push(self.parse_rule()?);
85 }
86 let lexers = lexical::declarations(&self.sections, &self.lexical_facts, &rules);
87 for rule in apply_retypes(rules) {
88 grammar.add_rule(rule);
89 }
90 lexical::complete_bindings(&mut grammar, &lexers);
91 if !lexers.is_empty() {
92 grammar.set_declarations(crate::grammar::GrammarDeclarations {
93 lexers,
94 ..crate::grammar::GrammarDeclarations::default()
95 });
96 }
97
98 let Some(start) = grammar
99 .rules()
100 .iter()
101 .find(|rule| rule.kind() == RuleKind::Normal)
102 .or_else(|| grammar.rules().first())
103 .map(|rule| rule.name.clone())
104 else {
105 return Err(parse_error(FORMAT, "ANTLR grammar does not contain rules"));
106 };
107 grammar.set_start(start);
108 Ok(grammar)
109 }
110
111 fn parse_rule(&mut self) -> Result<(GrammarRule, Option<String>), GrammarImportError> {
113 let comments = std::mem::take(&mut self.pending_comments);
114 let fragment = self.try_consume_keyword("fragment");
115 let name = self.expect_ident("rule name")?;
116 self.syntactic_production =
117 !fragment && !name.chars().next().is_some_and(char::is_uppercase);
118 self.collect_comments();
120 let mut comments = comments;
121 comments.append(&mut self.pending_comments);
122 let mut notes = Vec::new();
123 self.obligations.clear();
124 if let Some(section) = self
125 .section
126 .map(|index| &self.sections[index])
127 .filter(|section| section.kind == "parser")
128 {
129 self.obligations
130 .extend(
131 section
132 .unsupported_options
133 .iter()
134 .map(|source| lexical::Obligation {
135 category: "option".to_owned(),
136 source: source.clone(),
137 }),
138 );
139 }
140 self.parse_rule_prelude(&mut notes)?;
141 self.expect_colon()?;
142
143 let alternatives = self.parse_alternatives(&mut notes)?;
144 let expr = precedence_climbing(&name, alternatives);
145 let command = if self.try_consume_arrow() {
146 Some(self.parse_lexer_command()?)
147 } else {
148 None
149 };
150 self.expect_semicolon()?;
151
152 let kind = if fragment {
153 RuleKind::Silent
154 } else if name.chars().next().is_some_and(char::is_uppercase) {
155 RuleKind::Token
156 } else {
157 RuleKind::Normal
158 };
159
160 let channel = command.as_deref().and_then(command_channel);
161 let retype = if channel.is_none() {
162 command.as_deref().and_then(command_type)
163 } else {
164 None
165 };
166 self.lexical_facts.push(lexical::RuleFacts {
167 section: self.section,
168 mode: self.mode.clone().unwrap_or_else(|| "default".to_owned()),
169 command: command.clone().unwrap_or_default(),
170 retype: retype.clone().unwrap_or_default(),
171 obligations: std::mem::take(&mut self.obligations),
172 });
173 let mut rule = GrammarRule::new(name, expr).with_kind(kind);
174 if channel.is_some() {
175 rule = rule.with_attributes(RuleAttributes {
176 channel,
177 ..RuleAttributes::default()
178 });
179 }
180 if let Some(doc) = rule_doc(comments, notes, command) {
181 rule = rule.with_doc(doc);
182 }
183 Ok((rule, retype))
184 }
185
186 fn parse_rule_prelude(&mut self, notes: &mut Vec<String>) -> Result<(), GrammarImportError> {
190 self.rule_case_insensitive = self.case_insensitive;
191 if matches!(self.peek_kind(), Some(TokenKind::CharSet(_))) {
192 return Err(unsupported_error(FORMAT, "rule arguments"));
193 }
194 while !self.check_colon() {
195 if (self.check_keyword("returns") || self.check_keyword("locals"))
196 && let Some(TokenKind::CharSet(text)) = self.peek_next_kind()
197 {
198 let note = format!(
199 "dropped {} [{text}]",
200 self.peek().map(Token::text).unwrap_or_default()
201 );
202 self.advance();
203 self.advance();
204 notes.push(note);
205 } else if self.check_keyword("throws") {
206 self.advance();
207 let mut names = vec![self.expect_ident("exception name")?];
208 while matches!(self.peek_kind(), Some(TokenKind::Comma)) {
209 self.advance();
210 names.push(self.expect_ident("exception name")?);
211 }
212 notes.push(format!("dropped throws {}", names.join(", ")));
213 } else if self.check_keyword("options")
214 && let Some(TokenKind::Action(text)) = self.peek_next_kind()
215 {
216 let options = parse_options(text);
217 self.advance();
218 self.advance();
219 for (key, value) in options {
220 if key == "caseInsensitive" {
221 self.rule_case_insensitive = value == "true";
222 } else {
223 notes.push(format!("rule option {key}={value}"));
224 }
225 }
226 } else {
227 return Err(self.expected("':' before rule body"));
228 }
229 self.skip_inline_comments();
230 }
231 Ok(())
232 }
233
234 fn parse_choice(&mut self, notes: &mut Vec<String>) -> Result<GrammarExpr, GrammarImportError> {
235 let mut alternatives = Vec::new();
236 for (expr, _) in self.parse_alternatives(notes)? {
237 push_choice_alternative(&mut alternatives, expr);
238 }
239 Ok(finish_choice(alternatives))
240 }
241
242 fn parse_alternatives(
243 &mut self,
244 notes: &mut Vec<String>,
245 ) -> Result<Vec<(GrammarExpr, &'static str)>, GrammarImportError> {
246 let mut alternatives = vec![self.parse_alternative(notes)?];
247 while self.try_consume_pipe() {
248 alternatives.push(self.parse_alternative(notes)?);
249 }
250 Ok(alternatives)
251 }
252
253 fn parse_alternative(
258 &mut self,
259 notes: &mut Vec<String>,
260 ) -> Result<(GrammarExpr, &'static str), GrammarImportError> {
261 self.skip_inline_comments();
262 let options = if matches!(self.peek_kind(), Some(TokenKind::LAngle)) {
263 self.advance();
264 self.parse_element_options()?
265 } else {
266 Vec::new()
267 };
268 let mut assoc = None;
269 for (key, value) in options {
270 if key == "assoc" {
271 assoc = Some(value);
272 } else {
273 notes.push(format!("alternative option {key}={value}"));
274 }
275 }
276 let sequence = self.parse_sequence(notes)?;
277 if matches!(self.peek_kind(), Some(TokenKind::Hash)) {
278 self.advance();
279 let label = self.expect_ident("alternative label")?;
280 notes.push(format!("alternative {label}"));
281 self.skip_inline_comments();
282 }
283 let associativity = match assoc.as_deref() {
284 None | Some("left") => "left",
285 Some("right") => "right",
286 Some(other) => {
287 return Err(unsupported_error(FORMAT, format!("associativity {other}")));
288 }
289 };
290 Ok((sequence, associativity))
291 }
292
293 fn parse_element_options(&mut self) -> Result<Vec<(String, String)>, GrammarImportError> {
294 let mut options: Vec<(String, String)> = Vec::new();
295 loop {
296 let key = self.expect_ident("element option")?;
297 let mut value = "true".to_owned();
298 if matches!(self.peek_kind(), Some(TokenKind::Equal)) {
299 self.advance();
300 value = match self.peek_kind() {
301 Some(TokenKind::Ident(text) | TokenKind::String(text)) => text.clone(),
302 _ => return Err(self.expected("element option value")),
303 };
304 self.advance();
305 }
306 options.retain(|(existing, _)| *existing != key);
307 options.push((key, value));
308 if matches!(self.peek_kind(), Some(TokenKind::Comma)) {
309 self.advance();
310 } else {
311 break;
312 }
313 }
314 if !matches!(self.peek_kind(), Some(TokenKind::RAngle)) {
315 return Err(self.expected("'>'"));
316 }
317 self.advance();
318 Ok(options)
319 }
320
321 fn parse_sequence(
322 &mut self,
323 notes: &mut Vec<String>,
324 ) -> Result<GrammarExpr, GrammarImportError> {
325 let mut items = Vec::new();
326 loop {
327 self.skip_inline_comments();
328 if self.is_sequence_end() {
329 break;
330 }
331 push_sequence_item(&mut items, self.parse_element(notes)?);
332 }
333 Ok(finish_sequence(items))
334 }
335
336 fn parse_element(
337 &mut self,
338 notes: &mut Vec<String>,
339 ) -> Result<GrammarExpr, GrammarImportError> {
340 self.skip_inline_comments();
341 if matches!(self.peek_kind(), Some(TokenKind::Action(_))) {
342 return Ok(self.parse_action(notes));
343 }
344
345 if let Some(label) = self.label_ahead() {
346 self.advance();
347 self.advance();
348 let expr = self.parse_prefixed(notes)?;
349 return Ok(GrammarExpr::capture(label, expr));
350 }
351
352 self.parse_prefixed(notes)
353 }
354
355 fn parse_prefixed(
356 &mut self,
357 notes: &mut Vec<String>,
358 ) -> Result<GrammarExpr, GrammarImportError> {
359 self.skip_inline_comments();
360 let negated = self.try_consume_tilde();
361 let atom = self.parse_atom(notes)?;
362 let operands = match &atom {
363 GrammarExpr::Choice { alternatives, .. } => alternatives.as_slice(),
364 _ => std::slice::from_ref(&atom),
365 };
366 let (kinds, values): (Vec<_>, Vec<_>) = operands
369 .iter()
370 .map(|operand| {
371 let (kind, value) = match operand {
372 GrammarExpr::Terminal(value) => ("literal", value.as_str()),
373 GrammarExpr::NonTerminal(name) => ("ref", name.as_str()),
374 GrammarExpr::Not(inner) if matches!(inner.as_ref(), GrammarExpr::AnyChar) => {
375 ("not", "any")
376 }
377 _ => ("unsupported", ""),
378 };
379 (kind.to_owned(), value.to_owned())
380 })
381 .unzip();
382 let token_negation = negated
383 && lexical_kernel::parser_token_negation(self.syntactic_production, &kinds, &values);
384 let expr = if !negated {
385 atom
386 } else if token_negation {
387 GrammarExpr::Sequence(vec![GrammarExpr::Not(Box::new(atom)), GrammarExpr::AnyChar])
388 } else {
389 negate_expr(atom)
390 };
391 self.parse_suffixes(expr)
392 }
393
394 fn parse_atom(&mut self, notes: &mut Vec<String>) -> Result<GrammarExpr, GrammarImportError> {
395 self.skip_inline_comments();
396 let Some(token) = self.peek().cloned() else {
397 return Err(self.expected("expression element"));
398 };
399
400 match token.kind {
401 TokenKind::Ident(name) => {
402 self.advance();
403 if name == "EOF" {
405 return Ok(GrammarExpr::Not(Box::new(GrammarExpr::AnyChar)));
406 }
407 Ok(GrammarExpr::NonTerminal(name))
408 }
409 TokenKind::String(value) => {
410 self.advance();
411 if self.try_consume_range() {
412 let end = self.expect_string("range end")?;
413 let start = single_char(&value, "range start", token.offset)?;
414 let end = single_char(&end, "range end", token.offset)?;
415 if start > end {
416 return Err(error_at(token.offset, "literal range start exceeds end"));
417 }
418 if self.rule_case_insensitive {
419 let items = with_case_variants(&[UnicodeClassItem::Range(start, end)]);
420 if items.len() > 1 {
421 return Ok(class_expression(false, items));
422 }
423 }
424 Ok(GrammarExpr::CharRange(start, end))
425 } else if self.rule_case_insensitive && has_case(&value) {
426 Ok(GrammarExpr::TerminalInsensitive(value))
427 } else {
428 Ok(GrammarExpr::Terminal(value))
429 }
430 }
431 TokenKind::CharSet(content) => {
432 self.advance();
433 lower_char_set(&content, token.offset, self.rule_case_insensitive)
434 }
435 TokenKind::Dot => {
436 self.advance();
437 Ok(GrammarExpr::AnyChar)
438 }
439 TokenKind::LParen => {
440 self.advance();
441 let expr = self.parse_choice(notes)?;
442 self.expect_rparen()?;
443 Ok(expr)
444 }
445 TokenKind::Action(_) => Ok(self.parse_action(notes)),
446 _ => Err(self.expected("expression element")),
447 }
448 }
449
450 fn parse_action(&mut self, notes: &mut Vec<String>) -> GrammarExpr {
451 let source = match &self.advance().kind {
452 TokenKind::Action(source) => source.clone(),
453 _ => unreachable!("the action parser is called only for an action token"),
454 };
455 let category = if self.try_consume_question() {
456 "predicate"
457 } else {
458 "action"
459 };
460 self.obligations.push(lexical::Obligation {
461 category: category.to_owned(),
462 source,
463 });
464 notes.push(format!("dropped {category}"));
465 GrammarExpr::Empty
466 }
467
468 fn parse_suffixes(&mut self, mut expr: GrammarExpr) -> Result<GrammarExpr, GrammarImportError> {
469 loop {
470 let Some(suffix) = self.consume_suffix() else {
471 return Ok(expr);
472 };
473 expr = match suffix {
474 Suffix::Optional => GrammarExpr::optional(expr),
475 Suffix::ZeroOrMore => GrammarExpr::zero_or_more(expr),
476 Suffix::OneOrMore => GrammarExpr::one_or_more(expr),
477 };
478 if self.try_consume_question() {
479 expr = GrammarExpr::capture("non_greedy", expr);
480 }
481 }
482 }
483
484 fn parse_lexer_command(&mut self) -> Result<String, GrammarImportError> {
485 let mut tokens = Vec::new();
486 while !self.is_end() && !self.check_semicolon() {
487 if matches!(self.peek_kind(), Some(TokenKind::Comment(_))) {
488 self.advance();
489 } else {
490 tokens.push(self.advance().clone());
491 }
492 }
493 if tokens.is_empty() {
494 return Err(self.expected("lexer command"));
495 }
496 Ok(format_command(&tokens))
497 }
498
499 fn skip_until_semicolon(&mut self) -> Result<(), GrammarImportError> {
500 while !self.is_end() {
501 if self.try_consume_semicolon() {
502 return Ok(());
503 }
504 self.advance();
505 }
506 Err(self.expected("';' after directive"))
507 }
508
509 fn collect_comments(&mut self) {
510 while let Some(TokenKind::Comment(comment)) = self.peek_kind() {
511 self.pending_comments.push(comment.clone());
512 self.advance();
513 }
514 }
515
516 fn skip_inline_comments(&mut self) {
517 while matches!(self.peek_kind(), Some(TokenKind::Comment(_))) {
518 self.advance();
519 }
520 }
521
522 fn label_ahead(&self) -> Option<String> {
523 let label = self.peek()?.ident()?;
524 if matches!(
525 self.tokens.get(self.cursor + 1).map(|token| &token.kind),
526 Some(TokenKind::Equal | TokenKind::PlusEqual)
527 ) {
528 Some(label.to_string())
529 } else {
530 None
531 }
532 }
533
534 fn consume_suffix(&mut self) -> Option<Suffix> {
535 match self.peek_kind() {
536 Some(TokenKind::Question) => {
537 self.advance();
538 Some(Suffix::Optional)
539 }
540 Some(TokenKind::Star) => {
541 self.advance();
542 Some(Suffix::ZeroOrMore)
543 }
544 Some(TokenKind::Plus) => {
545 self.advance();
546 Some(Suffix::OneOrMore)
547 }
548 _ => None,
549 }
550 }
551
552 fn is_sequence_end(&self) -> bool {
553 self.is_end()
554 || matches!(
555 self.peek_kind(),
556 Some(
557 TokenKind::Pipe
558 | TokenKind::Semicolon
559 | TokenKind::Arrow
560 | TokenKind::RParen
561 | TokenKind::Hash
562 )
563 )
564 }
565
566 fn expect_ident(&mut self, role: &str) -> Result<String, GrammarImportError> {
567 let Some(token) = self.peek().cloned() else {
568 return Err(self.expected(role));
569 };
570 match token.kind {
571 TokenKind::Ident(value) => {
572 self.advance();
573 Ok(value)
574 }
575 _ => Err(self.expected(role)),
576 }
577 }
578
579 fn expect_string(&mut self, role: &str) -> Result<String, GrammarImportError> {
580 let Some(token) = self.peek().cloned() else {
581 return Err(self.expected(role));
582 };
583 match token.kind {
584 TokenKind::String(value) => {
585 self.advance();
586 Ok(value)
587 }
588 _ => Err(self.expected(role)),
589 }
590 }
591
592 fn expect_colon(&mut self) -> Result<(), GrammarImportError> {
593 if self.check_colon() {
594 self.advance();
595 Ok(())
596 } else {
597 Err(self.expected("':'"))
598 }
599 }
600
601 fn expect_semicolon(&mut self) -> Result<(), GrammarImportError> {
602 if self.check_semicolon() {
603 self.advance();
604 Ok(())
605 } else {
606 Err(self.expected("';'"))
607 }
608 }
609
610 fn expect_rparen(&mut self) -> Result<(), GrammarImportError> {
611 if matches!(self.peek_kind(), Some(TokenKind::RParen)) {
612 self.advance();
613 Ok(())
614 } else {
615 Err(self.expected("')'"))
616 }
617 }
618
619 fn expected(&self, expected: &str) -> GrammarImportError {
620 let offset = self.peek().map_or(0, |token| token.offset);
621 error_at(offset, format!("expected {expected}"))
622 }
623
624 fn try_consume_keyword(&mut self, keyword: &str) -> bool {
625 if self.check_keyword(keyword) {
626 self.advance();
627 true
628 } else {
629 false
630 }
631 }
632
633 fn try_consume_arrow(&mut self) -> bool {
634 if matches!(self.peek_kind(), Some(TokenKind::Arrow)) {
635 self.advance();
636 true
637 } else {
638 false
639 }
640 }
641
642 fn try_consume_pipe(&mut self) -> bool {
643 if matches!(self.peek_kind(), Some(TokenKind::Pipe)) {
644 self.advance();
645 true
646 } else {
647 false
648 }
649 }
650
651 fn try_consume_question(&mut self) -> bool {
652 if matches!(self.peek_kind(), Some(TokenKind::Question)) {
653 self.advance();
654 true
655 } else {
656 false
657 }
658 }
659
660 fn try_consume_tilde(&mut self) -> bool {
661 if matches!(self.peek_kind(), Some(TokenKind::Tilde)) {
662 self.advance();
663 true
664 } else {
665 false
666 }
667 }
668
669 fn try_consume_range(&mut self) -> bool {
670 if matches!(self.peek_kind(), Some(TokenKind::Range)) {
671 self.advance();
672 true
673 } else {
674 false
675 }
676 }
677
678 fn try_consume_semicolon(&mut self) -> bool {
679 if self.check_semicolon() {
680 self.advance();
681 true
682 } else {
683 false
684 }
685 }
686
687 fn check_keyword(&self, keyword: &str) -> bool {
688 self.peek().is_some_and(|token| token.is_keyword(keyword))
689 }
690
691 fn check_next_keyword(&self, keyword: &str) -> bool {
692 self.tokens
693 .get(self.cursor + 1)
694 .is_some_and(|token| token.is_keyword(keyword))
695 }
696
697 fn check_any_keyword(&self, keywords: &[&str]) -> bool {
698 self.peek()
699 .and_then(Token::ident)
700 .is_some_and(|value| keywords.contains(&value))
701 }
702
703 fn check_colon(&self) -> bool {
704 matches!(self.peek_kind(), Some(TokenKind::Colon))
705 }
706
707 fn check_semicolon(&self) -> bool {
708 matches!(self.peek_kind(), Some(TokenKind::Semicolon))
709 }
710
711 const fn is_end(&self) -> bool {
712 self.cursor >= self.tokens.len()
713 }
714
715 fn peek(&self) -> Option<&Token> {
716 self.tokens.get(self.cursor)
717 }
718
719 fn peek_kind(&self) -> Option<&TokenKind> {
720 self.peek().map(|token| &token.kind)
721 }
722
723 fn peek_next_kind(&self) -> Option<&TokenKind> {
724 self.tokens.get(self.cursor + 1).map(|token| &token.kind)
725 }
726
727 fn advance(&mut self) -> &Token {
728 let token = &self.tokens[self.cursor];
729 self.cursor += 1;
730 token
731 }
732}
733
734#[derive(Clone, Copy, Debug, PartialEq, Eq)]
735enum Suffix {
736 Optional,
737 ZeroOrMore,
738 OneOrMore,
739}
740
741fn parse_options(text: &str) -> Vec<(String, String)> {
743 let pairs = text.rsplit_once(';').map_or("", |(pairs, _)| pairs);
745 pairs
746 .split(';')
747 .filter_map(|part| {
748 let (key, value) = part.split_once('=')?;
749 let key = key.trim_end();
750 let start = key
751 .rfind(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
752 .map_or(0, |index| index + 1);
753 let key = &key[start..];
754 is_identifier(key).then(|| (key.to_owned(), value.trim().to_owned()))
755 })
756 .collect()
757}
758
759fn is_identifier(text: &str) -> bool {
760 let mut chars = text.chars();
761 chars
762 .next()
763 .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
764 && chars.all(|next| next.is_ascii_alphanumeric() || next == '_')
765}
766
767fn is_channel_number(text: &str) -> bool {
769 !text.starts_with('0') && !text.is_empty() && text.chars().all(|digit| digit.is_ascii_digit())
770}
771
772fn precedence_climbing(name: &str, alternatives: Vec<(GrammarExpr, &'static str)>) -> GrammarExpr {
776 let left_recursive = alternatives
777 .iter()
778 .any(|(expr, _)| edge_ref(expr, Edge::Left) == Some(name));
779 let count = alternatives.len();
780 let mut choice = Vec::new();
781 for (index, (expr, associativity)) in alternatives.into_iter().enumerate() {
782 let climbs = left_recursive
783 && (edge_ref(&expr, Edge::Left) == Some(name)
784 || edge_ref(&expr, Edge::Right) == Some(name));
785 let expr = if climbs {
786 let level = i64::try_from(count - index).unwrap_or(i64::MAX);
787 GrammarExpr::feature(FeatureExpr::Form(FeatureForm::new(
788 "precedence",
789 vec![
790 FieldValue::Integer(level),
791 FieldValue::Word(associativity.into()),
792 FieldValue::Expression(expr),
793 ],
794 )))
795 } else {
796 expr
797 };
798 push_choice_alternative(&mut choice, expr);
799 }
800 finish_choice(choice)
801}
802
803#[derive(Clone, Copy)]
804enum Edge {
805 Left,
806 Right,
807}
808
809fn edge_ref(expr: &GrammarExpr, edge: Edge) -> Option<&str> {
810 match expr {
811 GrammarExpr::NonTerminal(name) => Some(name),
812 GrammarExpr::Capture { expr, .. } => edge_ref(expr, edge),
813 GrammarExpr::Sequence(items) => match edge {
814 Edge::Left => items.first(),
815 Edge::Right => items.last(),
816 }
817 .and_then(|item| edge_ref(item, edge)),
818 _ => None,
819 }
820}
821
822fn finish_sequence(items: Vec<GrammarExpr>) -> GrammarExpr {
823 match items.len() {
824 0 => GrammarExpr::Empty,
825 1 => items.into_iter().next().expect("one sequence item exists"),
826 _ => GrammarExpr::Sequence(items),
827 }
828}
829
830fn push_sequence_item(items: &mut Vec<GrammarExpr>, item: GrammarExpr) {
831 match item {
832 GrammarExpr::Empty => {}
833 GrammarExpr::Sequence(nested) => {
834 for item in nested {
835 push_sequence_item(items, item);
836 }
837 }
838 item => items.push(item),
839 }
840}
841
842fn finish_choice(alternatives: Vec<GrammarExpr>) -> GrammarExpr {
843 if alternatives.iter().all(|expr| expr == &GrammarExpr::Empty) {
844 return GrammarExpr::Empty;
845 }
846 match alternatives.len() {
847 0 => GrammarExpr::Empty,
848 1 => alternatives
849 .into_iter()
850 .next()
851 .expect("one alternative exists"),
852 _ => GrammarExpr::Choice {
853 ordered: false,
854 alternatives,
855 },
856 }
857}
858
859fn push_choice_alternative(alternatives: &mut Vec<GrammarExpr>, alternative: GrammarExpr) {
860 match alternative {
861 GrammarExpr::Choice {
862 ordered: false,
863 alternatives: nested,
864 } => alternatives.extend(nested),
865 alternative => alternatives.push(alternative),
866 }
867}
868
869fn single_char(value: &str, role: &str, offset: usize) -> Result<char, GrammarImportError> {
870 let mut chars = value.chars();
871 let Some(character) = chars.next() else {
872 return Err(error_at(
873 offset,
874 format!("{role} must contain one character"),
875 ));
876 };
877 if chars.next().is_some() {
878 return Err(error_at(
879 offset,
880 format!("{role} {value:?} must contain one character"),
881 ));
882 }
883 Ok(character)
884}
885
886fn rule_doc(comments: Vec<String>, notes: Vec<String>, command: Option<String>) -> Option<String> {
887 let mut parts = Vec::new();
888 parts.extend(comments.into_iter().filter(|comment| !comment.is_empty()));
889 parts.extend(notes);
890 parts.extend(command);
891 if parts.is_empty() {
892 None
893 } else {
894 Some(parts.join("; "))
895 }
896}
897
898fn format_command(tokens: &[Token]) -> String {
899 let mut output = "->".to_string();
900 for token in tokens {
901 match token.kind {
902 TokenKind::LParen => output.push('('),
903 TokenKind::RParen => output.push(')'),
904 TokenKind::Comma => output.push_str(", "),
905 _ => {
906 if output == "->" || (!output.ends_with('(') && !output.ends_with(", ")) {
907 output.push(' ');
908 }
909 output.push_str(&token.text());
910 }
911 }
912 }
913 output
914}
915
916fn error_at(offset: usize, message: impl Into<String>) -> GrammarImportError {
917 parse_error(FORMAT, format!("{} at byte {offset}", message.into()))
918}