vtcode_safety/command_safety/shell_parser/ast.rs
1//! Bash AST access owned by `vtcode-safety`.
2//!
3//! The bash grammar is a security boundary, so `tree-sitter` and
4//! `tree-sitter-bash` live only in this crate. Callers outside
5//! `vtcode-safety` use the [`BashTree`] / [`BashNode`] wrappers instead of
6//! raw tree-sitter types, which keeps the grammar dependency out of
7//! `vtcode-core` and makes every AST consumer fail closed by construction:
8//! a parse failure is an `Err`, never a partially-valid tree.
9//!
10//! The wrappers deliberately expose only what the shell-classification and
11//! redirection-validation call sites need. Anything richer (arbitrary node
12//! kinds, byte offsets) is not part of the contract, so the surface cannot
13//! grow into a general-purpose AST API.
14
15use std::num::NonZeroUsize;
16use std::sync::Mutex;
17use std::sync::OnceLock;
18
19use lru::LruCache;
20use rustc_hash::FxBuildHasher;
21
22/// Upper bound on cached parsed bash trees.
23const SHELL_TREE_CACHE_CAPACITY: usize = 256;
24
25/// Process-wide LRU of parsed bash trees keyed by source text.
26///
27/// Command classification parses the *same* static script several times per
28/// validation: `contains_dynamic_find_syntax` (command extraction),
29/// `validate_redirection_paths` (AST walk), and `parse_shell_commands`
30/// (command extraction again) each run the grammar independently. A single
31/// `tree_sitter::Tree` is a cheap refcounted handle (`Clone` bumps a refcount,
32/// not a re-parse), so parsing once and sharing the tree across every pass
33/// removes N-1 tree-sitter runs per command — the same "compute the
34/// representation once" shape that unblocked the symbol-interner storm in the
35/// clippy `nonstandard_macro_braces` fix. The tree is a pure function of the
36/// source text, so caching cannot change any safety verdict; the cache only
37/// ever returns the exact grammar output for the exact input.
38static SHELL_TREE_CACHE: OnceLock<Mutex<LruCache<String, tree_sitter::Tree, FxBuildHasher>>> = OnceLock::new();
39
40/// Returns the shared parsed-tree cache, initializing it on first use.
41///
42/// A poisoned lock is recovered rather than propagated: a stale cache entry is
43/// a pure performance concern and must never turn into a fail-open safety path
44/// or a hard error on an otherwise classifiable command.
45fn shell_tree_cache() -> &'static Mutex<LruCache<String, tree_sitter::Tree, FxBuildHasher>> {
46 SHELL_TREE_CACHE.get_or_init(|| {
47 let capacity = NonZeroUsize::new(SHELL_TREE_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN);
48 Mutex::new(LruCache::with_hasher(capacity, FxBuildHasher))
49 })
50}
51
52/// A parsed bash script together with the source text it was parsed from.
53///
54/// Owning the source alongside the tree keeps every [`BashNode::text`] result
55/// a borrow of the same buffer, so AST consumers cannot accidentally read
56/// text from a different script.
57#[derive(Debug, Clone)]
58pub struct BashTree<'a> {
59 tree: tree_sitter::Tree,
60 source: &'a str,
61}
62
63impl<'a> BashTree<'a> {
64 /// Parses `script` into a bash AST.
65 ///
66 /// Returns `Err` when the grammar cannot be loaded or the script cannot be
67 /// parsed at all. A script that parses *with* syntax errors still yields a
68 /// tree; callers that must reject malformed input check
69 /// [`BashTree::has_error`].
70 pub fn parse(script: &'a str) -> Result<Self, String> {
71 let (tree, _) = parse_bash_tree(script)?;
72 Ok(Self { tree, source: script })
73 }
74
75 /// Returns the root node of the parsed script.
76 #[must_use]
77 pub fn root(&self) -> BashNode<'_> {
78 BashNode { node: self.tree.root_node(), source: self.source }
79 }
80
81 /// Whether the grammar reported a syntax error anywhere in the script.
82 ///
83 /// Tree-sitter applies error recovery instead of failing, so malformed
84 /// scripts parse into a tree whose error nodes must be rejected explicitly.
85 #[must_use]
86 pub fn has_error(&self) -> bool {
87 self.tree.root_node().has_error()
88 }
89}
90
91/// A node in a parsed bash script.
92#[derive(Debug, Clone, Copy)]
93pub struct BashNode<'a> {
94 node: tree_sitter::Node<'a>,
95 source: &'a str,
96}
97
98impl<'a> BashNode<'a> {
99 /// The grammar's node kind, such as `command`, `word`, or `file_redirect`.
100 #[must_use]
101 pub fn kind(&self) -> &'a str {
102 self.node.kind()
103 }
104
105 /// The source text covered by this node.
106 ///
107 /// Returns an empty string when the node's span is not valid UTF-8, which
108 /// keeps AST walks total instead of panicking on malformed input.
109 #[must_use]
110 pub fn text(&self) -> &'a str {
111 self.node.utf8_text(self.source.as_bytes()).unwrap_or("")
112 }
113
114 /// The byte offset where this node starts in the source text.
115 #[must_use]
116 pub fn start_byte(&self) -> usize {
117 self.node.start_byte()
118 }
119
120 /// Whether the grammar considers this node named.
121 ///
122 /// Anonymous nodes carry punctuation (`&&`, `|`, `;`), so a walk that must
123 /// reason about structure rather than operators checks this first.
124 #[must_use]
125 pub fn is_named(&self) -> bool {
126 self.node.is_named()
127 }
128
129 /// Returns the child bound to `field`, such as a command's `name`.
130 #[must_use]
131 pub fn field(&self, field: &str) -> Option<Self> {
132 self.node
133 .child_by_field_name(field)
134 .map(|node| Self { node, source: self.source })
135 }
136
137 /// Returns every child node, named and anonymous.
138 #[must_use]
139 pub fn children(&self) -> Vec<Self> {
140 let mut cursor = self.node.walk();
141 self.node
142 .children(&mut cursor)
143 .map(|node| Self { node, source: self.source })
144 .collect()
145 }
146
147 /// Returns every named child node.
148 #[must_use]
149 pub fn named_children(&self) -> Vec<Self> {
150 let mut cursor = self.node.walk();
151 self.node
152 .named_children(&mut cursor)
153 .map(|node| Self { node, source: self.source })
154 .collect()
155 }
156
157 /// Returns every child node bound to `field`.
158 ///
159 /// A node can bind the same field more than once, so this returns a list
160 /// rather than a single node.
161 #[must_use]
162 pub fn field_children(&self, field: &str) -> Vec<Self> {
163 let mut cursor = self.node.walk();
164 self.node
165 .children_by_field_name(field, &mut cursor)
166 .map(|node| Self { node, source: self.source })
167 .collect()
168 }
169}
170
171/// Parses `script` into a tree-sitter bash tree, reusing the cached tree when
172/// the exact source text was parsed before.
173///
174/// Returns the tree together with whether the grammar reported a syntax error,
175/// so callers keep their original `has_error` semantics. Tree-sitter applies
176/// error recovery instead of returning `None`, so the split between "did not
177/// parse at all" (`Err`) and "parsed with errors" (`Ok((.., true))`) is
178/// preserved for callers that must fail closed on malformed input.
179pub(crate) fn parse_bash_tree(script: &str) -> Result<(tree_sitter::Tree, bool), String> {
180 if let Some(tree) = {
181 let mut cache = shell_tree_cache().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
182 cache.get(script).cloned()
183 } {
184 let has_error = tree.root_node().has_error();
185 return Ok((tree, has_error));
186 }
187
188 let (tree, has_error) = {
189 if scanner_crash_shape(script) {
190 return Err("shell script rejected by the Bash scanner compatibility guard".to_string());
191 }
192 let parser_guard = get_bash_parser()?;
193 let mut parser = parser_guard.lock().map_err(|e| format!("Failed to lock parser: {e}"))?;
194 let tree = parser.parse(script, None).ok_or_else(|| "Failed to parse script".to_string())?;
195 let has_error = tree.root_node().has_error();
196 (tree, has_error)
197 };
198
199 let mut cache = shell_tree_cache().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
200 drop(cache.put(script.to_string(), tree.clone()));
201 Ok((tree, has_error))
202}
203
204// Avoid a known upstream Bash external scanner crash (tree-sitter-bash #337).
205// Check at the parser boundary so every AST consumer gets an ordinary error.
206fn scanner_crash_shape(script: &str) -> bool {
207 let mut saw_open_brace = false;
208 for byte in script.as_bytes() {
209 match byte {
210 b'{' => saw_open_brace = true,
211 0xF0..=0xF7 if saw_open_brace => return true,
212 _ => {}
213 }
214 }
215 false
216}
217
218/// Lazy-initialized tree-sitter bash parser (wrapped in Mutex for mutation)
219static BASH_PARSER: OnceLock<Result<Mutex<tree_sitter::Parser>, String>> = OnceLock::new();
220
221/// Gets or initializes the bash parser
222fn get_bash_parser() -> Result<&'static Mutex<tree_sitter::Parser>, String> {
223 BASH_PARSER
224 .get_or_init(|| {
225 let mut parser = tree_sitter::Parser::new();
226 let lang: tree_sitter::Language = tree_sitter_bash::LANGUAGE.into();
227 parser
228 .set_language(&lang)
229 .map_err(|e| format!("Failed to load bash grammar: {e}"))?;
230 Ok(Mutex::new(parser))
231 })
232 .as_ref()
233 .map_err(Clone::clone)
234}
235
236/// Ensures the bash tree-sitter parser is initialized.
237pub fn prewarm_bash_parser() -> Result<(), String> {
238 let _ = get_bash_parser()?;
239 Ok(())
240}
241
242#[cfg(test)]
243mod guard_tests {
244 use super::scanner_crash_shape;
245
246 #[test]
247 fn scanner_crash_shape_matches_issue_337_shape() {
248 assert!(scanner_crash_shape("{\u{2FA8E}"));
249 assert!(scanner_crash_shape("echo {a}\u{1F574}"));
250 assert!(scanner_crash_shape("{x} \u{1F847}"));
251 // No brace before the 4-byte lead: safe for the scanner.
252 assert!(!scanner_crash_shape("\u{2FA8E}{"));
253 // No 4-byte lead at all.
254 assert!(!scanner_crash_shape("{hello}"));
255 // 3-byte and 2-byte leads do not trigger the upstream crash.
256 assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
257 }
258}