Skip to main content

oak_testing/
parsing.rs

1//! Parser testing utilities for the Oak ecosystem.
2//!
3//! This module provides comprehensive testing infrastructure for parsers,
4//! including file-based testing, expected output comparison, timeout handling,
5//! and test result serialization.
6
7use 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
18/// A concurrent parser testing utility that can run tests against multiple files with timeout support.
19///
20/// The `ParserTester` provides functionality to test parsers against a directory
21/// of files with specific extensions, comparing actual output against expected
22/// results stored in JSON files, with configurable timeout protection.
23pub struct ParserTester {
24    root: PathBuf,
25    extensions: Vec<String>,
26    timeout: Duration,
27}
28
29/// Expected parser test results for comparison.
30///
31/// This struct represents the expected output of a parser test, including
32/// success status, node count, AST structure, and any expected errors.
33#[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/// AST node data structure for parser testing.
42///
43/// Represents a node in the abstract kind tree with its kind, children,
44/// text length, and leaf status used for testing parser output.
45#[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    /// Creates a new parser tester with the specified root directory and default 10-second timeout.
55    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    /// Adds a file extension to test against.
60    pub fn with_extension(mut self, extension: impl ToString) -> Self {
61        self.extensions.push(extension.to_string());
62        self
63    }
64
65    /// Sets the timeout for parsing operations.
66    pub fn with_timeout(mut self, timeout: Duration) -> Self {
67        self.timeout = timeout;
68        self
69    }
70
71    /// Run tests for the given parser against all files in the root directory with the specified extensions.
72    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                        // 忽略由 Tester 自身生成的输出文件,防止递归包含
102                        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        // Perform parsing in a thread and construct test results, with main thread handling timeout control
125        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                // Build AST structure if parse succeeded, else create a minimal error node
136                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                // Collect error messages
148                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                // Count nodes (including leaves)
154                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                    // Migration: If the new naming convention file doesn't exist, but the old one does, rename it
167                    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}