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