Add the expected_type
function for statements
This commit is contained in:
parent
dfee50003a
commit
a60df0274c
@ -1,6 +1,13 @@
|
||||
use crate::{Identifier, ReservedIdentifier, Span, Value};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::{self, Display, Formatter},
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Identifier, ReservedIdentifier, Span, Type, Value};
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
pub statement: Statement,
|
||||
pub span: Span,
|
||||
@ -15,7 +22,13 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
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 {
|
||||
// Top-level statements
|
||||
Assign(Box<Node>, Box<Node>),
|
||||
@ -31,3 +44,48 @@ pub enum Statement {
|
||||
Identifier(Identifier),
|
||||
ReservedIdentifier(ReservedIdentifier),
|
||||
}
|
||||
|
||||
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::Constant(value) => Some(value.r#type(variables)),
|
||||
Statement::Identifier(identifier) => variables
|
||||
.get(identifier)
|
||||
.map(|value| value.r#type(variables)),
|
||||
Statement::List(_) => None,
|
||||
Statement::Multiply(left, _) => left.statement.expected_type(variables),
|
||||
Statement::PropertyAccess(_, _) => None,
|
||||
Statement::ReservedIdentifier(reserved) => match reserved {
|
||||
ReservedIdentifier::IsEven => Some(Type::Boolean),
|
||||
ReservedIdentifier::IsOdd => Some(Type::Boolean),
|
||||
ReservedIdentifier::Length => Some(Type::Integer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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::PropertyAccess(left, right) => write!(f, "{}.{}", left, right),
|
||||
Statement::List(nodes) => {
|
||||
write!(f, "[")?;
|
||||
for (i, node) in nodes.iter().enumerate() {
|
||||
if i > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{}", node)?;
|
||||
}
|
||||
write!(f, "]")
|
||||
}
|
||||
Statement::Multiply(left, right) => write!(f, "{} * {}", left, right),
|
||||
Statement::Constant(value) => write!(f, "{}", value),
|
||||
Statement::Identifier(identifier) => write!(f, "{}", identifier),
|
||||
Statement::ReservedIdentifier(identifier) => write!(f, "{}", identifier),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -26,8 +26,8 @@ impl Analyzer {
|
||||
fn analyze_node(&self, node: &Node) -> Result<(), AnalyzerError> {
|
||||
match &node.statement {
|
||||
Statement::Add(left, right) => {
|
||||
self.analyze_node(&left)?;
|
||||
self.analyze_node(&right)?;
|
||||
self.analyze_node(left)?;
|
||||
self.analyze_node(right)?;
|
||||
}
|
||||
Statement::Assign(left, right) => {
|
||||
if let Statement::Identifier(_) = &left.statement {
|
||||
@ -38,7 +38,7 @@ impl Analyzer {
|
||||
});
|
||||
}
|
||||
|
||||
self.analyze_node(&right)?;
|
||||
self.analyze_node(right)?;
|
||||
}
|
||||
Statement::Constant(_) => {}
|
||||
Statement::Identifier(_) => {
|
||||
@ -52,8 +52,8 @@ impl Analyzer {
|
||||
}
|
||||
}
|
||||
Statement::Multiply(left, right) => {
|
||||
self.analyze_node(&left)?;
|
||||
self.analyze_node(&right)?;
|
||||
self.analyze_node(left)?;
|
||||
self.analyze_node(right)?;
|
||||
}
|
||||
Statement::PropertyAccess(left, right) => {
|
||||
if let Statement::Identifier(_) = &left.statement {
|
||||
@ -64,7 +64,7 @@ impl Analyzer {
|
||||
});
|
||||
}
|
||||
|
||||
self.analyze_node(&right)?;
|
||||
self.analyze_node(right)?;
|
||||
}
|
||||
Statement::ReservedIdentifier(_) => {}
|
||||
}
|
||||
|
@ -1,3 +1,7 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Identifier;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
@ -18,9 +22,19 @@ pub enum Token {
|
||||
Float(f64),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum ReservedIdentifier {
|
||||
IsEven,
|
||||
IsOdd,
|
||||
Length,
|
||||
}
|
||||
|
||||
impl Display for ReservedIdentifier {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ReservedIdentifier::IsEven => write!(f, "is_even"),
|
||||
ReservedIdentifier::IsOdd => write!(f, "is_odd"),
|
||||
ReservedIdentifier::Length => write!(f, "length"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -40,7 +40,7 @@ pub enum Type {
|
||||
},
|
||||
Float,
|
||||
Function {
|
||||
type_parameters: Option<Vec<Identifier>>,
|
||||
type_parameters: Option<Vec<Type>>,
|
||||
value_parameters: Option<Vec<(Identifier, Type)>>,
|
||||
return_type: Option<Box<Type>>,
|
||||
},
|
||||
|
@ -1,6 +1,6 @@
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
collections::BTreeMap,
|
||||
collections::{BTreeMap, HashMap},
|
||||
fmt::{self, Display, Formatter},
|
||||
ops::Range,
|
||||
sync::Arc,
|
||||
@ -12,7 +12,7 @@ use serde::{
|
||||
Deserialize, Deserializer, Serialize,
|
||||
};
|
||||
|
||||
use crate::{identifier::Identifier, Type};
|
||||
use crate::{identifier::Identifier, Statement, Type};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Value(Arc<ValueInner>);
|
||||
@ -50,8 +50,8 @@ impl Value {
|
||||
Value(Arc::new(ValueInner::String(to_string.to_string())))
|
||||
}
|
||||
|
||||
pub fn r#type(&self) -> Type {
|
||||
self.0.r#type()
|
||||
pub fn r#type(&self, variables: &HashMap<Identifier, Value>) -> Type {
|
||||
self.0.r#type(variables)
|
||||
}
|
||||
|
||||
pub fn as_boolean(&self) -> Option<bool> {
|
||||
@ -102,6 +102,7 @@ impl Display for Value {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
ValueInner::Function(function) => write!(f, "{function}"),
|
||||
ValueInner::Integer(integer) => write!(f, "{integer}"),
|
||||
ValueInner::List(list) => {
|
||||
write!(f, "[")?;
|
||||
@ -157,6 +158,7 @@ impl Serialize for Value {
|
||||
match self.0.as_ref() {
|
||||
ValueInner::Boolean(boolean) => serializer.serialize_bool(*boolean),
|
||||
ValueInner::Float(float) => serializer.serialize_f64(*float),
|
||||
ValueInner::Function(function) => function.serialize(serializer),
|
||||
ValueInner::Integer(integer) => serializer.serialize_i64(*integer),
|
||||
ValueInner::List(list) => {
|
||||
let mut list_ser = serializer.serialize_seq(Some(list.len()))?;
|
||||
@ -435,6 +437,7 @@ impl<'de> Deserialize<'de> for Value {
|
||||
pub enum ValueInner {
|
||||
Boolean(bool),
|
||||
Float(f64),
|
||||
Function(Function),
|
||||
Integer(i64),
|
||||
List(Vec<Value>),
|
||||
Map(BTreeMap<Identifier, Value>),
|
||||
@ -443,13 +446,18 @@ pub enum ValueInner {
|
||||
}
|
||||
|
||||
impl ValueInner {
|
||||
pub fn r#type(&self) -> Type {
|
||||
pub fn r#type(&self, variables: &HashMap<Identifier, Value>) -> Type {
|
||||
match self {
|
||||
ValueInner::Boolean(_) => Type::Boolean,
|
||||
ValueInner::Float(_) => Type::Float,
|
||||
ValueInner::Function(function) => Type::Function {
|
||||
type_parameters: function.type_parameters.clone(),
|
||||
value_parameters: function.value_parameters.clone(),
|
||||
return_type: function.return_type(variables).map(Box::new),
|
||||
},
|
||||
ValueInner::Integer(_) => Type::Integer,
|
||||
ValueInner::List(values) => {
|
||||
let item_type = values.first().unwrap().r#type();
|
||||
let item_type = values.first().unwrap().r#type(variables);
|
||||
|
||||
Type::List {
|
||||
length: values.len(),
|
||||
@ -460,7 +468,7 @@ impl ValueInner {
|
||||
let mut type_map = BTreeMap::new();
|
||||
|
||||
for (identifier, value) in value_map {
|
||||
let r#type = value.r#type();
|
||||
let r#type = value.r#type(variables);
|
||||
|
||||
type_map.insert(identifier.clone(), r#type);
|
||||
}
|
||||
@ -502,6 +510,8 @@ impl Ord for ValueInner {
|
||||
(Boolean(_), _) => Ordering::Greater,
|
||||
(Float(left), Float(right)) => left.total_cmp(right),
|
||||
(Float(_), _) => Ordering::Greater,
|
||||
(Function(left), Function(right)) => left.cmp(right),
|
||||
(Function(_), _) => Ordering::Greater,
|
||||
(Integer(left), Integer(right)) => left.cmp(right),
|
||||
(Integer(_), _) => Ordering::Greater,
|
||||
(List(left), List(right)) => left.cmp(right),
|
||||
@ -524,7 +534,61 @@ impl Ord for ValueInner {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Function {
|
||||
pub name: Identifier,
|
||||
pub type_parameters: Option<Vec<Type>>,
|
||||
pub value_parameters: Option<Vec<(Identifier, Type)>>,
|
||||
pub body: Vec<Statement>,
|
||||
}
|
||||
|
||||
impl Function {
|
||||
pub fn return_type(&self, variables: &HashMap<Identifier, Value>) -> Option<Type> {
|
||||
self.body.last().unwrap().expected_type(variables)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Function {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.name)?;
|
||||
|
||||
if let Some(type_parameters) = &self.type_parameters {
|
||||
write!(f, "<")?;
|
||||
|
||||
for (index, type_parameter) in type_parameters.iter().enumerate() {
|
||||
if index > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
|
||||
write!(f, "{}", type_parameter)?;
|
||||
}
|
||||
|
||||
write!(f, ">")?;
|
||||
}
|
||||
|
||||
write!(f, "(")?;
|
||||
|
||||
if let Some(value_paramers) = &self.value_parameters {
|
||||
for (index, (identifier, r#type)) in value_paramers.iter().enumerate() {
|
||||
if index > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
|
||||
write!(f, "{identifier}: {type}")?;
|
||||
}
|
||||
}
|
||||
|
||||
write!(f, ") {{")?;
|
||||
|
||||
for statement in &self.body {
|
||||
write!(f, "{}", statement)?;
|
||||
}
|
||||
|
||||
write!(f, "}}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum ValueError {
|
||||
CannotAdd(Value, Value),
|
||||
PropertyNotFound { value: Value, property: Identifier },
|
||||
|
@ -70,7 +70,7 @@ impl Vm {
|
||||
let identifier = if let Statement::Identifier(identifier) = &left.statement {
|
||||
identifier
|
||||
} else {
|
||||
return Err(VmError::ExpectedValue {
|
||||
return Err(VmError::ExpectedIdentifier {
|
||||
position: left.span,
|
||||
});
|
||||
};
|
||||
@ -170,10 +170,11 @@ pub enum VmError {
|
||||
|
||||
// Anaylsis Failures
|
||||
// These should be prevented by running the analyzer before the VM
|
||||
ExpectedValue { position: Span },
|
||||
ExpectedIdentifier { position: Span },
|
||||
ExpectedIdentifierOrInteger { position: Span },
|
||||
ExpectedList { position: Span },
|
||||
ExpectedInteger { position: Span },
|
||||
ExpectedList { position: Span },
|
||||
ExpectedValue { position: Span },
|
||||
}
|
||||
|
||||
impl From<ParseError> for VmError {
|
||||
|
Loading…
Reference in New Issue
Block a user