Skip to main content

winx_code_agent/utils/
syntax.rs

1use std::fmt::Write as FmtWrite;
2use std::path::Path;
3use std::process::Command;
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),
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    "try:\n",
160    "    compile(open(sys.argv[1], encoding='utf-8').read(), sys.argv[1], 'exec')\n",
161    "except SyntaxError as e:\n",
162    "    print(f'{e.msg} (line {e.lineno})', file=sys.stderr)\n",
163    "    sys.exit(1)\n",
164);
165
166fn python_warning(path: &Path) -> Option<String> {
167    let python = python_interpreter()?;
168
169    let output = Command::new(python).args(["-c", PY_SYNTAX_CHECK]).arg(path).output().ok()?;
170    (!output.status.success()).then(|| {
171        let stderr = String::from_utf8_lossy(&output.stderr);
172        format!("Syntax warning: Python parser reported: {}", stderr.trim())
173    })
174}
175
176/// The available Python interpreter, probed once. The probe used to re-spawn
177/// `python --version` on every `.py` write.
178fn python_interpreter() -> Option<&'static str> {
179    static PYTHON: std::sync::OnceLock<Option<&'static str>> = std::sync::OnceLock::new();
180    *PYTHON.get_or_init(|| {
181        if Command::new("python3").arg("--version").output().is_ok() {
182            Some("python3")
183        } else if Command::new("python").arg("--version").output().is_ok() {
184            Some("python")
185        } else {
186            None
187        }
188    })
189}
190
191#[cfg(test)]
192mod tests {
193    use super::syntax_warning;
194    use std::path::Path;
195
196    #[test]
197    fn reports_invalid_json() {
198        assert!(syntax_warning(Path::new("bad.json"), "{").is_some());
199    }
200
201    #[test]
202    fn accepts_valid_rust() {
203        assert!(syntax_warning(Path::new("lib.rs"), "fn main() {}\n").is_none());
204    }
205
206    #[test]
207    fn reports_invalid_bash() {
208        assert!(syntax_warning(Path::new("script.sh"), "if true; then\n").is_some());
209    }
210
211    #[test]
212    fn reports_invalid_zsh() {
213        // Regression: the old `if ext != "zsh"` guard skipped .zsh entirely.
214        assert!(syntax_warning(Path::new("script.zsh"), "if true; then\n").is_some());
215    }
216
217    #[test]
218    fn error_warning_includes_snippet() {
219        let warning = syntax_warning(Path::new("lib.rs"), "fn main() {\n").unwrap_or_default();
220        assert!(warning.contains("<snippet>"), "expected snippet, got: {warning}");
221    }
222
223    #[test]
224    fn checks_go() {
225        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main() {}\n").is_none());
226        assert!(syntax_warning(Path::new("main.go"), "package main\nfunc main( {\n").is_some());
227    }
228
229    #[test]
230    fn checks_php() {
231        assert!(syntax_warning(Path::new("a.php"), "<?php echo 1; ?>\n").is_none());
232        assert!(syntax_warning(Path::new("a.php"), "<?php echo (1; ?>\n").is_some());
233    }
234}