Skip to main content

meta_language/grammar/
round_trip.rs

1//! Mutation-guarded grammar interchange round trips.
2//!
3//! A plain round trip (import, emit, re-import, compare) cannot tell a correct
4//! importer/emitter pair from two that are wrong in mutually cancelling ways,
5//! and it cannot tell an emitter that re-emits a cached source from one that
6//! prints the grammar it was given. The guard therefore changes the grammar
7//! before export, requires the change in the exported text and in the
8//! re-imported grammar, and checks both the imported and the re-imported
9//! grammar against independent accept and reject samples that do not come
10//! from the pair under test. It mirrors `js/src/grammar-round-trip.js`.
11
12use std::error::Error;
13use std::fmt;
14
15mod lexical;
16
17use super::emit::{EmitReport, GrammarEmitError};
18use super::import::GrammarImportError;
19use super::merge::{GrammarMergeError, normalized_rule_definition};
20use super::runtime::GrammarParser;
21use super::{CharClassItem, Grammar, GrammarExpr, GrammarFormat, GrammarRule};
22
23/// The literal alternative the guard adds to the start rule by default.
24pub const GRAMMAR_ROUND_TRIP_MARKER: &str = "round-trip-mutation";
25
26/// Imports grammar source text of one notation.
27pub type GrammarImportFn<'a> = &'a dyn Fn(&str) -> Result<Grammar, GrammarImportError>;
28
29/// Emits a grammar in one notation, with its fidelity report.
30pub type GrammarEmitFn<'a> = &'a dyn Fn(&Grammar) -> Result<(String, EmitReport), GrammarEmitError>;
31
32/// The importer/emitter pair under test and the independent samples.
33#[derive(Clone, Copy)]
34pub struct GrammarRoundTrip<'a> {
35    /// Importer of the notation.
36    pub import: GrammarImportFn<'a>,
37    /// Emitter of the same notation.
38    pub emit: GrammarEmitFn<'a>,
39    /// Literal alternative added to the start rule before export.
40    pub marker: &'a str,
41    /// Texts the grammar must accept.
42    pub accepts: &'a [String],
43    /// Texts the grammar must reject.
44    pub rejects: &'a [String],
45}
46
47impl<'a> GrammarRoundTrip<'a> {
48    /// Builds a round trip through `import` and `emit` with the default
49    /// marker and no samples.
50    #[must_use]
51    pub const fn new(import: GrammarImportFn<'a>, emit: GrammarEmitFn<'a>) -> Self {
52        Self {
53            import,
54            emit,
55            marker: GRAMMAR_ROUND_TRIP_MARKER,
56            accepts: &[],
57            rejects: &[],
58        }
59    }
60
61    /// Returns this round trip with independent accept and reject samples.
62    #[must_use]
63    pub const fn with_samples(mut self, accepts: &'a [String], rejects: &'a [String]) -> Self {
64        self.accepts = accepts;
65        self.rejects = rejects;
66        self
67    }
68}
69
70/// Whether the pair carried the grammar and the mutation.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum GrammarRoundTripStatus {
73    /// Every check held.
74    Preserved,
75    /// At least one check failed.
76    Broken,
77}
78
79impl GrammarRoundTripStatus {
80    /// Stable tag shared with the JavaScript runtime.
81    #[must_use]
82    pub const fn as_str(self) -> &'static str {
83        match self {
84            Self::Preserved => "preserved",
85            Self::Broken => "broken",
86        }
87    }
88}
89
90/// What a failed check found.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum GrammarRoundTripFailureKind {
93    /// A text the grammar must accept was rejected.
94    SampleRejected,
95    /// A text the grammar must reject was accepted.
96    SampleAccepted,
97    /// The imported grammar already accepts the marker.
98    MarkerAlreadyAccepted,
99    /// The emitter reported a lossy conversion of the mutated grammar.
100    LossyExport,
101    /// The exported text does not carry the mutation.
102    MutationNotExported,
103    /// The re-imported rules differ from the mutated ones.
104    RulesChanged,
105    /// The re-imported grammar does not accept the marker.
106    MutationNotVisible,
107    /// A second export does not settle on the same rules and text.
108    ExportNotStable,
109}
110
111impl GrammarRoundTripFailureKind {
112    /// Stable tag shared with the JavaScript runtime.
113    #[must_use]
114    pub const fn as_str(self) -> &'static str {
115        match self {
116            Self::SampleRejected => "sample-rejected",
117            Self::SampleAccepted => "sample-accepted",
118            Self::MarkerAlreadyAccepted => "marker-already-accepted",
119            Self::LossyExport => "lossy-export",
120            Self::MutationNotExported => "mutation-not-exported",
121            Self::RulesChanged => "rules-changed",
122            Self::MutationNotVisible => "mutation-not-visible",
123            Self::ExportNotStable => "export-not-stable",
124        }
125    }
126}
127
128/// The grammar a failed check looked at.
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum GrammarRoundTripStage {
131    /// The grammar imported from the source.
132    Imported,
133    /// The exported text of the mutated grammar.
134    Exported,
135    /// The grammar re-imported from the exported text.
136    Reimported,
137}
138
139impl GrammarRoundTripStage {
140    /// Stable tag shared with the JavaScript runtime.
141    #[must_use]
142    pub const fn as_str(self) -> &'static str {
143        match self {
144            Self::Imported => "imported",
145            Self::Exported => "exported",
146            Self::Reimported => "reimported",
147        }
148    }
149}
150
151/// One failed check.
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct GrammarRoundTripFailure {
154    /// What the check found.
155    pub kind: GrammarRoundTripFailureKind,
156    /// The grammar it looked at.
157    pub stage: GrammarRoundTripStage,
158    /// The sample, marker, note or rule involved.
159    pub detail: String,
160}
161
162/// The outcome of [`check_grammar_round_trip`].
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct GrammarRoundTripReport {
165    /// Whether every check held.
166    pub status: GrammarRoundTripStatus,
167    /// Every failed check, in the order the guard ran them.
168    pub failures: Vec<GrammarRoundTripFailure>,
169    /// The imported grammar with the marker alternative.
170    pub mutated: Grammar,
171    /// The exported text of the mutated grammar.
172    pub exported: String,
173    /// The grammar re-imported from the exported text.
174    pub reimported: Grammar,
175}
176
177/// Why the guard could not run.
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub enum GrammarRoundTripError {
180    /// The importer rejected a source, such as a malformed grammar.
181    Import(GrammarImportError),
182    /// The emitter rejected a grammar.
183    Emit(GrammarEmitError),
184    /// A rule definition could not be normalized for comparison.
185    Normalize(GrammarMergeError),
186    /// The grammar has no start rule to mutate.
187    MissingStartRule,
188    /// A source-scoped lexical declaration cannot be extended faithfully.
189    LexicalDeclaration(String),
190}
191
192impl fmt::Display for GrammarRoundTripError {
193    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
194        match self {
195            Self::Import(error) => write!(formatter, "{error}"),
196            Self::Emit(error) => write!(formatter, "{error}"),
197            Self::Normalize(error) => write!(formatter, "{error}"),
198            Self::MissingStartRule => {
199                formatter.write_str("the grammar has no start rule to mutate")
200            }
201            Self::LexicalDeclaration(message) => formatter.write_str(message),
202        }
203    }
204}
205
206impl Error for GrammarRoundTripError {}
207
208impl From<GrammarImportError> for GrammarRoundTripError {
209    fn from(error: GrammarImportError) -> Self {
210        Self::Import(error)
211    }
212}
213
214impl From<GrammarEmitError> for GrammarRoundTripError {
215    fn from(error: GrammarEmitError) -> Self {
216        Self::Emit(error)
217    }
218}
219
220impl From<GrammarMergeError> for GrammarRoundTripError {
221    fn from(error: GrammarMergeError) -> Self {
222        Self::Normalize(error)
223    }
224}
225
226/// Adds `marker` as a literal alternative of the start rule.
227///
228/// PEG grammars get an ordered choice, every other notation an unordered one,
229/// so the mutation is expressible without a lossy fallback.
230pub fn mutate_grammar_start_rule(
231    grammar: &Grammar,
232    marker: &str,
233) -> Result<Grammar, GrammarRoundTripError> {
234    let start = grammar
235        .start_rule()
236        .ok_or(GrammarRoundTripError::MissingStartRule)?
237        .name
238        .clone();
239    let ordered = grammar.source_format() == Some(GrammarFormat::Peg);
240    let mut mutated = Grammar::new();
241    for rule in grammar.rules() {
242        let mut rule = rule.clone();
243        if rule.name == start {
244            rule.expr = GrammarExpr::Choice {
245                ordered,
246                alternatives: vec![rule.expr, GrammarExpr::Terminal(marker.to_owned())],
247            };
248        }
249        mutated.add_rule(rule);
250    }
251    if let Some(name) = grammar.start() {
252        mutated.set_start(name);
253    }
254    if let Some(format) = grammar.source_format() {
255        mutated.set_source_format(format);
256    }
257    mutated.set_kinds(grammar.kinds().to_vec());
258    let mut declarations = grammar.declarations().clone();
259    declarations.lexers = declarations
260        .lexers
261        .iter()
262        .map(|lexer| lexical::extend_literal(&mutated, lexer, &start, marker))
263        .collect::<Result<_, _>>()?;
264    mutated.set_declarations(declarations);
265    Ok(mutated)
266}
267
268/// Renders the full Links comparison under checked original-owner alpha-renaming.
269///
270/// # Errors
271///
272/// Refuses duplicate original owners, nonbijective actual public bindings and
273/// obligations whose labels cannot be separated from raw lexical rule names.
274pub fn render_grammar_lexical_owner_comparison(
275    grammar: &Grammar,
276) -> Result<String, GrammarRoundTripError> {
277    Ok(super::interchange::render_grammar_links(
278        &lexical::canonical_owners(grammar)?,
279    ))
280}
281
282/// Round trips `source` through a mutated export and reports every failure.
283///
284/// The grammar is imported, mutated, exported and re-imported, and every way
285/// the pair failed to carry the grammar and the mutation is reported.
286/// Malformed sources are rejected by the importer, whose error is returned.
287pub fn check_grammar_round_trip(
288    source: &str,
289    round_trip: &GrammarRoundTrip<'_>,
290) -> Result<GrammarRoundTripReport, GrammarRoundTripError> {
291    let mut failures = Vec::new();
292    let imported = (round_trip.import)(source)?;
293    check_samples(
294        &mut failures,
295        GrammarRoundTripStage::Imported,
296        &imported,
297        round_trip,
298    );
299    if accepts(&imported, round_trip.marker) {
300        failures.push(failure(
301            GrammarRoundTripFailureKind::MarkerAlreadyAccepted,
302            GrammarRoundTripStage::Imported,
303            round_trip.marker,
304        ));
305    }
306
307    let mutated = mutate_grammar_start_rule(&imported, round_trip.marker)?;
308    let (unmutated, _) = (round_trip.emit)(&imported)?;
309    let (exported, report) = (round_trip.emit)(&mutated)?;
310    for note in &report.lossy {
311        failures.push(failure(
312            GrammarRoundTripFailureKind::LossyExport,
313            GrammarRoundTripStage::Exported,
314            note,
315        ));
316    }
317    if exported == unmutated || !exported.contains(round_trip.marker) {
318        failures.push(failure(
319            GrammarRoundTripFailureKind::MutationNotExported,
320            GrammarRoundTripStage::Exported,
321            round_trip.marker,
322        ));
323    }
324
325    let reimported = (round_trip.import)(&exported)?;
326    compare_rules(&mut failures, &mutated, &reimported)?;
327    if !accepts(&reimported, round_trip.marker) {
328        failures.push(failure(
329            GrammarRoundTripFailureKind::MutationNotVisible,
330            GrammarRoundTripStage::Reimported,
331            round_trip.marker,
332        ));
333    }
334    check_samples(
335        &mut failures,
336        GrammarRoundTripStage::Reimported,
337        &reimported,
338        round_trip,
339    );
340    // A notation may print an equivalent construct differently once (ABNF has
341    // no character classes), so the second export must carry the same rules
342    // and be a fixpoint rather than repeat the first text.
343    let (again, _) = (round_trip.emit)(&reimported)?;
344    let settled = (round_trip.import)(&again)?;
345    if definitions(&mutated)? != definitions(&settled)? || (round_trip.emit)(&settled)?.0 != again {
346        failures.push(failure(
347            GrammarRoundTripFailureKind::ExportNotStable,
348            GrammarRoundTripStage::Reimported,
349            "a second export does not settle",
350        ));
351    }
352
353    Ok(GrammarRoundTripReport {
354        status: if failures.is_empty() {
355            GrammarRoundTripStatus::Preserved
356        } else {
357            GrammarRoundTripStatus::Broken
358        },
359        failures,
360        mutated,
361        exported,
362        reimported,
363    })
364}
365
366fn failure(
367    kind: GrammarRoundTripFailureKind,
368    stage: GrammarRoundTripStage,
369    detail: &str,
370) -> GrammarRoundTripFailure {
371    GrammarRoundTripFailure {
372        kind,
373        stage,
374        detail: detail.to_owned(),
375    }
376}
377
378fn compare_rules(
379    failures: &mut Vec<GrammarRoundTripFailure>,
380    expected: &Grammar,
381    actual: &Grammar,
382) -> Result<(), GrammarRoundTripError> {
383    let expected_names = expected.rule_names();
384    let actual_names = actual.rule_names();
385    if expected_names != actual_names {
386        failures.push(failure(
387            GrammarRoundTripFailureKind::RulesChanged,
388            GrammarRoundTripStage::Reimported,
389            &format!(
390                "rule names [{}] became [{}]",
391                expected_names.join(", "),
392                actual_names.join(", ")
393            ),
394        ));
395    }
396    let start = |grammar: &Grammar| grammar.start_rule().map(|rule| rule.name.clone());
397    if start(expected) != start(actual) {
398        failures.push(failure(
399            GrammarRoundTripFailureKind::RulesChanged,
400            GrammarRoundTripStage::Reimported,
401            "the start rule changed",
402        ));
403    }
404    for rule in expected.rules() {
405        if let Some(other) = actual.rule(&rule.name)
406            && canonical_rule_definition(other)? != canonical_rule_definition(rule)?
407        {
408            failures.push(failure(
409                GrammarRoundTripFailureKind::RulesChanged,
410                GrammarRoundTripStage::Reimported,
411                &format!("rule {} changed its definition", rule.name),
412            ));
413        }
414    }
415    Ok(())
416}
417
418fn definitions(grammar: &Grammar) -> Result<Vec<String>, GrammarRoundTripError> {
419    grammar
420        .rules()
421        .iter()
422        .map(|rule| {
423            Ok(format!(
424                "{}={}",
425                rule.name,
426                canonical_rule_definition(rule)?
427            ))
428        })
429        .collect()
430}
431
432/// The meaning-aware definition of a rule.
433///
434/// Every set of single characters is spelled as one unordered choice first: a
435/// character class, a choice of its ranges and an ordered choice of them all
436/// consume the same one character. Mirrors the JavaScript
437/// `canonicalRuleDefinition`.
438///
439/// # Errors
440///
441/// A [`GrammarRoundTripError`] when the rule does not normalize.
442pub fn canonical_rule_definition(rule: &GrammarRule) -> Result<String, GrammarRoundTripError> {
443    let canonical = GrammarRule {
444        expr: canonical_characters(&rule.expr),
445        ..rule.clone()
446    };
447    Ok(normalized_rule_definition(&canonical)?)
448}
449
450fn canonical_characters(expr: &GrammarExpr) -> GrammarExpr {
451    if let Some(mut set) = character_set(expr) {
452        return if set.len() == 1 {
453            set.remove(0)
454        } else {
455            GrammarExpr::Choice {
456                ordered: false,
457                alternatives: set,
458            }
459        };
460    }
461    let boxed = |inner: &GrammarExpr| Box::new(canonical_characters(inner));
462    match expr {
463        GrammarExpr::Choice {
464            ordered,
465            alternatives,
466        } => GrammarExpr::Choice {
467            ordered: *ordered,
468            alternatives: alternatives.iter().map(canonical_characters).collect(),
469        },
470        GrammarExpr::Sequence(items) => {
471            GrammarExpr::Sequence(items.iter().map(canonical_characters).collect())
472        }
473        GrammarExpr::Optional(inner) => GrammarExpr::Optional(boxed(inner)),
474        GrammarExpr::ZeroOrMore(inner) => GrammarExpr::ZeroOrMore(boxed(inner)),
475        GrammarExpr::OneOrMore(inner) => GrammarExpr::OneOrMore(boxed(inner)),
476        GrammarExpr::Repeat { expr, min, max } => GrammarExpr::Repeat {
477            expr: boxed(expr),
478            min: *min,
479            max: *max,
480        },
481        GrammarExpr::And(inner) => GrammarExpr::And(boxed(inner)),
482        GrammarExpr::Not(inner) => GrammarExpr::Not(boxed(inner)),
483        GrammarExpr::Capture { label, expr } => GrammarExpr::Capture {
484            label: label.clone(),
485            expr: boxed(expr),
486        },
487        other => other.clone(),
488    }
489}
490
491fn character_set(expr: &GrammarExpr) -> Option<Vec<GrammarExpr>> {
492    match expr {
493        GrammarExpr::Terminal(value) if value.chars().count() == 1 => Some(vec![expr.clone()]),
494        GrammarExpr::CharRange(..) => Some(vec![expr.clone()]),
495        GrammarExpr::CharClass {
496            negated: false,
497            items,
498        } => Some(
499            items
500                .iter()
501                .map(|item| match item {
502                    CharClassItem::Char(value) => GrammarExpr::Terminal(value.to_string()),
503                    CharClassItem::Range(start, end) => GrammarExpr::CharRange(*start, *end),
504                })
505                .collect(),
506        ),
507        GrammarExpr::Choice { alternatives, .. } => alternatives
508            .iter()
509            .map(character_set)
510            .collect::<Option<Vec<_>>>()
511            .map(|sets| sets.into_iter().flatten().collect()),
512        _ => None,
513    }
514}
515
516fn check_samples(
517    failures: &mut Vec<GrammarRoundTripFailure>,
518    stage: GrammarRoundTripStage,
519    grammar: &Grammar,
520    round_trip: &GrammarRoundTrip<'_>,
521) {
522    let parser = (grammar.source_format() != Some(GrammarFormat::Lark))
523        .then(|| GrammarParser::new(grammar.clone()));
524    let accepts = |text: &str| {
525        parser.as_ref().map_or_else(
526            || accepts_text(grammar, text),
527            |parser| parser.accepts(text),
528        )
529    };
530    for text in round_trip.accepts {
531        if !accepts(text) {
532            failures.push(failure(
533                GrammarRoundTripFailureKind::SampleRejected,
534                stage,
535                text,
536            ));
537        }
538    }
539    for text in round_trip.rejects {
540        if accepts(text) {
541            failures.push(failure(
542                GrammarRoundTripFailureKind::SampleAccepted,
543                stage,
544                text,
545            ));
546        }
547    }
548}
549
550/// Whether `text` parses with `grammar` on the native executor, as the
551/// JavaScript `acceptsText` does.
552#[must_use]
553pub fn accepts_text(grammar: &Grammar, text: &str) -> bool {
554    super::feature_runtime::parse_with_grammar(
555        grammar,
556        text.as_bytes(),
557        &super::feature_runtime::FeatureParseOptions::default(),
558    )
559    .is_ok()
560}
561
562fn accepts(grammar: &Grammar, text: &str) -> bool {
563    if grammar.source_format() == Some(GrammarFormat::Lark) {
564        accepts_text(grammar, text)
565    } else {
566        GrammarParser::new(grammar.clone()).accepts(text)
567    }
568}