Skip to main content

meta_language/grammar/
feature.rs

1//! The grammar feature union forms (`docs/grammar/feature-union.md`).
2//!
3//! One table describes every expression kind, every operation of the scanner
4//! and action language and every grammar declaration the feature union adds,
5//! and the native listing, links and JSON codecs read and write them from
6//! that table, so the serializations stay in step with each other and with
7//! `js/src/grammar-feature-forms.js`.
8
9use std::collections::BTreeSet;
10
11use super::{CharClassItem, Grammar, GrammarExpr};
12use crate::translation::grammar_selection_included_range_rules::{
13    accept_grammar_selection_included_range_candidate,
14    accept_grammar_selection_included_range_source_range,
15    read_grammar_selection_included_range_field_order,
16};
17use serde_json::Value;
18
19/// The type of one field of a feature form or an operation.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum FieldType {
22    /// One word out of a fixed list.
23    Choice(&'static [&'static str]),
24    /// A signed integer of at most 15 digits.
25    Integer,
26    /// A name: a rule, mode, token, stack, variable, field or attribute.
27    Name,
28    /// A text value.
29    Text,
30    /// One grammar expression.
31    Expression,
32    /// The remaining grammar expressions.
33    Expressions,
34    /// One condition operation.
35    Condition,
36    /// One value operation.
37    Value,
38    /// The remaining condition operations.
39    Conditions,
40    /// A statement list written as `WORD(...)`; the flag makes it optional.
41    Block(&'static str, bool),
42}
43
44/// The fields of one form, as `(key, type)` pairs in listing order.
45pub type FormFields = &'static [(&'static str, FieldType)];
46
47/// The expression kinds the feature union adds, with their fields in listing order.
48pub const FEATURE_EXPRESSION_FORMS: &[(&str, FormFields)] = &[
49    (
50        "precedence",
51        &[
52            ("level", FieldType::Integer),
53            (
54                "associativity",
55                FieldType::Choice(&["left", "right", "none"]),
56            ),
57            ("item", FieldType::Expression),
58        ],
59    ),
60    (
61        "namedPrecedence",
62        &[
63            ("name", FieldType::Name),
64            (
65                "associativity",
66                FieldType::Choice(&["left", "right", "none"]),
67            ),
68            ("item", FieldType::Expression),
69        ],
70    ),
71    (
72        "dynamicPrecedence",
73        &[
74            ("level", FieldType::Integer),
75            ("item", FieldType::Expression),
76        ],
77    ),
78    (
79        "lexicalPrecedence",
80        &[
81            ("level", FieldType::Integer),
82            ("item", FieldType::Expression),
83        ],
84    ),
85    ("longest", &[("items", FieldType::Expressions)]),
86    ("token", &[("item", FieldType::Expression)]),
87    ("immediateToken", &[("item", FieldType::Expression)]),
88    (
89        "alias",
90        &[("name", FieldType::Name), ("item", FieldType::Expression)],
91    ),
92    ("parameter", &[("name", FieldType::Name)]),
93    (
94        "predicate",
95        &[
96            ("item", FieldType::Expression),
97            ("condition", FieldType::Condition),
98        ],
99    ),
100    (
101        "recover",
102        &[
103            ("item", FieldType::Expression),
104            ("synchronize", FieldType::Expression),
105        ],
106    ),
107    ("missing", &[("item", FieldType::Expression)]),
108    (
109        "embed",
110        &[
111            ("language", FieldType::Name),
112            ("item", FieldType::Expression),
113        ],
114    ),
115    (
116        "expand",
117        &[
118            ("name", FieldType::Name),
119            ("arguments", FieldType::Expressions),
120        ],
121    ),
122];
123
124/// Whether an operation is a statement, a condition or a value.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum OperationCategory {
127    /// An operation run for its effect.
128    Statement,
129    /// An operation that holds or does not.
130    Condition,
131    /// An operation that computes an integer or a text.
132    Value,
133}
134
135impl OperationCategory {
136    /// The category's word in error messages.
137    #[must_use]
138    pub const fn as_str(self) -> &'static str {
139        match self {
140            Self::Statement => "statement",
141            Self::Condition => "condition",
142            Self::Value => "value",
143        }
144    }
145}
146
147const TWO_VALUES: FormFields = &[("left", FieldType::Value), ("right", FieldType::Value)];
148const STATEMENT: OperationCategory = OperationCategory::Statement;
149const CONDITION: OperationCategory = OperationCategory::Condition;
150const VALUE: OperationCategory = OperationCategory::Value;
151
152/// The operation language of external scanners, semantic actions and
153/// predicates, with each operation's category and fields in listing order.
154pub const OPERATION_FORMS: &[(&str, OperationCategory, FormFields)] = &[
155    ("advance", STATEMENT, &[]),
156    ("consume", STATEMENT, &[("item", FieldType::Expression)]),
157    ("skip", STATEMENT, &[("item", FieldType::Expression)]),
158    ("mark", STATEMENT, &[]),
159    ("emit", STATEMENT, &[("token", FieldType::Name)]),
160    ("fail", STATEMENT, &[]),
161    (
162        "if",
163        STATEMENT,
164        &[
165            ("condition", FieldType::Condition),
166            ("consequent", FieldType::Block("then", false)),
167            ("alternative", FieldType::Block("else", true)),
168        ],
169    ),
170    (
171        "while",
172        STATEMENT,
173        &[
174            ("condition", FieldType::Condition),
175            ("body", FieldType::Block("do", false)),
176        ],
177    ),
178    (
179        "push",
180        STATEMENT,
181        &[("stack", FieldType::Name), ("value", FieldType::Value)],
182    ),
183    ("pop", STATEMENT, &[("stack", FieldType::Name)]),
184    (
185        "set",
186        STATEMENT,
187        &[("variable", FieldType::Name), ("value", FieldType::Value)],
188    ),
189    ("pushMode", STATEMENT, &[("mode", FieldType::Name)]),
190    ("popMode", STATEMENT, &[]),
191    ("setMode", STATEMENT, &[("mode", FieldType::Name)]),
192    (
193        "setAttribute",
194        STATEMENT,
195        &[("attribute", FieldType::Name), ("value", FieldType::Value)],
196    ),
197    ("buildNode", STATEMENT, &[("kind", FieldType::Name)]),
198    ("valid", CONDITION, &[("token", FieldType::Name)]),
199    ("expected", CONDITION, &[("item", FieldType::Expression)]),
200    ("next", CONDITION, &[("item", FieldType::Expression)]),
201    ("atEnd", CONDITION, &[]),
202    ("equal", CONDITION, TWO_VALUES),
203    ("less", CONDITION, TWO_VALUES),
204    ("greater", CONDITION, TWO_VALUES),
205    ("all", CONDITION, &[("conditions", FieldType::Conditions)]),
206    ("some", CONDITION, &[("conditions", FieldType::Conditions)]),
207    ("not", CONDITION, &[("condition", FieldType::Condition)]),
208    ("integer", VALUE, &[("value", FieldType::Integer)]),
209    ("text", VALUE, &[("value", FieldType::Text)]),
210    ("variable", VALUE, &[("name", FieldType::Name)]),
211    ("top", VALUE, &[("stack", FieldType::Name)]),
212    ("depth", VALUE, &[("stack", FieldType::Name)]),
213    ("column", VALUE, &[]),
214    ("matched", VALUE, &[]),
215    ("mode", VALUE, &[]),
216    (
217        "attribute",
218        VALUE,
219        &[("field", FieldType::Name), ("attribute", FieldType::Name)],
220    ),
221    (
222        "sumOf",
223        VALUE,
224        &[("field", FieldType::Name), ("attribute", FieldType::Name)],
225    ),
226    ("fieldText", VALUE, &[("field", FieldType::Name)]),
227    ("length", VALUE, &[("value", FieldType::Value)]),
228    ("uppercase", VALUE, &[("value", FieldType::Value)]),
229    ("number", VALUE, &[("value", FieldType::Value)]),
230    ("add", VALUE, TWO_VALUES),
231    ("subtract", VALUE, TWO_VALUES),
232    ("multiply", VALUE, TWO_VALUES),
233];
234
235/// The ways a grammar may match: generalized (every alternative), PEG (first
236/// and greedy) or longest (generalized, ties going to the longer token).
237pub const MATCHING_MODES: &[&str] = &["generalized", "peg", "longest"];
238
239/// The steps that settle two parses of one text that end alike, as a
240/// grammar's `(settling STEP ...)` declares them.
241///
242/// In order (the lower repair cost always decides first): `tokens`, the tokens a lexer prefers (higher
243/// lexical precedence, longer, a literal over a pattern, earlier), with the
244/// lexing that goes with it (keywords, separators, immediate tokens);
245/// `precedence`, the shift or reduction an LR parser keeps by precedence and
246/// associativity, forking where a declared conflict asks; `dynamic`, the
247/// higher dynamic precedence. The last step settles a tie: `first` keeps the
248/// parse reached first, `ambiguity` keeps it and reports the ambiguity.
249pub const SETTLING_STEPS: &[&str] = &["tokens", "precedence", "dynamic", "first", "ambiguity"];
250
251/// The settling of a grammar that declares none, by its matching.
252#[must_use]
253pub fn default_settling(matching: &str) -> &'static [&'static str] {
254    match matching {
255        "peg" => &["first"],
256        "longest" => &["tokens", "precedence", "dynamic", "ambiguity"],
257        _ => &["dynamic", "ambiguity"],
258    }
259}
260
261/// Why `steps` is no settling, or `None`: every step is known and given
262/// once, and exactly the last one settles a tie.
263#[must_use]
264pub fn settling_problem<S: AsRef<str>>(steps: &[S]) -> Option<String> {
265    if steps.is_empty() {
266        return Some("the settling names no step".to_owned());
267    }
268    for (index, step) in steps.iter().enumerate() {
269        let step = step.as_ref();
270        if !SETTLING_STEPS.contains(&step) {
271            return Some(format!("unknown settling step {step}"));
272        }
273        if steps.iter().position(|other| other.as_ref() == step) != Some(index) {
274            return Some(format!("the settling step {step} is given twice"));
275        }
276        let tie = step == "first" || step == "ambiguity";
277        if tie != (index == steps.len() - 1) {
278            return Some("the settling ends with exactly one of first and ambiguity".to_owned());
279        }
280    }
281    None
282}
283
284/// The longest integer a form may spell, in decimal digits.
285pub const MAX_INTEGER_DIGITS: usize = 15;
286
287/// The fields of the feature expression form `head`, when it is one.
288#[must_use]
289pub fn feature_expression_fields(head: &str) -> Option<FormFields> {
290    FEATURE_EXPRESSION_FORMS
291        .iter()
292        .chain(super::lexical_forms::LEXICAL_EXPRESSION_FORMS.iter())
293        .chain(super::selection_forms::SELECTION_EXPRESSION_FORMS.iter())
294        .find(|(name, _)| *name == head)
295        .map(|(_, fields)| *fields)
296}
297
298/// The category and fields of the operation `head`, when it is one.
299#[must_use]
300pub fn operation_form(head: &str) -> Option<(OperationCategory, FormFields)> {
301    OPERATION_FORMS
302        .iter()
303        .find(|(name, _, _)| *name == head)
304        .map(|(_, category, fields)| (*category, *fields))
305}
306
307/// Checks the text of an integer field: an optional `-` and at most 15 digits.
308///
309/// # Errors
310///
311/// Returns the detail of the failure.
312pub fn check_integer(text: &str) -> Result<i64, String> {
313    let digits = text.strip_prefix('-').unwrap_or(text);
314    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
315        return Err(format!("expected an integer, not {text}"));
316    }
317    if digits.len() > MAX_INTEGER_DIGITS {
318        return Err(format!("integer {text} is too large"));
319    }
320    text.parse()
321        .map_err(|_| format!("expected an integer, not {text}"))
322}
323
324/// The value of one field of a feature form or an operation.
325#[derive(Clone, Debug, PartialEq, Eq)]
326pub enum FieldValue {
327    /// One word of a [`FieldType::Choice`].
328    Word(String),
329    /// An integer.
330    Integer(i64),
331    /// A name.
332    Name(String),
333    /// A text.
334    Text(String),
335    /// One expression.
336    Expression(GrammarExpr),
337    /// A list of expressions.
338    Expressions(Vec<GrammarExpr>),
339    /// One condition or value.
340    Operation(FeatureForm),
341    /// A list of conditions.
342    Operations(Vec<FeatureForm>),
343    /// A statement block; `None` for an absent optional block.
344    Block(Option<Vec<FeatureForm>>),
345}
346
347/// One feature expression form or one operation: a head word and its field
348/// values, in the order of [`FEATURE_EXPRESSION_FORMS`] or [`OPERATION_FORMS`].
349#[derive(Clone, Debug, PartialEq, Eq)]
350pub struct FeatureForm {
351    /// The form's head word, such as `precedence` or `pushMode`.
352    pub head: String,
353    /// The field values in table order.
354    pub fields: Vec<FieldValue>,
355}
356
357/// One operation of the scanner and action language.
358pub type Operation = FeatureForm;
359
360impl FeatureForm {
361    /// Builds a form from its head and field values.
362    #[must_use]
363    pub fn new(head: impl Into<String>, fields: Vec<FieldValue>) -> Self {
364        Self {
365            head: head.into(),
366            fields,
367        }
368    }
369
370    /// The table fields of this form, as an expression form or an operation.
371    #[must_use]
372    pub fn spec(&self) -> FormFields {
373        feature_expression_fields(&self.head)
374            .or_else(|| operation_form(&self.head).map(|(_, fields)| fields))
375            .unwrap_or(&[])
376    }
377
378    /// The value of the field `key`.
379    #[must_use]
380    pub fn field(&self, key: &str) -> Option<&FieldValue> {
381        let index = self.spec().iter().position(|(name, _)| *name == key)?;
382        self.fields.get(index)
383    }
384
385    /// The expression of the field `key`.
386    #[must_use]
387    pub fn expression(&self, key: &str) -> Option<&GrammarExpr> {
388        match self.field(key)? {
389            FieldValue::Expression(expr) => Some(expr),
390            _ => None,
391        }
392    }
393
394    /// The expression list of the field `key`.
395    #[must_use]
396    pub fn expressions(&self, key: &str) -> &[GrammarExpr] {
397        match self.field(key) {
398            Some(FieldValue::Expressions(items)) => items,
399            _ => &[],
400        }
401    }
402
403    /// The word, name or text of the field `key`.
404    #[must_use]
405    pub fn text(&self, key: &str) -> Option<&str> {
406        match self.field(key)? {
407            FieldValue::Word(value) | FieldValue::Name(value) | FieldValue::Text(value) => {
408                Some(value)
409            }
410            _ => None,
411        }
412    }
413
414    /// The integer of the field `key`.
415    #[must_use]
416    pub fn integer(&self, key: &str) -> Option<i64> {
417        match self.field(key)? {
418            FieldValue::Integer(value) => Some(*value),
419            _ => None,
420        }
421    }
422
423    /// The single operation of the field `key`.
424    #[must_use]
425    pub fn operation(&self, key: &str) -> Option<&Self> {
426        match self.field(key)? {
427            FieldValue::Operation(operation) => Some(operation),
428            _ => None,
429        }
430    }
431
432    /// The operation list or block of the field `key`; `None` for an absent block.
433    #[must_use]
434    pub fn operations(&self, key: &str) -> Option<&[Self]> {
435        match self.field(key)? {
436            FieldValue::Operations(items) | FieldValue::Block(Some(items)) => Some(items),
437            _ => None,
438        }
439    }
440
441    /// Every grammar expression this form holds directly, operations included.
442    pub fn for_each_expression<'a>(&'a self, visit: &mut impl FnMut(&'a GrammarExpr)) {
443        for value in &self.fields {
444            match value {
445                FieldValue::Expression(expr) => visit(expr),
446                FieldValue::Expressions(items) => items.iter().for_each(&mut *visit),
447                FieldValue::Operation(operation) => operation.for_each_expression(visit),
448                FieldValue::Operations(items) | FieldValue::Block(Some(items)) => {
449                    for operation in items {
450                        operation.for_each_expression(visit);
451                    }
452                }
453                _ => {}
454            }
455        }
456    }
457
458    /// Rewrites every grammar expression this form holds, operations included.
459    pub fn map_expressions(&mut self, map: &mut impl FnMut(&mut GrammarExpr)) {
460        for value in &mut self.fields {
461            match value {
462                FieldValue::Expression(expr) => map(expr),
463                FieldValue::Expressions(items) => items.iter_mut().for_each(&mut *map),
464                FieldValue::Operation(operation) => operation.map_expressions(map),
465                FieldValue::Operations(items) | FieldValue::Block(Some(items)) => {
466                    for operation in items {
467                        operation.map_expressions(map);
468                    }
469                }
470                _ => {}
471            }
472        }
473    }
474}
475
476/// One item of a byte class.
477#[derive(Clone, Copy, Debug, PartialEq, Eq)]
478pub enum ByteClassItem {
479    /// One byte.
480    Byte(u8),
481    /// An inclusive byte range.
482    Range(u8, u8),
483}
484
485/// One item of a character class that names Unicode properties.
486#[derive(Clone, Debug, PartialEq, Eq)]
487pub enum UnicodeClassItem {
488    /// A single character.
489    Char(char),
490    /// An inclusive character range.
491    Range(char, char),
492    /// A Unicode general category such as `Lu` or `L`.
493    Category(String),
494    /// A Unicode script such as `Greek` or `Han`.
495    Script(String),
496}
497
498/// A character class: a plain [`GrammarExpr::CharClass`] when every item is a
499/// character or a range, otherwise a [`FeatureExpr::UnicodeClass`].
500#[must_use]
501pub fn class_expression(negated: bool, items: Vec<UnicodeClassItem>) -> GrammarExpr {
502    let plain = items
503        .iter()
504        .map(|item| match item {
505            UnicodeClassItem::Char(value) => Some(CharClassItem::Char(*value)),
506            UnicodeClassItem::Range(start, end) => Some(CharClassItem::Range(*start, *end)),
507            UnicodeClassItem::Category(_) | UnicodeClassItem::Script(_) => None,
508        })
509        .collect::<Option<Vec<_>>>();
510    plain.map_or_else(
511        || GrammarExpr::feature(FeatureExpr::UnicodeClass { negated, items }),
512        |items| GrammarExpr::CharClass { negated, items },
513    )
514}
515
516/// An expression of the grammar feature union.
517#[derive(Clone, Debug, PartialEq, Eq)]
518pub enum FeatureExpr {
519    /// A form of [`FEATURE_EXPRESSION_FORMS`].
520    Form(FeatureForm),
521    /// A class of bytes, `byteClass` or `notByteClass`.
522    ByteClass {
523        /// Whether the class is negated.
524        negated: bool,
525        /// Bytes and byte ranges of the class.
526        items: Vec<ByteClassItem>,
527    },
528    /// A character class with at least one Unicode `category` or `script` item.
529    UnicodeClass {
530        /// Whether the class is negated.
531        negated: bool,
532        /// Characters, ranges, categories and scripts of the class.
533        items: Vec<UnicodeClassItem>,
534    },
535    /// A call of a parameterized rule, `ref(NAME, ARGUMENT, ...)`.
536    Call {
537        /// The called rule.
538        name: String,
539        /// The arguments, at least one.
540        arguments: Vec<GrammarExpr>,
541    },
542}
543
544impl FeatureExpr {
545    /// The head word of this expression in the native listing.
546    #[must_use]
547    pub fn head(&self) -> &str {
548        match self {
549            Self::Form(form) => &form.head,
550            Self::ByteClass { .. } => "byteClass",
551            Self::UnicodeClass { .. } => "charClass",
552            Self::Call { .. } => "ref",
553        }
554    }
555
556    /// Every grammar expression this one holds directly, operations included.
557    pub fn for_each_expression<'a>(&'a self, visit: &mut impl FnMut(&'a GrammarExpr)) {
558        match self {
559            Self::Form(form) => form.for_each_expression(visit),
560            Self::Call { arguments, .. } => arguments.iter().for_each(visit),
561            Self::ByteClass { .. } | Self::UnicodeClass { .. } => {}
562        }
563    }
564
565    /// Rewrites every grammar expression this one holds directly.
566    pub fn map_expressions(&mut self, map: &mut impl FnMut(&mut GrammarExpr)) {
567        match self {
568            Self::Form(form) => form.map_expressions(map),
569            Self::Call { arguments, .. } => arguments.iter_mut().for_each(map),
570            Self::ByteClass { .. } | Self::UnicodeClass { .. } => {}
571        }
572    }
573
574    /// Adds the rule names this expression references, as the JavaScript
575    /// `collectReferences` does: calls and the expressions of `item`,
576    /// `items`, `arguments` and `synchronize` fields.
577    pub(crate) fn collect_references(&self, names: &mut BTreeSet<String>) {
578        match self {
579            Self::Call { name, arguments } => {
580                names.insert(name.clone());
581                for argument in arguments {
582                    argument.collect_nonterminals(names);
583                }
584            }
585            Self::Form(form) => {
586                for value in &form.fields {
587                    match value {
588                        FieldValue::Expression(expr) => expr.collect_nonterminals(names),
589                        FieldValue::Expressions(items) => {
590                            for item in items {
591                                item.collect_nonterminals(names);
592                            }
593                        }
594                        _ => {}
595                    }
596                }
597            }
598            Self::ByteClass { .. } | Self::UnicodeClass { .. } => {}
599        }
600    }
601}
602
603/// The optional parts of a rule the feature union adds.
604#[derive(Clone, Debug, Default, PartialEq, Eq)]
605pub struct RuleAttributes {
606    /// The rule's parameters; empty for a rule without.
607    pub parameters: Vec<String>,
608    /// The channel; a channel other than `default` makes the rule trivia.
609    pub channel: Option<String>,
610    /// The lexer modes the rule may match in.
611    pub modes: Option<Vec<String>>,
612    /// The semantic action, a statement list.
613    pub action: Option<Vec<Operation>>,
614}
615
616impl RuleAttributes {
617    /// Whether no attribute is set.
618    #[must_use]
619    pub fn is_empty(&self) -> bool {
620        self == &Self::default()
621    }
622}
623
624/// A macro declaration: `macro NAME(P, ...) = EXPRESSION`.
625#[derive(Clone, Debug, PartialEq, Eq)]
626pub struct GrammarMacro {
627    /// The macro name.
628    pub name: String,
629    /// The macro parameters.
630    pub parameters: Vec<String>,
631    /// The macro body.
632    pub expression: GrammarExpr,
633}
634
635/// An external scanner declaration.
636#[derive(Clone, Debug, PartialEq, Eq)]
637pub struct GrammarScanner {
638    /// The scanner name.
639    pub name: String,
640    /// The tokens the scanner produces.
641    pub tokens: Vec<String>,
642    /// The scanner's statements.
643    pub operations: Vec<Operation>,
644}
645
646/// A source-local lexer declaration with its complete ordered Links plan.
647#[derive(Clone, Debug, PartialEq, Eq)]
648pub struct GrammarLexer {
649    /// The source lexer family name.
650    pub name: String,
651    /// The lexical declarations, candidates, bindings and obligations.
652    pub expression: GrammarExpr,
653}
654
655/// One entry of a precedence order: a named precedence or a rule, whose
656/// productions it ranks.
657#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
658pub enum PrecedenceEntry {
659    /// The precedence `namedPrecedence` gives this name.
660    Name(String),
661    /// Every precedence of this rule's productions.
662    Rule(String),
663}
664
665impl PrecedenceEntry {
666    /// Builds an entry from its kind word, `name` or `rule`, and its value.
667    #[must_use]
668    pub fn from_kind(kind: &str, value: String) -> Option<Self> {
669        match kind {
670            "name" => Some(Self::Name(value)),
671            "rule" => Some(Self::Rule(value)),
672            _ => None,
673        }
674    }
675
676    /// The entry's kind word, `name` or `rule`.
677    #[must_use]
678    pub const fn kind(&self) -> &'static str {
679        match self {
680            Self::Name(_) => "name",
681            Self::Rule(_) => "rule",
682        }
683    }
684
685    /// The precedence or rule name.
686    #[must_use]
687    pub fn value(&self) -> &str {
688        match self {
689            Self::Name(value) | Self::Rule(value) => value,
690        }
691    }
692}
693
694/// The grammar-level declarations of the feature union.
695#[derive(Clone, Debug, Default, PartialEq, Eq)]
696pub struct GrammarDeclarations {
697    /// `generalized`, `peg` or `longest`, when given.
698    pub matching: Option<String>,
699    /// The settling steps (see [`SETTLING_STEPS`]), when given.
700    pub settling: Option<Vec<String>>,
701    /// Names of grammars this one inherits from.
702    pub imports: Vec<String>,
703    /// The lexer modes beyond `default`.
704    pub modes: Vec<String>,
705    /// Trivia expressions allowed between any two tokens.
706    pub extras: Vec<GrammarExpr>,
707    /// Groups of rule names whose ambiguity is expected.
708    pub conflicts: Vec<Vec<String>>,
709    /// Orders of named precedences and rules, the earlier entry higher.
710    pub precedences: Vec<Vec<PrecedenceEntry>>,
711    /// Macro declarations.
712    pub macros: Vec<GrammarMacro>,
713    /// External scanner declarations.
714    pub scanners: Vec<GrammarScanner>,
715    /// Source-local lexer election declarations.
716    pub lexers: Vec<GrammarLexer>,
717}
718
719impl GrammarDeclarations {
720    /// Whether no declaration is given.
721    #[must_use]
722    pub fn is_empty(&self) -> bool {
723        self == &Self::default()
724    }
725
726    /// The token names the external scanners produce.
727    #[must_use]
728    pub fn external_tokens(&self) -> Vec<&str> {
729        self.scanners
730            .iter()
731            .flat_map(|scanner| scanner.tokens.iter().map(String::as_str))
732            .collect()
733    }
734
735    /// The names of the declaration kinds that are given, in listing order.
736    #[must_use]
737    pub fn present(&self) -> Vec<&'static str> {
738        let mut present = Vec::new();
739        if self.matching.is_some() {
740            present.push("matching");
741        }
742        if self.settling.is_some() {
743            present.push("settling");
744        }
745        for (name, empty) in [
746            ("imports", self.imports.is_empty()),
747            ("modes", self.modes.is_empty()),
748            ("extras", self.extras.is_empty()),
749            ("conflicts", self.conflicts.is_empty()),
750            ("precedences", self.precedences.is_empty()),
751            ("macros", self.macros.is_empty()),
752            ("scanners", self.scanners.is_empty()),
753            ("lexers", self.lexers.is_empty()),
754        ] {
755            if !empty {
756                present.push(name);
757            }
758        }
759        present
760    }
761}
762
763/// Check closed source-view forms before a positional codec can omit fields.
764pub(crate) fn check_grammar_selection_included_range_form(
765    form: &FeatureForm,
766) -> Result<bool, String> {
767    if super::field_range_forms::check_grammar_selection_field_range_form(form)? {
768        return Ok(true);
769    }
770    let role = match form.head.as_str() {
771        "grammar-range-candidate" => "candidate",
772        "source-range" => "range",
773        _ => return Ok(false),
774    };
775    if form.fields.len() + 1
776        != read_grammar_selection_included_range_field_order(role)
777            .split('|')
778            .count()
779    {
780        return Err("an included source view needs exactly its declared fields".to_owned());
781    }
782    if role == "range" {
783        let [FieldValue::Integer(start), FieldValue::Integer(end)] = form.fields.as_slice() else {
784            return Err(
785                "an included source range needs its kind and nonempty integer byte bounds"
786                    .to_owned(),
787            );
788        };
789        let number = |value| u32::try_from(value).map_or(f64::NAN, f64::from);
790        if !accept_grammar_selection_included_range_source_range(
791            &form.head,
792            number(*start),
793            number(*end),
794        ) {
795            return Err(
796                "an included source range needs its kind and nonempty integer byte bounds"
797                    .to_owned(),
798            );
799        }
800    } else {
801        let [FieldValue::Name(name), FieldValue::Name(mapping), ranges] = form.fields.as_slice()
802        else {
803            return Err(
804                "an included range candidate needs its name and explicit included-ranges mapping"
805                    .to_owned(),
806            );
807        };
808        if name.is_empty()
809            || !accept_grammar_selection_included_range_candidate(&form.head, mapping)
810        {
811            return Err(
812                "an included range candidate needs its name and explicit included-ranges mapping"
813                    .to_owned(),
814            );
815        }
816        let FieldValue::Expressions(ranges) = ranges else {
817            return Err("an included range candidate needs an ordinary range array".to_owned());
818        };
819        if ranges.is_empty() {
820            return Err(
821                "an included range candidate needs a nonempty dense range array".to_owned(),
822            );
823        }
824        for range in ranges {
825            let GrammarExpr::Feature(feature) = range else {
826                return Err("an included source view needs ordinary data records".to_owned());
827            };
828            let FeatureExpr::Form(range) = &**feature else {
829                return Err("an included source view needs exactly its declared fields".to_owned());
830            };
831            if range.head != "source-range" {
832                return Err(
833                    "an included source range needs its kind and nonempty integer byte bounds"
834                        .to_owned(),
835                );
836            }
837            check_grammar_selection_included_range_form(range)?;
838        }
839    }
840    Ok(true)
841}
842
843/// Inspect every original raw value before a reader can omit unknown fields.
844pub(crate) fn check_grammar_selection_included_range_data(root: &Value) -> Result<(), String> {
845    super::field_range_forms::check_grammar_selection_included_range_data(root)
846}
847
848fn check_included_range_fields(form: &FeatureForm) -> Result<(), String> {
849    check_grammar_selection_included_range_form(form)?;
850    for value in &form.fields {
851        match value {
852            FieldValue::Expression(expr) => {
853                check_grammar_selection_included_range_expression(expr)?;
854            }
855            FieldValue::Expressions(items) => {
856                for expr in items {
857                    check_grammar_selection_included_range_expression(expr)?;
858                }
859            }
860            FieldValue::Operation(form) => check_included_range_fields(form)?,
861            FieldValue::Operations(items) | FieldValue::Block(Some(items)) => {
862                for form in items {
863                    check_included_range_fields(form)?;
864                }
865            }
866            _ => {}
867        }
868    }
869    Ok(())
870}
871
872pub(crate) fn check_grammar_selection_included_range_expression(
873    expr: &GrammarExpr,
874) -> Result<(), String> {
875    match expr {
876        GrammarExpr::Feature(feature) => match &**feature {
877            FeatureExpr::Form(form) => check_included_range_fields(form)?,
878            FeatureExpr::Call { arguments, .. } => {
879                for item in arguments {
880                    check_grammar_selection_included_range_expression(item)?;
881                }
882            }
883            _ => {}
884        },
885        GrammarExpr::Choice {
886            alternatives: items,
887            ..
888        }
889        | GrammarExpr::Sequence(items) => {
890            for item in items {
891                check_grammar_selection_included_range_expression(item)?;
892            }
893        }
894        GrammarExpr::Optional(item)
895        | GrammarExpr::ZeroOrMore(item)
896        | GrammarExpr::OneOrMore(item)
897        | GrammarExpr::And(item)
898        | GrammarExpr::Not(item)
899        | GrammarExpr::Repeat { expr: item, .. }
900        | GrammarExpr::Capture { expr: item, .. } => {
901            check_grammar_selection_included_range_expression(item)?;
902        }
903        _ => {}
904    }
905    Ok(())
906}
907
908/// Check rule/declaration payloads before expansion, cloning or String emission.
909pub(crate) fn check_grammar_selection_included_range_grammar(
910    grammar: &Grammar,
911) -> Result<(), String> {
912    for rule in grammar.rules() {
913        check_grammar_selection_included_range_expression(rule.expr())?;
914        for form in rule.attributes.action.as_deref().unwrap_or_default() {
915            check_included_range_fields(form)?;
916        }
917    }
918    let declarations = grammar.declarations();
919    for item in &declarations.extras {
920        check_grammar_selection_included_range_expression(item)?;
921    }
922    for item in &declarations.macros {
923        check_grammar_selection_included_range_expression(&item.expression)?;
924    }
925    for item in &declarations.lexers {
926        check_grammar_selection_included_range_expression(&item.expression)?;
927    }
928    for scanner in &declarations.scanners {
929        for form in &scanner.operations {
930            check_included_range_fields(form)?;
931        }
932    }
933    Ok(())
934}