use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use blade_syntax::parse;
fn corpus_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")
}
fn blade_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
blade_files(&path, out);
} else if path.to_string_lossy().ends_with(".blade.php") {
out.push(path);
}
}
}
fn known_errors() -> BTreeSet<String> {
fs::read_to_string(corpus_dir().join("known-errors.txt"))
.unwrap()
.lines()
.map(|line| line.split(" #").next().unwrap().trim())
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(str::to_string)
.collect()
}
#[test]
fn corpus_round_trips_and_parses_cleanly() {
let files_dir = corpus_dir().join("files");
if !files_dir.is_dir() {
println!("corpus not fetched; run cargo xtask corpus");
return;
}
let mut files = Vec::new();
blade_files(&files_dir, &mut files);
files.sort();
let mut found = BTreeSet::new();
for path in &files {
let bytes = fs::read(path).unwrap();
let Ok(text) = String::from_utf8(bytes) else {
panic!("{} is not valid UTF-8", path.display());
};
let parse = parse(&text);
let printed = parse.syntax().to_string();
if printed != text {
let at = printed
.bytes()
.zip(text.bytes())
.position(|(a, b)| a != b)
.unwrap_or(printed.len().min(text.len()));
panic!(
"{} does not round-trip (first difference at byte {at})",
path.display()
);
}
let rel = path
.strip_prefix(&files_dir)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
for error in parse.errors() {
let line = text[..usize::from(error.range.start())]
.matches('\n')
.count()
+ 1;
found.insert(format!("{rel}: {}", error.message));
println!("{rel}:{line}: {}", error.message);
}
}
let known = known_errors();
let unexpected: Vec<_> = found.difference(&known).collect();
let stale: Vec<_> = known.difference(&found).collect();
assert!(
unexpected.is_empty() && stale.is_empty(),
"{} files parsed.\nUnexpected errors ({}):\n {}\nListed in known-errors.txt but no longer found ({}):\n {}",
files.len(),
unexpected.len(),
unexpected
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join("\n "),
stale.len(),
stale
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join("\n "),
);
println!("{} files round-trip and parse cleanly", files.len());
}