rlox/interpreter/tests/common/mod.rs

107 lines
2.8 KiB
Rust
Raw Normal View History

2024-09-01 19:15:55 +02:00
use std::cell::RefCell;
use std::io::stdin;
use std::path::PathBuf;
use std::rc::Rc;
use rlox2_frontend::lexer::TokenType;
use rlox2_interpreter::{run, Runtime};
2024-09-01 20:47:52 +02:00
#[cfg(test)]
pub fn run_test(path: impl Into<PathBuf>) {
2024-09-02 15:35:28 +02:00
use smol_str::SmolStr;
2024-09-01 19:15:55 +02:00
let path = &path.into();
// path.insert_str(0, "./tests/lox/");
let source = std::fs::read_to_string(path).unwrap();
let tokens = rlox2_frontend::lexer::scan_tokens(&source).unwrap();
2024-09-02 15:35:28 +02:00
let comments: Result<Vec<String>, SmolStr> =
tokens.into_iter().try_fold(Vec::new(), |mut acc, token| {
2024-09-01 19:15:55 +02:00
if let TokenType::Comment(s) = token.token_type {
2024-09-02 15:35:28 +02:00
if s.contains("Error") || s.contains("error") {
return Err(s);
} else if s.starts_with(" expect: ") {
acc.push(s.trim().strip_prefix("expect:").unwrap().trim().to_owned());
2024-09-01 19:15:55 +02:00
}
}
2024-09-02 15:35:28 +02:00
Ok(acc)
});
match comments {
Ok(ref comments) => {
println!("Expecting positive result");
for comment in comments.iter() {
println!("Comment: \"{comment}\"")
}
}
Err(ref e) => {
println!("Expecting error: {e}");
}
2024-09-01 19:15:55 +02:00
}
print!("\n\n");
let output: Vec<u8> = Vec::new();
let output = Rc::new(RefCell::new(output));
{
2024-09-01 23:16:00 +02:00
let output = Rc::clone(&output);
2024-09-01 19:15:55 +02:00
let mut runtime = Runtime::new(Rc::new(RefCell::new(stdin())), output);
match run(&source, &mut runtime) {
Ok(()) => (),
Err(e) => {
println!("{e}");
2024-09-02 15:35:28 +02:00
assert!(comments.is_err());
2024-09-01 19:15:55 +02:00
return;
}
}
}
2024-09-02 15:35:28 +02:00
let Ok(comments) = comments else {
panic!("Positive outcome, but expected error");
};
2024-09-01 19:15:55 +02:00
let mut output = output.as_ref().borrow_mut();
let output = String::from_utf8(std::mem::take(&mut *output)).unwrap();
println!("output: len = {}\n---", output.len());
println!("{output}");
println!("---");
let lines: Vec<String> = output
.split_terminator('\n')
.map(|s| s.to_owned())
.collect();
2024-09-01 23:53:04 +02:00
assert_eq!(
lines.len(),
comments.len(),
"Didn't get as many outputs as expected"
);
2024-09-01 19:15:55 +02:00
for (line, comment) in std::iter::zip(lines.into_iter(), comments.into_iter()) {
assert_eq!(line, comment);
}
}
2024-09-01 20:47:52 +02:00
// #[test]
// fn run_all_tests() {
// for lox_file in glob::glob("tests/lox/**/*.lox").unwrap() {
// let lox_file = lox_file.unwrap();
2024-09-01 19:15:55 +02:00
2024-09-01 20:47:52 +02:00
// print!("\n\n\n");
// println!(
// "================================================================================\n"
// );
// println!("Running test for file {}\n", lox_file.display());
2024-09-01 19:15:55 +02:00
2024-09-01 20:47:52 +02:00
// run_test(lox_file);
// }
// }