build.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use std::env;
  2. use std::fs::File;
  3. use std::io::Write;
  4. use std::path::Path;
  5. const TEST_PREFIX: &str = "
  6. #[cfg(test)]
  7. use pretty_assertions::assert_eq;
  8. use crate::{grammar,lexer};
  9. use std::io::Write;
  10. // to let us use pretty_assertions with strings, we write a newtype
  11. // that delegates Debug to Display
  12. #[derive(PartialEq, Eq)]
  13. struct StringWrapper<'a> {
  14. wrapped: &'a str,
  15. }
  16. impl<'a> core::fmt::Debug for StringWrapper<'a> {
  17. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
  18. core::fmt::Display::fmt(self.wrapped, f)
  19. }
  20. }
  21. fn assert_eq(x: &str, y: &str) {
  22. assert_eq!(StringWrapper {wrapped: x}, StringWrapper {wrapped: y});
  23. }
  24. ";
  25. const TEST_TEMPLATE: &str = "
  26. #[test]
  27. fn test_%PREFIX%() {
  28. let mut ast = crate::ast::ASTArena::new();
  29. let source = include_str!(\"%ROOT%/tests/%PREFIX%.matzo\");
  30. let lexer = lexer::tokens(source);
  31. let stmts = grammar::StmtsParser::new().parse(&mut ast, lexer);
  32. assert!(stmts.is_ok());
  33. let stmts = stmts.unwrap();
  34. let mut buf = Vec::new();
  35. for s in stmts {
  36. writeln!(buf, \"{:?}\", s.show(&ast)).unwrap();
  37. }
  38. assert_eq(
  39. std::str::from_utf8(&buf).unwrap().trim(),
  40. include_str!(\"%ROOT%/tests/%PREFIX%.parsed\").trim(),
  41. );
  42. }
  43. ";
  44. fn main() -> Result<(), Box<dyn std::error::Error>> {
  45. lalrpop::process_root()?;
  46. vergen::vergen(vergen::Config::default())?;
  47. let out_dir = env::var("OUT_DIR")?;
  48. let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
  49. let dest = Path::new(&out_dir).join("exp_tests.rs");
  50. let mut test_file = File::create(&dest)?;
  51. writeln!(test_file, "{}", TEST_PREFIX)?;
  52. for exp in std::fs::read_dir("tests")? {
  53. let exp = exp?.path().canonicalize()?;
  54. let fname = exp.file_name().ok_or("bad file name")?.to_string_lossy();
  55. if let Some(prefix) = fname.strip_suffix(".matzo") {
  56. let test = TEST_TEMPLATE
  57. .replace("%FILE%", &fname)
  58. .replace("%PREFIX%", prefix)
  59. .replace("%ROOT%", &manifest_dir);
  60. writeln!(test_file, "{}", test)?;
  61. }
  62. }
  63. Ok(())
  64. }