Skip to main content

bash_ast/
parse.rs

1use tree_sitter::{Parser, Tree};
2
3use crate::ast::Program;
4use crate::convert;
5use crate::error::ParseError;
6
7/// Parse bash source into a tree-sitter CST. Useful when callers want to walk the
8/// raw CST themselves; most consumers want [`parse_to_ast`] instead.
9pub fn parse(source: &str) -> Result<Tree, ParseError> {
10    let mut parser = Parser::new();
11    parser
12        .set_language(&tree_sitter_bash::LANGUAGE.into())
13        .map_err(|_| ParseError::LanguageInit)?;
14    parser.parse(source, None).ok_or(ParseError::NoTree)
15}
16
17/// Parse bash source and convert to the typed AST. Returns an error if any node kind
18/// is unrecognized (we treat unknown kinds as a bug rather than silently dropping
19/// them, so the typed surface stays in lockstep with the grammar).
20pub fn parse_to_ast(source: &str) -> Result<Program, ParseError> {
21    let tree = parse(source)?;
22    convert::tree_to_program(&tree, source.as_bytes())
23}