Compare commits
No commits in common. "06f3a9b746b2cdd50a0210b64877affa682c6d28" and "76a67c5117a84fcec85752b06015f83ca0df5133" have entirely different histories.
06f3a9b746
...
76a67c5117
@ -5,44 +5,45 @@ use std::{
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Identifier, ReservedIdentifier, Type, Value};
|
||||
use crate::{Identifier, ReservedIdentifier, Span, Type, Value};
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct AbstractSyntaxTree<P> {
|
||||
pub nodes: VecDeque<Node<P>>,
|
||||
pub struct AbstractSyntaxTree {
|
||||
pub nodes: VecDeque<Node>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Node<P> {
|
||||
pub statement: Statement<P>,
|
||||
pub position: P,
|
||||
pub struct Node {
|
||||
pub statement: Statement,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl<P> Node<P> {
|
||||
pub fn new(operation: Statement<P>, position: P) -> Self {
|
||||
impl Node {
|
||||
pub fn new(operation: Statement, span: Span) -> Self {
|
||||
Self {
|
||||
statement: operation,
|
||||
position,
|
||||
span,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Display for Node<P> {
|
||||
impl Display for Node {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.statement)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum Statement<P> {
|
||||
pub enum Statement {
|
||||
// Top-level statements
|
||||
Assign(Box<Node<P>>, Box<Node<P>>),
|
||||
Assign(Box<Node>, Box<Node>),
|
||||
|
||||
// Expressions
|
||||
Add(Box<Node<P>>, Box<Node<P>>),
|
||||
PropertyAccess(Box<Node<P>>, Box<Node<P>>),
|
||||
List(Vec<Node<P>>),
|
||||
Multiply(Box<Node<P>>, Box<Node<P>>),
|
||||
Add(Box<Node>, Box<Node>),
|
||||
BuiltInValue(Box<Node>),
|
||||
PropertyAccess(Box<Node>, Box<Node>),
|
||||
List(Vec<Node>),
|
||||
Multiply(Box<Node>, Box<Node>),
|
||||
|
||||
// Hard-coded values
|
||||
Constant(Value),
|
||||
@ -50,11 +51,12 @@ pub enum Statement<P> {
|
||||
ReservedIdentifier(ReservedIdentifier),
|
||||
}
|
||||
|
||||
impl<P> Statement<P> {
|
||||
impl Statement {
|
||||
pub fn expected_type(&self, variables: &HashMap<Identifier, Value>) -> Option<Type> {
|
||||
match self {
|
||||
Statement::Add(left, _) => left.statement.expected_type(variables),
|
||||
Statement::Assign(_, _) => None,
|
||||
Statement::BuiltInValue(reserved) => reserved.statement.expected_type(variables),
|
||||
Statement::Constant(value) => Some(value.r#type(variables)),
|
||||
Statement::Identifier(identifier) => variables
|
||||
.get(identifier)
|
||||
@ -70,11 +72,12 @@ impl<P> Statement<P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Display for Statement<P> {
|
||||
impl Display for Statement {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Statement::Assign(left, right) => write!(f, "{left} = {right}"),
|
||||
Statement::Add(left, right) => write!(f, "{left} + {right}"),
|
||||
Statement::BuiltInValue(reserved) => write!(f, "{reserved}"),
|
||||
Statement::PropertyAccess(left, right) => write!(f, "{left}.{right}"),
|
||||
Statement::List(nodes) => {
|
||||
write!(f, "[")?;
|
||||
|
@ -22,10 +22,10 @@ use crate::{AbstractSyntaxTree, Identifier, Node, Statement, Type, Value};
|
||||
///
|
||||
/// assert!(result.is_err());
|
||||
/// ```
|
||||
pub fn analyze<P: Clone>(
|
||||
abstract_tree: &AbstractSyntaxTree<P>,
|
||||
pub fn analyze(
|
||||
abstract_tree: &AbstractSyntaxTree,
|
||||
variables: &HashMap<Identifier, Value>,
|
||||
) -> Result<(), AnalyzerError<P>> {
|
||||
) -> Result<(), AnalyzerError> {
|
||||
let analyzer = Analyzer::new(abstract_tree, variables);
|
||||
|
||||
analyzer.analyze()
|
||||
@ -44,14 +44,14 @@ pub fn analyze<P: Clone>(
|
||||
/// let result = analyzer.analyze();
|
||||
///
|
||||
/// assert!(result.is_err());
|
||||
pub struct Analyzer<'a, P> {
|
||||
abstract_tree: &'a AbstractSyntaxTree<P>,
|
||||
pub struct Analyzer<'a> {
|
||||
abstract_tree: &'a AbstractSyntaxTree,
|
||||
variables: &'a HashMap<Identifier, Value>,
|
||||
}
|
||||
|
||||
impl<'a, P: Clone> Analyzer<'a, P> {
|
||||
impl<'a> Analyzer<'a> {
|
||||
pub fn new(
|
||||
abstract_tree: &'a AbstractSyntaxTree<P>,
|
||||
abstract_tree: &'a AbstractSyntaxTree,
|
||||
variables: &'a HashMap<Identifier, Value>,
|
||||
) -> Self {
|
||||
Self {
|
||||
@ -60,7 +60,7 @@ impl<'a, P: Clone> Analyzer<'a, P> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn analyze(&self) -> Result<(), AnalyzerError<P>> {
|
||||
pub fn analyze(&self) -> Result<(), AnalyzerError> {
|
||||
for node in &self.abstract_tree.nodes {
|
||||
self.analyze_node(node)?;
|
||||
}
|
||||
@ -68,7 +68,7 @@ impl<'a, P: Clone> Analyzer<'a, P> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn analyze_node(&self, node: &Node<P>) -> Result<(), AnalyzerError<P>> {
|
||||
fn analyze_node(&self, node: &Node) -> Result<(), AnalyzerError> {
|
||||
match &node.statement {
|
||||
Statement::Add(left, right) => {
|
||||
if let Some(Type::Integer) | Some(Type::Float) =
|
||||
@ -103,6 +103,9 @@ impl<'a, P: Clone> Analyzer<'a, P> {
|
||||
|
||||
self.analyze_node(right)?;
|
||||
}
|
||||
Statement::BuiltInValue(node) => {
|
||||
self.analyze_node(node)?;
|
||||
}
|
||||
Statement::Constant(_) => {}
|
||||
Statement::Identifier(_) => {
|
||||
return Err(AnalyzerError::UnexpectedIdentifier {
|
||||
@ -157,10 +160,10 @@ impl<'a, P: Clone> Analyzer<'a, P> {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AnalyzerError<P> {
|
||||
ExpectedIdentifier { actual: Node<P> },
|
||||
ExpectedIntegerOrFloat { actual: Node<P> },
|
||||
UnexpectedIdentifier { identifier: Node<P> },
|
||||
pub enum AnalyzerError {
|
||||
ExpectedIdentifier { actual: Node },
|
||||
ExpectedIntegerOrFloat { actual: Node },
|
||||
UnexpectedIdentifier { identifier: Node },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -23,20 +23,20 @@ use crate::{AbstractSyntaxTree, LexError, Lexer, Node, Span, Statement, Token, V
|
||||
/// statement: Statement::Assign(
|
||||
/// Box::new(Node {
|
||||
/// statement: Statement::Identifier("x".into()),
|
||||
/// position: (0, 1),
|
||||
/// span: (0, 1),
|
||||
/// }),
|
||||
/// Box::new(Node {
|
||||
/// statement: Statement::Constant(Value::integer(42)),
|
||||
/// position: (4, 6),
|
||||
/// span: (4, 6),
|
||||
/// })
|
||||
/// ),
|
||||
/// position: (0, 6),
|
||||
/// span: (0, 6),
|
||||
/// }
|
||||
/// ].into(),
|
||||
/// }),
|
||||
/// );
|
||||
/// ```
|
||||
pub fn parse(input: &str) -> Result<AbstractSyntaxTree<Span>, ParseError> {
|
||||
pub fn parse(input: &str) -> Result<AbstractSyntaxTree, ParseError> {
|
||||
let lexer = Lexer::new(input);
|
||||
let mut parser = Parser::new(lexer);
|
||||
let mut nodes = VecDeque::new();
|
||||
@ -77,19 +77,19 @@ pub fn parse(input: &str) -> Result<AbstractSyntaxTree<Span>, ParseError> {
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// nodes,
|
||||
/// Into::<VecDeque<Node<Span>>>::into([
|
||||
/// Into::<VecDeque<Node>>::into([
|
||||
/// Node {
|
||||
/// statement: Statement::Assign(
|
||||
/// Box::new(Node {
|
||||
/// statement: Statement::Identifier("x".into()),
|
||||
/// position: (0, 1),
|
||||
/// span: (0, 1),
|
||||
/// }),
|
||||
/// Box::new(Node {
|
||||
/// statement: Statement::Constant(Value::integer(42)),
|
||||
/// position: (4, 6),
|
||||
/// span: (4, 6),
|
||||
/// })
|
||||
/// ),
|
||||
/// position: (0, 6),
|
||||
/// span: (0, 6),
|
||||
/// }
|
||||
/// ]),
|
||||
/// );
|
||||
@ -107,7 +107,7 @@ impl<'src> Parser<'src> {
|
||||
Parser { lexer, current }
|
||||
}
|
||||
|
||||
pub fn parse(&mut self) -> Result<Node<Span>, ParseError> {
|
||||
pub fn parse(&mut self) -> Result<Node, ParseError> {
|
||||
self.parse_node(0)
|
||||
}
|
||||
|
||||
@ -121,9 +121,9 @@ impl<'src> Parser<'src> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_node(&mut self, precedence: u8) -> Result<Node<Span>, ParseError> {
|
||||
fn parse_node(&mut self, precedence: u8) -> Result<Node, ParseError> {
|
||||
let left_node = self.parse_primary()?;
|
||||
let left_start = left_node.position.0;
|
||||
let left_start = left_node.span.0;
|
||||
|
||||
if precedence < self.current_precedence() {
|
||||
match &self.current {
|
||||
@ -131,7 +131,7 @@ impl<'src> Parser<'src> {
|
||||
self.next_token()?;
|
||||
|
||||
let right_node = self.parse_node(self.current_precedence())?;
|
||||
let right_end = right_node.position.1;
|
||||
let right_end = right_node.span.1;
|
||||
|
||||
return Ok(Node::new(
|
||||
Statement::Add(Box::new(left_node), Box::new(right_node)),
|
||||
@ -142,7 +142,7 @@ impl<'src> Parser<'src> {
|
||||
self.next_token()?;
|
||||
|
||||
let right_node = self.parse_node(self.current_precedence())?;
|
||||
let right_end = right_node.position.1;
|
||||
let right_end = right_node.span.1;
|
||||
|
||||
return Ok(Node::new(
|
||||
Statement::Multiply(Box::new(left_node), Box::new(right_node)),
|
||||
@ -153,7 +153,7 @@ impl<'src> Parser<'src> {
|
||||
self.next_token()?;
|
||||
|
||||
let right_node = self.parse_node(self.current_precedence())?;
|
||||
let right_end = right_node.position.1;
|
||||
let right_end = right_node.span.1;
|
||||
|
||||
return Ok(Node::new(
|
||||
Statement::Assign(Box::new(left_node), Box::new(right_node)),
|
||||
@ -164,7 +164,7 @@ impl<'src> Parser<'src> {
|
||||
self.next_token()?;
|
||||
|
||||
let right_node = self.parse_node(self.current_precedence())?;
|
||||
let right_end = right_node.position.1;
|
||||
let right_end = right_node.span.1;
|
||||
|
||||
return Ok(Node::new(
|
||||
Statement::PropertyAccess(Box::new(left_node), Box::new(right_node)),
|
||||
@ -178,7 +178,7 @@ impl<'src> Parser<'src> {
|
||||
Ok(left_node)
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<Node<Span>, ParseError> {
|
||||
fn parse_primary(&mut self) -> Result<Node, ParseError> {
|
||||
match self.current.clone() {
|
||||
(Token::Boolean(boolean), span) => {
|
||||
self.next_token()?;
|
||||
|
@ -539,7 +539,7 @@ pub struct Function {
|
||||
pub name: Identifier,
|
||||
pub type_parameters: Option<Vec<Type>>,
|
||||
pub value_parameters: Option<Vec<(Identifier, Type)>>,
|
||||
pub body: Vec<Statement<()>>,
|
||||
pub body: Vec<Statement>,
|
||||
}
|
||||
|
||||
impl Function {
|
||||
|
@ -8,7 +8,7 @@ use crate::{
|
||||
pub fn run(
|
||||
input: &str,
|
||||
variables: &mut HashMap<Identifier, Value>,
|
||||
) -> Result<Option<Value>, VmError<Span>> {
|
||||
) -> Result<Option<Value>, VmError> {
|
||||
let abstract_syntax_tree = parse(input)?;
|
||||
let analyzer = Analyzer::new(&abstract_syntax_tree, variables);
|
||||
|
||||
@ -19,19 +19,19 @@ pub fn run(
|
||||
vm.run(variables)
|
||||
}
|
||||
|
||||
pub struct Vm<P> {
|
||||
abstract_tree: AbstractSyntaxTree<P>,
|
||||
pub struct Vm {
|
||||
abstract_tree: AbstractSyntaxTree,
|
||||
}
|
||||
|
||||
impl<P: Copy> Vm<P> {
|
||||
pub fn new(abstract_tree: AbstractSyntaxTree<P>) -> Self {
|
||||
impl Vm {
|
||||
pub fn new(abstract_tree: AbstractSyntaxTree) -> Self {
|
||||
Self { abstract_tree }
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
&mut self,
|
||||
variables: &mut HashMap<Identifier, Value>,
|
||||
) -> Result<Option<Value>, VmError<P>> {
|
||||
) -> Result<Option<Value>, VmError> {
|
||||
let mut previous_value = None;
|
||||
|
||||
while let Some(node) = self.abstract_tree.nodes.pop_front() {
|
||||
@ -43,15 +43,16 @@ impl<P: Copy> Vm<P> {
|
||||
|
||||
fn run_node(
|
||||
&self,
|
||||
node: Node<P>,
|
||||
node: Node,
|
||||
variables: &mut HashMap<Identifier, Value>,
|
||||
) -> Result<Option<Value>, VmError<P>> {
|
||||
) -> Result<Option<Value>, VmError> {
|
||||
match node.statement {
|
||||
Statement::BuiltInValue(node) => self.run_node(*node, variables),
|
||||
Statement::Constant(value) => Ok(Some(value.clone())),
|
||||
Statement::Identifier(_) => Ok(None),
|
||||
Statement::ReservedIdentifier(_) => Ok(None),
|
||||
Statement::Add(left, right) => {
|
||||
let left_span = left.position;
|
||||
let left_span = left.span;
|
||||
let left = if let Some(value) = self.run_node(*left, variables)? {
|
||||
value
|
||||
} else {
|
||||
@ -59,7 +60,7 @@ impl<P: Copy> Vm<P> {
|
||||
position: left_span,
|
||||
});
|
||||
};
|
||||
let right_span = right.position;
|
||||
let right_span = right.span;
|
||||
let right = if let Some(value) = self.run_node(*right, variables)? {
|
||||
value
|
||||
} else {
|
||||
@ -76,10 +77,10 @@ impl<P: Copy> Vm<P> {
|
||||
identifier
|
||||
} else {
|
||||
return Err(VmError::ExpectedIdentifier {
|
||||
position: left.position,
|
||||
position: left.span,
|
||||
});
|
||||
};
|
||||
let right_span = right.position;
|
||||
let right_span = right.span;
|
||||
let value = if let Some(value) = self.run_node(*right, variables)? {
|
||||
value
|
||||
} else {
|
||||
@ -96,20 +97,20 @@ impl<P: Copy> Vm<P> {
|
||||
let values = nodes
|
||||
.into_iter()
|
||||
.map(|node| {
|
||||
let span = node.position;
|
||||
let span = node.span;
|
||||
if let Some(value) = self.run_node(node, variables)? {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(VmError::ExpectedValue { position: span })
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<Value>, VmError<P>>>()?;
|
||||
.collect::<Result<Vec<Value>, VmError>>()?;
|
||||
|
||||
Ok(Some(Value::list(values)))
|
||||
}
|
||||
Statement::Multiply(_, _) => todo!(),
|
||||
Statement::PropertyAccess(left, right) => {
|
||||
let left_span = left.position;
|
||||
let left_span = left.span;
|
||||
let left = if let Some(value) = self.run_node(*left, variables)? {
|
||||
value
|
||||
} else {
|
||||
@ -117,7 +118,7 @@ impl<P: Copy> Vm<P> {
|
||||
position: left_span,
|
||||
});
|
||||
};
|
||||
let right_span = right.position;
|
||||
let right_span = right.span;
|
||||
|
||||
if let Statement::ReservedIdentifier(reserved) = &right.statement {
|
||||
match reserved {
|
||||
@ -169,33 +170,33 @@ impl<P: Copy> Vm<P> {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum VmError<P> {
|
||||
AnaylyzerError(AnalyzerError<P>),
|
||||
pub enum VmError {
|
||||
AnaylyzerError(AnalyzerError),
|
||||
ParseError(ParseError),
|
||||
ValueError(ValueError),
|
||||
|
||||
// Anaylsis Failures
|
||||
// These should be prevented by running the analyzer before the VM
|
||||
ExpectedIdentifier { position: P },
|
||||
ExpectedIdentifierOrInteger { position: P },
|
||||
ExpectedInteger { position: P },
|
||||
ExpectedList { position: P },
|
||||
ExpectedValue { position: P },
|
||||
ExpectedIdentifier { position: Span },
|
||||
ExpectedIdentifierOrInteger { position: Span },
|
||||
ExpectedInteger { position: Span },
|
||||
ExpectedList { position: Span },
|
||||
ExpectedValue { position: Span },
|
||||
}
|
||||
|
||||
impl<P> From<AnalyzerError<P>> for VmError<P> {
|
||||
fn from(error: AnalyzerError<P>) -> Self {
|
||||
impl From<AnalyzerError> for VmError {
|
||||
fn from(error: AnalyzerError) -> Self {
|
||||
Self::AnaylyzerError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> From<ParseError> for VmError<P> {
|
||||
impl From<ParseError> for VmError {
|
||||
fn from(error: ParseError) -> Self {
|
||||
Self::ParseError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> From<ValueError> for VmError<P> {
|
||||
impl From<ValueError> for VmError {
|
||||
fn from(error: ValueError) -> Self {
|
||||
Self::ValueError(error)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user