crftng-intrprtrs/src/lib.rs

83 lines
1.9 KiB
Rust
Raw Normal View History

2022-04-29 20:00:06 +02:00
#![feature(char_indices_offset)]
2022-04-03 21:54:26 +02:00
pub mod ast;
pub mod error;
pub mod interpreter;
pub mod lexer;
2022-04-23 16:27:11 +02:00
use ast::parser::ParseAllResult;
use ast::statement::statement_node::Statement;
2022-04-19 00:46:33 +02:00
use interpreter::ast_walker::{Interpret, RuntimeError};
2022-04-03 21:54:26 +02:00
use interpreter::types::Value;
2022-04-19 00:46:33 +02:00
use lexer::{token::Token, Lexer, LexingError};
2022-04-03 21:54:26 +02:00
2022-04-19 00:46:33 +02:00
pub fn lex<'a, 'b>(
code: &'a str,
file: Option<&'b str>,
) -> Result<Vec<Token<'b>>, Vec<LexingError>> {
let mut lexer = Lexer::new(code, file);
lexer.scan_tokens()
}
2022-04-03 21:54:26 +02:00
2022-04-23 16:27:11 +02:00
pub fn parse(tokens: Vec<Token>) -> ParseAllResult {
2022-04-03 21:54:26 +02:00
let mut parser = crate::ast::parser::Parser::new(tokens.into_iter());
parser.parse_all()
2022-04-19 00:46:33 +02:00
}
2022-04-03 21:54:26 +02:00
2022-04-23 16:27:11 +02:00
pub fn exec(nodes: Vec<Statement>) -> Result<Value, RuntimeError> {
2022-04-23 19:43:42 +02:00
let mut last_res = Value::Nil;
2022-04-23 16:27:11 +02:00
for statement in nodes {
2022-04-23 19:43:42 +02:00
last_res = statement.interpret()?;
2022-04-23 16:27:11 +02:00
}
2022-04-23 19:43:42 +02:00
Ok(last_res)
2022-04-19 00:46:33 +02:00
}
pub fn run(code: &str) -> Result<Value, run::Error> {
let tokens = lex(code, None)?;
let nodes = parse(tokens)?;
Ok(exec(nodes)?)
2022-04-03 21:54:26 +02:00
}
mod run {
use std::fmt::Display;
use super::ast;
use super::interpreter::ast_walker::RuntimeError;
use super::lexer;
use from_variants::FromVariants;
#[derive(Debug, FromVariants)]
pub enum Error {
Lexing(Vec<lexer::LexingError>),
ASTParsing(Vec<ast::parser::ASTParsingError>),
Runtime(RuntimeError),
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let error_kind = match *self {
Error::Lexing(_) => "lexing",
Error::ASTParsing(_) => "ast generation",
Error::Runtime(_) => "runtime",
};
2022-04-03 22:07:19 +02:00
writeln!(f, "Errors occured during {error_kind}")?;
2022-04-03 21:54:26 +02:00
match *self {
Error::Lexing(ref errors) => {
for error in errors {
2022-04-03 22:07:19 +02:00
writeln!(f, "{error} ")?;
2022-04-03 21:54:26 +02:00
}
}
Error::ASTParsing(ref errors) => {
for error in errors {
2022-04-03 22:07:19 +02:00
writeln!(f, "{error} ")?;
2022-04-03 21:54:26 +02:00
}
}
2022-04-03 22:07:19 +02:00
Error::Runtime(ref error) => writeln!(f, "{error} ")?,
2022-04-03 21:54:26 +02:00
};
Ok(())
}
}
impl std::error::Error for Error {}
}