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 + 'static,
76 L::ElementType: Serialize + Debug + Sync + Send + Eq,
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 { Err(OakError::test_regenerated(self.root)) } else { Ok(()) }
88 }
89
90 fn find_test_files(&self) -> Result<Vec<PathBuf>, OakError> {
91 let mut files = Vec::new();
92
93 for entry in WalkDir::new(&self.root) {
94 let entry = entry.unwrap();
95 let path = entry.path();
96
97 if path.is_file() {
98 if let Some(ext) = path.extension() {
99 let ext_str = ext.to_str().unwrap_or("");
100 if self.extensions.iter().any(|e| e == ext_str) {
101 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
103 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");
104
105 if !is_output_file {
106 files.push(path.to_path_buf());
107 }
108 }
109 }
110 }
111 }
112
113 Ok(files)
114 }
115
116 fn test_single_file<L, P>(&self, file_path: &Path, parser: &P, force_regenerated: bool) -> Result<bool, OakError>
117 where
118 P: Parser<L> + Send + Sync,
119 L: Language + Send + Sync + 'static,
120 L::ElementType: Serialize + Debug + Sync + Send,
121 {
122 let source = source_from_path(file_path)?;
123
124 use std::sync::mpsc;
126 let (tx, rx) = mpsc::channel();
127 let timeout = self.timeout;
128 let file_path_string = file_path.display().to_string();
129
130 std::thread::scope(|s| {
131 s.spawn(move || {
132 let mut cache = oak_core::parser::ParseSession::<L>::default();
133 let parse_out = parser.parse(&source, &[], &mut cache);
134
135 let (success, ast_structure) = match &parse_out.result {
137 Ok(root) => {
138 let ast = Self::to_ast::<L>(root);
139 (true, ast)
140 }
141 Err(_) => {
142 let ast = AstNodeData { kind: "Error".to_string(), children: vec![], text_length: 0, is_leaf: true };
143 (false, ast)
144 }
145 };
146
147 let mut error_messages: Vec<String> = parse_out.diagnostics.iter().map(|e| e.to_string()).collect();
149 if let Err(e) = &parse_out.result {
150 error_messages.push(e.to_string());
151 }
152
153 let node_count = Self::count_nodes(&ast_structure);
155
156 let test_result = ParserTestExpected { success, node_count, ast_structure, errors: error_messages };
157
158 let _ = tx.send(Ok::<ParserTestExpected, OakError>(test_result));
159 });
160
161 let mut regenerated = false;
162 match rx.recv_timeout(timeout) {
163 Ok(Ok(test_result)) => {
164 let expected_file = file_path.with_extension(format!("{}.parsed.json", file_path.extension().unwrap_or_default().to_str().unwrap_or("")));
165
166 if !expected_file.exists() {
168 let legacy_file = file_path.with_extension("expected.json");
169 if legacy_file.exists() {
170 let _ = std::fs::rename(&legacy_file, &expected_file);
171 }
172 }
173
174 if expected_file.exists() && !force_regenerated {
175 let expected_json = json_from_path(&expected_file)?;
176 let expected: ParserTestExpected = serde_json::from_value(expected_json).map_err(|e| OakError::custom_error(e.to_string()))?;
177 if test_result != expected {
178 return Err(OakError::test_failure(file_path.to_path_buf(), format!("{:#?}", expected), format!("{:#?}", test_result)));
179 }
180 }
181 else {
182 use std::io::Write;
183 let mut file = create_file(&expected_file)?;
184 let json_val = serde_json::to_string_pretty(&test_result).map_err(|e| OakError::custom_error(e.to_string()))?;
185 file.write_all(json_val.as_bytes()).map_err(|e| OakError::custom_error(e.to_string()))?;
186
187 if force_regenerated {
188 regenerated = true;
189 }
190 else {
191 return Err(OakError::test_regenerated(expected_file));
192 }
193 }
194 }
195 Ok(Err(e)) => return Err(e),
196 Err(mpsc::RecvTimeoutError::Timeout) => {
197 return Err(OakError::custom_error(format!("Parser test timed out after {:?} for file: {}", timeout, file_path_string)));
198 }
199 Err(mpsc::RecvTimeoutError::Disconnected) => {
200 return Err(OakError::custom_error("Parser thread disconnected unexpectedly"));
201 }
202 }
203 Ok(regenerated)
204 })
205 }
206
207 fn to_ast<'a, L: Language>(root: &'a oak_core::GreenNode<'a, L>) -> AstNodeData {
208 let kind_str = format!("{:?}", root.kind);
209 let mut children = Vec::new();
210 let mut leaf_count: usize = 0;
211 let mut leaf_text_length: usize = 0;
212
213 for c in root.children {
214 match c {
215 oak_core::GreenTree::Node(n) => children.push(Self::to_ast(n)),
216 oak_core::GreenTree::Leaf(l) => {
217 leaf_count += 1;
218 leaf_text_length += l.length as usize;
219 }
220 }
221 }
222
223 if leaf_count > 0 {
224 children.push(AstNodeData { kind: format!("Leaves({})", leaf_count), children: vec![], text_length: leaf_text_length, is_leaf: true });
225 }
226
227 AstNodeData { kind: kind_str, children, text_length: root.text_len as usize, is_leaf: false }
228 }
229
230 fn count_nodes(node: &AstNodeData) -> usize {
231 1 + node.children.iter().map(Self::count_nodes).sum::<usize>()
232 }
233}