1use crate::{create_file, json_from_path, source_from_path};
8use oak_core::{Language, Parser, errors::OakError};
9use serde::{Deserialize, Serialize};
10
11use std::{
12 fmt::Debug,
13 path::{Path, PathBuf},
14 time::Duration,
15};
16use walkdir::WalkDir;
17
18pub struct ParserTester {
24 root: PathBuf,
25 extensions: Vec<String>,
26 timeout: Duration,
27}
28
29#[derive(Debug, Serialize, Deserialize, PartialEq)]
34pub struct ParserTestExpected {
35 pub success: bool,
36 pub node_count: usize,
37 pub ast_structure: AstNodeData,
38 pub errors: Vec<String>,
39}
40
41#[derive(Debug, Serialize, Deserialize, PartialEq)]
46pub struct AstNodeData {
47 pub kind: String,
48 pub children: Vec<AstNodeData>,
49 pub text_length: usize,
50 pub is_leaf: bool,
51}
52
53impl ParserTester {
54 pub fn new<P: AsRef<Path>>(root: P) -> Self {
56 Self { root: root.as_ref().to_path_buf(), extensions: vec![], timeout: Duration::from_secs(10) }
57 }
58
59 pub fn with_extension(mut self, extension: impl ToString) -> Self {
61 self.extensions.push(extension.to_string());
62 self
63 }
64
65 pub fn with_timeout(mut self, timeout: Duration) -> Self {
67 self.timeout = timeout;
68 self
69 }
70
71 pub fn run_tests<L, P>(self, parser: &P) -> Result<(), OakError>
73 where
74 P: Parser<L> + Send + Sync,
75 L: Language + Send + Sync,
76 L::ElementType: Serialize + Debug + Sync + Send + Eq + From<L::TokenType>,
77 {
78 let test_files = self.find_test_files()?;
79 let force_regenerated = std::env::var("REGENERATE_TESTS").unwrap_or("0".to_string()) == "1";
80 let mut regenerated_any = false;
81
82 for file_path in test_files {
83 println!("Testing file: {}", file_path.display());
84 regenerated_any |= self.test_single_file::<L, P>(&file_path, parser, force_regenerated)?;
85 }
86
87 if regenerated_any && force_regenerated {
88 println!("Tests regenerated for: {}", self.root.display());
89 Ok(())
90 }
91 else {
92 Ok(())
93 }
94 }
95
96 fn find_test_files(&self) -> Result<Vec<PathBuf>, OakError> {
97 let mut files = Vec::new();
98
99 for entry in WalkDir::new(&self.root) {
100 let entry = entry.unwrap();
101 let path = entry.path();
102
103 if path.is_file() {
104 if let Some(ext) = path.extension() {
105 let ext_str = ext.to_str().unwrap_or("");
106 if self.extensions.iter().any(|e| e == ext_str) {
107 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
109 let is_output_file = file_name.ends_with(".parsed.json") || file_name.ends_with(".lexed.json") || file_name.ends_with(".built.json") || file_name.ends_with(".expected.json");
110
111 if !is_output_file {
112 files.push(path.to_path_buf());
113 }
114 }
115 }
116 }
117 }
118
119 Ok(files)
120 }
121
122 fn test_single_file<L, P>(&self, file_path: &Path, parser: &P, force_regenerated: bool) -> Result<bool, OakError>
123 where
124 P: Parser<L> + Send + Sync,
125 L: Language + Send + Sync,
126 L::ElementType: Serialize + Debug + Sync + Send + From<L::TokenType>,
127 {
128 let source = source_from_path(file_path)?;
129
130 use std::sync::mpsc;
132 let (tx, rx) = mpsc::channel();
133 let timeout = self.timeout;
134
135 std::thread::scope(|s| {
136 s.spawn(move || {
137 let mut cache = oak_core::parser::ParseSession::<L>::default();
138 let parse_out = parser.parse(&source, &[], &mut cache);
139
140 let (success, ast_structure) = match &parse_out.result {
142 Ok(root) => {
143 let ast = Self::to_ast::<L>(root);
144 (true, ast)
145 }
146 Err(_) => {
147 let ast = AstNodeData { kind: "Error".to_string(), children: vec![], text_length: 0, is_leaf: true };
148 (false, ast)
149 }
150 };
151
152 let mut error_messages: Vec<String> = parse_out.diagnostics.iter().map(|e| e.to_string()).collect();
154 if let Err(e) = &parse_out.result {
155 error_messages.push(e.to_string());
156 }
157
158 let node_count = Self::count_nodes(&ast_structure);
160
161 let test_result = ParserTestExpected { success, node_count, ast_structure, errors: error_messages };
162
163 let _ = tx.send(Ok::<ParserTestExpected, OakError>(test_result));
164 });
165
166 let mut regenerated = false;
167 match rx.recv_timeout(timeout) {
168 Ok(Ok(test_result)) => {
169 let expected_file = file_path.with_extension(format!("{}.parsed.json", file_path.extension().unwrap_or_default().to_str().unwrap_or("")));
170
171 if !expected_file.exists() {
173 let legacy_file = file_path.with_extension("expected.json");
174 if legacy_file.exists() {
175 let _ = std::fs::rename(&legacy_file, &expected_file);
176 }
177 }
178
179 if expected_file.exists() && !force_regenerated {
180 let expected_json = json_from_path(&expected_file)?;
181 let expected: ParserTestExpected = serde_json::from_value(expected_json).map_err(|e| OakError::custom_error(e.to_string()))?;
182 if test_result != expected {
183 return Err(OakError::test_failure(file_path.to_path_buf(), format!("{:#?}", expected), format!("{:#?}", test_result)));
184 }
185 }
186 else {
187 use std::io::Write;
188 let mut file = create_file(&expected_file)?;
189 let json_val = serde_json::to_string_pretty(&test_result).map_err(|e| OakError::custom_error(e.to_string()))?;
190 file.write_all(json_val.as_bytes()).map_err(|e| OakError::custom_error(e.to_string()))?;
191
192 if force_regenerated {
193 regenerated = true;
194 }
195 else {
196 return Err(OakError::test_regenerated(expected_file));
197 }
198 }
199 }
200 Ok(Err(e)) => return Err(e),
201 Err(mpsc::RecvTimeoutError::Timeout) => {
202 return Err(OakError::custom_error(&format!("Parser test timed out after {:?} for file: {}", timeout, file_path.display())));
203 }
204 Err(mpsc::RecvTimeoutError::Disconnected) => {
205 return Err(OakError::custom_error("Parser test thread disconnected unexpectedly"));
206 }
207 }
208 Ok(regenerated)
209 })
210 }
211
212 fn to_ast<'a, L: Language>(root: &'a oak_core::GreenNode<'a, L>) -> AstNodeData {
213 let kind_str = format!("{:?}", root.kind);
214 let mut children = Vec::new();
215 let mut leaf_count: usize = 0;
216 let mut leaf_text_length: usize = 0;
217
218 for c in root.children {
219 match c {
220 oak_core::GreenTree::Node(n) => children.push(Self::to_ast(n)),
221 oak_core::GreenTree::Leaf(l) => {
222 leaf_count += 1;
223 leaf_text_length += l.length as usize;
224 }
225 }
226 }
227
228 if leaf_count > 0 {
229 children.push(AstNodeData { kind: format!("Leaves({})", leaf_count), children: vec![], text_length: leaf_text_length, is_leaf: true });
230 }
231
232 AstNodeData { kind: kind_str, children, text_length: root.text_len as usize, is_leaf: false }
233 }
234
235 fn count_nodes(node: &AstNodeData) -> usize {
236 1 + node.children.iter().map(Self::count_nodes).sum::<usize>()
237 }
238}