Skip to main content

meta_language/grammar/interchange/
native.rs

1//! The native grammar listing written and read by the `meta-language grammar`
2//! commands.
3//!
4//! An optional `format TAG` line, a `start NAME` line for the start rule, then
5//! one `rule NAME = KIND EXPRESSION` line per rule in grammar order, with
6//! expressions spelled as the shared grammar parity fixtures spell them
7//! (`seq(ref(a), literal("b"))`). Mirrors the native listing of
8//! `js/src/grammar-interchange.js`.
9
10use super::super::feature::class_expression;
11use super::super::{
12    CharClassItem, FeatureExpr, Grammar, GrammarDeclarations, GrammarExpr, GrammarFormat,
13    GrammarImportError, GrammarLexer, GrammarMacro, GrammarRule, GrammarScanner, MATCHING_MODES,
14    Operation, PrecedenceEntry, RuleAttributes, RuleKind, UnicodeClassItem, settling_problem,
15};
16use super::feature_forms::{FormCodec, render_feature_form, render_operation};
17
18/// The longest repetition bound a listing may spell, in decimal digits.
19const MAX_BOUND_DIGITS: usize = 9;
20
21fn native_error(line: Option<usize>, detail: impl Into<String>) -> GrammarImportError {
22    let detail = detail.into();
23    GrammarImportError::Parse {
24        format: GrammarFormat::MetaLanguage,
25        message: line.map_or_else(|| detail.clone(), |line| format!("line {line}: {detail}")),
26    }
27}
28
29/// Renders the native grammar listing of `grammar`.
30///
31/// The listing holds the `format` and `start` lines, the feature union declarations (`matching`, `import`, `mode`,
32/// `extra`, `conflict`, `macro` and `scanner` lines, in that order), then one
33/// rule line per rule, with its parameters and its `channel(...)`,
34/// `modes(...)` and `action(...)` attributes.
35#[must_use]
36pub fn render_native_grammar(grammar: &Grammar) -> String {
37    let mut lines = Vec::new();
38    if let Some(format) = grammar.source_format() {
39        lines.push(format!("format {}", format.as_str()));
40    }
41    if let Some(start) = grammar.start_rule() {
42        lines.push(format!("start {}", render_name(&start.name)));
43    }
44    let declarations = grammar.declarations();
45    let names = |names: &[String], separator: &str| {
46        names
47            .iter()
48            .map(|name| render_name(name))
49            .collect::<Vec<_>>()
50            .join(separator)
51    };
52    let parameters = |parameters: &[String]| {
53        if parameters.is_empty() {
54            String::new()
55        } else {
56            format!("({})", names(parameters, ", "))
57        }
58    };
59    let operations = |operations: &[Operation]| {
60        operations
61            .iter()
62            .map(|operation| render_operation(operation, &LineCodec))
63            .collect::<Vec<_>>()
64            .join(", ")
65    };
66    if let Some(matching) = &declarations.matching {
67        lines.push(format!("matching {matching}"));
68    }
69    if let Some(settling) = &declarations.settling {
70        lines.push(format!("settling {}", settling.join(" ")));
71    }
72    for name in &declarations.imports {
73        lines.push(format!("import {}", render_name(name)));
74    }
75    for name in &declarations.modes {
76        lines.push(format!("mode {}", render_name(name)));
77    }
78    for extra in &declarations.extras {
79        lines.push(format!("extra {}", render_native_expression(extra)));
80    }
81    for group in &declarations.conflicts {
82        lines.push(format!("conflict {}", names(group, " ")));
83    }
84    for order in &declarations.precedences {
85        let entries = order
86            .iter()
87            .map(|entry| format!("{}({})", entry.kind(), render_name(entry.value())))
88            .collect::<Vec<_>>();
89        lines.push(format!("precedences {}", entries.join(" ")));
90    }
91    for declared in &declarations.macros {
92        lines.push(format!(
93            "macro {}{} = {}",
94            render_name(&declared.name),
95            parameters(&declared.parameters),
96            render_native_expression(&declared.expression)
97        ));
98    }
99    for scanner in &declarations.scanners {
100        lines.push(format!(
101            "scanner {} tokens({}) operations({})",
102            render_name(&scanner.name),
103            names(&scanner.tokens, ", "),
104            operations(&scanner.operations)
105        ));
106    }
107    for lexer in &declarations.lexers {
108        lines.push(format!(
109            "lexer {} = {}",
110            render_name(&lexer.name),
111            render_native_expression(&lexer.expression)
112        ));
113    }
114    for rule in grammar.rules() {
115        let attributes = &rule.attributes;
116        let mut line = format!(
117            "rule {}{} = {} {}",
118            render_name(&rule.name),
119            parameters(&attributes.parameters),
120            rule.kind().as_str(),
121            render_native_expression(rule.expr())
122        );
123        let mut attribute = |head: &str, body: String| {
124            line.push(' ');
125            line.push_str(head);
126            line.push('(');
127            line.push_str(&body);
128            line.push(')');
129        };
130        if let Some(channel) = &attributes.channel {
131            attribute("channel", render_name(channel));
132        }
133        if let Some(modes) = &attributes.modes {
134            attribute("modes", names(modes, ", "));
135        }
136        if let Some(action) = &attributes.action {
137            attribute("action", operations(action));
138        }
139        lines.push(line);
140    }
141    lines.into_iter().map(|line| line + "\n").collect()
142}
143
144/// The native listing spelling of the feature union forms.
145struct LineCodec;
146
147impl FormCodec for LineCodec {
148    fn name(&self, value: &str) -> String {
149        render_name(value)
150    }
151
152    fn text(&self, value: &str) -> String {
153        quote(value)
154    }
155
156    fn expression(&self, expr: &GrammarExpr) -> String {
157        render_native_expression(expr)
158    }
159
160    fn call(&self, head: &str, parts: Vec<String>) -> String {
161        if parts.is_empty() {
162            head.to_owned()
163        } else {
164            format!("{head}({})", parts.join(", "))
165        }
166    }
167
168    fn block(&self, word: &str, parts: Vec<String>) -> String {
169        format!("{word}({})", parts.join(", "))
170    }
171
172    fn byte_class(&self, negated: bool, items: Vec<String>) -> String {
173        format!(
174            "{}({})",
175            if negated { "notByteClass" } else { "byteClass" },
176            items.join(", ")
177        )
178    }
179}
180
181/// Renders one feature union expression with the native listing spelling.
182#[must_use]
183pub fn render_native_feature(feature: &FeatureExpr) -> String {
184    match feature {
185        FeatureExpr::UnicodeClass { negated, items } => {
186            let items = items
187                .iter()
188                .map(|item| match item {
189                    UnicodeClassItem::Char(value) => format!("char({})", quote_char(*value)),
190                    UnicodeClassItem::Range(start, end) => render_range(*start, *end),
191                    UnicodeClassItem::Category(value) => format!("category({})", quote(value)),
192                    UnicodeClassItem::Script(value) => format!("script({})", quote(value)),
193                })
194                .collect::<Vec<_>>()
195                .join(", ");
196            format!("{}({items})", if *negated { "notClass" } else { "class" })
197        }
198        FeatureExpr::Call { name, arguments } => format!(
199            "ref({}, {})",
200            render_name(name),
201            arguments
202                .iter()
203                .map(render_native_expression)
204                .collect::<Vec<_>>()
205                .join(", ")
206        ),
207        FeatureExpr::Form(_) | FeatureExpr::ByteClass { .. } => {
208            render_feature_form(feature, &LineCodec).unwrap_or_default()
209        }
210    }
211}
212
213/// Renders one expression with the native listing spelling.
214#[must_use]
215pub fn render_native_expression(expr: &GrammarExpr) -> String {
216    let list = |items: &[GrammarExpr]| {
217        items
218            .iter()
219            .map(render_native_expression)
220            .collect::<Vec<_>>()
221            .join(", ")
222    };
223    match expr {
224        GrammarExpr::Empty => "empty".to_owned(),
225        GrammarExpr::AnyChar => "any".to_owned(),
226        GrammarExpr::Terminal(value) => format!("literal({})", quote(value)),
227        GrammarExpr::TerminalInsensitive(value) => format!("literalInsensitive({})", quote(value)),
228        GrammarExpr::CharRange(start, end) => render_range(*start, *end),
229        GrammarExpr::CharClass { negated, items } => {
230            let items = items
231                .iter()
232                .map(|item| match item {
233                    CharClassItem::Range(start, end) => render_range(*start, *end),
234                    CharClassItem::Char(value) => format!("char({})", quote_char(*value)),
235                })
236                .collect::<Vec<_>>()
237                .join(", ");
238            format!("{}({items})", if *negated { "notClass" } else { "class" })
239        }
240        GrammarExpr::NonTerminal(name) => format!("ref({})", render_name(name)),
241        GrammarExpr::Choice {
242            ordered,
243            alternatives,
244        } => format!(
245            "{}({})",
246            if *ordered { "orderedChoice" } else { "choice" },
247            list(alternatives)
248        ),
249        GrammarExpr::Sequence(items) => format!("seq({})", list(items)),
250        GrammarExpr::Optional(inner) => format!("optional({})", render_native_expression(inner)),
251        GrammarExpr::ZeroOrMore(inner) => format!("repeat0({})", render_native_expression(inner)),
252        GrammarExpr::OneOrMore(inner) => format!("repeat1({})", render_native_expression(inner)),
253        GrammarExpr::And(inner) => format!("and({})", render_native_expression(inner)),
254        GrammarExpr::Not(inner) => format!("not({})", render_native_expression(inner)),
255        GrammarExpr::Repeat { expr, min, max } => format!(
256            "repeat({}, {min}, {})",
257            render_native_expression(expr),
258            max.map_or_else(|| "unbounded".to_owned(), |max| max.to_string())
259        ),
260        GrammarExpr::Capture { label, expr } => format!(
261            "capture({}, {})",
262            label.as_deref().map_or_else(|| "null".to_owned(), quote),
263            render_native_expression(expr)
264        ),
265        GrammarExpr::Feature(feature) => render_native_feature(feature),
266    }
267}
268
269fn render_range(start: char, end: char) -> String {
270    format!("range({}, {})", quote_char(start), quote_char(end))
271}
272
273pub(super) fn quote(value: &str) -> String {
274    serde_json::to_string(value).unwrap_or_default()
275}
276
277fn quote_char(value: char) -> String {
278    quote(&value.to_string())
279}
280
281/// Whether `value` ends a bare rule name.
282const fn is_name_stop(value: char) -> bool {
283    value.is_whitespace() || matches!(value, '(' | ')' | ',' | '"' | '=')
284}
285
286pub(super) fn render_name(name: &str) -> String {
287    if !name.is_empty() && !name.chars().any(is_name_stop) {
288        name.to_owned()
289    } else {
290        quote(name)
291    }
292}
293
294/// Parses a native grammar listing written by [`render_native_grammar`].
295///
296/// # Errors
297///
298/// Returns a [`GrammarImportError`] of the meta-language format naming the
299/// first line that does not parse.
300pub fn parse_native_grammar(source: &str) -> Result<Grammar, GrammarImportError> {
301    let mut rules: Vec<GrammarRule> = Vec::new();
302    let mut start: Option<(String, usize)> = None;
303    let mut source_format: Option<GrammarFormat> = None;
304    let mut declarations = GrammarDeclarations::default();
305    for (index, text) in source.split('\n').enumerate() {
306        let line = index + 1;
307        let text = text.strip_suffix('\r').unwrap_or(text);
308        let mut cursor = Cursor {
309            chars: text.chars().collect(),
310            line,
311            position: 0,
312        };
313        cursor.skip_spaces();
314        if cursor.done() || cursor.peek() == Some('#') {
315            continue;
316        }
317        let directive = cursor.word()?;
318        cursor.require_space()?;
319        match directive.as_str() {
320            "format" => {
321                if source_format.is_some() {
322                    return Err(cursor.fail("the format is given twice"));
323                }
324                let tag = cursor.word()?;
325                source_format = Some(
326                    GrammarFormat::from_tag(&tag)
327                        .ok_or_else(|| cursor.fail(format!("unknown source format {tag}")))?,
328                );
329            }
330            "start" => {
331                if start.is_some() {
332                    return Err(cursor.fail("the start rule is given twice"));
333                }
334                start = Some((cursor.name()?, line));
335            }
336            "rule" => {
337                let name = cursor.name()?;
338                let parameters = cursor.parameters()?;
339                cursor.skip_spaces();
340                cursor.expect('=')?;
341                cursor.skip_spaces();
342                let kind = cursor.word()?;
343                let kind = RuleKind::from_tag(&kind)
344                    .ok_or_else(|| cursor.fail(format!("unknown rule kind {kind}")))?;
345                cursor.require_space()?;
346                let expr = cursor.expression()?;
347                if rules.iter().any(|rule| rule.name == name) {
348                    return Err(cursor.fail(format!("rule {name} is defined twice")));
349                }
350                let mut attributes = cursor.rule_attributes()?;
351                attributes.parameters = parameters;
352                rules.push(
353                    GrammarRule::new(name, expr)
354                        .with_kind(kind)
355                        .with_attributes(attributes),
356                );
357            }
358            "matching" => {
359                if declarations.matching.is_some() {
360                    return Err(cursor.fail("the matching is given twice"));
361                }
362                let matching = cursor.word()?;
363                if !MATCHING_MODES.contains(&matching.as_str()) {
364                    return Err(cursor.fail(format!("unknown matching {matching}")));
365                }
366                declarations.matching = Some(matching);
367            }
368            "settling" => {
369                if declarations.settling.is_some() {
370                    return Err(cursor.fail("the settling is given twice"));
371                }
372                let mut steps = Vec::new();
373                while !cursor.done() {
374                    steps.push(cursor.word()?);
375                    cursor.skip_spaces();
376                }
377                if let Some(problem) = settling_problem(&steps) {
378                    return Err(cursor.fail(problem));
379                }
380                declarations.settling = Some(steps);
381            }
382            "import" => declarations.imports.push(cursor.name()?),
383            "mode" => declarations.modes.push(cursor.name()?),
384            "extra" => declarations.extras.push(cursor.expression()?),
385            "conflict" => {
386                let mut group = vec![cursor.name()?];
387                cursor.skip_spaces();
388                while !cursor.done() {
389                    group.push(cursor.name()?);
390                    cursor.skip_spaces();
391                }
392                declarations.conflicts.push(group);
393            }
394            "precedences" => {
395                let mut order = Vec::new();
396                while !cursor.done() {
397                    let kind = cursor.word()?;
398                    let mut values = cursor.list(Cursor::name)?;
399                    let Some(entry) = (values.len() == 1)
400                        .then(|| values.pop())
401                        .flatten()
402                        .and_then(|value| PrecedenceEntry::from_kind(&kind, value))
403                    else {
404                        return Err(cursor.fail(if kind == "name" || kind == "rule" {
405                            format!("{kind}(...) names one entry")
406                        } else {
407                            format!("a precedence entry is name(NAME) or rule(NAME), not {kind}")
408                        }));
409                    };
410                    order.push(entry);
411                    cursor.skip_spaces();
412                }
413                if order.len() < 2 {
414                    return Err(cursor.fail("precedences orders at least two entries"));
415                }
416                declarations.precedences.push(order);
417            }
418            "macro" => {
419                let name = cursor.name()?;
420                let parameters = cursor.parameters()?;
421                cursor.skip_spaces();
422                cursor.expect('=')?;
423                cursor.skip_spaces();
424                let expression = cursor.expression()?;
425                declarations.macros.push(GrammarMacro {
426                    name,
427                    parameters,
428                    expression,
429                });
430            }
431            "lexer" => {
432                let name = cursor.name()?;
433                cursor.skip_spaces();
434                cursor.expect('=')?;
435                cursor.skip_spaces();
436                let expression = cursor.expression()?;
437                declarations.lexers.push(GrammarLexer { name, expression });
438            }
439            "scanner" => {
440                let name = cursor.name()?;
441                cursor.require_space()?;
442                if cursor.word()? != "tokens" {
443                    return Err(cursor.fail("expected tokens(...)"));
444                }
445                let tokens = cursor.list(Cursor::name)?;
446                cursor.require_space()?;
447                if cursor.word()? != "operations" {
448                    return Err(cursor.fail("expected operations(...)"));
449                }
450                let operations = cursor.statements()?;
451                declarations.scanners.push(GrammarScanner {
452                    name,
453                    tokens,
454                    operations,
455                });
456            }
457            other => return Err(cursor.fail(format!("unknown directive {other}"))),
458        }
459        cursor.skip_spaces();
460        if !cursor.done() {
461            return Err(cursor.fail("unexpected text at the end of the line"));
462        }
463    }
464    let Some(first) = rules.first().map(|rule| rule.name.clone()) else {
465        return Err(native_error(None, "the listing defines no rules"));
466    };
467    let start = match start {
468        Some((name, line)) => {
469            if !rules.iter().any(|rule| rule.name == name) {
470                return Err(native_error(
471                    Some(line),
472                    format!("start rule {name} is not defined"),
473                ));
474            }
475            name
476        }
477        None => first,
478    };
479    let mut grammar = Grammar::new();
480    for rule in rules {
481        grammar.add_rule(rule);
482    }
483    grammar.set_start(start);
484    if let Some(format) = source_format {
485        grammar.set_source_format(format);
486    }
487    grammar.set_declarations(declarations);
488    Ok(grammar)
489}
490
491/// Parses one expression written by [`render_native_expression`].
492///
493/// # Errors
494///
495/// Returns a [`GrammarImportError`] of the meta-language format when the text
496/// is not exactly one expression.
497pub fn parse_native_expression(text: &str) -> Result<GrammarExpr, GrammarImportError> {
498    let mut cursor = Cursor {
499        chars: text.chars().collect(),
500        line: 1,
501        position: 0,
502    };
503    cursor.skip_spaces();
504    let expr = cursor.expression()?;
505    cursor.skip_spaces();
506    if cursor.done() {
507        Ok(expr)
508    } else {
509        Err(cursor.fail("unexpected text after the expression"))
510    }
511}
512
513pub(super) struct Cursor {
514    pub(super) chars: Vec<char>,
515    pub(super) line: usize,
516    pub(super) position: usize,
517}
518
519impl Cursor {
520    pub(super) fn fail(&self, detail: impl Into<String>) -> GrammarImportError {
521        native_error(Some(self.line), detail)
522    }
523
524    pub(super) const fn done(&self) -> bool {
525        self.position >= self.chars.len()
526    }
527
528    pub(super) fn peek(&self) -> Option<char> {
529        self.chars.get(self.position).copied()
530    }
531
532    pub(super) fn text(&self, begin: usize) -> String {
533        self.chars[begin..self.position].iter().collect()
534    }
535
536    pub(super) fn skip_spaces(&mut self) {
537        while matches!(self.peek(), Some(' ' | '\t')) {
538            self.position += 1;
539        }
540    }
541
542    pub(super) fn require_space(&mut self) -> Result<(), GrammarImportError> {
543        if !matches!(self.peek(), Some(' ' | '\t')) {
544            return Err(self.fail("expected a space"));
545        }
546        self.skip_spaces();
547        Ok(())
548    }
549
550    pub(super) fn expect(&mut self, expected: char) -> Result<(), GrammarImportError> {
551        if self.peek() != Some(expected) {
552            return Err(self.fail(format!("expected {expected}")));
553        }
554        self.position += 1;
555        Ok(())
556    }
557
558    pub(super) fn word(&mut self) -> Result<String, GrammarImportError> {
559        let begin = self.position;
560        while self
561            .peek()
562            .is_some_and(|value| value.is_ascii_alphanumeric() || matches!(value, '_' | '-'))
563        {
564            self.position += 1;
565        }
566        if begin == self.position {
567            return Err(self.fail("expected a word"));
568        }
569        Ok(self.text(begin))
570    }
571
572    pub(super) fn name(&mut self) -> Result<String, GrammarImportError> {
573        if self.peek() == Some('"') {
574            return self.string();
575        }
576        let begin = self.position;
577        while self.peek().is_some_and(|value| !is_name_stop(value)) {
578            self.position += 1;
579        }
580        if begin == self.position {
581            return Err(self.fail("expected a name"));
582        }
583        Ok(self.text(begin))
584    }
585
586    pub(super) fn string(&mut self) -> Result<String, GrammarImportError> {
587        if self.peek() != Some('"') {
588            return Err(self.fail("expected a string"));
589        }
590        let begin = self.position;
591        self.position += 1;
592        while let Some(value) = self.peek() {
593            if value == '"' {
594                break;
595            }
596            self.position += if value == '\\' { 2 } else { 1 };
597        }
598        if self.done() {
599            return Err(self.fail("unterminated string"));
600        }
601        self.position += 1;
602        serde_json::from_str::<String>(&self.text(begin)).map_err(|_| self.fail("invalid string"))
603    }
604
605    pub(super) fn character(&mut self) -> Result<char, GrammarImportError> {
606        let value = self.string()?;
607        let mut chars = value.chars();
608        match (chars.next(), chars.next()) {
609            (Some(value), None) => Ok(value),
610            _ => Err(self.fail("a character must be one code point")),
611        }
612    }
613
614    fn bound(&mut self, allow_unbounded: bool) -> Result<Option<usize>, GrammarImportError> {
615        if allow_unbounded && self.peek() == Some('u') {
616            if self.word()? != "unbounded" {
617                return Err(self.fail("expected a repetition bound"));
618            }
619            return Ok(None);
620        }
621        let begin = self.position;
622        while self.peek().is_some_and(|value| value.is_ascii_digit()) {
623            self.position += 1;
624        }
625        let digits = self.text(begin);
626        if digits.is_empty() {
627            return Err(self.fail("expected a repetition bound"));
628        }
629        if digits.len() > MAX_BOUND_DIGITS {
630            return Err(self.fail(format!("repetition bound {digits} is too large")));
631        }
632        digits
633            .parse()
634            .map(Some)
635            .map_err(|_| self.fail("expected a repetition bound"))
636    }
637
638    pub(super) fn separator(&mut self) -> Result<(), GrammarImportError> {
639        self.skip_spaces();
640        self.expect(',')?;
641        self.skip_spaces();
642        Ok(())
643    }
644
645    pub(super) fn open(&mut self) -> Result<(), GrammarImportError> {
646        self.expect('(')?;
647        self.skip_spaces();
648        Ok(())
649    }
650
651    pub(super) fn close(&mut self) -> Result<(), GrammarImportError> {
652        self.skip_spaces();
653        self.expect(')')
654    }
655
656    pub(super) fn list<T>(
657        &mut self,
658        item: fn(&mut Self) -> Result<T, GrammarImportError>,
659    ) -> Result<Vec<T>, GrammarImportError> {
660        self.open()?;
661        let mut items = Vec::new();
662        self.skip_spaces();
663        while self.peek() != Some(')') {
664            if !items.is_empty() {
665                self.separator()?;
666            }
667            items.push(item(self)?);
668            self.skip_spaces();
669            if self.done() {
670                return Err(self.fail("expected )"));
671            }
672        }
673        self.close()?;
674        Ok(items)
675    }
676
677    fn inner(&mut self) -> Result<Box<GrammarExpr>, GrammarImportError> {
678        self.open()?;
679        let expr = self.expression()?;
680        self.close()?;
681        Ok(Box::new(expr))
682    }
683
684    pub(super) fn expression(&mut self) -> Result<GrammarExpr, GrammarImportError> {
685        let kind = self.word()?;
686        Ok(match kind.as_str() {
687            "empty" => GrammarExpr::Empty,
688            "any" => GrammarExpr::AnyChar,
689            "literal" | "literalInsensitive" => {
690                self.open()?;
691                let value = self.string()?;
692                self.close()?;
693                if kind == "literal" {
694                    GrammarExpr::Terminal(value)
695                } else {
696                    GrammarExpr::TerminalInsensitive(value)
697                }
698            }
699            "range" => {
700                self.open()?;
701                let start = self.character()?;
702                self.separator()?;
703                let end = self.character()?;
704                self.close()?;
705                GrammarExpr::CharRange(start, end)
706            }
707            "class" | "notClass" => {
708                let negated = kind == "notClass";
709                class_expression(negated, self.list(Self::class_item)?)
710            }
711            "ref" => {
712                self.open()?;
713                let name = self.name()?;
714                let mut arguments = Vec::new();
715                self.skip_spaces();
716                while self.peek() == Some(',') {
717                    self.separator()?;
718                    arguments.push(self.expression()?);
719                    self.skip_spaces();
720                }
721                self.close()?;
722                if arguments.is_empty() {
723                    GrammarExpr::NonTerminal(name)
724                } else {
725                    GrammarExpr::feature(FeatureExpr::Call { name, arguments })
726                }
727            }
728            "choice" | "orderedChoice" => GrammarExpr::Choice {
729                ordered: kind == "orderedChoice",
730                alternatives: self.list(Self::expression)?,
731            },
732            "seq" => GrammarExpr::Sequence(self.list(Self::expression)?),
733            "repeat" => {
734                self.open()?;
735                let expr = Box::new(self.expression()?);
736                self.separator()?;
737                let min = self.bound(false)?.unwrap_or_default();
738                self.separator()?;
739                let max = self.bound(true)?;
740                self.close()?;
741                if max.is_some_and(|max| max < min) {
742                    let max = max.unwrap_or_default();
743                    return Err(self.fail(format!("repetition bounds {min}, {max} are reversed")));
744                }
745                GrammarExpr::Repeat { expr, min, max }
746            }
747            "capture" => {
748                self.open()?;
749                let label = if self.peek() == Some('"') {
750                    Some(self.string()?)
751                } else if self.word()? == "null" {
752                    None
753                } else {
754                    return Err(self.fail("expected a capture label or null"));
755                };
756                self.separator()?;
757                let expr = Box::new(self.expression()?);
758                self.close()?;
759                GrammarExpr::Capture { label, expr }
760            }
761            other => {
762                if let Some(feature) = self.feature(other)? {
763                    return Ok(feature);
764                }
765                match other {
766                    "optional" => GrammarExpr::Optional(self.inner()?),
767                    "repeat0" => GrammarExpr::ZeroOrMore(self.inner()?),
768                    "repeat1" => GrammarExpr::OneOrMore(self.inner()?),
769                    "and" => GrammarExpr::And(self.inner()?),
770                    "not" => GrammarExpr::Not(self.inner()?),
771                    _ => return Err(self.fail(format!("unknown expression {other}"))),
772                }
773            }
774        })
775    }
776
777    fn class_item(&mut self) -> Result<UnicodeClassItem, GrammarImportError> {
778        let kind = self.word()?;
779        self.open()?;
780        let item = match kind.as_str() {
781            "char" => UnicodeClassItem::Char(self.character()?),
782            "range" => {
783                let start = self.character()?;
784                self.separator()?;
785                UnicodeClassItem::Range(start, self.character()?)
786            }
787            "category" => UnicodeClassItem::Category(self.string()?),
788            "script" => UnicodeClassItem::Script(self.string()?),
789            other => return Err(self.fail(format!("unknown class item {other}"))),
790        };
791        self.close()?;
792        Ok(item)
793    }
794
795    /// The optional `(NAME, ...)` parameter list after a rule or macro name.
796    fn parameters(&mut self) -> Result<Vec<String>, GrammarImportError> {
797        if self.peek() != Some('(') {
798            return Ok(Vec::new());
799        }
800        let names = self.list(Self::name)?;
801        if names.is_empty() {
802            return Err(self.fail("a parameter list names at least one parameter"));
803        }
804        let mut seen = std::collections::BTreeSet::new();
805        if !names.iter().all(|name| seen.insert(name)) {
806            return Err(self.fail("a parameter is named twice"));
807        }
808        Ok(names)
809    }
810
811    /// The `channel(NAME)`, `modes(MODE, ...)` and `action(OPERATION, ...)`
812    /// attributes after a rule expression; other text is trailing text.
813    fn rule_attributes(&mut self) -> Result<RuleAttributes, GrammarImportError> {
814        const ORDER: [&str; 3] = ["channel", "modes", "action"];
815        let mut attributes = RuleAttributes::default();
816        let mut next = 0;
817        self.skip_spaces();
818        while !self.done() {
819            let begin = self.position;
820            while self.peek().is_some_and(|value| value.is_ascii_alphabetic()) {
821                self.position += 1;
822            }
823            let attribute = self.text(begin);
824            let position = ORDER.iter().position(|word| *word == attribute);
825            let Some(position) = position.filter(|_| self.peek() == Some('(')) else {
826                self.position = begin;
827                return Err(self.fail("unexpected text at the end of the line"));
828            };
829            if position < next {
830                return Err(self.fail(format!("rule attribute {attribute} is out of order")));
831            }
832            next = position + 1;
833            match position {
834                0 => {
835                    self.open()?;
836                    attributes.channel = Some(self.name()?);
837                    self.close()?;
838                }
839                1 => attributes.modes = Some(self.list(Self::name)?),
840                _ => attributes.action = Some(self.statements()?),
841            }
842            self.skip_spaces();
843        }
844        Ok(attributes)
845    }
846}