Skip to main content

skullbrain_parser/
lib.rs

1//! # skullbrain-parser
2//!
3//! The skullbrain crate is a library that provides a parser,, and a concrete syntax tree.
4
5mod cstree_impl;
6mod primitive;
7mod state;
8mod syntax;
9mod syntax_kind;
10
11/// A typed-cst layer
12pub mod cst;
13
14/// A typed-ast layer
15pub mod ast;
16
17#[cfg(test)]
18mod test;
19use std::path::Path;
20
21pub(crate) use syntax_kind::SyntaxKind;
22
23use cstree::build::NodeCache;
24use cstree_impl::CstreeBuilder;
25use state::{Diagnostics, ParserState};
26
27use crate::cst::SyntaxNode;
28use crate::state::ConcreteSyntaxTreeBuilder;
29
30/// Represents the complete Concrete Syntax Tree (CST) for a source file.
31pub struct SourceSyntaxTree {
32    node: SyntaxNode,
33}
34
35/// Parses the given source code
36#[allow(private_bounds)]
37pub fn parse_source(
38    file_name: &Path,
39    input: &str,
40    cache: &mut NodeCache,
41    diagnostic: impl Diagnostics,
42) -> SourceSyntaxTree {
43    let builder = CstreeBuilder::new(cache, input);
44    let mut state = ParserState::new(file_name, input, diagnostic, builder);
45    while let Some(_) = state.peek() {
46        state.parse_expression();
47    }
48
49    let green = state.finish();
50    let node = SyntaxNode::new_root(green);
51
52    SourceSyntaxTree { node }
53}
54
55/// Parses the given source code
56#[allow(private_bounds)]
57pub fn parse_file(
58    file_name: &Path,
59    cache: &mut NodeCache,
60    diagnostic: impl Diagnostics,
61) -> std::io::Result<SourceSyntaxTree> {
62    let input = std::fs::read_to_string(file_name)?;
63    Ok(parse_source(file_name, input.as_str(), cache, diagnostic))
64}
65
66impl SourceSyntaxTree {
67    ///
68    pub fn expressions(&self) -> impl Iterator<Item = crate::cst::Expr> + use<'_> {
69        self.node
70            .children_with_tokens()
71            .map(|syn| crate::cst::Expr::cast_element(syn))
72    }
73}