1
0
dust/src/abstract_tree/mod.rs

91 lines
2.0 KiB
Rust
Raw Normal View History

2024-02-25 18:49:26 +00:00
pub mod assignment;
pub mod block;
2024-02-26 21:27:01 +00:00
pub mod expression;
2024-03-09 12:34:34 +00:00
pub mod function_call;
2024-02-25 18:49:26 +00:00
pub mod identifier;
2024-03-08 19:01:05 +00:00
pub mod if_else;
2024-03-07 17:29:07 +00:00
pub mod index;
2024-02-25 18:49:26 +00:00
pub mod logic;
pub mod r#loop;
2024-03-07 11:33:54 +00:00
pub mod math;
2024-02-25 18:49:26 +00:00
pub mod statement;
pub mod r#type;
2024-02-26 21:27:01 +00:00
pub mod value_node;
2024-03-11 21:58:26 +00:00
pub mod r#while;
2024-02-25 18:49:26 +00:00
2024-03-17 06:51:33 +00:00
use chumsky::span::{SimpleSpan, Span};
2024-02-25 18:49:26 +00:00
pub use self::{
assignment::{Assignment, AssignmentOperator},
block::Block,
expression::Expression,
2024-03-09 12:34:34 +00:00
function_call::FunctionCall,
identifier::Identifier,
2024-03-08 19:01:05 +00:00
if_else::IfElse,
index::Index,
logic::Logic,
math::Math,
r#loop::Loop,
r#type::Type,
2024-03-11 21:58:26 +00:00
r#while::While,
statement::Statement,
2024-03-07 11:33:54 +00:00
value_node::ValueNode,
2024-02-25 18:49:26 +00:00
};
use crate::{
context::Context,
error::{RuntimeError, ValidationError},
Value,
};
2024-02-25 18:49:26 +00:00
2024-03-17 04:49:01 +00:00
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
2024-03-17 11:31:45 +00:00
pub struct WithPosition<T> {
2024-03-17 04:49:01 +00:00
pub node: T,
2024-03-17 11:48:06 +00:00
pub position: SourcePosition,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct SourcePosition(pub usize, pub usize);
impl From<SimpleSpan> for SourcePosition {
fn from(span: SimpleSpan) -> Self {
SourcePosition(span.start(), span.end())
}
}
impl From<(usize, usize)> for SourcePosition {
fn from((start, end): (usize, usize)) -> Self {
SourcePosition(start, end)
}
2024-03-17 04:49:01 +00:00
}
pub trait AbstractTree: Sized {
fn expected_type(&self, context: &Context) -> Result<Type, ValidationError>;
fn validate(&self, context: &Context) -> Result<(), ValidationError>;
2024-03-08 17:24:11 +00:00
fn run(self, context: &Context) -> Result<Action, RuntimeError>;
2024-03-17 04:49:01 +00:00
2024-03-17 11:48:06 +00:00
fn with_position<T: Into<SourcePosition>>(self, span: T) -> WithPosition<Self> {
2024-03-17 11:31:45 +00:00
WithPosition {
2024-03-17 04:49:01 +00:00
node: self,
2024-03-17 11:48:06 +00:00
position: span.into(),
2024-03-17 04:49:01 +00:00
}
}
2024-03-08 17:24:11 +00:00
}
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub enum Action {
Return(Value),
2024-03-12 01:57:27 +00:00
Break,
2024-03-08 17:24:11 +00:00
None,
}
impl Action {
pub fn as_return_value(self) -> Result<Value, ValidationError> {
if let Action::Return(value) = self {
Ok(value)
} else {
Err(ValidationError::InterpreterExpectedReturn)
}
}
2024-02-25 18:49:26 +00:00
}