parser/bin/snapshot.rs
Saif Eddin Gmati 558ce71563
feat: add test generator (#134)
Co-authored-by: Ryan Chandler <ryangjchandler@gmail.com>
closes https://github.com/ryangjchandler/php-parser-rs/issues/130
2022-11-29 23:19:51 +00:00

79 lines
2.6 KiB
Rust

use php_parser_rs::{Lexer, Parser};
use std::env;
use std::fs::read_dir;
use std::path::PathBuf;
fn main() {
let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut entries = read_dir(manifest.join("tests"))
.unwrap()
.flatten()
.map(|entry| entry.path())
.filter(|entry| entry.is_dir())
.collect::<Vec<PathBuf>>();
entries.sort();
let mut content = String::new();
content.push_str("/// this file is auto-generated by the build script.\n");
content.push_str("/// you should never manually change it.\n\n\n");
for entry in entries {
let code_filename = entry.join("code.php");
let ast_filename = entry.join("ast.txt");
let lexer_error_filename = entry.join("lexer-error.txt");
let parser_error_filename = entry.join("parser-error.txt");
if !code_filename.exists() {
continue;
}
if ast_filename.exists() {
std::fs::remove_file(&ast_filename).unwrap();
}
if lexer_error_filename.exists() {
std::fs::remove_file(&lexer_error_filename).unwrap();
}
if parser_error_filename.exists() {
std::fs::remove_file(&parser_error_filename).unwrap();
}
let code = std::fs::read_to_string(&code_filename).unwrap();
let mut lexer = Lexer::new(None);
let tokens = lexer.tokenize(code.as_bytes());
match tokens {
Ok(tokens) => {
let mut parser = Parser::new(None);
let ast = parser.parse(tokens);
match ast {
Ok(ast) => {
std::fs::write(ast_filename, format!("{:#?}\n", ast)).unwrap();
println!("✅ generated `ast.txt` for `{}`", entry.to_string_lossy());
}
Err(error) => {
std::fs::write(
parser_error_filename,
format!("{:?} -> {}\n", error, error),
)
.unwrap();
println!(
"✅ generated `parser-error.txt` for `{}`",
entry.to_string_lossy()
);
}
}
}
Err(error) => {
std::fs::write(lexer_error_filename, format!("{:?}\n", error)).unwrap();
println!(
"✅ generated `lexer-error.txt` for `{}`",
entry.to_string_lossy()
);
}
}
}
}