1mod 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#[derive(Clone, Debug, PartialEq, Eq)]
171pub enum GrammarExpr {
172 Empty,
174 Terminal(String),
176 TerminalInsensitive(String),
178 CharRange(char, char),
180 CharClass {
182 negated: bool,
184 items: Vec<CharClassItem>,
186 },
187 AnyChar,
189 NonTerminal(String),
191 Choice {
193 ordered: bool,
195 alternatives: Vec<Self>,
197 },
198 Sequence(Vec<Self>),
200 Optional(Box<Self>),
202 ZeroOrMore(Box<Self>),
204 OneOrMore(Box<Self>),
206 Repeat {
208 expr: Box<Self>,
210 min: usize,
212 max: Option<usize>,
214 },
215 And(Box<Self>),
217 Not(Box<Self>),
219 Capture {
221 label: Option<String>,
223 expr: Box<Self>,
225 },
226 Feature(Box<FeatureExpr>),
228}
229
230impl GrammarExpr {
231 #[must_use]
233 pub const fn empty() -> Self {
234 Self::Empty
235 }
236
237 #[must_use]
239 pub fn terminal(value: impl Into<String>) -> Self {
240 Self::Terminal(value.into())
241 }
242
243 #[must_use]
245 pub fn terminal_insensitive(value: impl Into<String>) -> Self {
246 Self::TerminalInsensitive(value.into())
247 }
248
249 #[must_use]
251 pub const fn char_range(start: char, end: char) -> Self {
252 Self::CharRange(start, end)
253 }
254
255 #[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 #[must_use]
269 pub const fn any_char() -> Self {
270 Self::AnyChar
271 }
272
273 #[must_use]
275 pub fn non_terminal(value: impl Into<String>) -> Self {
276 Self::NonTerminal(value.into())
277 }
278
279 #[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 #[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 #[must_use]
302 pub fn optional(expr: Self) -> Self {
303 Self::Optional(Box::new(expr))
304 }
305
306 #[must_use]
308 pub fn zero_or_more(expr: Self) -> Self {
309 Self::ZeroOrMore(Box::new(expr))
310 }
311
312 #[must_use]
314 pub fn one_or_more(expr: Self) -> Self {
315 Self::OneOrMore(Box::new(expr))
316 }
317
318 #[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 #[must_use]
330 pub fn and(expr: Self) -> Self {
331 Self::And(Box::new(expr))
332 }
333
334 #[must_use]
336 #[allow(clippy::should_implement_trait)]
337 pub fn not(expr: Self) -> Self {
338 Self::Not(Box::new(expr))
339 }
340
341 #[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 #[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 #[must_use]
361 pub fn feature(feature: FeatureExpr) -> Self {
362 Self::Feature(Box::new(feature))
363 }
364
365 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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
480pub enum CharClassItem {
481 Char(char),
483 Range(char, char),
485}
486
487impl CharClassItem {
488 #[must_use]
490 pub const fn char(value: char) -> Self {
491 Self::Char(value)
492 }
493
494 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
519pub enum RuleKind {
520 Normal,
522 Atomic,
524 Silent,
526 Token,
528}
529
530impl RuleKind {
531 #[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#[derive(Clone, Debug, PartialEq, Eq)]
561pub struct GrammarRule {
562 pub name: String,
564 pub expr: GrammarExpr,
566 pub kind: RuleKind,
568 pub concept: Option<String>,
570 pub source_names: Vec<GrammarSourceName>,
572 pub doc: Option<String>,
574 pub attributes: RuleAttributes,
576}
577
578impl GrammarRule {
579 #[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 #[must_use]
595 pub fn with_attributes(mut self, attributes: RuleAttributes) -> Self {
596 self.attributes = attributes;
597 self
598 }
599
600 #[must_use]
602 pub const fn with_kind(mut self, kind: RuleKind) -> Self {
603 self.kind = kind;
604 self
605 }
606
607 #[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 #[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 #[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 #[must_use]
631 pub fn name(&self) -> &str {
632 &self.name
633 }
634
635 #[must_use]
637 pub const fn expr(&self) -> &GrammarExpr {
638 &self.expr
639 }
640
641 #[must_use]
643 pub const fn kind(&self) -> RuleKind {
644 self.kind
645 }
646
647 #[must_use]
649 pub fn concept(&self) -> Option<&str> {
650 self.concept.as_deref()
651 }
652
653 #[must_use]
655 pub fn source_names(&self) -> &[GrammarSourceName] {
656 &self.source_names
657 }
658
659 #[must_use]
661 pub fn doc(&self) -> Option<&str> {
662 self.doc.as_deref()
663 }
664}
665
666#[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 #[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 #[must_use]
702 pub const fn builder() -> GrammarBuilder {
703 GrammarBuilder::new()
704 }
705
706 #[must_use]
708 pub const fn expr() -> ExprBuilder {
709 ExprBuilder
710 }
711
712 #[must_use]
714 pub fn with_rule(mut self, rule: GrammarRule) -> Self {
715 self.rules.push(rule);
716 self
717 }
718
719 #[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 #[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 #[must_use]
735 pub fn with_declarations(mut self, declarations: GrammarDeclarations) -> Self {
736 self.declarations = declarations;
737 self
738 }
739
740 #[must_use]
742 pub const fn declarations(&self) -> &GrammarDeclarations {
743 &self.declarations
744 }
745
746 pub fn set_declarations(&mut self, declarations: GrammarDeclarations) {
748 self.declarations = declarations;
749 }
750
751 #[must_use]
753 pub fn kinds(&self) -> &[GrammarKind] {
754 &self.kinds
755 }
756
757 pub fn set_kinds(&mut self, kinds: Vec<GrammarKind>) {
759 self.kinds = kinds;
760 }
761
762 pub fn add_rule(&mut self, rule: GrammarRule) {
764 self.rules.push(rule);
765 }
766
767 pub fn set_start(&mut self, start: impl Into<String>) {
769 self.start = Some(start.into());
770 }
771
772 pub fn clear_start(&mut self) {
774 self.start = None;
775 }
776
777 pub const fn set_source_format(&mut self, source_format: GrammarFormat) {
779 self.source_format = Some(source_format);
780 }
781
782 #[must_use]
784 pub fn rules(&self) -> &[GrammarRule] {
785 &self.rules
786 }
787
788 #[must_use]
790 pub fn rule(&self, name: &str) -> Option<&GrammarRule> {
791 self.rules.iter().find(|rule| rule.name == name)
792 }
793
794 #[must_use]
796 pub fn start(&self) -> Option<&str> {
797 self.start.as_deref()
798 }
799
800 #[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 #[must_use]
810 pub const fn source_format(&self) -> Option<GrammarFormat> {
811 self.source_format
812 }
813
814 #[must_use]
816 pub fn rule_names(&self) -> Vec<&str> {
817 self.rules.iter().map(GrammarRule::name).collect()
818 }
819
820 #[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 #[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#[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}