oak_matlab/builder/
mod.rs1use crate::{ast::*, language::MatlabLanguage, parser::MatlabParser};
2use oak_core::{Builder, BuilderCache, GreenNode, OakDiagnostics, Source, SourceText, TextEdit};
3
4#[derive(Clone)]
5pub struct MatlabBuilder<'config> {
6 config: &'config MatlabLanguage,
7}
8
9impl<'config> MatlabBuilder<'config> {
10 pub fn new(config: &'config MatlabLanguage) -> Self {
11 Self { config }
12 }
13
14 pub fn build_root(&self, green_tree: &GreenNode<MatlabLanguage>, source: &SourceText) -> Result<MatlabRoot, oak_core::OakError> {
15 let red_root = oak_core::tree::RedNode::new(green_tree, 0);
16 let mut items = Vec::new();
17 for child in red_root.children() {
18 if let oak_core::tree::RedTree::Node(node) = child {
19 if let Some(item) = self.build_item(&node, source) {
20 items.push(item);
21 }
22 }
23 }
24 Ok(MatlabRoot { items })
25 }
26
27 pub fn build_item(&self, node: &oak_core::RedNode<MatlabLanguage>, source: &SourceText) -> Option<Item> {
28 use crate::kind::MatlabSyntaxKind::*;
29 let kind = node.green.kind;
30
31 match kind {
32 FunctionDef => {
33 let mut name = "anonymous".to_string();
34 for child in node.children() {
35 if let oak_core::RedTree::Node(n) = child {
36 if n.green.kind == Identifier {
37 name = source.get_text_in(n.span()).to_string();
38 break;
39 }
40 }
41 }
42 Some(Item::Function(crate::ast::Function { name, inputs: Vec::new(), outputs: Vec::new(), body: Vec::new(), span: node.span() }))
43 }
44 ClassDef => {
45 let mut name = "Unknown".to_string();
46 for child in node.children() {
47 if let oak_core::RedTree::Node(n) = child {
48 if n.green.kind == Identifier {
49 name = source.get_text_in(n.span()).to_string();
50 break;
51 }
52 }
53 }
54 Some(Item::Class(crate::ast::Class { name, superclasses: Vec::new(), properties: Vec::new(), methods: Vec::new(), span: node.span() }))
55 }
56 Expression | Block | Statement => Some(Item::Statement(crate::ast::Statement::Expression { value: source.get_text_in(node.span()).to_string(), span: node.span() })),
57 _ => None,
58 }
59 }
60}
61
62impl<'config> Builder<MatlabLanguage> for MatlabBuilder<'config> {
63 fn build<'a, S: Source + ?Sized>(&self, source: &S, edits: &[TextEdit], _cache: &'a mut impl BuilderCache<MatlabLanguage>) -> oak_core::builder::BuildOutput<MatlabLanguage> {
64 let parser = MatlabParser::new(self.config);
65 let lexer = crate::lexer::MatlabLexer::new(&self.config);
66 let mut cache = oak_core::parser::session::ParseSession::<MatlabLanguage>::default();
67 let parse_result = oak_core::parser::parse(&parser, &lexer, source, edits, &mut cache);
68
69 match parse_result.result {
70 Ok(green_tree) => {
71 let source_text = SourceText::new(source.get_text_in((0..source.length()).into()).into_owned());
72 OakDiagnostics { result: self.build_root(&green_tree, &source_text), diagnostics: parse_result.diagnostics }
73 }
74 Err(parse_error) => OakDiagnostics { result: Err(parse_error), diagnostics: parse_result.diagnostics },
75 }
76 }
77}