1use 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
23pub const GRAMMAR_ROUND_TRIP_MARKER: &str = "round-trip-mutation";
25
26pub type GrammarImportFn<'a> = &'a dyn Fn(&str) -> Result<Grammar, GrammarImportError>;
28
29pub type GrammarEmitFn<'a> = &'a dyn Fn(&Grammar) -> Result<(String, EmitReport), GrammarEmitError>;
31
32#[derive(Clone, Copy)]
34pub struct GrammarRoundTrip<'a> {
35 pub import: GrammarImportFn<'a>,
37 pub emit: GrammarEmitFn<'a>,
39 pub marker: &'a str,
41 pub accepts: &'a [String],
43 pub rejects: &'a [String],
45}
46
47impl<'a> GrammarRoundTrip<'a> {
48 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum GrammarRoundTripStatus {
73 Preserved,
75 Broken,
77}
78
79impl GrammarRoundTripStatus {
80 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum GrammarRoundTripFailureKind {
93 SampleRejected,
95 SampleAccepted,
97 MarkerAlreadyAccepted,
99 LossyExport,
101 MutationNotExported,
103 RulesChanged,
105 MutationNotVisible,
107 ExportNotStable,
109}
110
111impl GrammarRoundTripFailureKind {
112 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum GrammarRoundTripStage {
131 Imported,
133 Exported,
135 Reimported,
137}
138
139impl GrammarRoundTripStage {
140 #[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#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct GrammarRoundTripFailure {
154 pub kind: GrammarRoundTripFailureKind,
156 pub stage: GrammarRoundTripStage,
158 pub detail: String,
160}
161
162#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct GrammarRoundTripReport {
165 pub status: GrammarRoundTripStatus,
167 pub failures: Vec<GrammarRoundTripFailure>,
169 pub mutated: Grammar,
171 pub exported: String,
173 pub reimported: Grammar,
175}
176
177#[derive(Clone, Debug, PartialEq, Eq)]
179pub enum GrammarRoundTripError {
180 Import(GrammarImportError),
182 Emit(GrammarEmitError),
184 Normalize(GrammarMergeError),
186 MissingStartRule,
188 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
226pub 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
268pub 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
282pub 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 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
432pub 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#[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}