1
0

Compare commits

...

3 Commits

Author SHA1 Message Date
c0254e8a94 Refactor to use type checking 2024-08-11 19:18:13 -04:00
77814c4576 Begin refactoring to use type checking 2024-08-11 19:00:37 -04:00
7259206c98 Add analyzing built-in function calls 2024-08-11 18:11:59 -04:00
6 changed files with 183 additions and 272 deletions

View File

@ -136,7 +136,6 @@ impl Statement {
let item_type = nodes.first().unwrap().inner.expected_type(context)?; let item_type = nodes.first().unwrap().inner.expected_type(context)?;
Some(Type::List { Some(Type::List {
length: nodes.len(),
item_type: Box::new(item_type), item_type: Box::new(item_type),
}) })
} }

View File

@ -11,8 +11,8 @@ use std::{
}; };
use crate::{ use crate::{
abstract_tree::BinaryOperator, parse, AbstractSyntaxTree, BuiltInFunction, Context, DustError, abstract_tree::BinaryOperator, parse, AbstractSyntaxTree, Context, DustError, Node, Span,
Node, Span, Statement, Type, Statement, Type,
}; };
/// Analyzes the abstract syntax tree for errors. /// Analyzes the abstract syntax tree for errors.
@ -22,15 +22,14 @@ use crate::{
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// # use dust_lang::*; /// # use dust_lang::*;
/// let input = "x = 1 + false"; /// let input = "x = 1 + false";
/// let abstract_tree = parse(input).unwrap(); /// let result = analyze(input);
/// let mut context = Context::new();
/// let result = analyze(&abstract_tree, &mut context);
/// ///
/// assert!(result.is_err()); /// assert!(result.is_err());
/// ``` /// ```
pub fn analyze<'src>(source: &'src str, context: &mut Context) -> Result<(), DustError<'src>> { pub fn analyze(source: &str) -> Result<(), DustError> {
let abstract_tree = parse(source)?; let abstract_tree = parse(source)?;
let mut analyzer = Analyzer::new(&abstract_tree, context); let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
analyzer analyzer
.analyze() .analyze()
@ -91,7 +90,6 @@ impl<'a> Analyzer<'a> {
identifier.clone(), identifier.clone(),
right_type.ok_or(AnalyzerError::ExpectedValue { right_type.ok_or(AnalyzerError::ExpectedValue {
actual: right.as_ref().clone(), actual: right.as_ref().clone(),
position: right.position,
})?, })?,
); );
@ -114,34 +112,20 @@ impl<'a> Analyzer<'a> {
| BinaryOperator::Less | BinaryOperator::Less
| BinaryOperator::LessOrEqual = operator.inner | BinaryOperator::LessOrEqual = operator.inner
{ {
match (left_type, right_type) { if let Some(expected_type) = left_type {
(Some(Type::Integer), Some(Type::Integer)) => {} if let Some(actual_type) = right_type {
(Some(Type::Float), Some(Type::Float)) => {} expected_type.check(&actual_type).map_err(|conflict| {
(Some(Type::String), Some(Type::String)) => {} AnalyzerError::TypeConflict {
(Some(Type::Integer), _) => { actual_statement: right.as_ref().clone(),
return Err(AnalyzerError::ExpectedInteger { actual_type: conflict.actual,
expected: conflict.expected,
}
})?;
} else {
return Err(AnalyzerError::ExpectedValue {
actual: right.as_ref().clone(), actual: right.as_ref().clone(),
position: right.position,
}); });
} }
(Some(Type::Float), _) => {
return Err(AnalyzerError::ExpectedFloat {
actual: right.as_ref().clone(),
position: right.position,
});
}
(Some(Type::String), _) => {
return Err(AnalyzerError::ExpectedString {
actual: right.as_ref().clone(),
position: right.position,
});
}
(_, _) => {
return Err(AnalyzerError::ExpectedIntegerFloatOrString {
actual: right.as_ref().clone(),
position: right.position,
})
}
} }
} }
} }
@ -150,7 +134,61 @@ impl<'a> Analyzer<'a> {
self.analyze_node(statement)?; self.analyze_node(statement)?;
} }
} }
Statement::BuiltInFunctionCall { .. } => {} Statement::BuiltInFunctionCall {
function,
value_arguments,
..
} => {
let value_parameters = function.value_parameters();
if let Some(arguments) = value_arguments {
for argument in arguments {
self.analyze_node(argument)?;
}
if arguments.len() != value_parameters.len() {
return Err(AnalyzerError::ExpectedValueArgumentCount {
expected: value_parameters.len(),
actual: arguments.len(),
position: node.position,
});
}
for ((_identifier, parameter_type), argument) in
value_parameters.iter().zip(arguments)
{
let argument_type_option = argument.inner.expected_type(self.context);
if let Some(argument_type) = argument_type_option {
parameter_type.check(&argument_type).map_err(|conflict| {
AnalyzerError::TypeConflict {
actual_statement: argument.clone(),
actual_type: conflict.actual,
expected: parameter_type.clone(),
}
})?;
} else {
return Err(AnalyzerError::ExpectedValue {
actual: argument.clone(),
});
}
}
if arguments.is_empty() && !value_parameters.is_empty() {
return Err(AnalyzerError::ExpectedValueArgumentCount {
expected: value_parameters.len(),
actual: 0,
position: node.position,
});
}
} else if !value_parameters.is_empty() {
return Err(AnalyzerError::ExpectedValueArgumentCount {
expected: value_parameters.len(),
actual: 0,
position: node.position,
});
}
}
Statement::Constant(_) => {} Statement::Constant(_) => {}
Statement::FunctionCall { function, .. } => { Statement::FunctionCall { function, .. } => {
if let Statement::Identifier(_) = &function.inner { if let Statement::Identifier(_) = &function.inner {
@ -294,22 +332,10 @@ impl<'a> Analyzer<'a> {
} else { } else {
return Err(AnalyzerError::ExpectedValue { return Err(AnalyzerError::ExpectedValue {
actual: left.as_ref().clone(), actual: left.as_ref().clone(),
position: left.position,
}); });
} }
if let Statement::BuiltInFunctionCall { function, .. } = &right.inner { self.analyze_node(left)?;
if function == &BuiltInFunction::IsEven || function == &BuiltInFunction::IsOdd {
if let Some(Type::Integer) = left.inner.expected_type(self.context) {
} else {
return Err(AnalyzerError::ExpectedIntegerOrFloat {
actual: left.as_ref().clone(),
position: left.position,
});
}
}
}
self.analyze_node(right)?; self.analyze_node(right)?;
} }
Statement::While { condition, body } => { Statement::While { condition, body } => {
@ -332,52 +358,35 @@ impl<'a> Analyzer<'a> {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum AnalyzerError { pub enum AnalyzerError {
ExpectedBoolean {
actual: Node<Statement>,
position: Span,
},
ExpectedFloat {
actual: Node<Statement>,
position: (usize, usize),
},
ExpectedFunction {
actual: Node<Statement>,
position: Span,
},
ExpectedIdentifier { ExpectedIdentifier {
actual: Node<Statement>, actual: Node<Statement>,
position: Span, position: Span,
}, },
ExpectedInteger { ExpectedBoolean {
actual: Node<Statement>, actual: Node<Statement>,
position: Span, position: Span,
}, },
ExpectedIntegerOrFloat {
actual: Node<Statement>,
position: Span,
},
ExpectedIntegerFloatOrString {
actual: Node<Statement>,
position: Span,
},
ExpectedString {
actual: Node<Statement>,
position: (usize, usize),
},
ExpectedValue { ExpectedValue {
actual: Node<Statement>, actual: Node<Statement>,
},
ExpectedValueArgumentCount {
expected: usize,
actual: usize,
position: Span, position: Span,
}, },
TypeConflict {
actual_statement: Node<Statement>,
actual_type: Type,
expected: Type,
},
UndefinedVariable { UndefinedVariable {
identifier: Node<Statement>, identifier: Node<Statement>,
}, },
UnexpectedIdentifier { UnexpectedIdentifier {
identifier: Node<Statement>, identifier: Node<Statement>,
position: Span,
}, },
UnexectedString { UnexectedString {
actual: Node<Statement>, actual: Node<Statement>,
position: (usize, usize),
}, },
} }
@ -385,17 +394,15 @@ impl AnalyzerError {
pub fn position(&self) -> Span { pub fn position(&self) -> Span {
match self { match self {
AnalyzerError::ExpectedBoolean { position, .. } => *position, AnalyzerError::ExpectedBoolean { position, .. } => *position,
AnalyzerError::ExpectedFloat { position, .. } => *position,
AnalyzerError::ExpectedFunction { position, .. } => *position,
AnalyzerError::ExpectedIdentifier { position, .. } => *position, AnalyzerError::ExpectedIdentifier { position, .. } => *position,
AnalyzerError::ExpectedValue { position, .. } => *position, AnalyzerError::ExpectedValue { actual } => actual.position,
AnalyzerError::ExpectedInteger { position, .. } => *position, AnalyzerError::ExpectedValueArgumentCount { position, .. } => *position,
AnalyzerError::ExpectedIntegerOrFloat { position, .. } => *position, AnalyzerError::TypeConflict {
AnalyzerError::ExpectedIntegerFloatOrString { position, .. } => *position, actual_statement, ..
AnalyzerError::ExpectedString { position, .. } => *position, } => actual_statement.position,
AnalyzerError::UndefinedVariable { identifier } => identifier.position, AnalyzerError::UndefinedVariable { identifier } => identifier.position,
AnalyzerError::UnexpectedIdentifier { position, .. } => *position, AnalyzerError::UnexpectedIdentifier { identifier } => identifier.position,
AnalyzerError::UnexectedString { position, .. } => *position, AnalyzerError::UnexectedString { actual } => actual.position,
} }
} }
} }
@ -408,30 +415,26 @@ impl Display for AnalyzerError {
AnalyzerError::ExpectedBoolean { actual, .. } => { AnalyzerError::ExpectedBoolean { actual, .. } => {
write!(f, "Expected boolean, found {}", actual) write!(f, "Expected boolean, found {}", actual)
} }
AnalyzerError::ExpectedFunction { actual, .. } => {
write!(f, "Expected function, found {}", actual)
}
AnalyzerError::ExpectedFloat { actual, .. } => {
write!(f, "Expected float, found {}", actual)
}
AnalyzerError::ExpectedIdentifier { actual, .. } => { AnalyzerError::ExpectedIdentifier { actual, .. } => {
write!(f, "Expected identifier, found {}", actual) write!(f, "Expected identifier, found {}", actual)
} }
AnalyzerError::ExpectedInteger { actual, .. } => {
write!(f, "Expected integer, found {}", actual)
}
AnalyzerError::ExpectedIntegerOrFloat { actual, .. } => {
write!(f, "Expected integer or float, found {}", actual)
}
AnalyzerError::ExpectedIntegerFloatOrString { actual, .. } => {
write!(f, "Expected integer, float, or string, found {}", actual)
}
AnalyzerError::ExpectedString { actual, .. } => {
write!(f, "Expected string, found {}", actual)
}
AnalyzerError::ExpectedValue { actual, .. } => { AnalyzerError::ExpectedValue { actual, .. } => {
write!(f, "Expected value, found {}", actual) write!(f, "Expected value, found {}", actual)
} }
AnalyzerError::ExpectedValueArgumentCount {
expected, actual, ..
} => write!(f, "Expected {} value arguments, found {}", expected, actual),
AnalyzerError::TypeConflict {
actual_statement,
actual_type,
expected,
} => {
write!(
f,
"Expected type {}, found {}, which has type {}",
expected, actual_statement, actual_type
)
}
AnalyzerError::UndefinedVariable { identifier } => { AnalyzerError::UndefinedVariable { identifier } => {
write!(f, "Undefined variable {}", identifier) write!(f, "Undefined variable {}", identifier)
} }
@ -447,166 +450,113 @@ impl Display for AnalyzerError {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{BuiltInFunction, Identifier, Value}; use crate::{Identifier, Value};
use super::*; use super::*;
#[test] #[test]
fn write_line_wrong_arguments() { fn length_no_arguments() {
let abstract_tree = AbstractSyntaxTree { let source = "length()";
nodes: [Node::new(
Statement::BuiltInFunctionCall {
function: BuiltInFunction::WriteLine,
type_arguments: None,
value_arguments: Some(vec![Node::new(
Statement::Constant(Value::integer(1)),
(0, 1),
)]),
},
(0, 1),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::ExpectedString { Err(DustError::AnalyzerError {
actual: Node::new(Statement::Constant(Value::integer(1)), (0, 1)), analyzer_error: AnalyzerError::ExpectedValueArgumentCount {
position: (0, 1) expected: 1,
actual: 0,
position: (0, 6)
},
source
}) })
) );
} }
#[test] #[test]
fn float_plus_integer() { fn float_plus_integer() {
let abstract_tree = AbstractSyntaxTree { let source = "42.0 + 2";
nodes: [Node::new(
Statement::BinaryOperation {
left: Box::new(Node::new(Statement::Constant(Value::float(1.0)), (0, 1))),
operator: Node::new(BinaryOperator::Add, (1, 2)),
right: Box::new(Node::new(Statement::Constant(Value::integer(1)), (3, 4))),
},
(0, 2),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::ExpectedFloat { Err(DustError::AnalyzerError {
actual: Node::new(Statement::Constant(Value::integer(1)), (3, 4)), analyzer_error: AnalyzerError::TypeConflict {
position: (3, 4) actual_statement: Node::new(Statement::Constant(Value::integer(2)), (7, 8)),
actual_type: Type::Integer,
expected: Type::Float,
},
source
}) })
) )
} }
#[test] #[test]
fn integer_plus_boolean() { fn integer_plus_boolean() {
let abstract_tree = AbstractSyntaxTree { let source = "42 + true";
nodes: [Node::new(
Statement::BinaryOperation {
left: Box::new(Node::new(Statement::Constant(Value::integer(1)), (0, 1))),
operator: Node::new(BinaryOperator::Add, (1, 2)),
right: Box::new(Node::new(Statement::Constant(Value::boolean(true)), (3, 4))),
},
(0, 2),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::ExpectedInteger { Err(DustError::AnalyzerError {
actual: Node::new(Statement::Constant(Value::boolean(true)), (3, 4)), analyzer_error: AnalyzerError::TypeConflict {
position: (3, 4) actual_statement: Node::new(Statement::Constant(Value::boolean(true)), (5, 9)),
actual_type: Type::Boolean,
expected: Type::Integer,
},
source
}) })
) )
} }
#[test] #[test]
fn is_even_expects_number() { fn is_even_expects_number() {
let abstract_tree = AbstractSyntaxTree { let source = "is_even('hello')";
nodes: [Node::new(
Statement::PropertyAccess(
Box::new(Node::new(Statement::Constant(Value::boolean(true)), (0, 1))),
Box::new(Node::new(
Statement::BuiltInFunctionCall {
function: BuiltInFunction::IsEven,
type_arguments: None,
value_arguments: None,
},
(1, 2),
)),
),
(0, 2),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::ExpectedIntegerOrFloat { Err(DustError::AnalyzerError {
actual: Node::new(Statement::Constant(Value::boolean(true)), (0, 1)), analyzer_error: AnalyzerError::TypeConflict {
position: (0, 1) actual_statement: Node::new(
Statement::Constant(Value::string("hello")),
(8, 15)
),
actual_type: Type::String,
expected: Type::Number,
},
source
}) })
) );
} }
#[test] #[test]
fn is_odd_expects_number() { fn is_odd_expects_number() {
let abstract_tree = AbstractSyntaxTree { let source = "is_odd('hello')";
nodes: [Node::new(
Statement::PropertyAccess(
Box::new(Node::new(Statement::Constant(Value::boolean(true)), (0, 1))),
Box::new(Node::new(
Statement::BuiltInFunctionCall {
function: BuiltInFunction::IsOdd,
type_arguments: None,
value_arguments: None,
},
(1, 2),
)),
),
(0, 2),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::ExpectedIntegerOrFloat { Err(DustError::AnalyzerError {
actual: Node::new(Statement::Constant(Value::boolean(true)), (0, 1)), analyzer_error: AnalyzerError::TypeConflict {
position: (0, 1) actual_statement: Node::new(
Statement::Constant(Value::string("hello")),
(7, 14)
),
actual_type: Type::String,
expected: Type::Number,
},
source
}) })
) );
} }
#[test] #[test]
fn undefined_variable() { fn undefined_variable() {
let abstract_tree = AbstractSyntaxTree { let source = "foo";
nodes: [Node::new(
Statement::Identifier(Identifier::new("x")),
(0, 1),
)]
.into(),
};
let mut context = Context::new();
let mut analyzer = Analyzer::new(&abstract_tree, &mut context);
assert_eq!( assert_eq!(
analyzer.analyze(), analyze(source),
Err(AnalyzerError::UndefinedVariable { Err(DustError::AnalyzerError {
identifier: Node::new(Statement::Identifier(Identifier::new("x")), (0, 1)) analyzer_error: AnalyzerError::UndefinedVariable {
identifier: Node::new(Statement::Identifier(Identifier::new("foo")), (0, 3)),
},
source
}) })
) );
} }
} }

View File

@ -42,14 +42,13 @@ impl BuiltInFunction {
pub fn value_parameters(&self) -> Vec<(Identifier, Type)> { pub fn value_parameters(&self) -> Vec<(Identifier, Type)> {
match self { match self {
BuiltInFunction::ToString => vec![("value".into(), Type::Any)], BuiltInFunction::ToString => vec![("value".into(), Type::Any)],
BuiltInFunction::IsEven => vec![("value".into(), Type::Integer)], BuiltInFunction::IsEven => vec![("value".into(), Type::Number)],
BuiltInFunction::IsOdd => vec![("value".into(), Type::Integer)], BuiltInFunction::IsOdd => vec![("value".into(), Type::Number)],
BuiltInFunction::Length => { BuiltInFunction::Length => {
vec![( vec![(
"value".into(), "value".into(),
Type::List { Type::List {
item_type: Box::new(Type::Any), item_type: Box::new(Type::Any),
length: 1,
}, },
)] )]
} }

View File

@ -48,10 +48,10 @@ pub enum Type {
}, },
Integer, Integer,
List { List {
length: usize,
item_type: Box<Type>, item_type: Box<Type>,
}, },
Map(BTreeMap<Identifier, Type>), Map(BTreeMap<Identifier, Type>),
Number,
Range, Range,
String, String,
Structure { Structure {
@ -137,15 +137,13 @@ impl Type {
} }
( (
Type::List { Type::List {
length: left_length,
item_type: left_type, item_type: left_type,
}, },
Type::List { Type::List {
length: right_length,
item_type: right_type, item_type: right_type,
}, },
) => { ) => {
if left_length != right_length || left_type != right_type { if left_type.check(right_type).is_err() {
return Err(TypeConflict { return Err(TypeConflict {
actual: other.clone(), actual: other.clone(),
expected: self.clone(), expected: self.clone(),
@ -199,6 +197,10 @@ impl Type {
return Ok(()); return Ok(());
} }
} }
(Type::Number, Type::Number | Type::Integer | Type::Float)
| (Type::Integer | Type::Float, Type::Number) => {
return Ok(());
}
_ => {} _ => {}
} }
@ -244,7 +246,7 @@ impl Display for Type {
} }
} }
Type::Integer => write!(f, "int"), Type::Integer => write!(f, "int"),
Type::List { length, item_type } => write!(f, "[{length}; {}]", item_type), Type::List { item_type } => write!(f, "[{item_type}]"),
Type::Map(map) => { Type::Map(map) => {
write!(f, "{{ ")?; write!(f, "{{ ")?;
@ -258,6 +260,7 @@ impl Display for Type {
write!(f, " }}") write!(f, " }}")
} }
Type::Number => write!(f, "num"),
Type::Range => write!(f, "range"), Type::Range => write!(f, "range"),
Type::String => write!(f, "str"), Type::String => write!(f, "str"),
Type::Function { Type::Function {
@ -310,11 +313,9 @@ mod tests {
assert_eq!(Type::Integer.check(&Type::Integer), Ok(())); assert_eq!(Type::Integer.check(&Type::Integer), Ok(()));
assert_eq!( assert_eq!(
Type::List { Type::List {
length: 4,
item_type: Box::new(Type::Boolean), item_type: Box::new(Type::Boolean),
} }
.check(&Type::List { .check(&Type::List {
length: 4,
item_type: Box::new(Type::Boolean), item_type: Box::new(Type::Boolean),
}), }),
Ok(()) Ok(())
@ -356,7 +357,6 @@ mod tests {
Type::Float, Type::Float,
Type::Integer, Type::Integer,
Type::List { Type::List {
length: 10,
item_type: Box::new(Type::Integer), item_type: Box::new(Type::Integer),
}, },
Type::Map(BTreeMap::new()), Type::Map(BTreeMap::new()),

View File

@ -640,7 +640,6 @@ impl ValueInner {
let item_type = values.first().unwrap().r#type(context); let item_type = values.first().unwrap().r#type(context);
Type::List { Type::List {
length: values.len(),
item_type: Box::new(item_type), item_type: Box::new(item_type),
} }
} }

View File

@ -464,42 +464,6 @@ impl Vm {
} }
} }
if let (
value,
Statement::BuiltInFunctionCall {
function,
type_arguments: _,
value_arguments: value_argument_nodes,
},
) = (left_value, right.inner)
{
let mut value_arguments = Vec::new();
value_arguments.push(value);
if let Some(value_nodes) = value_argument_nodes {
for node in value_nodes {
let position = node.position;
let value = if let Some(value) = self.run_node(node, context)? {
value
} else {
return Err(VmError::ExpectedValue { position });
};
value_arguments.push(value);
}
}
let function_call_return = function.call(None, Some(value_arguments)).map_err(
|built_in_function_error| VmError::BuiltInFunctionError {
error: built_in_function_error,
position: right_span,
},
)?;
return Ok(function_call_return);
}
Err(VmError::ExpectedIdentifierOrInteger { Err(VmError::ExpectedIdentifierOrInteger {
position: right_span, position: right_span,
}) })
@ -648,7 +612,7 @@ mod tests {
#[test] #[test]
fn to_string() { fn to_string() {
let input = "42.to_string()"; let input = "to_string(42)";
assert_eq!( assert_eq!(
run(input, &mut Context::new()), run(input, &mut Context::new()),
@ -824,7 +788,7 @@ mod tests {
#[test] #[test]
fn is_even() { fn is_even() {
let input = "42.is_even()"; let input = "is_even(42)";
assert_eq!( assert_eq!(
run(input, &mut Context::new()), run(input, &mut Context::new()),
@ -834,7 +798,7 @@ mod tests {
#[test] #[test]
fn is_odd() { fn is_odd() {
let input = "42.is_odd()"; let input = "is_odd(42)";
assert_eq!( assert_eq!(
run(input, &mut Context::new()), run(input, &mut Context::new()),
@ -844,7 +808,7 @@ mod tests {
#[test] #[test]
fn length() { fn length() {
let input = "[1, 2, 3].length()"; let input = "length([1, 2, 3])";
assert_eq!(run(input, &mut Context::new()), Ok(Some(Value::integer(3)))); assert_eq!(run(input, &mut Context::new()), Ok(Some(Value::integer(3))));
} }