dust/dust-lang/src/lib.rs

327 lines
12 KiB
Rust
Raw Normal View History

2024-02-25 18:49:26 +00:00
pub mod abstract_tree;
2024-03-23 12:15:48 +00:00
pub mod built_in_functions;
2024-02-25 18:49:26 +00:00
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-24 19:35:19 +00:00
use std::{cell::RefCell, ops::Range, rc::Rc, vec};
2024-03-24 13:10:49 +00:00
use abstract_tree::Type;
use ariadne::{Color, Fmt, Label, Report, ReportKind};
2024-03-24 00:36:23 +00:00
use context::Context;
2024-03-24 13:10:49 +00:00
use error::{Error, RuntimeError, TypeConflict, ValidationError};
2024-03-06 20:36:58 +00:00
use lexer::lex;
2024-03-19 21:12:32 +00:00
use parser::parse;
2024-02-26 21:27:01 +00:00
pub use value::Value;
2024-02-25 08:12:09 +00:00
2024-03-24 19:35:19 +00:00
pub fn interpret<'src>(source_id: &str, source: &str) -> Result<Option<Value>, InterpreterError> {
2024-03-24 00:36:23 +00:00
let mut interpreter = Interpreter::new(Context::new());
2024-03-23 12:15:48 +00:00
2024-03-24 19:47:23 +00:00
interpreter.load_std()?;
interpreter.run(Rc::from(source_id), Rc::from(source))
2024-03-24 13:10:49 +00:00
}
pub fn interpret_without_std(
2024-03-24 19:35:19 +00:00
source_id: &str,
2024-03-24 13:10:49 +00:00
source: &str,
) -> Result<Option<Value>, InterpreterError> {
let mut interpreter = Interpreter::new(Context::new());
2024-03-24 19:47:23 +00:00
interpreter.run(Rc::from(source_id.to_string()), Rc::from(source))
2024-03-24 19:35:19 +00:00
}
pub struct Interpreter {
context: Context,
2024-03-24 19:47:23 +00:00
sources: Rc<RefCell<Vec<(Rc<str>, Rc<str>)>>>,
2024-03-24 19:35:19 +00:00
}
impl Interpreter {
pub fn new(context: Context) -> Self {
Interpreter {
context,
sources: Rc::new(RefCell::new(Vec::new())),
}
}
pub fn run(
&mut self,
2024-03-24 19:47:23 +00:00
source_id: Rc<str>,
2024-03-24 19:35:19 +00:00
source: Rc<str>,
) -> Result<Option<Value>, InterpreterError> {
let tokens = lex(source.as_ref()).map_err(|errors| InterpreterError {
source_id: source_id.clone(),
errors,
})?;
let abstract_tree = parse(&tokens).map_err(|errors| InterpreterError {
source_id: source_id.clone(),
errors,
})?;
let value_option = abstract_tree
.run(&self.context)
.map_err(|errors| InterpreterError {
source_id: source_id.clone(),
errors,
})?;
self.sources.borrow_mut().push((source_id, source.into()));
Ok(value_option)
}
2024-03-24 19:47:23 +00:00
pub fn run_all<T: IntoIterator<Item = (Rc<str>, Rc<str>)>>(
2024-03-24 19:35:19 +00:00
&mut self,
sources: T,
) -> Result<Option<Value>, InterpreterError> {
let mut previous_value_option = None;
for (source_id, source) in sources {
previous_value_option = self.run(source_id.clone(), source)?;
}
Ok(previous_value_option)
}
pub fn load_std(&mut self) -> Result<Option<Value>, InterpreterError> {
self.run_all([
(
2024-03-24 19:47:23 +00:00
Rc::from("std/io.ds"),
2024-03-24 19:35:19 +00:00
Rc::from(include_str!("../../std/io.ds")),
),
(
2024-03-24 19:47:23 +00:00
Rc::from("std/thread.ds"),
2024-03-24 19:35:19 +00:00
Rc::from(include_str!("../../std/thread.ds")),
),
])
}
2024-03-24 19:47:23 +00:00
pub fn sources(&self) -> vec::IntoIter<(Rc<str>, Rc<str>)> {
2024-03-24 19:35:19 +00:00
self.sources.borrow().clone().into_iter()
}
2024-03-24 13:10:49 +00:00
}
#[derive(Debug, PartialEq)]
pub struct InterpreterError {
2024-03-24 19:47:23 +00:00
source_id: Rc<str>,
2024-03-24 13:10:49 +00:00
errors: Vec<Error>,
}
impl InterpreterError {
pub fn errors(&self) -> &Vec<Error> {
&self.errors
}
}
impl InterpreterError {
2024-03-24 19:47:23 +00:00
pub fn build_reports<'a>(self) -> Vec<Report<'a, (Rc<str>, Range<usize>)>> {
2024-03-24 13:10:49 +00:00
let mut reports = Vec::new();
for error in self.errors {
let (mut builder, validation_error, error_position) = match error {
Error::Lex {
expected,
span,
reason,
} => {
let description = if expected.is_empty() {
"Invalid character.".to_string()
} else {
format!("Expected {expected}.")
};
(
Report::build(
ReportKind::Custom("Lexing Error", Color::Yellow),
self.source_id.clone(),
span.1,
)
.with_message(description)
.with_label(
Label::new((self.source_id.clone(), span.0..span.1))
.with_message(reason)
.with_color(Color::Red),
),
None,
span.into(),
)
}
Error::Parse {
expected,
span,
reason,
} => {
let description = if expected.is_empty() {
"Invalid token.".to_string()
} else {
format!("Expected {expected}.")
};
(
Report::build(
ReportKind::Custom("Parsing Error", Color::Yellow),
self.source_id.clone(),
span.1,
)
.with_message(description)
.with_label(
Label::new((self.source_id.clone(), span.0..span.1))
.with_message(reason)
.with_color(Color::Red),
),
None,
span.into(),
)
}
Error::Runtime { error, position } => (
Report::build(
ReportKind::Custom("Runtime Error", Color::Red),
self.source_id.clone(),
position.1,
)
.with_message("An error occured that forced the program to exit.")
.with_note(
"There may be unexpected side-effects because the program could not finish.",
)
.with_help(
"This is the interpreter's fault. Please submit a bug with this error message.",
),
if let RuntimeError::ValidationFailure(validation_error) = error {
Some(validation_error)
} else {
None
},
position,
),
Error::Validation { error, position } => (
Report::build(
ReportKind::Custom("Validation Error", Color::Magenta),
self.source_id.clone(),
position.1,
)
.with_message("The syntax is valid but this code is not sound.")
.with_note("This error was detected by the interpreter before running the code."),
Some(error),
position,
),
};
let type_color = Color::Green;
let identifier_color = Color::Blue;
if let Some(validation_error) = validation_error {
match validation_error {
ValidationError::ExpectedBoolean { actual, position } => {
builder.add_label(
Label::new((self.source_id.clone(), position.0..position.1))
.with_message(format!(
"Expected {} but got {}.",
"boolean".fg(type_color),
actual.fg(type_color)
)),
);
}
ValidationError::ExpectedIntegerOrFloat(position) => {
builder.add_label(
Label::new((self.source_id.clone(), position.0..position.1))
.with_message(format!(
"Expected {} or {}.",
"integer".fg(type_color),
"float".fg(type_color)
)),
);
}
ValidationError::RwLockPoison(_) => todo!(),
ValidationError::TypeCheck {
conflict,
actual_position,
expected_position: expected_postion,
} => {
let TypeConflict { actual, expected } = conflict;
builder.add_labels([
Label::new((
self.source_id.clone(),
expected_postion.0..expected_postion.1,
))
.with_message(format!(
"Type {} established here.",
expected.fg(type_color)
)),
Label::new((
self.source_id.clone(),
actual_position.0..actual_position.1,
))
.with_message(format!("Got type {} here.", actual.fg(type_color))),
]);
}
ValidationError::VariableNotFound(identifier) => builder.add_label(
Label::new((self.source_id.clone(), error_position.0..error_position.1))
.with_message(format!(
"Variable {} does not exist in this context.",
identifier.fg(identifier_color)
)),
),
ValidationError::CannotIndex { r#type, position } => builder.add_label(
Label::new((self.source_id.clone(), position.0..position.1)).with_message(
format!("Cannot index into a {}.", r#type.fg(type_color)),
),
),
ValidationError::CannotIndexWith {
collection_type,
collection_position,
index_type,
index_position,
} => {
builder = builder.with_message(format!(
"Cannot index into {} with {}.",
collection_type.clone().fg(type_color),
index_type.clone().fg(type_color)
));
builder.add_labels([
Label::new((
self.source_id.clone(),
collection_position.0..collection_position.1,
))
.with_message(format!(
"This has type {}.",
collection_type.fg(type_color),
)),
Label::new((
self.source_id.clone(),
index_position.0..index_position.1,
))
.with_message(format!("This has type {}.", index_type.fg(type_color),)),
])
}
ValidationError::InterpreterExpectedReturn(_) => todo!(),
ValidationError::ExpectedFunction { .. } => todo!(),
ValidationError::ExpectedValue(_) => todo!(),
ValidationError::PropertyNotFound { .. } => todo!(),
ValidationError::WrongArguments { .. } => todo!(),
ValidationError::ExpectedIntegerFloatOrString { actual, position } => {
builder = builder.with_message(format!(
"Expected an {}, {} or {}.",
Type::Integer.fg(type_color),
Type::Float.fg(type_color),
Type::String.fg(type_color)
));
builder.add_labels([Label::new((
self.source_id.clone(),
position.0..position.1,
))
.with_message(format!("This has type {}.", actual.fg(type_color),))])
}
}
}
let report = builder.finish();
reports.push(report);
}
reports
}
2024-03-06 23:15:25 +00:00
}