1use std::cell::Cell;
30use std::collections::HashMap;
31
32use crate::peg::{Grammar, Peg};
33use crate::{BuildError, Diagnostic};
34
35pub mod codes {
37 pub const NO_FINITE_DERIVATION: &str = "dsl_kit::example_gen::no_finite_derivation";
40 pub const UNKNOWN_RULE: &str = "dsl_kit::example_gen::unknown_rule";
42}
43
44pub const COMPOSITE_DEPTH: u32 = 2;
48
49#[derive(Debug, Clone)]
51pub struct RuleExample {
52 pub rule: String,
54 pub text: String,
56}
57
58#[derive(Debug, Clone)]
60pub struct GrammarExamples {
61 pub per_rule: Vec<RuleExample>,
65 pub composite: String,
68}
69
70pub fn examples_from_grammar(grammar: &Grammar) -> Result<GrammarExamples, BuildError> {
76 let synth = Synth::prepare(grammar)?;
77
78 let mut underivable = Vec::new();
79 for (name, _) in &synth.rules_in_order {
80 if synth.rule_cost(name) == INFINITE {
81 underivable.push(Diagnostic::error(
82 codes::NO_FINITE_DERIVATION,
83 format!("rule `{name}` has no finite derivation — no example input exists"),
84 ));
85 }
86 }
87 if !underivable.is_empty() {
88 return Err(BuildError::new(underivable));
89 }
90
91 let mut per_rule = Vec::new();
92 for (name, body) in &synth.rules_in_order {
93 if *name == grammar.start {
94 continue;
95 }
96 if name == crate::import::IMPORT_VARIANT {
101 continue;
102 }
103 let mut tokens = Vec::new();
104 synth.emit(body, 0, &mut tokens)?;
105 per_rule.push(RuleExample {
106 rule: name.clone(),
107 text: render(&tokens),
108 });
109 }
110
111 let start_body = synth.rule_body(&grammar.start)?;
112 let mut tokens = Vec::new();
113 synth.emit(start_body, COMPOSITE_DEPTH, &mut tokens)?;
114 let composite = render(&tokens);
115
116 Ok(GrammarExamples {
117 per_rule,
118 composite,
119 })
120}
121
122const INFINITE: u64 = u64::MAX;
124
125struct Synth<'g> {
126 by_name: HashMap<&'g str, &'g Peg>,
128 rules_in_order: Vec<(String, &'g Peg)>,
130 costs: HashMap<String, u64>,
132 key_seq: Cell<u32>,
138}
139
140impl<'g> Synth<'g> {
141 fn prepare(grammar: &'g Grammar) -> Result<Self, BuildError> {
142 let mut by_name = HashMap::new();
143 let mut rules_in_order = Vec::new();
144 for r in &grammar.rules {
145 if let Peg::Rule { name, body, .. } = r {
146 by_name.insert(name.as_str(), body.as_ref());
147 rules_in_order.push((name.clone(), body.as_ref()));
148 }
149 }
150
151 let mut costs: HashMap<String, u64> = rules_in_order
155 .iter()
156 .map(|(n, _)| (n.clone(), INFINITE))
157 .collect();
158 loop {
159 let mut changed = false;
160 for (name, body) in &rules_in_order {
161 let c = peg_cost(body, &costs);
162 if c < costs[name] {
163 costs.insert(name.clone(), c);
164 changed = true;
165 }
166 }
167 if !changed {
168 break;
169 }
170 }
171
172 Ok(Self {
173 by_name,
174 rules_in_order,
175 costs,
176 key_seq: Cell::new(0),
177 })
178 }
179
180 fn rule_cost(&self, name: &str) -> u64 {
181 self.costs.get(name).copied().unwrap_or(INFINITE)
182 }
183
184 fn rule_body(&self, name: &str) -> Result<&'g Peg, BuildError> {
185 self.by_name.get(name).copied().ok_or_else(|| {
186 BuildError::single(Diagnostic::error(
187 codes::UNKNOWN_RULE,
188 format!("reference to undefined rule `{name}`"),
189 ))
190 })
191 }
192
193 fn emit(&self, peg: &Peg, rich_depth: u32, out: &mut Vec<String>) -> Result<(), BuildError> {
197 match peg {
198 Peg::Token { pat, .. } => {
199 out.push(token_input(pat));
200 Ok(())
201 }
202 Peg::Seq { items, .. } => {
203 for item in items {
204 self.emit(item, rich_depth, out)?;
205 }
206 Ok(())
207 }
208 Peg::Choice { alts, .. } => {
209 let arm = self.pick_arm(alts, rich_depth)?;
210 self.emit(arm, rich_depth, out)
211 }
212 Peg::Repeat { body, min, max, .. } => {
213 let count = if rich_depth > 0 {
214 (*min).max(2.min(max.unwrap_or(2)))
215 } else {
216 *min
217 };
218 for _ in 0..count {
219 self.emit(body, rich_depth, out)?;
220 }
221 Ok(())
222 }
223 Peg::RuleRef { name, .. } => {
224 let body = self.rule_body(name)?;
225 self.emit(body, rich_depth.saturating_sub(1), out)
226 }
227 Peg::Rule { body, .. } | Peg::Node { body, .. } | Peg::Field { body, .. } => {
228 self.emit(body, rich_depth, out)
229 }
230 Peg::KeyedEntry { key, value, .. } => {
242 let n = self.key_seq.get() + 1;
243 self.key_seq.set(n);
244 self.emit_key(key, n, rich_depth, out)?;
245 self.emit(value, rich_depth, out)
246 }
247 }
248 }
249
250 fn emit_key(
259 &self,
260 peg: &Peg,
261 n: u32,
262 rich_depth: u32,
263 out: &mut Vec<String>,
264 ) -> Result<(), BuildError> {
265 match peg {
266 Peg::Token { pat, .. } => {
267 out.push(keyed_token_input(pat, n));
268 Ok(())
269 }
270 Peg::Seq { items, .. } => {
271 for item in items {
272 self.emit_key(item, n, rich_depth, out)?;
273 }
274 Ok(())
275 }
276 Peg::Choice { alts, .. } => {
277 let arm = self.pick_arm(alts, rich_depth)?;
278 self.emit_key(arm, n, rich_depth, out)
279 }
280 other => self.emit(other, rich_depth, out),
281 }
282 }
283
284 fn pick_arm<'p>(&self, alts: &'p [Peg], rich_depth: u32) -> Result<&'p Peg, BuildError> {
291 let finite = alts
292 .iter()
293 .filter(|a| !is_import_arm(a))
294 .map(|a| (a, peg_cost(a, &self.costs)))
295 .filter(|(_, c)| *c != INFINITE);
296 let picked = if rich_depth > 0 {
297 finite.max_by_key(|(_, c)| *c)
298 } else {
299 finite.min_by_key(|(_, c)| *c)
300 };
301 picked.map(|(a, _)| a).ok_or_else(|| {
302 BuildError::single(Diagnostic::error(
303 codes::NO_FINITE_DERIVATION,
304 "choice has no finite alternative".to_string(),
305 ))
306 })
307 }
308}
309
310fn is_import_arm(peg: &Peg) -> bool {
313 match peg {
314 Peg::RuleRef { name, .. } => name == crate::import::IMPORT_VARIANT,
315 Peg::Node { variant, .. } => variant == crate::import::IMPORT_VARIANT,
316 _ => false,
317 }
318}
319
320fn peg_cost(peg: &Peg, costs: &HashMap<String, u64>) -> u64 {
323 match peg {
324 Peg::Token { .. } => 1,
325 Peg::Seq { items, .. } => items
326 .iter()
327 .try_fold(0u64, |acc, i| {
328 let c = peg_cost(i, costs);
329 if c == INFINITE {
330 None
331 } else {
332 Some(acc.saturating_add(c))
333 }
334 })
335 .unwrap_or(INFINITE),
336 Peg::Choice { alts, .. } => alts
337 .iter()
338 .map(|a| peg_cost(a, costs))
339 .min()
340 .unwrap_or(INFINITE),
341 Peg::Repeat { body, min, .. } => {
342 if *min == 0 {
343 0
344 } else {
345 let c = peg_cost(body, costs);
346 if c == INFINITE {
347 INFINITE
348 } else {
349 c.saturating_mul(u64::from(*min))
350 }
351 }
352 }
353 Peg::RuleRef { name, .. } => costs.get(name).copied().unwrap_or(INFINITE),
354 Peg::Rule { body, .. } | Peg::Node { body, .. } | Peg::Field { body, .. } => {
355 peg_cost(body, costs)
356 }
357 Peg::KeyedEntry { key, value, .. } => {
360 let (k, v) = (peg_cost(key, costs), peg_cost(value, costs));
361 if k == INFINITE || v == INFINITE {
362 INFINITE
363 } else {
364 k.saturating_add(v)
365 }
366 }
367 }
368}
369
370fn keyed_token_input(pat: &str, n: u32) -> String {
376 match pat {
377 "%str" => format!("\"key{n}\""),
378 "%ident" => format!("key{n}"),
379 other => token_input(other),
380 }
381}
382
383fn token_input(pat: &str) -> String {
385 if let Some(kw) = pat.strip_prefix("%kw:") {
386 return kw.to_string();
387 }
388 match pat {
389 "%int" => "1".to_string(),
390 "%str" => "\"example\"".to_string(),
391 "%ident" => "x".to_string(),
392 "%ws" => " ".to_string(),
393 literal => literal.to_string(),
394 }
395}
396
397fn render(tokens: &[String]) -> String {
401 let mut out = String::new();
402 for t in tokens {
403 let tight_before = matches!(t.as_str(), "," | ")" | "]" | "}" | ":" | "(");
404 let tight_after_prev = out.ends_with('(') || out.ends_with('[') || out.ends_with('{');
405 if !out.is_empty() && !tight_before && !tight_after_prev {
406 out.push(' ');
407 }
408 out.push_str(t);
409 }
410 out
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use crate::check_conformance;
417 use crate::schema_gen::checked_grammar_from_schema;
418 use dsl_kit_core::IdGen;
419 use dsl_kit_schema::{
420 ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, VariantSchema,
421 };
422
423 fn demo_schema() -> NodeSchema {
426 NodeSchema {
427 name: "Expr".into(),
428 variants: vec![
429 VariantSchema {
430 name: "Lit".into(),
431 fields: vec![FieldSchema {
432 name: "value".into(),
433 ty: "i64".into(),
434 optional: false,
435 }],
436 children: vec![],
437 },
438 VariantSchema {
439 name: "Name".into(),
440 fields: vec![
441 FieldSchema {
442 name: "text".into(),
443 ty: "String".into(),
444 optional: false,
445 },
446 FieldSchema {
447 name: "quoted".into(),
448 ty: "bool".into(),
449 optional: false,
450 },
451 ],
452 children: vec![],
453 },
454 VariantSchema {
455 name: "Add".into(),
456 fields: vec![],
457 children: vec![
458 ChildSchema {
459 name: "lhs".into(),
460 multiplicity: Multiplicity::One,
461 value_shape: ChildValueShape::Recursive,
462 scalar_shorthands: vec![],
463 },
464 ChildSchema {
465 name: "rhs".into(),
466 multiplicity: Multiplicity::One,
467 value_shape: ChildValueShape::Recursive,
468 scalar_shorthands: vec![],
469 },
470 ],
471 },
472 VariantSchema {
473 name: "Neg".into(),
474 fields: vec![],
475 children: vec![ChildSchema {
476 name: "body".into(),
477 multiplicity: Multiplicity::Optional,
478 value_shape: ChildValueShape::Recursive,
479 scalar_shorthands: vec![],
480 }],
481 },
482 VariantSchema {
483 name: "List".into(),
484 fields: vec![],
485 children: vec![ChildSchema {
486 name: "items".into(),
487 multiplicity: Multiplicity::Many,
488 value_shape: ChildValueShape::Recursive,
489 scalar_shorthands: vec![],
490 }],
491 },
492 VariantSchema {
493 name: "Env".into(),
494 fields: vec![],
495 children: vec![ChildSchema {
496 name: "entries".into(),
497 multiplicity: Multiplicity::Map,
498 value_shape: ChildValueShape::Recursive,
499 scalar_shorthands: vec![],
500 }],
501 },
502 VariantSchema {
503 name: "Unit".into(),
504 fields: vec![],
505 children: vec![],
506 },
507 ],
508 }
509 }
510
511 fn demo_examples() -> (Grammar, GrammarExamples) {
512 let g = checked_grammar_from_schema(&demo_schema(), &IdGen::new())
513 .expect("demo schema generates");
514 let ex = examples_from_grammar(&g).expect("examples synthesize");
515 (g, ex)
516 }
517
518 #[test]
519 fn every_per_rule_example_parses_as_its_own_variant() {
520 let (g, ex) = demo_examples();
521 assert_eq!(ex.per_rule.len(), 7, "one example per variant");
522 for e in &ex.per_rule {
523 let tree = g.parse(&e.text).unwrap_or_else(|err| {
524 panic!(
525 "example for `{}` failed to parse: {:?}\n text: {}",
526 e.rule, err.diagnostics, e.text
527 )
528 });
529 assert_eq!(tree.variant, e.rule, "example enters at its own variant");
530 let diags = check_conformance(&tree, &demo_schema());
531 assert!(
532 diags.is_empty(),
533 "conformance clean for {}: {diags:?}",
534 e.rule
535 );
536 }
537 }
538
539 #[test]
540 fn minimal_examples_have_the_expected_spellings() {
541 let (_, ex) = demo_examples();
542 let by_rule: HashMap<&str, &str> = ex
543 .per_rule
544 .iter()
545 .map(|e| (e.rule.as_str(), e.text.as_str()))
546 .collect();
547 assert_eq!(by_rule["Lit"], "Lit(value: 1)");
548 assert_eq!(by_rule["Name"], "Name(text: \"example\", quoted: true)");
549 assert_eq!(
550 by_rule["Add"], "Add(lhs: Unit(), rhs: Unit())",
551 "nested slots fill with the cheapest variant"
552 );
553 assert_eq!(
554 by_rule["Neg"], "Neg(body: none)",
555 "Optional minimal = absent"
556 );
557 assert_eq!(
558 by_rule["List"], "List(items: [])",
559 "Many minimal = empty list"
560 );
561 assert_eq!(
562 by_rule["Env"], "Env(entries: {})",
563 "Map minimal = empty map, braces tight like the empty list"
564 );
565 assert_eq!(by_rule["Unit"], "Unit()");
566 }
567
568 #[test]
574 fn rich_keyed_map_example_uses_distinct_keys() {
575 let map_only = NodeSchema {
576 name: "Cfg".into(),
577 variants: vec![
578 VariantSchema {
579 name: "Env".into(),
580 fields: vec![],
581 children: vec![ChildSchema {
582 name: "entries".into(),
583 multiplicity: Multiplicity::Map,
584 value_shape: ChildValueShape::Recursive,
585 scalar_shorthands: vec![],
586 }],
587 },
588 VariantSchema {
589 name: "Unit".into(),
590 fields: vec![],
591 children: vec![],
592 },
593 ],
594 };
595 let g = checked_grammar_from_schema(&map_only, &IdGen::new()).expect("generates");
596 let ex = examples_from_grammar(&g).expect("synthesizes");
597
598 let tree = g.parse(&ex.composite).unwrap_or_else(|err| {
599 panic!(
600 "composite failed to parse: {:?}\n text: {}",
601 err.diagnostics, ex.composite
602 )
603 });
604 let entries = tree
605 .keyed_child_slot("entries")
606 .expect("rich mode fills the keyed slot");
607 assert!(
608 entries.len() >= 2,
609 "rich mode should expand the map: {}",
610 ex.composite
611 );
612 let diags = check_conformance(&tree, &map_only);
613 assert!(
614 diags.is_empty(),
615 "synthesized example must conform: {diags:?}\n text: {}",
616 ex.composite
617 );
618 }
619
620 #[test]
624 fn keyed_entry_inherits_an_underivable_value() {
625 let ids = IdGen::new();
626 use crate::peg::{keyed_entry, node, rule, rule_ref, token};
629 let entry = keyed_entry(&ids, "entries", token(&ids, "%ident"), rule_ref(&ids, "s"));
630 let g = Grammar::new(vec![rule(&ids, "s", node(&ids, "N", entry))], "s");
631 let err = examples_from_grammar(&g).expect_err("no finite derivation exists");
632 assert!(
633 err.diagnostics
634 .iter()
635 .any(|d| d.code == codes::NO_FINITE_DERIVATION),
636 "expected NO_FINITE_DERIVATION; got {:?}",
637 err.diagnostics
638 .iter()
639 .map(|d| d.code.as_str())
640 .collect::<Vec<_>>()
641 );
642 }
643
644 #[test]
645 fn composite_parses_and_shows_nesting() {
646 let (g, ex) = demo_examples();
647 let tree = g.parse(&ex.composite).unwrap_or_else(|err| {
648 panic!(
649 "composite failed to parse: {:?}\n text: {}",
650 err.diagnostics, ex.composite
651 )
652 });
653 assert!(check_conformance(&tree, &demo_schema()).is_empty());
654 assert!(
657 !tree.children.is_empty(),
658 "composite has child structure: {}",
659 ex.composite
660 );
661 }
662
663 #[test]
664 fn underivable_rules_fail_loudly_with_the_full_list() {
665 let schema = NodeSchema {
668 name: "Loop".into(),
669 variants: vec![VariantSchema {
670 name: "Rec".into(),
671 fields: vec![],
672 children: vec![ChildSchema {
673 name: "inner".into(),
674 multiplicity: Multiplicity::One,
675 value_shape: ChildValueShape::Recursive,
676 scalar_shorthands: vec![],
677 }],
678 }],
679 };
680 let g = crate::schema_gen::grammar_from_schema(&schema, &IdGen::new())
681 .expect("generation itself succeeds");
682 let err = examples_from_grammar(&g).expect_err("no finite derivation");
683 assert!(
684 err.diagnostics
685 .iter()
686 .all(|d| d.code == codes::NO_FINITE_DERIVATION),
687 "{:?}",
688 err.diagnostics
689 );
690 assert_eq!(err.diagnostics.len(), 2);
692 }
693}