dust/dust-lang/src/analyzer.rs

277 lines
8.7 KiB
Rust
Raw Normal View History

2024-08-07 16:13:49 +00:00
/// Tools for analyzing an abstract syntax tree and catch errors before running the virtual
/// machine.
///
/// This module provides to anlysis options, both of which borrow an abstract syntax tree and a
/// hash map of variables:
/// - `analyze` convenience function
/// - `Analyzer` struct
2024-08-07 15:57:15 +00:00
use std::collections::HashMap;
use crate::{AbstractSyntaxTree, Identifier, Node, Statement, Type, Value};
/// Analyzes the abstract syntax tree for errors.
///
/// # Examples
/// ```
/// # use std::collections::HashMap;
/// # use dust_lang::*;
/// let input = "x = 1 + false";
/// let abstract_tree = parse(input).unwrap();
/// let variables = HashMap::new();
/// let result = analyze(&abstract_tree, &variables);
///
/// assert!(result.is_err());
/// ```
2024-08-07 19:47:37 +00:00
pub fn analyze<P: Clone>(
abstract_tree: &AbstractSyntaxTree<P>,
2024-08-07 15:57:15 +00:00
variables: &HashMap<Identifier, Value>,
2024-08-07 19:47:37 +00:00
) -> Result<(), AnalyzerError<P>> {
2024-08-07 15:57:15 +00:00
let analyzer = Analyzer::new(abstract_tree, variables);
2024-08-05 04:40:51 +00:00
analyzer.analyze()
}
2024-08-07 16:13:49 +00:00
/// Static analyzer that checks for potential runtime errors.
///
/// # Examples
/// ```
/// # use std::collections::HashMap;
/// # use dust_lang::*;
/// let input = "x = 1 + false";
/// let abstract_tree = parse(input).unwrap();
/// let variables = HashMap::new();
/// let analyzer = Analyzer::new(&abstract_tree, &variables);
/// let result = analyzer.analyze();
///
/// assert!(result.is_err());
2024-08-07 19:47:37 +00:00
pub struct Analyzer<'a, P> {
abstract_tree: &'a AbstractSyntaxTree<P>,
2024-08-07 15:57:15 +00:00
variables: &'a HashMap<Identifier, Value>,
2024-08-05 03:11:04 +00:00
}
2024-08-07 19:47:37 +00:00
impl<'a, P: Clone> Analyzer<'a, P> {
2024-08-07 15:57:15 +00:00
pub fn new(
2024-08-07 19:47:37 +00:00
abstract_tree: &'a AbstractSyntaxTree<P>,
2024-08-07 15:57:15 +00:00
variables: &'a HashMap<Identifier, Value>,
) -> Self {
Self {
abstract_tree,
variables,
}
2024-08-05 03:11:04 +00:00
}
2024-08-07 19:47:37 +00:00
pub fn analyze(&self) -> Result<(), AnalyzerError<P>> {
2024-08-07 15:38:08 +00:00
for node in &self.abstract_tree.nodes {
2024-08-05 03:11:04 +00:00
self.analyze_node(node)?;
}
Ok(())
}
2024-08-07 19:47:37 +00:00
fn analyze_node(&self, node: &Node<P>) -> Result<(), AnalyzerError<P>> {
2024-08-05 04:40:51 +00:00
match &node.statement {
Statement::Add(left, right) => {
2024-08-07 15:57:15 +00:00
if let Some(Type::Integer) | Some(Type::Float) =
left.statement.expected_type(self.variables)
{
} else {
return Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: left.as_ref().clone(),
});
}
if let Some(Type::Integer) | Some(Type::Float) =
right.statement.expected_type(self.variables)
{
} else {
return Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: right.as_ref().clone(),
});
}
self.analyze_node(left)?;
self.analyze_node(right)?;
2024-08-05 03:11:04 +00:00
}
2024-08-05 04:40:51 +00:00
Statement::Assign(left, right) => {
if let Statement::Identifier(_) = &left.statement {
// Identifier is in the correct position
2024-08-05 03:11:04 +00:00
} else {
return Err(AnalyzerError::ExpectedIdentifier {
2024-08-05 04:40:51 +00:00
actual: left.as_ref().clone(),
2024-08-05 03:11:04 +00:00
});
}
self.analyze_node(right)?;
2024-08-05 03:11:04 +00:00
}
Statement::BuiltInFunctionCall { .. } => {}
2024-08-05 03:11:04 +00:00
Statement::Constant(_) => {}
Statement::FunctionCall { function, .. } => {
if let Statement::Identifier(_) = &function.statement {
// Function is in the correct position
} else {
return Err(AnalyzerError::ExpectedIdentifier {
actual: function.as_ref().clone(),
});
}
}
2024-08-05 04:40:51 +00:00
Statement::Identifier(_) => {
return Err(AnalyzerError::UnexpectedIdentifier {
identifier: node.clone(),
});
}
Statement::List(statements) => {
for statement in statements {
self.analyze_node(statement)?;
2024-08-05 03:11:04 +00:00
}
}
2024-08-05 04:40:51 +00:00
Statement::Multiply(left, right) => {
2024-08-07 15:57:15 +00:00
if let Some(Type::Integer) | Some(Type::Float) =
left.statement.expected_type(self.variables)
{
} else {
return Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: left.as_ref().clone(),
});
}
if let Some(Type::Integer) | Some(Type::Float) =
right.statement.expected_type(self.variables)
{
} else {
return Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: right.as_ref().clone(),
});
}
self.analyze_node(left)?;
self.analyze_node(right)?;
2024-08-05 03:11:04 +00:00
}
2024-08-05 18:31:08 +00:00
Statement::PropertyAccess(left, right) => {
2024-08-07 15:57:15 +00:00
if let Statement::Identifier(_) | Statement::Constant(_) | Statement::List(_) =
&left.statement
{
// Left side is valid
2024-08-05 18:31:08 +00:00
} else {
return Err(AnalyzerError::ExpectedIdentifier {
actual: left.as_ref().clone(),
});
}
self.analyze_node(right)?;
2024-08-05 18:31:08 +00:00
}
2024-08-05 03:11:04 +00:00
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
2024-08-07 19:47:37 +00:00
pub enum AnalyzerError<P> {
ExpectedFunction { position: P },
2024-08-07 19:47:37 +00:00
ExpectedIdentifier { actual: Node<P> },
ExpectedIntegerOrFloat { actual: Node<P> },
UnexpectedIdentifier { identifier: Node<P> },
2024-08-05 03:11:04 +00:00
}
#[cfg(test)]
mod tests {
2024-08-05 04:40:51 +00:00
use crate::{Identifier, Value};
2024-08-05 03:11:04 +00:00
use super::*;
#[test]
2024-08-07 15:57:15 +00:00
fn multiply_expect_integer_or_float() {
2024-08-07 15:38:08 +00:00
let abstract_tree = AbstractSyntaxTree {
nodes: [Node::new(
2024-08-07 15:57:15 +00:00
Statement::Multiply(
2024-08-07 15:38:08 +00:00
Box::new(Node::new(Statement::Constant(Value::integer(1)), (0, 1))),
2024-08-07 15:57:15 +00:00
Box::new(Node::new(
Statement::Constant(Value::boolean(false)),
(1, 2),
)),
2024-08-07 15:38:08 +00:00
),
(0, 2),
)]
.into(),
};
2024-08-07 15:57:15 +00:00
let variables = HashMap::new();
let analyzer = Analyzer::new(&abstract_tree, &variables);
2024-08-05 03:11:04 +00:00
assert_eq!(
analyzer.analyze(),
2024-08-07 15:57:15 +00:00
Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: Node::new(Statement::Constant(Value::boolean(false)), (1, 2))
2024-08-05 03:11:04 +00:00
})
)
}
2024-08-05 04:40:51 +00:00
#[test]
2024-08-07 15:57:15 +00:00
fn add_expect_integer_or_float() {
2024-08-07 15:38:08 +00:00
let abstract_tree = AbstractSyntaxTree {
nodes: [Node::new(
2024-08-07 15:57:15 +00:00
Statement::Add(
Box::new(Node::new(Statement::Constant(Value::integer(1)), (0, 1))),
Box::new(Node::new(
Statement::Constant(Value::boolean(false)),
(1, 2),
)),
),
(0, 2),
2024-08-07 15:38:08 +00:00
)]
.into(),
};
2024-08-07 15:57:15 +00:00
let variables = HashMap::new();
let analyzer = Analyzer::new(&abstract_tree, &variables);
2024-08-05 04:40:51 +00:00
assert_eq!(
analyzer.analyze(),
2024-08-07 15:57:15 +00:00
Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: Node::new(Statement::Constant(Value::boolean(false)), (1, 2))
2024-08-05 04:40:51 +00:00
})
)
}
#[test]
2024-08-07 15:57:15 +00:00
fn assignment_expect_identifier() {
2024-08-07 15:38:08 +00:00
let abstract_tree = AbstractSyntaxTree {
nodes: [Node::new(
2024-08-07 15:57:15 +00:00
Statement::Assign(
2024-08-07 15:38:08 +00:00
Box::new(Node::new(Statement::Constant(Value::integer(1)), (0, 1))),
2024-08-07 15:57:15 +00:00
Box::new(Node::new(Statement::Constant(Value::integer(2)), (1, 2))),
2024-08-07 15:38:08 +00:00
),
2024-08-07 15:57:15 +00:00
(0, 2),
2024-08-07 15:38:08 +00:00
)]
.into(),
};
2024-08-07 15:57:15 +00:00
let variables = HashMap::new();
let analyzer = Analyzer::new(&abstract_tree, &variables);
2024-08-07 15:38:08 +00:00
2024-08-07 15:57:15 +00:00
assert_eq!(
analyzer.analyze(),
Err(AnalyzerError::ExpectedIdentifier {
actual: Node::new(Statement::Constant(Value::integer(1)), (0, 1))
})
)
}
#[test]
fn unexpected_identifier() {
let abstract_tree = AbstractSyntaxTree {
nodes: [Node::new(
Statement::Identifier(Identifier::new("x")),
(0, 1),
)]
.into(),
};
let variables = HashMap::new();
let analyzer = Analyzer::new(&abstract_tree, &variables);
2024-08-05 04:40:51 +00:00
assert_eq!(
analyzer.analyze(),
Err(AnalyzerError::UnexpectedIdentifier {
2024-08-07 15:57:15 +00:00
identifier: Node::new(Statement::Identifier(Identifier::new("x")), (0, 1))
2024-08-05 04:40:51 +00:00
})
)
}
2024-08-05 03:11:04 +00:00
}