From a60df0274cefa5de427a17b5ba5c31efb22fc6c1 Mon Sep 17 00:00:00 2001 From: Jeff Date: Wed, 7 Aug 2024 10:03:33 -0400 Subject: [PATCH] Add the `expected_type` function for statements --- dust-lang/src/abstract_tree.rs | 64 +++++++++++++++++++++++++-- dust-lang/src/analyzer.rs | 12 ++--- dust-lang/src/token.rs | 16 ++++++- dust-lang/src/type.rs | 2 +- dust-lang/src/value.rs | 80 ++++++++++++++++++++++++++++++---- dust-lang/src/vm.rs | 7 +-- 6 files changed, 159 insertions(+), 22 deletions(-) diff --git a/dust-lang/src/abstract_tree.rs b/dust-lang/src/abstract_tree.rs index 9a38ebf..e321bb1 100644 --- a/dust-lang/src/abstract_tree.rs +++ b/dust-lang/src/abstract_tree.rs @@ -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, Box), @@ -31,3 +44,48 @@ pub enum Statement { Identifier(Identifier), ReservedIdentifier(ReservedIdentifier), } + +impl Statement { + pub fn expected_type(&self, variables: &HashMap) -> Option { + 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), + } + } +} diff --git a/dust-lang/src/analyzer.rs b/dust-lang/src/analyzer.rs index a592a64..013c368 100644 --- a/dust-lang/src/analyzer.rs +++ b/dust-lang/src/analyzer.rs @@ -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(_) => {} } diff --git a/dust-lang/src/token.rs b/dust-lang/src/token.rs index 3bbe859..ba91423 100644 --- a/dust-lang/src/token.rs +++ b/dust-lang/src/token.rs @@ -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"), + } + } +} diff --git a/dust-lang/src/type.rs b/dust-lang/src/type.rs index ea9c678..c7acf40 100644 --- a/dust-lang/src/type.rs +++ b/dust-lang/src/type.rs @@ -40,7 +40,7 @@ pub enum Type { }, Float, Function { - type_parameters: Option>, + type_parameters: Option>, value_parameters: Option>, return_type: Option>, }, diff --git a/dust-lang/src/value.rs b/dust-lang/src/value.rs index a0b3706..3588f74 100644 --- a/dust-lang/src/value.rs +++ b/dust-lang/src/value.rs @@ -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); @@ -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) -> Type { + self.0.r#type(variables) } pub fn as_boolean(&self) -> Option { @@ -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), Map(BTreeMap), @@ -443,13 +446,18 @@ pub enum ValueInner { } impl ValueInner { - pub fn r#type(&self) -> Type { + pub fn r#type(&self, variables: &HashMap) -> 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>, + pub value_parameters: Option>, + pub body: Vec, +} + +impl Function { + pub fn return_type(&self, variables: &HashMap) -> Option { + 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 }, diff --git a/dust-lang/src/vm.rs b/dust-lang/src/vm.rs index 51cbf3e..edb1917 100644 --- a/dust-lang/src/vm.rs +++ b/dust-lang/src/vm.rs @@ -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 for VmError {