Skip to main content

winx_code_agent/utils/
syntax.rs

1use std::fmt::Write as FmtWrite;
2use std::path::Path;
3use std::process::{Command, Stdio};
4
5use tree_sitter::{Node, Parser};
6
7pub fn syntax_warning(path: &Path, content: &str) -> Option<String> {
8    let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or_default();
9    let file_name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
10
11    match ext {
12        "json" => serde_json::from_str::<serde_json::Value>(content)
13            .err()
14            .map(|error| format!("Syntax warning: JSON parser reported: {error}")),
15        "toml" => toml::from_str::<toml::Value>(content)
16            .err()
17            .map(|error| format!("Syntax warning: TOML parser reported: {error}")),
18        "rs" => {
19            let language = tree_sitter_rust::LANGUAGE.into();
20            tree_sitter_warning(content, &language, "Rust")
21        }
22        "js" | "mjs" | "cjs" | "jsx" => {
23            let language = tree_sitter_javascript::LANGUAGE.into();
24            tree_sitter_warning(content, &language, "JavaScript")
25        }
26        "ts" => {
27            let language = tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into();
28            tree_sitter_warning(content, &language, "TypeScript")
29        }
30        "tsx" => {
31            let language = tree_sitter_typescript::LANGUAGE_TSX.into();
32            tree_sitter_warning(content, &language, "TSX")
33        }
34        // zsh is checked with the bash grammar too. The previous `if ext != "zsh"`
35        // guard made the whole arm a no-op for .zsh files.
36        "sh" | "bash" | "zsh" => {
37            let language = tree_sitter_bash::LANGUAGE.into();
38            tree_sitter_warning(content, &language, "shell")
39        }
40        "go" => {
41            let language = tree_sitter_go::LANGUAGE.into();
42            tree_sitter_warning(content, &language, "Go")
43        }
44        "c" => {
45            let language = tree_sitter_c::LANGUAGE.into();
46            tree_sitter_warning(content, &language, "C")
47        }
48        // `.h` is parsed with the C++ grammar, which accepts C headers too.
49        "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "h" => {
50            let language = tree_sitter_cpp::LANGUAGE.into();
51            tree_sitter_warning(content, &language, "C++")
52        }
53        "java" => {
54            let language = tree_sitter_java::LANGUAGE.into();
55            tree_sitter_warning(content, &language, "Java")
56        }
57        "rb" => {
58            let language = tree_sitter_ruby::LANGUAGE.into();
59            tree_sitter_warning(content, &language, "Ruby")
60        }
61        "css" => {
62            let language = tree_sitter_css::LANGUAGE.into();
63            tree_sitter_warning(content, &language, "CSS")
64        }
65        "html" | "htm" => {
66            let language = tree_sitter_html::LANGUAGE.into();
67            tree_sitter_warning(content, &language, "HTML")
68        }
69        "php" => {
70            let language = tree_sitter_php::LANGUAGE_PHP.into();
71            tree_sitter_warning(content, &language, "PHP")
72        }
73        "cs" => {
74            let language = tree_sitter_c_sharp::LANGUAGE.into();
75            tree_sitter_warning(content, &language, "C#")
76        }
77        "lua" => {
78            let language = tree_sitter_lua::LANGUAGE.into();
79            tree_sitter_warning(content, &language, "Lua")
80        }
81        // Python keeps the interpreter `compile()` check (not tree-sitter): the
82        // tree-sitter-python grammar silently accepts IndentationError and py2
83        // `print` statements, and indentation is *the* classic Python mistake —
84        // verified empirically that tree-sitter misses those, compile() catches them.
85        "py" | "pyi" => python_warning(path, content),
86        _ if matches!(file_name, "Dockerfile" | "Makefile") => None,
87        _ => None,
88    }
89}
90
91fn tree_sitter_warning(
92    content: &str,
93    language: &tree_sitter::Language,
94    language_name: &str,
95) -> Option<String> {
96    let mut parser = Parser::new();
97    if let Err(error) = parser.set_language(language) {
98        return Some(format!("Syntax warning: failed to load {language_name} parser: {error}"));
99    }
100
101    let tree = parser.parse(content, None)?;
102    let root = tree.root_node();
103    if !root.has_error() {
104        return None;
105    }
106
107    let mut message =
108        format!("Syntax warning: tree-sitter reported {language_name} syntax errors.");
109    if let Some(row) = first_error_row(root) {
110        let _ = write!(message, "\n{}", error_context(content, row));
111    }
112    Some(message)
113}
114
115/// Depth-first search for the first ERROR or MISSING node, returning its 0-based
116/// start row. Mirrors wcgw's `get_context_for_errors`, which surfaces *where* the
117/// parse broke instead of just stating that it did.
118fn first_error_row(node: Node<'_>) -> Option<usize> {
119    if node.is_error() || node.is_missing() {
120        return Some(node.start_position().row);
121    }
122    if !node.has_error() {
123        return None;
124    }
125    let mut cursor = node.walk();
126    for child in node.children(&mut cursor) {
127        if let Some(row) = first_error_row(child) {
128            return Some(row);
129        }
130    }
131    None
132}
133
134/// Render the ~10 lines around `error_row` (0-based) with a `>` marker on the
135/// offending line, so the model can see and fix the error in place.
136fn error_context(content: &str, error_row: usize) -> String {
137    let lines: Vec<&str> = content.lines().collect();
138    if lines.is_empty() {
139        return String::new();
140    }
141    let start = error_row.saturating_sub(10);
142    let end = (error_row + 11).min(lines.len());
143    let mut out = String::from("<snippet>\n");
144    for (offset, line) in lines[start..end].iter().enumerate() {
145        let line_no = start + offset + 1;
146        let marker = if start + offset == error_row { '>' } else { ' ' };
147        let _ = writeln!(out, "{marker}{line_no} {line}");
148    }
149    out.push_str("</snippet>");
150    out
151}
152
153/// Syntax-check argv[1] via `compile()` (so no `.pyc` is emitted, unlike
154/// `py_compile`) and print just `msg (line N)` on error. Catching `SyntaxError`
155/// ourselves keeps the interpreter from dumping a traceback whose top frames are
156/// *this* wrapper — the model should see only the error in its own file.
157const PY_SYNTAX_CHECK: &str = concat!(
158    "import sys\n",
159    // The content arrives on stdin; argv[1] is only the display name for error
160    // messages. Reading stdin instead of re-opening argv[1] removes a TOCTOU /
161    // symlink-swap window — we check exactly the bytes we already validated and
162    // are about to write, not whatever is on disk at this path right now.
163    "name = sys.argv[1] if len(sys.argv) > 1 else '<file>'\n",
164    "try:\n",
165    "    compile(sys.stdin.read(), name, 'exec')\n",
166    "except SyntaxError as e:\n",
167    "    print(f'{e.msg} (line {e.lineno})', file=sys.stderr)\n",
168    "    sys.exit(1)\n",
169);
170
171fn python_warning(path: &Path, content: &str) -> Option<String> {
172    let python = python_interpreter()?;
173
174    let mut child = Command::new(python)
175        .args(["-c", PY_SYNTAX_CHECK])
176        .arg(path)
177        .stdin(Stdio::piped())
178        .stdout(Stdio::null())
179        .stderr(Stdio::piped())
180        .spawn()
181        .ok()?;
182
183    // Feed the content from a separate thread so a large file can't deadlock on
184    // a full pipe buffer while the child is still being scheduled.
185    let mut stdin = child.stdin.take()?;
186    let owned = content.to_owned();
187    let writer = std::thread::spawn(move || {
188        use std::io::Write;
189        let _ = stdin.write_all(owned.as_bytes());
190        // `stdin` is dropped here, closing the pipe so the child sees EOF.
191    });
192
193    let output = child.wait_with_output().ok()?;
194    let _ = writer.join();
195
196    (!output.status.success()).then(|| {
197        let stderr = String::from_utf8_lossy(&output.stderr);
198        format!("Syntax warning: Python parser reported: {}", stderr.trim())
199    })
200}
201
202/// The available Python interpreter, probed once. The probe used to re-spawn
203/// `python --version` on every `.py` write.
204fn python_interpreter() -> Option<&'static str> {
205    static PYTHON: std::sync::OnceLock<Option<&'static str>> = std::sync::OnceLock::new();
206    *PYTHON.get_or_init(|| {
207        if Command::new("python3").arg("--version").output().is_ok() {
208            Some("python3")
209        } else if Command::new("python").arg("--version").output().is_ok() {
210            Some("python")
211        } else {
212            None
213        }
214    })
215}
216
217#[cfg(test)]
218mod tests {
219    use super::syntax_warning;
220    use std::path::Path;
221
222    #[test]
223    fn reports_invalid_json() {
224        assert!(syntax_warning(Path::new("bad.json"), "{").is_some());
225    }
226
227    #[test]
228    fn accepts_valid_rust() {
229        assert!(syntax_warning(Path::new("lib.rs"), "fn main() {}\n").is_none());
230    }
231
232    #[test]
233    fn reports_invalid_bash() {
234        assert!(syntax_warning(Path::new("script.sh"), "if true; then\n").is_some());
235    }
236
237    #[test]
238    fn reports_invalid_zsh() {
239        // Regression: the old `if ext != "zsh"` guard skipped .zsh entirely.
240        assert!(syntax_warning(Path::new("script.zsh"), "if true; then\n").is_some());
241    }
242
243    #[test]
244    fn error_warning_includes_snippet() {
245        let warning = syntax_warning(Path::new("lib.rs"), "fn main() {\n").unwrap_or_default();
246        assert!(warning.contains("<snippet>"), "expected snippet, got: {warning}");
247    }
248
249    #[test]
250    fn checks_go() {
251        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main() {}\n").is_none());
252        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main( {\n").is_some());
253    }
254
255    #[test]
256    fn checks_php() {
257        assert!(syntax_warning(Path::new("a.php"), "<?php echo 1; ?>\n").is_none());
258        assert!(syntax_warning(Path::new("a.php"), "<?php echo (1; ?>\n").is_some());
259    }
260}