1
0
dust/src/lib.rs

65 lines
1.6 KiB
Rust
Raw Normal View History

2024-02-25 18:49:26 +00:00
pub mod abstract_tree;
pub mod context;
pub mod error;
pub mod lexer;
pub mod parser;
2024-02-26 21:27:01 +00:00
pub mod value;
2024-02-23 12:40:01 +00:00
2024-03-08 17:24:11 +00:00
use abstract_tree::{AbstractTree, Action};
2024-02-25 18:49:26 +00:00
use context::Context;
use error::Error;
2024-03-06 20:36:58 +00:00
use lexer::lex;
pub use parser::{parse, parser, DustParser};
2024-02-26 21:27:01 +00:00
pub use value::Value;
2024-02-25 08:12:09 +00:00
2024-03-08 17:24:11 +00:00
pub fn interpret(source: &str) -> Result<Option<Value>, Vec<Error>> {
2024-03-06 23:15:25 +00:00
let context = Context::new();
let mut interpreter = Interpreter::new(context);
interpreter.run(source)
}
2024-03-06 20:36:58 +00:00
pub struct Interpreter {
context: Context,
2024-02-25 08:12:09 +00:00
}
2024-03-06 20:36:58 +00:00
impl Interpreter {
pub fn new(context: Context) -> Self {
Interpreter { context }
}
2024-03-08 17:24:11 +00:00
pub fn run(&mut self, source: &str) -> Result<Option<Value>, Vec<Error>> {
2024-03-06 20:36:58 +00:00
let tokens = lex(source)?;
let statements = parse(&tokens)?;
2024-03-06 21:50:44 +00:00
let errors = statements
.iter()
2024-03-16 19:01:45 +00:00
.filter_map(|statement| {
2024-03-06 22:32:31 +00:00
statement
2024-03-17 06:51:33 +00:00
.node
2024-03-06 22:32:31 +00:00
.validate(&self.context)
.err()
2024-03-17 06:51:33 +00:00
.map(|validation_error| Error::Validation(validation_error, statement.position))
2024-03-06 21:50:44 +00:00
})
.collect::<Vec<Error>>();
if !errors.is_empty() {
return Err(errors);
}
2024-03-06 20:36:58 +00:00
2024-03-08 17:24:11 +00:00
let mut value = None;
2024-02-23 17:14:15 +00:00
2024-03-16 19:01:45 +00:00
for statement in statements {
2024-03-17 06:51:33 +00:00
value = match statement.node.run(&self.context) {
2024-03-08 17:24:11 +00:00
Ok(action) => match action {
Action::Break => None,
2024-03-08 17:24:11 +00:00
Action::Return(value) => Some(value),
Action::None => continue,
},
2024-03-06 20:36:58 +00:00
Err(runtime_error) => return Err(vec![Error::Runtime(runtime_error)]),
}
}
2024-02-23 12:40:01 +00:00
2024-03-06 20:36:58 +00:00
Ok(value)
2023-09-28 19:58:01 +00:00
}
}