Skip to main content

oak_c/builder/
mod.rs

1#![doc = include_str!("readme.md")]
2use crate::{CParser, ast::*, language::CLanguage, lexer::CTokenType, parser::CElementType};
3use oak_core::{Builder, BuilderCache, GreenNode, OakDiagnostics, OakError, Parser, RedNode, RedTree, SourceText, TextEdit, builder::BuildOutput, source::Source};
4
5mod build_type_system;
6
7/// AST builder for the C language.
8#[derive(Clone, Copy)]
9pub struct CBuilder<'config> {
10    /// Language configuration.
11    config: &'config CLanguage,
12}
13
14impl<'config> CBuilder<'config> {
15    /// Creates a new `CBuilder` with the given language configuration.
16    pub fn new(config: &'config CLanguage) -> Self {
17        Self { config }
18    }
19}
20
21impl<'config> Builder<CLanguage> for CBuilder<'config> {
22    /// Builds the C AST from the green tree.
23    fn build<'a, S: Source + ?Sized>(&self, source: &S, edits: &[TextEdit], cache: &'a mut impl BuilderCache<CLanguage>) -> BuildOutput<CLanguage> {
24        // Parse source code to get green tree.
25        let parser = CParser::new(self.config);
26
27        // Utilize the provided cache for incremental parsing.
28        let parse_result = parser.parse(source, edits, cache);
29
30        // Check if parsing succeeded.
31        match parse_result.result {
32            Ok(green_tree) => {
33                // Build AST.
34                let source_text = SourceText::new(source.get_text_in((0..source.length()).into()).into_owned());
35                match self.build_root(green_tree, &source_text) {
36                    Ok(ast_root) => OakDiagnostics { result: Ok(ast_root), diagnostics: parse_result.diagnostics },
37                    Err(build_error) => {
38                        let mut diagnostics = parse_result.diagnostics;
39                        diagnostics.push(build_error.clone());
40                        OakDiagnostics { result: Err(build_error), diagnostics }
41                    }
42                }
43            }
44            Err(parse_error) => OakDiagnostics { result: Err(parse_error), diagnostics: parse_result.diagnostics },
45        }
46    }
47}
48
49impl<'config> CBuilder<'config> {
50    /// Builds the AST root from the green tree.
51    pub(crate) fn build_root<'a>(&self, green_tree: &'a GreenNode<'a, CLanguage>, source: &SourceText) -> Result<CRoot, OakError> {
52        let root_node = RedNode::new(green_tree, 0);
53        let mut external_declarations = Vec::new();
54
55        for child in root_node.children() {
56            if let RedTree::Node(n) = child {
57                match n.green.kind {
58                    CElementType::FunctionDefinition => external_declarations.push(ExternalDeclaration::FunctionDefinition(self.build_function_definition(n, source)?)),
59                    CElementType::DeclarationStatement => external_declarations.push(ExternalDeclaration::Declaration(self.build_declaration(n, source)?)),
60                    _ => {}
61                }
62            }
63        }
64
65        Ok(CRoot { translation_unit: TranslationUnit { external_declarations, span: root_node.span() }, span: root_node.span() })
66    }
67
68    /// Builds a function definition from a red node.
69    fn build_function_definition(&self, node: RedNode<CLanguage>, source: &SourceText) -> Result<FunctionDefinition, OakError> {
70        let mut declaration_specifiers = Vec::new();
71        let mut declarator = None;
72        let mut compound_statement = None;
73
74        for child in node.children() {
75            match child {
76                RedTree::Node(n) => match n.green.kind {
77                    CElementType::CompoundStatement => compound_statement = Some(self.build_compound_statement(n, source)?),
78                    CElementType::Declarator => {
79                        // In a real implementation, we'd use a more robust way to find the declarator.
80                        // For now, we assume the first node with kind Declarator is it.
81                    }
82                    _ => {}
83                },
84                RedTree::Leaf(t) => match t.kind {
85                    CTokenType::Int => declaration_specifiers.push(DeclarationSpecifier::TypeSpecifier(TypeSpecifier::Int { span: t.span.clone() })),
86                    CTokenType::Void => declaration_specifiers.push(DeclarationSpecifier::TypeSpecifier(TypeSpecifier::Void { span: t.span.clone() })),
87                    CTokenType::Identifier => {
88                        let name = text(source, t.span.clone());
89                        if declarator.is_none() {
90                            declarator = Some(Declarator { pointer: None, direct_declarator: DirectDeclarator::Identifier(name, t.span.clone()), span: t.span.clone() })
91                        }
92                    }
93                    _ => {}
94                },
95            }
96        }
97
98        let final_declarator = declarator.unwrap_or_else(|| Declarator { pointer: None, direct_declarator: DirectDeclarator::Identifier("main".to_string(), (0..0).into()), span: (0..0).into() });
99
100        // Build canonical type
101        let _canonical_type = self.build_type(&declaration_specifiers, &final_declarator, source);
102
103        Ok(FunctionDefinition { declaration_specifiers, declarator: final_declarator, compound_statement: compound_statement.unwrap_or_else(|| CompoundStatement { block_items: vec![], span: (0..0).into() }), span: node.span() })
104    }
105
106    /// Builds a declaration from a red node.
107    fn build_declaration(&self, node: RedNode<CLanguage>, _source: &SourceText) -> Result<Declaration, OakError> {
108        Ok(Declaration { declaration_specifiers: vec![], init_declarators: vec![], span: node.span() })
109    }
110
111    fn build_compound_statement(&self, node: RedNode<CLanguage>, source: &SourceText) -> Result<CompoundStatement, OakError> {
112        let mut block_items = Vec::new();
113
114        for child in node.children() {
115            if let RedTree::Node(n) = child {
116                match n.green.kind {
117                    CElementType::ReturnStatement => block_items.push(BlockItem::Statement(Statement::Jump(self.build_return_statement(n, source)?))),
118                    CElementType::ExpressionStatement => {
119                        if let Some(expr) = self.build_expression(n, source)? {
120                            block_items.push(BlockItem::Statement(Statement::Expression(ExpressionStatement { expression: Some(expr), span: n.span() })))
121                        }
122                    }
123                    _ => {}
124                }
125            }
126        }
127
128        Ok(CompoundStatement { block_items, span: node.span() })
129    }
130
131    fn build_return_statement(&self, node: RedNode<CLanguage>, source: &SourceText) -> Result<JumpStatement, OakError> {
132        let mut expression = None;
133        for child in node.children() {
134            match child {
135                RedTree::Node(n) => {
136                    if n.green.kind == CElementType::ExpressionStatement {
137                        expression = self.build_expression(n, source)?
138                    }
139                }
140                RedTree::Leaf(t) => {
141                    if t.kind == CTokenType::IntConstant {
142                        let val = text(source, t.span.clone());
143                        let int_val = val.parse::<i64>().unwrap_or(0);
144                        expression = Some(Expression { kind: Box::new(ExpressionKind::Constant(Constant::Integer(int_val, t.span.clone()), t.span.clone())), span: t.span.clone() })
145                    }
146                }
147            }
148        }
149        Ok(JumpStatement::Return(expression, node.span()))
150    }
151
152    fn build_expression(&self, node: RedNode<CLanguage>, source: &SourceText) -> Result<Option<Expression>, OakError> {
153        for child in node.children() {
154            match child {
155                RedTree::Leaf(t) => match t.kind {
156                    CTokenType::IntConstant => {
157                        let val = text(source, t.span.clone());
158                        let int_val = val.parse::<i64>().unwrap_or(0);
159                        return Ok(Some(Expression { kind: Box::new(ExpressionKind::Constant(Constant::Integer(int_val, t.span.clone()), t.span.clone())), span: t.span.clone() }));
160                    }
161                    CTokenType::Identifier => {
162                        let name = text(source, t.span.clone());
163                        return Ok(Some(Expression { kind: Box::new(ExpressionKind::Identifier(name, t.span.clone())), span: t.span.clone() }));
164                    }
165                    _ => {}
166                },
167                RedTree::Node(n) => {
168                    // Recursively handle expression child nodes.
169                    if let Some(expr) = self.build_expression(n, source)? {
170                        return Ok(Some(expr));
171                    }
172                }
173            }
174        }
175        Ok(None)
176    }
177}
178
179fn text(source: &SourceText, span: core::range::Range<usize>) -> String {
180    source.get_text_in(span).to_string()
181}