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        "ex" | "exs" => {
82            let language = tree_sitter_elixir::LANGUAGE.into();
83            tree_sitter_warning(content, &language, "Elixir")
84        }
85        // Python keeps the interpreter `compile()` check (not tree-sitter): the
86        // tree-sitter-python grammar silently accepts IndentationError and py2
87        // `print` statements, and indentation is *the* classic Python mistake —
88        // verified empirically that tree-sitter misses those, compile() catches them.
89        "py" | "pyi" => python_warning(path, content),
90        _ if matches!(file_name, "Dockerfile" | "Makefile") => None,
91        _ => None,
92    }
93}
94
95fn tree_sitter_warning(
96    content: &str,
97    language: &tree_sitter::Language,
98    language_name: &str,
99) -> Option<String> {
100    let mut parser = Parser::new();
101    if let Err(error) = parser.set_language(language) {
102        return Some(format!("Syntax warning: failed to load {language_name} parser: {error}"));
103    }
104
105    let tree = parser.parse(content, None)?;
106    let root = tree.root_node();
107    if !root.has_error() {
108        return None;
109    }
110
111    let mut message =
112        format!("Syntax warning: tree-sitter reported {language_name} syntax errors.");
113    if let Some(row) = first_error_row(root) {
114        let _ = write!(message, "\n{}", error_context(content, row));
115    }
116    Some(message)
117}
118
119/// Depth-first search for the first ERROR or MISSING node, returning its 0-based
120/// start row. Mirrors wcgw's `get_context_for_errors`, which surfaces *where* the
121/// parse broke instead of just stating that it did.
122fn first_error_row(node: Node<'_>) -> Option<usize> {
123    if node.is_error() || node.is_missing() {
124        return Some(node.start_position().row);
125    }
126    if !node.has_error() {
127        return None;
128    }
129    let mut cursor = node.walk();
130    for child in node.children(&mut cursor) {
131        if let Some(row) = first_error_row(child) {
132            return Some(row);
133        }
134    }
135    None
136}
137
138/// Render the ~10 lines around `error_row` (0-based) with a `>` marker on the
139/// offending line, so the model can see and fix the error in place.
140fn error_context(content: &str, error_row: usize) -> String {
141    let lines: Vec<&str> = content.lines().collect();
142    if lines.is_empty() {
143        return String::new();
144    }
145    let start = error_row.saturating_sub(10);
146    let end = (error_row + 11).min(lines.len());
147    let mut out = String::from("<snippet>\n");
148    for (offset, line) in lines[start..end].iter().enumerate() {
149        let line_no = start + offset + 1;
150        let marker = if start + offset == error_row { '>' } else { ' ' };
151        let _ = writeln!(out, "{marker}{line_no} {line}");
152    }
153    out.push_str("</snippet>");
154    out
155}
156
157/// Syntax-check argv[1] via `compile()` (so no `.pyc` is emitted, unlike
158/// `py_compile`) and print just `msg (line N)` on error. Catching `SyntaxError`
159/// ourselves keeps the interpreter from dumping a traceback whose top frames are
160/// *this* wrapper — the model should see only the error in its own file.
161const PY_SYNTAX_CHECK: &str = concat!(
162    "import sys\n",
163    // The content arrives on stdin; argv[1] is only the display name for error
164    // messages. Reading stdin instead of re-opening argv[1] removes a TOCTOU /
165    // symlink-swap window — we check exactly the bytes we already validated and
166    // are about to write, not whatever is on disk at this path right now.
167    "name = sys.argv[1] if len(sys.argv) > 1 else '<file>'\n",
168    "try:\n",
169    "    compile(sys.stdin.read(), name, 'exec')\n",
170    "except SyntaxError as e:\n",
171    "    print(f'{e.msg} (line {e.lineno})', file=sys.stderr)\n",
172    "    sys.exit(1)\n",
173);
174
175fn python_warning(path: &Path, content: &str) -> Option<String> {
176    let python = python_interpreter()?;
177
178    let mut child = Command::new(python)
179        .args(["-c", PY_SYNTAX_CHECK])
180        .arg(path)
181        .stdin(Stdio::piped())
182        .stdout(Stdio::null())
183        .stderr(Stdio::piped())
184        .spawn()
185        .ok()?;
186
187    // Feed the content from a separate thread so a large file can't deadlock on
188    // a full pipe buffer while the child is still being scheduled.
189    let mut stdin = child.stdin.take()?;
190    let owned = content.to_owned();
191    let writer = std::thread::spawn(move || {
192        use std::io::Write;
193        let _ = stdin.write_all(owned.as_bytes());
194        // `stdin` is dropped here, closing the pipe so the child sees EOF.
195    });
196
197    let output = child.wait_with_output().ok()?;
198    let _ = writer.join();
199
200    (!output.status.success()).then(|| {
201        let stderr = String::from_utf8_lossy(&output.stderr);
202        format!("Syntax warning: Python parser reported: {}", stderr.trim())
203    })
204}
205
206/// The available Python interpreter, probed once. The probe used to re-spawn
207/// `python --version` on every `.py` write.
208fn python_interpreter() -> Option<&'static str> {
209    static PYTHON: std::sync::OnceLock<Option<&'static str>> = std::sync::OnceLock::new();
210    *PYTHON.get_or_init(|| {
211        if Command::new("python3").arg("--version").output().is_ok() {
212            Some("python3")
213        } else if Command::new("python").arg("--version").output().is_ok() {
214            Some("python")
215        } else {
216            None
217        }
218    })
219}
220
221#[cfg(test)]
222mod tests {
223    use super::syntax_warning;
224    use std::path::Path;
225
226    #[test]
227    fn reports_invalid_json() {
228        assert!(syntax_warning(Path::new("bad.json"), "{").is_some());
229    }
230
231    #[test]
232    fn accepts_valid_rust() {
233        assert!(syntax_warning(Path::new("lib.rs"), "fn main() {}\n").is_none());
234    }
235
236    #[test]
237    fn reports_invalid_bash() {
238        assert!(syntax_warning(Path::new("script.sh"), "if true; then\n").is_some());
239    }
240
241    #[test]
242    fn reports_invalid_zsh() {
243        // Regression: the old `if ext != "zsh"` guard skipped .zsh entirely.
244        assert!(syntax_warning(Path::new("script.zsh"), "if true; then\n").is_some());
245    }
246
247    #[test]
248    fn error_warning_includes_snippet() {
249        let warning = syntax_warning(Path::new("lib.rs"), "fn main() {\n").unwrap_or_default();
250        assert!(warning.contains("<snippet>"), "expected snippet, got: {warning}");
251    }
252
253    #[test]
254    fn checks_go() {
255        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main() {}\n").is_none());
256        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main( {\n").is_some());
257    }
258
259    #[test]
260    fn checks_php() {
261        assert!(syntax_warning(Path::new("a.php"), "<?php echo 1; ?>\n").is_none());
262        assert!(syntax_warning(Path::new("a.php"), "<?php echo (1; ?>\n").is_some());
263    }
264
265    #[test]
266    fn checks_elixir() {
267        assert!(syntax_warning(Path::new("worker.ex"), "defmodule Worker do\nend\n").is_none());
268        assert!(syntax_warning(Path::new("worker.ex"), "defmodule Worker do\n").is_some());
269    }
270}