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 let mut tokens = Vec::new();
97 synth.emit(body, 0, &mut tokens)?;
98 per_rule.push(RuleExample {
99 rule: name.clone(),
100 text: render(&tokens),
101 });
102 }
103
104 let start_body = synth.rule_body(&grammar.start)?;
105 let mut tokens = Vec::new();
106 synth.emit(start_body, COMPOSITE_DEPTH, &mut tokens)?;
107 let composite = render(&tokens);
108
109 Ok(GrammarExamples {
110 per_rule,
111 composite,
112 })
113}
114
115const INFINITE: u64 = u64::MAX;
117
118struct Synth<'g> {
119 by_name: HashMap<&'g str, &'g Peg>,
121 rules_in_order: Vec<(String, &'g Peg)>,
123 costs: HashMap<String, u64>,
125 key_seq: Cell<u32>,
131}
132
133impl<'g> Synth<'g> {
134 fn prepare(grammar: &'g Grammar) -> Result<Self, BuildError> {
135 let mut by_name = HashMap::new();
136 let mut rules_in_order = Vec::new();
137 for r in &grammar.rules {
138 if let Peg::Rule { name, body, .. } = r {
139 by_name.insert(name.as_str(), body.as_ref());
140 rules_in_order.push((name.clone(), body.as_ref()));
141 }
142 }
143
144 let mut costs: HashMap<String, u64> = rules_in_order
148 .iter()
149 .map(|(n, _)| (n.clone(), INFINITE))
150 .collect();
151 loop {
152 let mut changed = false;
153 for (name, body) in &rules_in_order {
154 let c = peg_cost(body, &costs);
155 if c < costs[name] {
156 costs.insert(name.clone(), c);
157 changed = true;
158 }
159 }
160 if !changed {
161 break;
162 }
163 }
164
165 Ok(Self {
166 by_name,
167 rules_in_order,
168 costs,
169 key_seq: Cell::new(0),
170 })
171 }
172
173 fn rule_cost(&self, name: &str) -> u64 {
174 self.costs.get(name).copied().unwrap_or(INFINITE)
175 }
176
177 fn rule_body(&self, name: &str) -> Result<&'g Peg, BuildError> {
178 self.by_name.get(name).copied().ok_or_else(|| {
179 BuildError::single(Diagnostic::error(
180 codes::UNKNOWN_RULE,
181 format!("reference to undefined rule `{name}`"),
182 ))
183 })
184 }
185
186 fn emit(&self, peg: &Peg, rich_depth: u32, out: &mut Vec<String>) -> Result<(), BuildError> {
190 match peg {
191 Peg::Token { pat, .. } => {
192 out.push(token_input(pat));
193 Ok(())
194 }
195 Peg::Seq { items, .. } => {
196 for item in items {
197 self.emit(item, rich_depth, out)?;
198 }
199 Ok(())
200 }
201 Peg::Choice { alts, .. } => {
202 let arm = self.pick_arm(alts, rich_depth)?;
203 self.emit(arm, rich_depth, out)
204 }
205 Peg::Repeat { body, min, max, .. } => {
206 let count = if rich_depth > 0 {
207 (*min).max(2.min(max.unwrap_or(2)))
208 } else {
209 *min
210 };
211 for _ in 0..count {
212 self.emit(body, rich_depth, out)?;
213 }
214 Ok(())
215 }
216 Peg::RuleRef { name, .. } => {
217 let body = self.rule_body(name)?;
218 self.emit(body, rich_depth.saturating_sub(1), out)
219 }
220 Peg::Rule { body, .. } | Peg::Node { body, .. } | Peg::Field { body, .. } => {
221 self.emit(body, rich_depth, out)
222 }
223 Peg::KeyedEntry { key, value, .. } => {
235 let n = self.key_seq.get() + 1;
236 self.key_seq.set(n);
237 self.emit_key(key, n, rich_depth, out)?;
238 self.emit(value, rich_depth, out)
239 }
240 }
241 }
242
243 fn emit_key(
252 &self,
253 peg: &Peg,
254 n: u32,
255 rich_depth: u32,
256 out: &mut Vec<String>,
257 ) -> Result<(), BuildError> {
258 match peg {
259 Peg::Token { pat, .. } => {
260 out.push(keyed_token_input(pat, n));
261 Ok(())
262 }
263 Peg::Seq { items, .. } => {
264 for item in items {
265 self.emit_key(item, n, rich_depth, out)?;
266 }
267 Ok(())
268 }
269 Peg::Choice { alts, .. } => {
270 let arm = self.pick_arm(alts, rich_depth)?;
271 self.emit_key(arm, n, rich_depth, out)
272 }
273 other => self.emit(other, rich_depth, out),
274 }
275 }
276
277 fn pick_arm<'p>(&self, alts: &'p [Peg], rich_depth: u32) -> Result<&'p Peg, BuildError> {
280 let finite = alts
281 .iter()
282 .map(|a| (a, peg_cost(a, &self.costs)))
283 .filter(|(_, c)| *c != INFINITE);
284 let picked = if rich_depth > 0 {
285 finite.max_by_key(|(_, c)| *c)
286 } else {
287 finite.min_by_key(|(_, c)| *c)
288 };
289 picked.map(|(a, _)| a).ok_or_else(|| {
290 BuildError::single(Diagnostic::error(
291 codes::NO_FINITE_DERIVATION,
292 "choice has no finite alternative".to_string(),
293 ))
294 })
295 }
296}
297
298fn peg_cost(peg: &Peg, costs: &HashMap<String, u64>) -> u64 {
301 match peg {
302 Peg::Token { .. } => 1,
303 Peg::Seq { items, .. } => items
304 .iter()
305 .try_fold(0u64, |acc, i| {
306 let c = peg_cost(i, costs);
307 if c == INFINITE {
308 None
309 } else {
310 Some(acc.saturating_add(c))
311 }
312 })
313 .unwrap_or(INFINITE),
314 Peg::Choice { alts, .. } => alts
315 .iter()
316 .map(|a| peg_cost(a, costs))
317 .min()
318 .unwrap_or(INFINITE),
319 Peg::Repeat { body, min, .. } => {
320 if *min == 0 {
321 0
322 } else {
323 let c = peg_cost(body, costs);
324 if c == INFINITE {
325 INFINITE
326 } else {
327 c.saturating_mul(u64::from(*min))
328 }
329 }
330 }
331 Peg::RuleRef { name, .. } => costs.get(name).copied().unwrap_or(INFINITE),
332 Peg::Rule { body, .. } | Peg::Node { body, .. } | Peg::Field { body, .. } => {
333 peg_cost(body, costs)
334 }
335 Peg::KeyedEntry { key, value, .. } => {
338 let (k, v) = (peg_cost(key, costs), peg_cost(value, costs));
339 if k == INFINITE || v == INFINITE {
340 INFINITE
341 } else {
342 k.saturating_add(v)
343 }
344 }
345 }
346}
347
348fn keyed_token_input(pat: &str, n: u32) -> String {
354 match pat {
355 "%str" => format!("\"key{n}\""),
356 "%ident" => format!("key{n}"),
357 other => token_input(other),
358 }
359}
360
361fn token_input(pat: &str) -> String {
363 if let Some(kw) = pat.strip_prefix("%kw:") {
364 return kw.to_string();
365 }
366 match pat {
367 "%int" => "1".to_string(),
368 "%str" => "\"example\"".to_string(),
369 "%ident" => "x".to_string(),
370 "%ws" => " ".to_string(),
371 literal => literal.to_string(),
372 }
373}
374
375fn render(tokens: &[String]) -> String {
379 let mut out = String::new();
380 for t in tokens {
381 let tight_before = matches!(t.as_str(), "," | ")" | "]" | "}" | ":" | "(");
382 let tight_after_prev = out.ends_with('(') || out.ends_with('[') || out.ends_with('{');
383 if !out.is_empty() && !tight_before && !tight_after_prev {
384 out.push(' ');
385 }
386 out.push_str(t);
387 }
388 out
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394 use crate::check_conformance;
395 use crate::schema_gen::checked_grammar_from_schema;
396 use dsl_kit_core::IdGen;
397 use dsl_kit_schema::{ChildSchema, FieldSchema, Multiplicity, NodeSchema, VariantSchema};
398
399 fn demo_schema() -> NodeSchema {
402 NodeSchema {
403 name: "Expr".into(),
404 variants: vec![
405 VariantSchema {
406 name: "Lit".into(),
407 fields: vec![FieldSchema {
408 name: "value".into(),
409 ty: "i64".into(),
410 optional: false,
411 }],
412 children: vec![],
413 },
414 VariantSchema {
415 name: "Name".into(),
416 fields: vec![
417 FieldSchema {
418 name: "text".into(),
419 ty: "String".into(),
420 optional: false,
421 },
422 FieldSchema {
423 name: "quoted".into(),
424 ty: "bool".into(),
425 optional: false,
426 },
427 ],
428 children: vec![],
429 },
430 VariantSchema {
431 name: "Add".into(),
432 fields: vec![],
433 children: vec![
434 ChildSchema {
435 name: "lhs".into(),
436 multiplicity: Multiplicity::One,
437 },
438 ChildSchema {
439 name: "rhs".into(),
440 multiplicity: Multiplicity::One,
441 },
442 ],
443 },
444 VariantSchema {
445 name: "Neg".into(),
446 fields: vec![],
447 children: vec![ChildSchema {
448 name: "body".into(),
449 multiplicity: Multiplicity::Optional,
450 }],
451 },
452 VariantSchema {
453 name: "List".into(),
454 fields: vec![],
455 children: vec![ChildSchema {
456 name: "items".into(),
457 multiplicity: Multiplicity::Many,
458 }],
459 },
460 VariantSchema {
461 name: "Env".into(),
462 fields: vec![],
463 children: vec![ChildSchema {
464 name: "entries".into(),
465 multiplicity: Multiplicity::Map,
466 }],
467 },
468 VariantSchema {
469 name: "Unit".into(),
470 fields: vec![],
471 children: vec![],
472 },
473 ],
474 }
475 }
476
477 fn demo_examples() -> (Grammar, GrammarExamples) {
478 let g = checked_grammar_from_schema(&demo_schema(), &IdGen::new())
479 .expect("demo schema generates");
480 let ex = examples_from_grammar(&g).expect("examples synthesize");
481 (g, ex)
482 }
483
484 #[test]
485 fn every_per_rule_example_parses_as_its_own_variant() {
486 let (g, ex) = demo_examples();
487 assert_eq!(ex.per_rule.len(), 7, "one example per variant");
488 for e in &ex.per_rule {
489 let tree = g.parse(&e.text).unwrap_or_else(|err| {
490 panic!(
491 "example for `{}` failed to parse: {:?}\n text: {}",
492 e.rule, err.diagnostics, e.text
493 )
494 });
495 assert_eq!(tree.variant, e.rule, "example enters at its own variant");
496 let diags = check_conformance(&tree, &demo_schema());
497 assert!(
498 diags.is_empty(),
499 "conformance clean for {}: {diags:?}",
500 e.rule
501 );
502 }
503 }
504
505 #[test]
506 fn minimal_examples_have_the_expected_spellings() {
507 let (_, ex) = demo_examples();
508 let by_rule: HashMap<&str, &str> = ex
509 .per_rule
510 .iter()
511 .map(|e| (e.rule.as_str(), e.text.as_str()))
512 .collect();
513 assert_eq!(by_rule["Lit"], "Lit(value: 1)");
514 assert_eq!(by_rule["Name"], "Name(text: \"example\", quoted: true)");
515 assert_eq!(
516 by_rule["Add"], "Add(lhs: Unit(), rhs: Unit())",
517 "nested slots fill with the cheapest variant"
518 );
519 assert_eq!(
520 by_rule["Neg"], "Neg(body: none)",
521 "Optional minimal = absent"
522 );
523 assert_eq!(
524 by_rule["List"], "List(items: [])",
525 "Many minimal = empty list"
526 );
527 assert_eq!(
528 by_rule["Env"], "Env(entries: {})",
529 "Map minimal = empty map, braces tight like the empty list"
530 );
531 assert_eq!(by_rule["Unit"], "Unit()");
532 }
533
534 #[test]
540 fn rich_keyed_map_example_uses_distinct_keys() {
541 let map_only = NodeSchema {
542 name: "Cfg".into(),
543 variants: vec![
544 VariantSchema {
545 name: "Env".into(),
546 fields: vec![],
547 children: vec![ChildSchema {
548 name: "entries".into(),
549 multiplicity: Multiplicity::Map,
550 }],
551 },
552 VariantSchema {
553 name: "Unit".into(),
554 fields: vec![],
555 children: vec![],
556 },
557 ],
558 };
559 let g = checked_grammar_from_schema(&map_only, &IdGen::new()).expect("generates");
560 let ex = examples_from_grammar(&g).expect("synthesizes");
561
562 let tree = g.parse(&ex.composite).unwrap_or_else(|err| {
563 panic!(
564 "composite failed to parse: {:?}\n text: {}",
565 err.diagnostics, ex.composite
566 )
567 });
568 let entries = tree
569 .keyed_child_slot("entries")
570 .expect("rich mode fills the keyed slot");
571 assert!(
572 entries.len() >= 2,
573 "rich mode should expand the map: {}",
574 ex.composite
575 );
576 let diags = check_conformance(&tree, &map_only);
577 assert!(
578 diags.is_empty(),
579 "synthesized example must conform: {diags:?}\n text: {}",
580 ex.composite
581 );
582 }
583
584 #[test]
588 fn keyed_entry_inherits_an_underivable_value() {
589 let ids = IdGen::new();
590 use crate::peg::{keyed_entry, node, rule, rule_ref, token};
593 let entry = keyed_entry(&ids, "entries", token(&ids, "%ident"), rule_ref(&ids, "s"));
594 let g = Grammar::new(vec![rule(&ids, "s", node(&ids, "N", entry))], "s");
595 let err = examples_from_grammar(&g).expect_err("no finite derivation exists");
596 assert!(
597 err.diagnostics
598 .iter()
599 .any(|d| d.code == codes::NO_FINITE_DERIVATION),
600 "expected NO_FINITE_DERIVATION; got {:?}",
601 err.diagnostics
602 .iter()
603 .map(|d| d.code.as_str())
604 .collect::<Vec<_>>()
605 );
606 }
607
608 #[test]
609 fn composite_parses_and_shows_nesting() {
610 let (g, ex) = demo_examples();
611 let tree = g.parse(&ex.composite).unwrap_or_else(|err| {
612 panic!(
613 "composite failed to parse: {:?}\n text: {}",
614 err.diagnostics, ex.composite
615 )
616 });
617 assert!(check_conformance(&tree, &demo_schema()).is_empty());
618 assert!(
621 !tree.children.is_empty(),
622 "composite has child structure: {}",
623 ex.composite
624 );
625 }
626
627 #[test]
628 fn underivable_rules_fail_loudly_with_the_full_list() {
629 let schema = NodeSchema {
632 name: "Loop".into(),
633 variants: vec![VariantSchema {
634 name: "Rec".into(),
635 fields: vec![],
636 children: vec![ChildSchema {
637 name: "inner".into(),
638 multiplicity: Multiplicity::One,
639 }],
640 }],
641 };
642 let g = crate::schema_gen::grammar_from_schema(&schema, &IdGen::new())
643 .expect("generation itself succeeds");
644 let err = examples_from_grammar(&g).expect_err("no finite derivation");
645 assert!(
646 err.diagnostics
647 .iter()
648 .all(|d| d.code == codes::NO_FINITE_DERIVATION),
649 "{:?}",
650 err.diagnostics
651 );
652 assert_eq!(err.diagnostics.len(), 2);
654 }
655}