regenerate.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use matzo::grammar;
  2. use matzo::interp;
  3. use matzo::lexer;
  4. use std::collections::BTreeMap;
  5. use std::io::Write;
  6. const MAX_RUN_EXPECTATIONS: u64 = 64;
  7. fn generate_runs(source: &str) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
  8. let mut found_results: BTreeMap<String, u64> = BTreeMap::new();
  9. for seed in 0..MAX_RUN_EXPECTATIONS {
  10. let state = interp::State::new_from_seed(seed);
  11. let mut out = Vec::new();
  12. state.run_with_writer(source, &mut out)?;
  13. let out = std::str::from_utf8(&out).unwrap().trim().to_string();
  14. if !found_results.contains_key(&out) {
  15. let _ = found_results.insert(out, seed);
  16. }
  17. }
  18. let output = found_results
  19. .into_iter()
  20. .map(|(k, v)| (format!("{}", v), k))
  21. .collect();
  22. Ok(output)
  23. }
  24. fn main() -> Result<(), Box<dyn std::error::Error>> {
  25. for exp in std::fs::read_dir("tests")? {
  26. let exp = exp?.path().canonicalize()?;
  27. let fname = exp.file_name().ok_or("bad file name")?.to_string_lossy();
  28. if let Some(prefix) = fname.strip_suffix(".matzo") {
  29. println!("regenerating {}.matzo", prefix);
  30. let exp_filename = |new_suffix| {
  31. let mut f = exp.clone();
  32. f.pop();
  33. f.push(format!("{}.{}", prefix, new_suffix));
  34. f
  35. };
  36. let mut ast = matzo::ast::ASTArena::new();
  37. let src = std::fs::read_to_string(&exp)?;
  38. let tokens = lexer::tokens(&src);
  39. let file = ast.add_file(src.to_string());
  40. if let Ok(stmts) = grammar::StmtsParser::new().parse(&mut ast, file, tokens) {
  41. let mut f = std::fs::File::create(exp_filename("parsed"))?;
  42. for stmt in stmts {
  43. writeln!(f, "{:#?}", stmt.show(&ast))?;
  44. }
  45. }
  46. if let Ok(existing) = std::fs::read_to_string(exp_filename("output")) {
  47. let existing: BTreeMap<String, String> = serde_yaml::from_str(&existing)?;
  48. print!(" generating output for {}: ", fname);
  49. let map = generate_runs(&src)?;
  50. if map != existing {
  51. let mut f = std::fs::File::create(exp_filename("output"))?;
  52. writeln!(f, "# generated for {}", env!("VERGEN_GIT_SHA"))?;
  53. writeln!(f, "{}", serde_yaml::to_string(&map)?)?;
  54. println!("generated {} cases", map.len());
  55. } else {
  56. println!("no changes needed");
  57. }
  58. }
  59. }
  60. }
  61. Ok(())
  62. }