oak_typst/builder/
mod.rs

1use crate::{ast::TypstRoot, language::TypstLanguage, parser::TypstParser};
2use oak_core::{
3    Builder, BuilderCache, GreenNode, OakDiagnostics, OakError, Parser, RedNode,
4    source::{Source, TextEdit},
5};
6
7/// Typst 语言的 AST 构建器
8#[derive(Clone)]
9pub struct TypstBuilder<'config> {
10    config: &'config TypstLanguage,
11}
12
13impl<'config> TypstBuilder<'config> {
14    pub fn new(config: &'config TypstLanguage) -> Self {
15        Self { config }
16    }
17}
18
19impl<'config> Builder<TypstLanguage> for TypstBuilder<'config> {
20    fn build<'a, S: Source + ?Sized>(&self, source: &'a S, edits: &[TextEdit], cache: &'a mut impl BuilderCache<TypstLanguage>) -> OakDiagnostics<TypstRoot> {
21        let parser = TypstParser::new(self.config);
22
23        let parse_result = parser.parse(source, edits, cache);
24
25        match parse_result.result {
26            Ok(green_tree) => match self.build_root(green_tree) {
27                Ok(ast_root) => OakDiagnostics { result: Ok(ast_root), diagnostics: parse_result.diagnostics },
28                Err(build_error) => {
29                    let mut diagnostics = parse_result.diagnostics;
30                    diagnostics.push(build_error.clone());
31                    OakDiagnostics { result: Err(build_error), diagnostics }
32                }
33            },
34            Err(parse_error) => OakDiagnostics { result: Err(parse_error), diagnostics: parse_result.diagnostics },
35        }
36    }
37}
38
39impl<'config> TypstBuilder<'config> {
40    pub(crate) fn build_root(&self, green_tree: &GreenNode<TypstLanguage>) -> Result<TypstRoot, OakError> {
41        let red_root = RedNode::new(green_tree, 0);
42        Ok(TypstRoot::new(red_root.span()))
43    }
44}