1use crate::{create_file, json_from_path, source_from_path};
8use oak_core::{
9 Language, Lexer, Source, TokenType,
10 errors::{OakDiagnostics, OakError},
11};
12use serde::{Deserialize, Serialize};
13
14use std::{
15 path::{Path, PathBuf},
16 sync::{Arc, Mutex},
17 thread,
18 time::{Duration, Instant},
19};
20use walkdir::WalkDir;
21
22pub struct LexerTester {
28 root: PathBuf,
29 extensions: Vec<String>,
30 timeout: Duration,
31}
32
33#[derive(Debug, PartialEq, Serialize, Deserialize)]
38pub struct LexerTestExpected {
39 pub success: bool,
40 pub count: usize,
41 pub tokens: Vec<TokenData>,
42 pub errors: Vec<String>,
43}
44
45#[derive(Debug, PartialEq, Serialize, Deserialize)]
50pub struct TokenData {
51 pub kind: String,
52 pub text: String,
53 pub start: usize,
54 pub end: usize,
55}
56
57impl LexerTester {
58 pub fn new<P: AsRef<Path>>(root: P) -> Self {
60 Self { root: root.as_ref().to_path_buf(), extensions: vec![], timeout: Duration::from_secs(10) }
61 }
62
63 pub fn with_extension(mut self, extension: impl ToString) -> Self {
65 self.extensions.push(extension.to_string());
66 self
67 }
68 pub fn with_timeout(mut self, time: Duration) -> Self {
70 self.timeout = time;
71 self
72 }
73
74 pub fn run_tests<L, Lex>(self, lexer: &Lex) -> Result<(), OakError>
76 where
77 L: Language + Send + Sync + 'static,
78 L::TokenType: Serialize + std::fmt::Debug + Send + Sync,
79 Lex: Lexer<L> + Send + Sync + 'static + Clone,
80 {
81 let test_files = self.find_test_files()?;
82 let force_regenerated = std::env::var("REGENERATE_TESTS").unwrap_or("0".to_string()) == "1";
83 let mut regenerated_any = false;
84
85 for file_path in test_files {
86 println!("Testing file: {}", file_path.display());
87 regenerated_any |= self.test_single_file::<L, Lex>(&file_path, lexer, force_regenerated)?;
88 }
89
90 if regenerated_any && force_regenerated { Err(OakError::test_regenerated(self.root)) } else { Ok(()) }
91 }
92
93 fn find_test_files(&self) -> Result<Vec<PathBuf>, OakError> {
94 let mut files = Vec::new();
95
96 for entry in WalkDir::new(&self.root) {
97 let entry = entry.unwrap();
98 let path = entry.path();
99
100 if path.is_file() {
101 if let Some(ext) = path.extension() {
102 let ext_str = ext.to_str().unwrap_or("");
103 if self.extensions.iter().any(|e| e == ext_str) {
104 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
106 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");
107
108 if !is_output_file {
109 files.push(path.to_path_buf());
110 }
111 }
112 }
113 }
114 }
115
116 Ok(files)
117 }
118
119 fn test_single_file<L, Lex>(&self, file_path: &Path, lexer: &Lex, force_regenerated: bool) -> Result<bool, OakError>
120 where
121 L: Language + Send + Sync + 'static,
122 L::TokenType: Serialize + std::fmt::Debug + Send + Sync,
123 Lex: Lexer<L> + Send + Sync + 'static + Clone,
124 {
125 let source = source_from_path(file_path)?;
126
127 let result = Arc::new(Mutex::new(None));
129 let result_clone = Arc::clone(&result);
130
131 let lexer_clone = lexer.clone();
133 let source_arc = Arc::new(source);
135 let source_clone = Arc::clone(&source_arc);
136
137 let handle = thread::spawn(move || {
139 let mut cache = oak_core::parser::ParseSession::<L>::default();
140 let output = lexer_clone.lex(&*source_clone, &[], &mut cache);
141 let mut result = result_clone.lock().unwrap();
142 *result = Some(output);
143 });
144
145 let start_time = Instant::now();
147 let timeout_occurred = loop {
148 if handle.is_finished() {
150 break false;
151 }
152
153 if start_time.elapsed() > self.timeout {
155 break true;
156 }
157
158 thread::sleep(Duration::from_millis(10));
160 };
161
162 if timeout_occurred {
164 return Err(OakError::custom_error(&format!("Lexer test timed out after {:?} for file: {}", self.timeout, file_path.display())));
165 }
166
167 let OakDiagnostics { result: tokens_result, mut diagnostics } = {
169 let result_guard = result.lock().unwrap();
170 match result_guard.as_ref() {
171 Some(output) => output.clone(),
172 None => return Err(OakError::custom_error("Failed to get lexer result")),
173 }
174 };
175
176 let mut success = true;
178 let tokens = match tokens_result {
179 Ok(tokens) => tokens,
180 Err(e) => {
181 success = false;
182 diagnostics.push(e);
183 triomphe::Arc::from_iter(Vec::new())
184 }
185 };
186
187 if !diagnostics.is_empty() {
188 success = false;
189 }
190
191 let tokens: Vec<TokenData> = tokens
192 .iter()
193 .filter(|token| !token.kind.is_ignored())
194 .map(|token| {
195 let len = source_arc.as_ref().length();
196 let start = token.span.start.min(len);
197 let end = token.span.end.min(len).max(start);
198 let text = source_arc.as_ref().get_text_in((start..end).into()).to_string();
199 TokenData { kind: format!("{:?}", token.kind), text, start: token.span.start, end: token.span.end }
200 })
201 .take(100)
202 .collect();
203
204 let errors: Vec<String> = diagnostics.iter().map(|e| e.to_string()).collect();
205 let test_result = LexerTestExpected { success, count: tokens.len(), tokens, errors };
206
207 let expected_file = file_path.with_extension(format!("{}.lexed.json", file_path.extension().unwrap_or_default().to_str().unwrap_or("")));
209
210 if !expected_file.exists() {
212 let legacy_file = file_path.with_extension("expected.json");
213 if legacy_file.exists() {
214 let _ = std::fs::rename(&legacy_file, &expected_file);
215 }
216 }
217
218 let mut regenerated = false;
219 if expected_file.exists() && !force_regenerated {
220 let expected_json = json_from_path(&expected_file)?;
221 let expected: LexerTestExpected = serde_json::from_value(expected_json).map_err(|e| OakError::custom_error(e.to_string()))?;
222 if test_result != expected {
223 return Err(OakError::test_failure(file_path.to_path_buf(), format!("{:#?}", expected), format!("{:#?}", test_result)));
224 }
225 }
226 else {
227 use std::io::Write;
228 let mut file = create_file(&expected_file)?;
229 let json_val = serde_json::to_string_pretty(&test_result).map_err(|e| OakError::custom_error(e.to_string()))?;
230 file.write_all(json_val.as_bytes()).map_err(|e| OakError::custom_error(e.to_string()))?;
231 regenerated = true;
232 }
233
234 Ok(regenerated)
235 }
236}