Skip to main content

meta_language/grammar/
mod.rs

1//! Grammar intermediate representation and links encoding.
2//!
3//! The grammar IR is a small expression algebra that can hold PEG, BNF, EBNF,
4//! ABNF, and inferred grammars without committing to one textual surface
5//! syntax. Values can be encoded as first-class grammar links in a
6//! [`LinkNetwork`](crate::LinkNetwork).
7//!
8//! # Example
9//!
10//! ```
11//! use meta_language::{
12//!     FromLinks, Grammar, LinkType, LinksDecoder, LinksEncoder, ToLinks,
13//! };
14//!
15//! let expr = Grammar::expr();
16//! let grammar = Grammar::builder().start("word").rule("word", expr.rep1(expr.char_range('a', 'z'))).build();
17//!
18//! let mut encoder = LinksEncoder::new();
19//! let root = grammar.to_links(&mut encoder);
20//! let network = encoder.into_network();
21//! assert!(network.links().any(|link| link.metadata().link_type() == Some(LinkType::Grammar)));
22//! let mut decoder = LinksDecoder::new(&network);
23//! assert_eq!(Grammar::from_links(&mut decoder, root).expect("grammar decodes"), grammar);
24//! ```
25
26mod builder;
27pub mod concepts;
28pub mod decorators;
29pub mod emit;
30pub mod feature;
31pub mod feature_runtime;
32pub mod fidelity;
33mod field_range_forms;
34pub mod import;
35pub mod inference;
36pub mod interchange;
37mod lexical_forms;
38mod links;
39pub mod merge;
40mod metadata;
41pub mod reverse;
42pub mod round_trip;
43pub mod runtime;
44mod selection_forms;
45pub mod surface;
46pub mod translate;
47pub mod validate;
48
49pub use builder::{
50    ExprBuilder, GrammarBuilder, RepetitionBoundsError, canonical_repeat, choice, sequence,
51};
52pub use concepts::{
53    GRAMMAR_CONCEPTS, GrammarConcept, annotate_grammar_concepts, grammar_expr_concept_id,
54    rule_concept_id,
55};
56pub use decorators::{decorate_emitted, decorate_grammar, decorate_syntax_tree};
57pub use emit::{
58    EmitReport, GrammarEmitError, JsParserArtifacts, RustParserArtifacts, emit_abnf, emit_antlr,
59    emit_bnf, emit_ebnf, emit_gbnf, emit_javascript_parser, emit_lark, emit_peggy, emit_pest,
60    emit_rust_parser, emit_tree_sitter_grammar_js, emit_tree_sitter_grammar_js_with_report,
61    emit_tree_sitter_json, render_rust_type,
62};
63pub use feature::{
64    ByteClassItem, FEATURE_EXPRESSION_FORMS, FeatureExpr, FeatureForm, FieldType, FieldValue,
65    GrammarDeclarations, GrammarLexer, GrammarMacro, GrammarScanner, MATCHING_MODES,
66    OPERATION_FORMS, Operation, OperationCategory, PrecedenceEntry, RuleAttributes, SETTLING_STEPS,
67    UnicodeClassItem, default_settling, settling_problem,
68};
69pub use fidelity::{
70    FORMER_GRAMMAR_CONSTRUCTS, GRAMMAR_CONSTRUCTS, GRAMMAR_FORMATS, GrammarFidelityLevel,
71    GrammarFormatProfile, canonical_grammar_format, current_grammar_construct,
72    grammar_format_profile,
73};
74pub use import::{
75    GrammarImportError, import_abnf, import_antlr, import_bnf, import_ebnf, import_gbnf,
76    import_lark, import_pest, import_tree_sitter_json,
77};
78pub use inference::active::{
79    ActiveLearningConfig, ActiveLearningError, Dfa, GrammarAcceptorOracle,
80    Oracle as ActiveLearningOracle, ParserAcceptancePredicate, ParserMembershipOracle,
81    SamplingEquivalenceOracle, Symbol as ActiveSymbol, clean_structural_acceptance, learn_dfa,
82    learn_grammar,
83};
84pub use inference::advisor::{
85    AdviceDecision, AdviceDecisionKind, AdviceSource, ConceptNamingAdvisor, FallbackAdvisor,
86    MdlMergeAdvisor, MergeAdvisor, MergeCandidate, MergeRequest, MergeScore, NameCandidate,
87    NamingAdvisor, NamingRequest,
88};
89#[cfg(feature = "llm-assist")]
90pub use inference::advisor::{LlmClient, LlmError, LlmMergeAdvisor, LlmNamingAdvisor};
91pub use inference::cfg::{
92    InferenceOptions, InferenceReport, InferenceResult, Oracle, PositiveOnlyOracle, infer_cfg,
93    infer_cfg_with_advisors,
94};
95pub use inference::eval::{
96    BenchmarkReport, EvalError, GOLDEN_CORPORA, GoldenCorpus, GrammarOracle, MembershipOracle,
97    MetricScores, SampleConfig, ScoringMode, evaluate, mdl, run_corpus, run_named_corpus, sample,
98    size_symbols,
99};
100pub use inference::lexical::{
101    CharCategory, LexicalConfig, LexicalModel, Token, categorise, infer_lexical_classes,
102};
103pub use inference::minimize::{
104    Mdl, MinimizeOptions, MinimizeReport, MinimizeResult, mdl_cost, minimize,
105};
106pub use inference::prior::{
107    ByteSpan, Delimiter, LeafKind, PriorOptions, SeedNode, SeedTree, StructuralPrior,
108    WhitespacePolicy, build_structural_prior,
109};
110pub use inference::semantic::{
111    ConstraintAtom, ConstraintClause, ConstraintPattern, LengthUnit, NonTerminalRef,
112    SemanticConstraint, SemanticInferenceConfig, default_pattern_catalog, evaluate_atom,
113    evaluate_clause, evaluate_constraint, evaluate_probabilistic, mine_semantic_constraints,
114};
115pub use inference::sequitur::{Symbol, run_sequitur};
116pub use inference::state_merging::{InferredAutomaton, MergeStrategy, Sample, infer_dfa};
117pub use interchange::{
118    GRAMMAR_COMMAND_USAGE, GRAMMAR_EXPORT_FORMATS, GRAMMAR_IMPORT_FORMATS,
119    GRAMMAR_LOSSLESS_FORMATS, GrammarCommandOutput, GrammarEmitter, GrammarFileReader,
120    GrammarImporter, GrammarLayout, GrammarLayoutDefinition, GrammarLayoutImplicit,
121    GrammarLosslessError, GrammarSourceDefinition, GrammarSourceSplit, capture_grammar_layout,
122    deserialize_grammar, emit_grammar_lossless, grammar_emitter, grammar_importer,
123    import_grammar_lossless, parse_grammar_layout_links, parse_grammar_links,
124    parse_links_expression, parse_native_grammar, percent_decode_links_text,
125    percent_encode_links_text, render_declaration_links, render_grammar_layout_links,
126    render_grammar_links, render_links_expression, render_native_expression, render_native_feature,
127    render_native_grammar, render_rule_fields, render_rule_link, run_grammar_command,
128    serialize_grammar, split_grammar_source,
129};
130pub use merge::{
131    GRAMMAR_MERGE_METHOD, GrammarMergeAlternative, GrammarMergeAlternativeReason,
132    GrammarMergeDecision, GrammarMergeDecisionKind, GrammarMergeError, GrammarMergeFailure,
133    GrammarMergeFailureKind, GrammarMergeFailureReason, GrammarMergeNomination,
134    GrammarMergeNominationBasis, GrammarMergeNominationOutcome, GrammarMergeOptions,
135    GrammarMergeProduction, GrammarMergeResult, GrammarMergeSource, GrammarRenameError,
136    GrammarRenameErrorKind, MergedGrammarGroup, RenamedGrammar, RuleAlias, assert_merge_complete,
137    assert_merge_shares, merge_grammars, normalized_rule_definition, rename_grammar_rule,
138    restore_source_names, shared_rule_decisions,
139};
140pub use metadata::{GrammarFormat, GrammarKind, GrammarSourceName};
141pub use reverse::{
142    GrammarReverseConversion, GrammarReverseFailure, GrammarReverseFailureKind,
143    GrammarReverseReport, GrammarReverseStage, GrammarReverseStatus,
144    check_grammar_reverse_conversion,
145};
146pub use round_trip::{
147    GRAMMAR_ROUND_TRIP_MARKER, GrammarEmitFn, GrammarImportFn, GrammarRoundTrip,
148    GrammarRoundTripError, GrammarRoundTripFailure, GrammarRoundTripFailureKind,
149    GrammarRoundTripReport, GrammarRoundTripStage, GrammarRoundTripStatus, accepts_text,
150    canonical_rule_definition, check_grammar_round_trip, mutate_grammar_start_rule,
151    render_grammar_lexical_owner_comparison,
152};
153pub use runtime::{GrammarParser, register_grammar, with_grammar};
154pub use surface::{
155    GrammarSurfaceError, grammar_from_lino, grammar_to_lino, parse_grammar_surface,
156    write_grammar_surface,
157};
158pub use translate::{
159    GrammarTranslateError, grammar_concept_translation_rules, translate_grammar_surface,
160};
161pub use validate::{
162    DiagnosticKind, GRAMMAR_DIAGNOSTIC_KINDS, GrammarDiagnostic, RuleSpan, Severity,
163    display_grammar_expression, validate,
164};
165
166use std::collections::BTreeSet;
167use std::fmt;
168
169/// One node of the grammar expression algebra.
170#[derive(Clone, Debug, PartialEq, Eq)]
171pub enum GrammarExpr {
172    /// Matches the empty string.
173    Empty,
174    /// Literal string terminal, for example `"fn"`.
175    Terminal(String),
176    /// Case-insensitive literal string terminal.
177    TerminalInsensitive(String),
178    /// Inclusive character range, for example `'a'..='z'`.
179    CharRange(char, char),
180    /// Explicit set of characters or ranges.
181    CharClass {
182        /// Whether the class is negated.
183        negated: bool,
184        /// Characters and ranges accepted by the class.
185        items: Vec<CharClassItem>,
186    },
187    /// The any-character wildcard.
188    AnyChar,
189    /// Reference to another grammar rule by name.
190    NonTerminal(String),
191    /// Alternation between expressions.
192    Choice {
193        /// Whether alternatives are ordered, as in PEG choice.
194        ordered: bool,
195        /// Alternative expressions.
196        alternatives: Vec<Self>,
197    },
198    /// Concatenation of expressions.
199    Sequence(Vec<Self>),
200    /// Optional expression.
201    Optional(Box<Self>),
202    /// Zero-or-more repetition.
203    ZeroOrMore(Box<Self>),
204    /// One-or-more repetition.
205    OneOrMore(Box<Self>),
206    /// Counted repetition.
207    Repeat {
208        /// Repeated expression.
209        expr: Box<Self>,
210        /// Minimum number of repetitions.
211        min: usize,
212        /// Maximum number of repetitions, or `None` for unbounded.
213        max: Option<usize>,
214    },
215    /// Positive lookahead predicate.
216    And(Box<Self>),
217    /// Negative lookahead predicate.
218    Not(Box<Self>),
219    /// Labelled or anonymous capture.
220    Capture {
221        /// Optional capture label.
222        label: Option<String>,
223        /// Captured expression.
224        expr: Box<Self>,
225    },
226    /// A form of the grammar feature union (`docs/grammar/feature-union.md`).
227    Feature(Box<FeatureExpr>),
228}
229
230impl GrammarExpr {
231    /// Builds an empty-string expression.
232    #[must_use]
233    pub const fn empty() -> Self {
234        Self::Empty
235    }
236
237    /// Builds a literal terminal expression.
238    #[must_use]
239    pub fn terminal(value: impl Into<String>) -> Self {
240        Self::Terminal(value.into())
241    }
242
243    /// Builds a case-insensitive literal terminal expression.
244    #[must_use]
245    pub fn terminal_insensitive(value: impl Into<String>) -> Self {
246        Self::TerminalInsensitive(value.into())
247    }
248
249    /// Builds an inclusive character range expression.
250    #[must_use]
251    pub const fn char_range(start: char, end: char) -> Self {
252        Self::CharRange(start, end)
253    }
254
255    /// Builds a character class expression.
256    #[must_use]
257    pub fn char_class<I>(negated: bool, items: I) -> Self
258    where
259        I: IntoIterator<Item = CharClassItem>,
260    {
261        Self::CharClass {
262            negated,
263            items: items.into_iter().collect(),
264        }
265    }
266
267    /// Builds an any-character wildcard expression.
268    #[must_use]
269    pub const fn any_char() -> Self {
270        Self::AnyChar
271    }
272
273    /// Builds a non-terminal reference expression.
274    #[must_use]
275    pub fn non_terminal(value: impl Into<String>) -> Self {
276        Self::NonTerminal(value.into())
277    }
278
279    /// Builds a choice expression.
280    #[must_use]
281    pub fn choice<I>(ordered: bool, alternatives: I) -> Self
282    where
283        I: IntoIterator<Item = Self>,
284    {
285        Self::Choice {
286            ordered,
287            alternatives: alternatives.into_iter().collect(),
288        }
289    }
290
291    /// Builds a sequence expression.
292    #[must_use]
293    pub fn sequence<I>(items: I) -> Self
294    where
295        I: IntoIterator<Item = Self>,
296    {
297        Self::Sequence(items.into_iter().collect())
298    }
299
300    /// Builds an optional expression.
301    #[must_use]
302    pub fn optional(expr: Self) -> Self {
303        Self::Optional(Box::new(expr))
304    }
305
306    /// Builds a zero-or-more repetition expression.
307    #[must_use]
308    pub fn zero_or_more(expr: Self) -> Self {
309        Self::ZeroOrMore(Box::new(expr))
310    }
311
312    /// Builds a one-or-more repetition expression.
313    #[must_use]
314    pub fn one_or_more(expr: Self) -> Self {
315        Self::OneOrMore(Box::new(expr))
316    }
317
318    /// Builds a counted repetition expression.
319    #[must_use]
320    pub fn repeat(expr: Self, min: usize, max: Option<usize>) -> Self {
321        Self::Repeat {
322            expr: Box::new(expr),
323            min,
324            max,
325        }
326    }
327
328    /// Builds a positive lookahead expression.
329    #[must_use]
330    pub fn and(expr: Self) -> Self {
331        Self::And(Box::new(expr))
332    }
333
334    /// Builds a negative lookahead expression.
335    #[must_use]
336    #[allow(clippy::should_implement_trait)]
337    pub fn not(expr: Self) -> Self {
338        Self::Not(Box::new(expr))
339    }
340
341    /// Builds a labelled capture expression.
342    #[must_use]
343    pub fn capture(label: impl Into<String>, expr: Self) -> Self {
344        Self::Capture {
345            label: Some(label.into()),
346            expr: Box::new(expr),
347        }
348    }
349
350    /// Builds an anonymous capture expression.
351    #[must_use]
352    pub fn capture_unlabeled(expr: Self) -> Self {
353        Self::Capture {
354            label: None,
355            expr: Box::new(expr),
356        }
357    }
358
359    /// Builds a feature union expression.
360    #[must_use]
361    pub fn feature(feature: FeatureExpr) -> Self {
362        Self::Feature(Box::new(feature))
363    }
364
365    /// Copies a feature form with every nested expression rewritten by `map`.
366    pub(crate) fn rewrite_feature(
367        feature: &FeatureExpr,
368        mut map: impl FnMut(&Self) -> Self,
369    ) -> Self {
370        let mut copy = feature.clone();
371        copy.map_expressions(&mut |expr| *expr = map(expr));
372        Self::Feature(Box::new(copy))
373    }
374
375    /// The first feature union form in this expression, in source order.
376    #[must_use]
377    pub fn first_feature(&self) -> Option<&FeatureExpr> {
378        match self {
379            Self::Feature(feature) => Some(feature),
380            Self::Choice { alternatives, .. } | Self::Sequence(alternatives) => {
381                alternatives.iter().find_map(Self::first_feature)
382            }
383            Self::Optional(inner)
384            | Self::ZeroOrMore(inner)
385            | Self::OneOrMore(inner)
386            | Self::And(inner)
387            | Self::Not(inner)
388            | Self::Repeat { expr: inner, .. }
389            | Self::Capture { expr: inner, .. } => inner.first_feature(),
390            Self::Empty
391            | Self::Terminal(_)
392            | Self::TerminalInsensitive(_)
393            | Self::CharRange(_, _)
394            | Self::CharClass { .. }
395            | Self::AnyChar
396            | Self::NonTerminal(_) => None,
397        }
398    }
399
400    pub(crate) fn collect_nonterminals(&self, names: &mut BTreeSet<String>) {
401        match self {
402            Self::Feature(feature) => feature.collect_references(names),
403            Self::NonTerminal(name) => {
404                names.insert(name.clone());
405            }
406            Self::Choice { alternatives, .. } => {
407                for alternative in alternatives {
408                    alternative.collect_nonterminals(names);
409                }
410            }
411            Self::Sequence(items) => {
412                for item in items {
413                    item.collect_nonterminals(names);
414                }
415            }
416            Self::Optional(expr)
417            | Self::ZeroOrMore(expr)
418            | Self::OneOrMore(expr)
419            | Self::And(expr)
420            | Self::Not(expr)
421            | Self::Capture { expr, .. }
422            | Self::Repeat { expr, .. } => expr.collect_nonterminals(names),
423            Self::Empty
424            | Self::Terminal(_)
425            | Self::TerminalInsensitive(_)
426            | Self::CharRange(_, _)
427            | Self::CharClass { .. }
428            | Self::AnyChar => {}
429        }
430    }
431}
432
433impl fmt::Display for GrammarExpr {
434    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
435        match self {
436            Self::Empty => formatter.write_str("empty"),
437            Self::Terminal(value) => write!(formatter, "{value:?}"),
438            Self::TerminalInsensitive(value) => write!(formatter, "i{value:?}"),
439            Self::CharRange(start, end) => write!(formatter, "{start:?}..={end:?}"),
440            Self::CharClass { negated, items } => {
441                let marker = if *negated { "^" } else { "" };
442                write!(formatter, "[{marker}")?;
443                for item in items {
444                    write!(formatter, "{item}")?;
445                }
446                formatter.write_str("]")
447            }
448            Self::AnyChar => formatter.write_str("."),
449            Self::NonTerminal(name) => formatter.write_str(name),
450            Self::Choice {
451                ordered,
452                alternatives,
453            } => {
454                let separator = if *ordered { " / " } else { " | " };
455                write_joined(formatter, alternatives, separator)
456            }
457            Self::Sequence(items) => write_joined(formatter, items, " "),
458            Self::Optional(expr) => write!(formatter, "({expr})?"),
459            Self::ZeroOrMore(expr) => write!(formatter, "({expr})*"),
460            Self::OneOrMore(expr) => write!(formatter, "({expr})+"),
461            Self::Repeat { expr, min, max } => match max {
462                Some(max) => write!(formatter, "({expr}){{{min},{max}}}"),
463                None => write!(formatter, "({expr}){{{min},}}"),
464            },
465            Self::And(expr) => write!(formatter, "&({expr})"),
466            Self::Not(expr) => write!(formatter, "!({expr})"),
467            Self::Capture { label, expr } => match label {
468                Some(label) => write!(formatter, "{label}:({expr})"),
469                None => write!(formatter, "capture({expr})"),
470            },
471            Self::Feature(feature) => {
472                formatter.write_str(&interchange::render_native_feature(feature))
473            }
474        }
475    }
476}
477
478/// One item inside a character class.
479#[derive(Clone, Debug, PartialEq, Eq)]
480pub enum CharClassItem {
481    /// A single character.
482    Char(char),
483    /// An inclusive character range.
484    Range(char, char),
485}
486
487impl CharClassItem {
488    /// Builds a single-character class item.
489    #[must_use]
490    pub const fn char(value: char) -> Self {
491        Self::Char(value)
492    }
493
494    /// Builds an inclusive character range class item.
495    #[must_use]
496    pub const fn range(start: char, end: char) -> Self {
497        Self::Range(start, end)
498    }
499}
500
501impl fmt::Display for CharClassItem {
502    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
503        match self {
504            Self::Char(value) => write!(formatter, "{}", value.escape_default()),
505            Self::Range(start, end) => {
506                write!(
507                    formatter,
508                    "{}-{}",
509                    start.escape_default(),
510                    end.escape_default()
511                )
512            }
513        }
514    }
515}
516
517/// How a rule participates in parsing.
518#[derive(Clone, Copy, Debug, PartialEq, Eq)]
519pub enum RuleKind {
520    /// A normal rule that participates in the parse tree.
521    Normal,
522    /// An atomic rule whose inner expression is treated as an indivisible token.
523    Atomic,
524    /// A silent rule that can be omitted from visible parse output.
525    Silent,
526    /// A token-level rule.
527    Token,
528}
529
530impl RuleKind {
531    /// Stable tag used in links encoding and display output.
532    #[must_use]
533    pub const fn as_str(self) -> &'static str {
534        match self {
535            Self::Normal => "normal",
536            Self::Atomic => "atomic",
537            Self::Silent => "silent",
538            Self::Token => "token",
539        }
540    }
541
542    pub(crate) fn from_tag(value: &str) -> Option<Self> {
543        match value {
544            "normal" => Some(Self::Normal),
545            "atomic" => Some(Self::Atomic),
546            "silent" => Some(Self::Silent),
547            "token" => Some(Self::Token),
548            _ => None,
549        }
550    }
551}
552
553impl fmt::Display for RuleKind {
554    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
555        formatter.write_str(self.as_str())
556    }
557}
558
559/// A named grammar rule.
560#[derive(Clone, Debug, PartialEq, Eq)]
561pub struct GrammarRule {
562    /// Rule name.
563    pub name: String,
564    /// Rule expression.
565    pub expr: GrammarExpr,
566    /// Rule participation kind.
567    pub kind: RuleKind,
568    /// Optional concept-ontology alignment.
569    pub concept: Option<String>,
570    /// The names the rule has in the grammars it was merged from.
571    pub source_names: Vec<GrammarSourceName>,
572    /// Optional free-text documentation or comment.
573    pub doc: Option<String>,
574    /// Parameters, channel, modes and action of the feature union.
575    pub attributes: RuleAttributes,
576}
577
578impl GrammarRule {
579    /// Builds a normal grammar rule.
580    #[must_use]
581    pub fn new(name: impl Into<String>, expr: GrammarExpr) -> Self {
582        Self {
583            name: name.into(),
584            expr,
585            kind: RuleKind::Normal,
586            concept: None,
587            source_names: Vec::new(),
588            doc: None,
589            attributes: RuleAttributes::default(),
590        }
591    }
592
593    /// Returns this rule with feature union attributes.
594    #[must_use]
595    pub fn with_attributes(mut self, attributes: RuleAttributes) -> Self {
596        self.attributes = attributes;
597        self
598    }
599
600    /// Returns this rule with a different rule kind.
601    #[must_use]
602    pub const fn with_kind(mut self, kind: RuleKind) -> Self {
603        self.kind = kind;
604        self
605    }
606
607    /// Returns this rule with concept-ontology alignment.
608    #[must_use]
609    pub fn with_concept(mut self, concept: impl Into<String>) -> Self {
610        self.concept = Some(concept.into());
611        self
612    }
613
614    /// Returns this rule with the names it has in the grammars it was merged
615    /// from.
616    #[must_use]
617    pub fn with_source_names(mut self, source_names: Vec<GrammarSourceName>) -> Self {
618        self.source_names = source_names;
619        self
620    }
621
622    /// Returns this rule with documentation text.
623    #[must_use]
624    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
625        self.doc = Some(doc.into());
626        self
627    }
628
629    /// Rule name.
630    #[must_use]
631    pub fn name(&self) -> &str {
632        &self.name
633    }
634
635    /// Rule expression.
636    #[must_use]
637    pub const fn expr(&self) -> &GrammarExpr {
638        &self.expr
639    }
640
641    /// Rule participation kind.
642    #[must_use]
643    pub const fn kind(&self) -> RuleKind {
644        self.kind
645    }
646
647    /// Concept-ontology alignment, when present.
648    #[must_use]
649    pub fn concept(&self) -> Option<&str> {
650        self.concept.as_deref()
651    }
652
653    /// The names the rule has in the grammars it was merged from.
654    #[must_use]
655    pub fn source_names(&self) -> &[GrammarSourceName] {
656        &self.source_names
657    }
658
659    /// Rule documentation, when present.
660    #[must_use]
661    pub fn doc(&self) -> Option<&str> {
662        self.doc.as_deref()
663    }
664}
665
666/// Order-preserving grammar.
667#[derive(Clone, Debug, Default, PartialEq, Eq)]
668pub struct Grammar {
669    rules: Vec<GrammarRule>,
670    start: Option<String>,
671    source_format: Option<GrammarFormat>,
672    declarations: GrammarDeclarations,
673    kinds: Vec<GrammarKind>,
674}
675
676impl Grammar {
677    /// Builds an empty grammar.
678    #[must_use]
679    pub const fn new() -> Self {
680        Self {
681            rules: Vec::new(),
682            start: None,
683            source_format: None,
684            declarations: GrammarDeclarations {
685                matching: None,
686                settling: None,
687                imports: Vec::new(),
688                modes: Vec::new(),
689                extras: Vec::new(),
690                conflicts: Vec::new(),
691                precedences: Vec::new(),
692                macros: Vec::new(),
693                scanners: Vec::new(),
694                lexers: Vec::new(),
695            },
696            kinds: Vec::new(),
697        }
698    }
699
700    /// Builds a fluent grammar builder.
701    #[must_use]
702    pub const fn builder() -> GrammarBuilder {
703        GrammarBuilder::new()
704    }
705
706    /// Builds an expression builder.
707    #[must_use]
708    pub const fn expr() -> ExprBuilder {
709        ExprBuilder
710    }
711
712    /// Returns this grammar with an additional rule.
713    #[must_use]
714    pub fn with_rule(mut self, rule: GrammarRule) -> Self {
715        self.rules.push(rule);
716        self
717    }
718
719    /// Returns this grammar with a start rule name.
720    #[must_use]
721    pub fn with_start(mut self, start: impl Into<String>) -> Self {
722        self.start = Some(start.into());
723        self
724    }
725
726    /// Returns this grammar with a source format.
727    #[must_use]
728    pub const fn with_source_format(mut self, source_format: GrammarFormat) -> Self {
729        self.source_format = Some(source_format);
730        self
731    }
732
733    /// Returns this grammar with feature union declarations.
734    #[must_use]
735    pub fn with_declarations(mut self, declarations: GrammarDeclarations) -> Self {
736        self.declarations = declarations;
737        self
738    }
739
740    /// The feature union declarations.
741    #[must_use]
742    pub const fn declarations(&self) -> &GrammarDeclarations {
743        &self.declarations
744    }
745
746    /// Replaces the feature union declarations.
747    pub fn set_declarations(&mut self, declarations: GrammarDeclarations) {
748        self.declarations = declarations;
749    }
750
751    /// The node kinds no rule defines that keep their source names.
752    #[must_use]
753    pub fn kinds(&self) -> &[GrammarKind] {
754        &self.kinds
755    }
756
757    /// Replaces the node kinds no rule defines.
758    pub fn set_kinds(&mut self, kinds: Vec<GrammarKind>) {
759        self.kinds = kinds;
760    }
761
762    /// Adds a rule to the grammar.
763    pub fn add_rule(&mut self, rule: GrammarRule) {
764        self.rules.push(rule);
765    }
766
767    /// Sets the grammar start rule name.
768    pub fn set_start(&mut self, start: impl Into<String>) {
769        self.start = Some(start.into());
770    }
771
772    /// Clears the explicit grammar start rule.
773    pub fn clear_start(&mut self) {
774        self.start = None;
775    }
776
777    /// Sets the grammar source format.
778    pub const fn set_source_format(&mut self, source_format: GrammarFormat) {
779        self.source_format = Some(source_format);
780    }
781
782    /// Returns all rules in source order.
783    #[must_use]
784    pub fn rules(&self) -> &[GrammarRule] {
785        &self.rules
786    }
787
788    /// Returns the rule with `name`, when present.
789    #[must_use]
790    pub fn rule(&self, name: &str) -> Option<&GrammarRule> {
791        self.rules.iter().find(|rule| rule.name == name)
792    }
793
794    /// Returns the explicitly configured start symbol, if present.
795    #[must_use]
796    pub fn start(&self) -> Option<&str> {
797        self.start.as_deref()
798    }
799
800    /// Returns the start rule, defaulting to the first rule when unset.
801    #[must_use]
802    pub fn start_rule(&self) -> Option<&GrammarRule> {
803        self.start
804            .as_deref()
805            .map_or_else(|| self.rules.first(), |start| self.rule(start))
806    }
807
808    /// Returns the source format, if known.
809    #[must_use]
810    pub const fn source_format(&self) -> Option<GrammarFormat> {
811        self.source_format
812    }
813
814    /// Returns rule names in source order.
815    #[must_use]
816    pub fn rule_names(&self) -> Vec<&str> {
817        self.rules.iter().map(GrammarRule::name).collect()
818    }
819
820    /// Returns non-terminal names referenced from every rule expression.
821    #[must_use]
822    pub fn referenced_nonterminals(&self) -> BTreeSet<String> {
823        let mut names = BTreeSet::new();
824        for rule in &self.rules {
825            rule.expr.collect_nonterminals(&mut names);
826        }
827        for extra in &self.declarations.extras {
828            extra.collect_nonterminals(&mut names);
829        }
830        for declared in &self.declarations.macros {
831            declared.expression.collect_nonterminals(&mut names);
832        }
833        for lexer in &self.declarations.lexers {
834            if let GrammarExpr::Sequence(entries) = &lexer.expression {
835                for entry in entries {
836                    if let GrammarExpr::Feature(feature) = entry {
837                        let role = feature_runtime::lexical_kernel::entry_form(feature.head());
838                        if (role == 1 || role == 2)
839                            && let FeatureExpr::Form(form) = &**feature
840                            && let Some(item) = form.expression("item")
841                        {
842                            item.collect_nonterminals(&mut names);
843                        }
844                    }
845                }
846            }
847        }
848        names
849    }
850
851    /// Returns referenced non-terminals that do not have a local rule.
852    #[must_use]
853    pub fn undefined_nonterminals(&self) -> BTreeSet<String> {
854        let defined = self
855            .rules
856            .iter()
857            .map(|rule| rule.name.clone())
858            .chain(
859                self.declarations
860                    .external_tokens()
861                    .into_iter()
862                    .map(str::to_owned),
863            )
864            .collect::<BTreeSet<_>>();
865        self.referenced_nonterminals()
866            .difference(&defined)
867            .cloned()
868            .collect()
869    }
870}
871
872/// Copies the documentation of every rule of `source` onto the rule of
873/// `target` that `rename` names it.
874///
875/// As the JavaScript `carryRuleDocs` does, a rule of `source` without
876/// documentation, or one `target` lacks, changes nothing.
877#[must_use]
878pub fn carry_rule_docs(
879    mut target: Grammar,
880    source: &Grammar,
881    rename: &dyn Fn(&str) -> String,
882) -> Grammar {
883    for rule in source.rules() {
884        let Some(doc) = &rule.doc else {
885            continue;
886        };
887        let name = rename(&rule.name);
888        for carried in target
889            .rules
890            .iter_mut()
891            .filter(|carried| carried.name == name)
892        {
893            carried.doc = Some(doc.clone());
894        }
895    }
896    target
897}
898
899fn write_joined(
900    formatter: &mut fmt::Formatter<'_>,
901    expressions: &[GrammarExpr],
902    separator: &str,
903) -> fmt::Result {
904    if let Some((first, rest)) = expressions.split_first() {
905        write!(formatter, "{first}")?;
906        for expression in rest {
907            formatter.write_str(separator)?;
908            write!(formatter, "{expression}")?;
909        }
910    }
911    Ok(())
912}