Skip to main content

brooks_lib/mel/compiler/
mod.rs

1// brooks, Copyright 2026, Will Hawkins
2//
3// This file is part of brooks.
4
5// This file is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18use tree_sitter;
19
20use crate::common::TextLocation;
21use crate::mel::ast::Expr;
22use crate::mel::compiler::compile::MELCompiler;
23use crate::mel::compiler::compile::MELCompilerContext;
24use crate::mel::compiler::compile::SyntaxVisitorDriver;
25use crate::mel::compiler::error::CompileResult;
26use crate::mel::compiler::error::CompilerError;
27use crate::mel::compiler::error::CompilerLocatableError;
28
29pub mod compile;
30pub mod error;
31
32#[cfg(test)]
33mod test;
34
35pub fn compile(source: &str) -> CompileResult<Expr<()>> {
36    let mut parser = tree_sitter::Parser::new();
37    let language = tree_sitter_mel::LANGUAGE;
38    parser
39        .set_language(&language.into())
40        .map_err(|e| CompilerLocatableError {
41            error: CompilerError::SyntaxError(format!("Could not parse: {e}")),
42            location: TextLocation {
43                start: 0,
44                extent: 0,
45            },
46        })?;
47    let result = parser.parse(source, None).ok_or(CompilerLocatableError {
48        error: CompilerError::SyntaxError("Could not parse.".to_string()),
49        location: TextLocation {
50            start: 0,
51            extent: 0,
52        },
53    })?;
54
55    let vd = SyntaxVisitorDriver {};
56    let sd = MELCompiler::new(source);
57    let cc = MELCompilerContext::default();
58
59    let result = vd.visit(result.root_node(), &sd, cc)?;
60
61    match result {
62        MELCompilerContext::Expr(expr) => Ok(expr),
63        _ => Err(CompilerLocatableError {
64            error: CompilerError::EmptyContext,
65            location: TextLocation {
66                start: 0,
67                extent: 0,
68            },
69        }),
70    }
71}