use std::num::NonZeroUsize;
use std::sync::Mutex;
use std::sync::OnceLock;
use lru::LruCache;
use rustc_hash::FxBuildHasher;
const SHELL_TREE_CACHE_CAPACITY: usize = 256;
static SHELL_TREE_CACHE: OnceLock<Mutex<LruCache<String, tree_sitter::Tree, FxBuildHasher>>> = OnceLock::new();
fn shell_tree_cache() -> &'static Mutex<LruCache<String, tree_sitter::Tree, FxBuildHasher>> {
SHELL_TREE_CACHE.get_or_init(|| {
let capacity = NonZeroUsize::new(SHELL_TREE_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN);
Mutex::new(LruCache::with_hasher(capacity, FxBuildHasher))
})
}
#[derive(Debug, Clone)]
pub struct BashTree<'a> {
tree: tree_sitter::Tree,
source: &'a str,
}
impl<'a> BashTree<'a> {
pub fn parse(script: &'a str) -> Result<Self, String> {
let (tree, _) = parse_bash_tree(script)?;
Ok(Self { tree, source: script })
}
#[must_use]
pub fn root(&self) -> BashNode<'_> {
BashNode { node: self.tree.root_node(), source: self.source }
}
#[must_use]
pub fn has_error(&self) -> bool {
self.tree.root_node().has_error()
}
}
#[derive(Debug, Clone, Copy)]
pub struct BashNode<'a> {
node: tree_sitter::Node<'a>,
source: &'a str,
}
impl<'a> BashNode<'a> {
#[must_use]
pub fn kind(&self) -> &'a str {
self.node.kind()
}
#[must_use]
pub fn text(&self) -> &'a str {
self.node.utf8_text(self.source.as_bytes()).unwrap_or("")
}
#[must_use]
pub fn start_byte(&self) -> usize {
self.node.start_byte()
}
#[must_use]
pub fn is_named(&self) -> bool {
self.node.is_named()
}
#[must_use]
pub fn field(&self, field: &str) -> Option<Self> {
self.node
.child_by_field_name(field)
.map(|node| Self { node, source: self.source })
}
#[must_use]
pub fn children(&self) -> Vec<Self> {
let mut cursor = self.node.walk();
self.node
.children(&mut cursor)
.map(|node| Self { node, source: self.source })
.collect()
}
#[must_use]
pub fn named_children(&self) -> Vec<Self> {
let mut cursor = self.node.walk();
self.node
.named_children(&mut cursor)
.map(|node| Self { node, source: self.source })
.collect()
}
#[must_use]
pub fn field_children(&self, field: &str) -> Vec<Self> {
let mut cursor = self.node.walk();
self.node
.children_by_field_name(field, &mut cursor)
.map(|node| Self { node, source: self.source })
.collect()
}
}
pub(crate) fn parse_bash_tree(script: &str) -> Result<(tree_sitter::Tree, bool), String> {
if let Some(tree) = {
let mut cache = shell_tree_cache().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
cache.get(script).cloned()
} {
let has_error = tree.root_node().has_error();
return Ok((tree, has_error));
}
let (tree, has_error) = {
if scanner_crash_shape(script) {
return Err("shell script rejected by the Bash scanner compatibility guard".to_string());
}
let parser_guard = get_bash_parser()?;
let mut parser = parser_guard.lock().map_err(|e| format!("Failed to lock parser: {e}"))?;
let tree = parser.parse(script, None).ok_or_else(|| "Failed to parse script".to_string())?;
let has_error = tree.root_node().has_error();
(tree, has_error)
};
let mut cache = shell_tree_cache().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
drop(cache.put(script.to_string(), tree.clone()));
Ok((tree, has_error))
}
fn scanner_crash_shape(script: &str) -> bool {
let mut saw_open_brace = false;
for byte in script.as_bytes() {
match byte {
b'{' => saw_open_brace = true,
0xF0..=0xF7 if saw_open_brace => return true,
_ => {}
}
}
false
}
static BASH_PARSER: OnceLock<Result<Mutex<tree_sitter::Parser>, String>> = OnceLock::new();
fn get_bash_parser() -> Result<&'static Mutex<tree_sitter::Parser>, String> {
BASH_PARSER
.get_or_init(|| {
let mut parser = tree_sitter::Parser::new();
let lang: tree_sitter::Language = tree_sitter_bash::LANGUAGE.into();
parser
.set_language(&lang)
.map_err(|e| format!("Failed to load bash grammar: {e}"))?;
Ok(Mutex::new(parser))
})
.as_ref()
.map_err(Clone::clone)
}
pub fn prewarm_bash_parser() -> Result<(), String> {
let _ = get_bash_parser()?;
Ok(())
}
#[cfg(test)]
mod guard_tests {
use super::scanner_crash_shape;
#[test]
fn scanner_crash_shape_matches_issue_337_shape() {
assert!(scanner_crash_shape("{\u{2FA8E}"));
assert!(scanner_crash_shape("echo {a}\u{1F574}"));
assert!(scanner_crash_shape("{x} \u{1F847}"));
assert!(!scanner_crash_shape("\u{2FA8E}{"));
assert!(!scanner_crash_shape("{hello}"));
assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
}
}