1
0

Run clippy and clean up everything

This commit is contained in:
Jeff 2024-07-12 10:20:52 -04:00
parent 4ab838509b
commit ad409b69f3
22 changed files with 150 additions and 152 deletions

View File

@ -62,7 +62,7 @@ impl AbstractNode for As {
ValidationError::ExpectedValueStatement(expression_position), ValidationError::ExpectedValueStatement(expression_position),
)); ));
}; };
let r#type = self.constructor.construct(&context)?; let r#type = self.constructor.construct(context)?;
let (from_value, to_type): (&ValueInner, Type) = (value.inner().borrow(), r#type); let (from_value, to_type): (&ValueInner, Type) = (value.inner().borrow(), r#type);
let converted = match (from_value, to_type) { let converted = match (from_value, to_type) {
@ -74,9 +74,7 @@ impl AbstractNode for As {
} }
fn expected_type(&self, context: &Context) -> Result<Option<Type>, ValidationError> { fn expected_type(&self, context: &Context) -> Result<Option<Type>, ValidationError> {
self.constructor self.constructor.construct(context).map(Some)
.construct(&context)
.map(|r#type| Some(r#type))
} }
} }

View File

@ -52,7 +52,7 @@ impl AbstractNode for Assignment {
scope: SourcePosition, scope: SourcePosition,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
let r#type = if let Some(constructor) = &self.constructor { let r#type = if let Some(constructor) = &self.constructor {
constructor.construct(&context)? constructor.construct(context)?
} else if let Some(r#type) = self.statement.expected_type(context)? { } else if let Some(r#type) = self.statement.expected_type(context)? {
r#type r#type
} else { } else {

View File

@ -48,7 +48,7 @@ impl AbstractNode for AsyncBlock {
let statement_count = self.statements.len(); let statement_count = self.statements.len();
let error_option = self.statements.into_par_iter().enumerate().find_map_any( let error_option = self.statements.into_par_iter().enumerate().find_map_any(
|(index, statement)| -> Option<RuntimeError> { |(index, statement)| -> Option<RuntimeError> {
let result = statement.evaluate(&_context, false, scope); let result = statement.evaluate(_context, false, scope);
if let Err(error) = result { if let Err(error) = result {
return Some(error); return Some(error);

View File

@ -300,6 +300,6 @@ impl FunctionLogic for JsonParse {
Ok(value) Ok(value)
} }
parse_value(&input, target_type).map(|value| Some(value)) parse_value(input, target_type).map(Some)
} }
} }

View File

@ -36,7 +36,7 @@ impl AbstractNode for EnumDeclaration {
&self, &self,
context: &Context, context: &Context,
_: bool, _: bool,
scope: SourcePosition, _scope: SourcePosition,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
let EnumDeclaration { let EnumDeclaration {
name, name,
@ -60,7 +60,7 @@ impl AbstractNode for EnumDeclaration {
let mut types = Vec::with_capacity(content.len()); let mut types = Vec::with_capacity(content.len());
for constructor in content { for constructor in content {
let r#type = constructor.construct(&context)?; let r#type = constructor.construct(context)?;
types.push(r#type); types.push(r#type);
} }
@ -95,7 +95,7 @@ impl AbstractNode for EnumDeclaration {
self, self,
_: &Context, _: &Context,
_: bool, _: bool,
scope: SourcePosition, _scope: SourcePosition,
) -> Result<Option<Evaluation>, RuntimeError> { ) -> Result<Option<Evaluation>, RuntimeError> {
Ok(None) Ok(None)
} }

View File

@ -73,7 +73,7 @@ impl AbstractNode for FunctionCall {
}); });
} }
for (identifier, constructor) in parameters.into_iter().zip(arguments.into_iter()) { for (identifier, constructor) in parameters.into_iter().zip(arguments.iter()) {
let r#type = constructor.construct(context)?; let r#type = constructor.construct(context)?;
context.set_type(identifier, r#type, self.function_expression.position())?; context.set_type(identifier, r#type, self.function_expression.position())?;
@ -82,9 +82,7 @@ impl AbstractNode for FunctionCall {
match (value_parameters, &self.value_arguments) { match (value_parameters, &self.value_arguments) {
(Some(parameters), Some(arguments)) => { (Some(parameters), Some(arguments)) => {
for ((identifier, _), expression) in for ((identifier, _), expression) in parameters.iter().zip(arguments.iter()) {
parameters.iter().zip(arguments.into_iter())
{
let r#type = if let Some(r#type) = expression.expected_type(context)? { let r#type = if let Some(r#type) = expression.expected_type(context)? {
r#type r#type
} else { } else {
@ -241,7 +239,7 @@ impl AbstractNode for FunctionCall {
return function return function
.call(context, manage_memory) .call(context, manage_memory)
.map(|option| option.map(|value| Evaluation::Return(value))); .map(|option| option.map(Evaluation::Return));
} }
Err(RuntimeError::ValidationFailure( Err(RuntimeError::ValidationFailure(
@ -277,7 +275,7 @@ impl AbstractNode for FunctionCall {
}) = return_type.clone().map(|r#box| *r#box) }) = return_type.clone().map(|r#box| *r#box)
{ {
if let (Some(parameters), Some(arguments)) = (type_parameters, &self.type_arguments) { if let (Some(parameters), Some(arguments)) = (type_parameters, &self.type_arguments) {
for (identifier, constructor) in parameters.into_iter().zip(arguments.into_iter()) { for (identifier, constructor) in parameters.into_iter().zip(arguments.iter()) {
if identifier == return_identifier { if identifier == return_identifier {
let r#type = constructor.construct(context)?; let r#type = constructor.construct(context)?;
@ -347,6 +345,18 @@ impl PartialOrd for FunctionCall {
impl Ord for FunctionCall { impl Ord for FunctionCall {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
todo!() let expression_cmp = self.function_expression.cmp(&other.function_expression);
if expression_cmp.is_eq() {
let type_arg_cmp = self.type_arguments.cmp(&other.type_arguments);
if type_arg_cmp.is_eq() {
self.value_arguments.cmp(&other.value_arguments)
} else {
type_arg_cmp
}
} else {
expression_cmp
}
} }
} }

View File

@ -126,7 +126,7 @@ impl AbstractNode for Logic {
) -> Result<Option<Evaluation>, RuntimeError> { ) -> Result<Option<Evaluation>, RuntimeError> {
let run_and_expect_value = |expression: Expression| -> Result<Value, RuntimeError> { let run_and_expect_value = |expression: Expression| -> Result<Value, RuntimeError> {
let expression_position = expression.position(); let expression_position = expression.position();
let evaluation = expression.evaluate(&mut context.clone(), _manage_memory, scope)?; let evaluation = expression.evaluate(context, _manage_memory, scope)?;
let value = if let Some(Evaluation::Return(value)) = evaluation { let value = if let Some(Evaluation::Return(value)) = evaluation {
value value
} else { } else {
@ -140,7 +140,7 @@ impl AbstractNode for Logic {
let run_and_expect_boolean = |expression: Expression| -> Result<bool, RuntimeError> { let run_and_expect_boolean = |expression: Expression| -> Result<bool, RuntimeError> {
let expression_position = expression.position(); let expression_position = expression.position();
let evaluation = expression.evaluate(&mut context.clone(), _manage_memory, scope)?; let evaluation = expression.evaluate(context, _manage_memory, scope)?;
let value = if let Some(Evaluation::Return(value)) = evaluation { let value = if let Some(Evaluation::Return(value)) = evaluation {
value value
} else { } else {
@ -152,12 +152,12 @@ impl AbstractNode for Logic {
if let ValueInner::Boolean(boolean) = value.inner().as_ref() { if let ValueInner::Boolean(boolean) = value.inner().as_ref() {
Ok(*boolean) Ok(*boolean)
} else { } else {
return Err(RuntimeError::ValidationFailure( Err(RuntimeError::ValidationFailure(
ValidationError::ExpectedBoolean { ValidationError::ExpectedBoolean {
actual: value.r#type(context)?, actual: value.r#type(context)?,
position: expression_position, position: expression_position,
}, },
)); ))
} }
}; };

View File

@ -81,10 +81,7 @@ impl AbstractNode for MapIndex {
if let (ValueInner::Map(map), Expression::Identifier(index)) = if let (ValueInner::Map(map), Expression::Identifier(index)) =
(collection.inner().as_ref(), self.index) (collection.inner().as_ref(), self.index)
{ {
let eval_option = map let eval_option = map.get(&index.node).cloned().map(Evaluation::Return);
.get(&index.node)
.cloned()
.map(|value| Evaluation::Return(value));
Ok(eval_option) Ok(eval_option)
} else { } else {
@ -133,7 +130,7 @@ impl AbstractNode for MapIndex {
for (property, constructor_option, expression) in properties { for (property, constructor_option, expression) in properties {
if property == &index.node { if property == &index.node {
return if let Some(constructor) = constructor_option { return if let Some(constructor) = constructor_option {
let r#type = constructor.clone().construct(&context)?; let r#type = constructor.clone().construct(context)?;
Ok(Some(r#type)) Ok(Some(r#type))
} else { } else {

View File

@ -25,7 +25,7 @@ impl AbstractNode for Math {
&self, &self,
context: &Context, context: &Context,
_manage_memory: bool, _manage_memory: bool,
scope: SourcePosition, _scope: SourcePosition,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
match self { match self {
Math::Add(left, right) => { Math::Add(left, right) => {
@ -90,20 +90,19 @@ impl AbstractNode for Math {
_manage_memory: bool, _manage_memory: bool,
scope: SourcePosition, scope: SourcePosition,
) -> Result<Option<Evaluation>, RuntimeError> { ) -> Result<Option<Evaluation>, RuntimeError> {
let run_and_expect_value = |position: SourcePosition, let run_and_expect_value =
expression: Expression| |position: SourcePosition, expression: Expression| -> Result<Value, RuntimeError> {
-> Result<Value, RuntimeError> { let evaluation = expression.evaluate(_context, _manage_memory, scope)?;
let evaluation = expression.evaluate(&mut _context.clone(), _manage_memory, scope)?; let value = if let Some(Evaluation::Return(value)) = evaluation {
let value = if let Some(Evaluation::Return(value)) = evaluation { value
value } else {
} else { return Err(RuntimeError::ValidationFailure(
return Err(RuntimeError::ValidationFailure( ValidationError::ExpectedValueStatement(position),
ValidationError::ExpectedValueStatement(position), ));
)); };
};
Ok(value) Ok(value)
}; };
let value = match self { let value = match self {
Math::Add(left, right) => { Math::Add(left, right) => {
@ -220,7 +219,7 @@ impl AbstractNode for Math {
} }
(ValueInner::Integer(_) | ValueInner::Float(_), _) => { (ValueInner::Integer(_) | ValueInner::Float(_), _) => {
return Err(RuntimeError::ValidationFailure( return Err(RuntimeError::ValidationFailure(
ValidationError::ExpectedIntegerOrFloat(right_position).into(), ValidationError::ExpectedIntegerOrFloat(right_position),
)) ))
} }
_ => { _ => {
@ -259,7 +258,7 @@ impl AbstractNode for Math {
} }
(ValueInner::Integer(_) | ValueInner::Float(_), _) => { (ValueInner::Integer(_) | ValueInner::Float(_), _) => {
return Err(RuntimeError::ValidationFailure( return Err(RuntimeError::ValidationFailure(
ValidationError::ExpectedIntegerOrFloat(right_position).into(), ValidationError::ExpectedIntegerOrFloat(right_position),
)) ))
} }
_ => { _ => {
@ -298,7 +297,7 @@ impl AbstractNode for Math {
} }
(ValueInner::Integer(_) | ValueInner::Float(_), _) => { (ValueInner::Integer(_) | ValueInner::Float(_), _) => {
return Err(RuntimeError::ValidationFailure( return Err(RuntimeError::ValidationFailure(
ValidationError::ExpectedIntegerOrFloat(right_position).into(), ValidationError::ExpectedIntegerOrFloat(right_position),
)) ))
} }
_ => { _ => {

View File

@ -32,7 +32,7 @@ impl AbstractNode for StructureDefinition {
let mut fields = Vec::with_capacity(self.fields.len()); let mut fields = Vec::with_capacity(self.fields.len());
for (identifier, constructor) in &self.fields { for (identifier, constructor) in &self.fields {
let r#type = constructor.construct(&context)?; let r#type = constructor.construct(context)?;
fields.push((identifier.clone(), r#type)); fields.push((identifier.clone(), r#type));
} }
@ -56,7 +56,7 @@ impl AbstractNode for StructureDefinition {
let mut fields = Vec::with_capacity(self.fields.len()); let mut fields = Vec::with_capacity(self.fields.len());
for (identifier, constructor) in self.fields { for (identifier, constructor) in self.fields {
let r#type = constructor.construct(&context)?; let r#type = constructor.construct(context)?;
fields.push((identifier, r#type)); fields.push((identifier, r#type));
} }

View File

@ -63,7 +63,7 @@ impl Type {
}, },
) => match (left, right) { ) => match (left, right) {
(Some(left), Some(right)) => { (Some(left), Some(right)) => {
if left.check(&right).is_ok() { if left.check(right).is_ok() {
return Ok(()); return Ok(());
} }
} }
@ -81,7 +81,7 @@ impl Type {
} }
} }
(Type::ListOf(left), Type::ListOf(right)) => { (Type::ListOf(left), Type::ListOf(right)) => {
if left.check(&right).is_ok() { if left.check(right).is_ok() {
return Ok(()); return Ok(());
} }
} }
@ -143,7 +143,7 @@ impl Type {
}, },
Type::ListOf(left_type), Type::ListOf(left_type),
) => { ) => {
if right_type.check(&left_type).is_err() { if right_type.check(left_type).is_err() {
return Err(TypeConflict { return Err(TypeConflict {
actual: other.clone(), actual: other.clone(),
expected: self.clone(), expected: self.clone(),
@ -247,7 +247,7 @@ impl Display for Type {
Type::Map(map) => { Type::Map(map) => {
write!(f, "{{ ")?; write!(f, "{{ ")?;
for (index, (key, r#type)) in map.into_iter().enumerate() { for (index, (key, r#type)) in map.iter().enumerate() {
write!(f, "{key}: {type}")?; write!(f, "{key}: {type}")?;
if index != map.len() - 1 { if index != map.len() - 1 {

View File

@ -32,7 +32,7 @@ impl AbstractNode for TypeAlias {
_: bool, _: bool,
scope: SourcePosition, scope: SourcePosition,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
let r#type = self.constructor.construct(&context)?; let r#type = self.constructor.construct(context)?;
context.set_type(self.identifier.node.clone(), r#type, scope)?; context.set_type(self.identifier.node.clone(), r#type, scope)?;

View File

@ -86,7 +86,7 @@ impl TypeConstructor {
let type_parameters = declared_type_parameters.as_ref().map(|identifiers| { let type_parameters = declared_type_parameters.as_ref().map(|identifiers| {
identifiers identifiers
.into_iter() .iter()
.map(|identifier| identifier.node.clone()) .map(|identifier| identifier.node.clone())
.collect() .collect()
}); });
@ -95,7 +95,7 @@ impl TypeConstructor {
let mut parameters = Vec::with_capacity(declared_value_parameters.len()); let mut parameters = Vec::with_capacity(declared_value_parameters.len());
for (identifier, constructor) in declared_value_parameters { for (identifier, constructor) in declared_value_parameters {
let r#type = constructor.construct(&context)?; let r#type = constructor.construct(context)?;
parameters.push((identifier.node.clone(), r#type)); parameters.push((identifier.node.clone(), r#type));
} }
@ -127,7 +127,7 @@ impl TypeConstructor {
} }
} }
TypeConstructor::ListOf(item_type) => { TypeConstructor::ListOf(item_type) => {
let item_type = item_type.node.construct(&context)?; let item_type = item_type.node.construct(context)?;
Type::ListOf(Box::new(item_type)) Type::ListOf(Box::new(item_type))
} }

View File

@ -4,7 +4,6 @@ use std::{
sync::{Arc, RwLock}, sync::{Arc, RwLock},
}; };
use chumsky::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
@ -99,18 +98,18 @@ impl Eq for Use {}
impl PartialEq for Use { impl PartialEq for Use {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
todo!() self.path == other.path
} }
} }
impl PartialOrd for Use { impl PartialOrd for Use {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
todo!() Some(self.cmp(other))
} }
} }
impl Ord for Use { impl Ord for Use {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { fn cmp(&self, other: &Self) -> std::cmp::Ordering {
todo!() self.path.cmp(&other.path)
} }
} }

View File

@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use crate::{ use crate::{
context::Context, context::Context,
error::{RuntimeError, ValidationError}, error::{RuntimeError, ValidationError},
identifier::{self, Identifier}, identifier::Identifier,
Value, Value,
}; };
@ -66,7 +66,7 @@ impl AbstractNode for ValueNode {
scope: SourcePosition, scope: SourcePosition,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
if let ValueNode::List(list) = self { if let ValueNode::List(list) = self {
let mut items = list.into_iter(); let mut items = list.iter();
let first_item = if let Some(item) = items.next() { let first_item = if let Some(item) = items.next() {
item item
} else { } else {
@ -161,7 +161,7 @@ impl AbstractNode for ValueNode {
expression.position(), expression.position(),
)); ));
}; };
let expected_type = constructor.clone().construct(&context)?; let expected_type = constructor.clone().construct(context)?;
expected_type.check(&actual_type).map_err(|conflict| { expected_type.check(&actual_type).map_err(|conflict| {
ValidationError::TypeCheck { ValidationError::TypeCheck {
@ -375,7 +375,7 @@ impl AbstractNode for ValueNode {
let mut parameters = Vec::with_capacity(value_parameters.len()); let mut parameters = Vec::with_capacity(value_parameters.len());
for (identifier, constructor) in value_parameters { for (identifier, constructor) in value_parameters {
let r#type = constructor.construct(&outer_context)?; let r#type = constructor.construct(outer_context)?;
parameters.push((identifier, r#type)); parameters.push((identifier, r#type));
} }
@ -385,7 +385,7 @@ impl AbstractNode for ValueNode {
None None
}; };
let return_type = if let Some(constructor) = return_type { let return_type = if let Some(constructor) = return_type {
Some(constructor.construct(&outer_context)?) Some(constructor.construct(outer_context)?)
} else { } else {
None None
}; };
@ -456,12 +456,10 @@ impl AbstractNode for ValueNode {
for (identifier, constructor_option, expression) in fields { for (identifier, constructor_option, expression) in fields {
let r#type = if let Some(constructor) = constructor_option { let r#type = if let Some(constructor) = constructor_option {
constructor.construct(context)? constructor.construct(context)?
} else if let Some(r#type) = expression.expected_type(context)? {
r#type
} else { } else {
if let Some(r#type) = expression.expected_type(context)? { return Err(ValidationError::CannotAssignToNone(expression.position()));
r#type
} else {
return Err(ValidationError::CannotAssignToNone(expression.position()));
}
}; };
field_types.insert(identifier.clone(), r#type); field_types.insert(identifier.clone(), r#type);
@ -481,7 +479,7 @@ impl AbstractNode for ValueNode {
let mut parameters = Vec::with_capacity(value_parameters.len()); let mut parameters = Vec::with_capacity(value_parameters.len());
for (identifier, type_constructor) in value_parameters { for (identifier, type_constructor) in value_parameters {
let r#type = type_constructor.clone().construct(&context)?; let r#type = type_constructor.clone().construct(context)?;
parameters.push((identifier.clone(), r#type)); parameters.push((identifier.clone(), r#type));
} }
@ -490,12 +488,9 @@ impl AbstractNode for ValueNode {
} else { } else {
None None
}; };
let type_parameters = type_parameters.clone().map(|parameters| { let type_parameters = type_parameters
parameters .clone()
.iter() .map(|parameters| parameters.into_iter().collect());
.map(|identifier| identifier.clone())
.collect()
});
let return_type = if let Some(constructor) = return_type { let return_type = if let Some(constructor) = return_type {
Some(Box::new(constructor.construct(context)?)) Some(Box::new(constructor.construct(context)?))
} else { } else {

View File

@ -51,10 +51,7 @@ impl AbstractNode for While {
) -> Result<Option<Evaluation>, RuntimeError> { ) -> Result<Option<Evaluation>, RuntimeError> {
let get_boolean = || -> Result<Value, RuntimeError> { let get_boolean = || -> Result<Value, RuntimeError> {
let expression_position = self.expression.position(); let expression_position = self.expression.position();
let evaluation = let evaluation = self.expression.clone().evaluate(_context, false, scope)?;
self.expression
.clone()
.evaluate(&mut _context.clone(), false, scope)?;
if let Some(Evaluation::Return(value)) = evaluation { if let Some(Evaluation::Return(value)) = evaluation {
Ok(value) Ok(value)
@ -67,9 +64,7 @@ impl AbstractNode for While {
while let ValueInner::Boolean(true) = get_boolean()?.inner().as_ref() { while let ValueInner::Boolean(true) = get_boolean()?.inner().as_ref() {
for statement in &self.statements { for statement in &self.statements {
let evaluation = statement let evaluation = statement.clone().evaluate(_context, false, scope)?;
.clone()
.evaluate(&mut _context.clone(), false, scope)?;
if let Some(Evaluation::Break) = evaluation { if let Some(Evaluation::Break) = evaluation {
return Ok(evaluation); return Ok(evaluation);

View File

@ -17,10 +17,12 @@ use crate::{
Value, Value,
}; };
type VariableInfo = (VariableData, UsageData, SourcePosition);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Context { pub struct Context {
id: u32, id: u32,
variables: Arc<RwLock<HashMap<Identifier, (VariableData, UsageData, SourcePosition)>>>, variables: Arc<RwLock<HashMap<Identifier, VariableInfo>>>,
is_clean: Arc<RwLock<bool>>, is_clean: Arc<RwLock<bool>>,
} }
@ -138,7 +140,7 @@ impl Context {
usage_data.inner().write()?.actual += 1; usage_data.inner().write()?.actual += 1;
*self.is_clean.write()? = false; *self.is_clean.write()? = false;
return Ok(Some(value.clone())); Ok(Some(value.clone()))
} else { } else {
Ok(None) Ok(None)
} }
@ -202,7 +204,7 @@ impl Context {
if let Some((_, usage_data, _)) = variables.get(identifier) { if let Some((_, usage_data, _)) = variables.get(identifier) {
usage_data.inner().write()?.expected += 1; usage_data.inner().write()?.expected += 1;
return Ok(true); Ok(true)
} else { } else {
Ok(false) Ok(false)
} }
@ -295,3 +297,9 @@ impl UsageData {
}))) })))
} }
} }
impl Default for UsageData {
fn default() -> Self {
UsageData::new()
}
}

View File

@ -32,7 +32,7 @@ impl Identifier {
} }
pub fn as_str(&self) -> &str { pub fn as_str(&self) -> &str {
&self.0.as_str() self.0.as_str()
} }
} }

View File

@ -1,7 +1,4 @@
use std::{ use std::fmt::{self, Display, Formatter};
f64::{INFINITY, NAN, NEG_INFINITY},
fmt::{self, Display, Formatter},
};
use chumsky::prelude::*; use chumsky::prelude::*;
@ -176,7 +173,7 @@ impl Display for Symbol {
} }
} }
pub fn lex<'src>(source: &'src str) -> Result<Vec<(Token<'src>, SimpleSpan)>, Vec<DustError>> { pub fn lex(source: &str) -> Result<Vec<(Token, SimpleSpan)>, Vec<DustError>> {
lexer() lexer()
.parse(source) .parse(source)
.into_result() .into_result()
@ -222,9 +219,9 @@ pub fn lexer<'src>() -> impl Parser<
let float = choice(( let float = choice((
float_numeric, float_numeric,
just("Infinity").to(Token::Float(INFINITY)), just("Infinity").to(Token::Float(f64::INFINITY)),
just("-Infinity").to(Token::Float(NEG_INFINITY)), just("-Infinity").to(Token::Float(f64::NEG_INFINITY)),
just("NaN").to(Token::Float(NAN)), just("NaN").to(Token::Float(f64::NAN)),
)); ));
let integer = just('-') let integer = just('-')

View File

@ -29,9 +29,11 @@ pub fn interpret(source_id: &str, source: &str) -> Result<Option<Value>, Interpr
interpreter.run(Arc::from(source_id), Arc::from(source)) interpreter.run(Arc::from(source_id), Arc::from(source))
} }
type Source = (Arc<str>, Arc<str>);
pub struct Interpreter { pub struct Interpreter {
context: Context, context: Context,
sources: Arc<RwLock<Vec<(Arc<str>, Arc<str>)>>>, sources: Arc<RwLock<Vec<Source>>>,
} }
impl Interpreter { impl Interpreter {
@ -52,15 +54,15 @@ impl Interpreter {
sources.clear(); sources.clear();
sources.push((source_id.clone(), Arc::from(source))); sources.push((source_id.clone(), Arc::from(source)));
lex(source.as_ref()) lex(source)
.map(|tokens| tokens.into_iter().map(|(token, _)| token).collect()) .map(|tokens| tokens.into_iter().map(|(token, _)| token).collect())
.map_err(|errors| InterpreterError { source_id, errors }) .map_err(|errors| InterpreterError { source_id, errors })
} }
pub fn parse<'src>( pub fn parse(
&self, &self,
source_id: Arc<str>, source_id: Arc<str>,
source: &'src str, source: &str,
) -> Result<AbstractTree, InterpreterError> { ) -> Result<AbstractTree, InterpreterError> {
let mut sources = self.sources.write().unwrap(); let mut sources = self.sources.write().unwrap();
@ -229,9 +231,9 @@ impl InterpreterError {
ValidationError::CannotAssignToNone(postion) => { ValidationError::CannotAssignToNone(postion) => {
builder.add_label( builder.add_label(
Label::new((self.source_id.clone(), postion.0..postion.1)) Label::new((self.source_id.clone(), postion.0..postion.1))
.with_message(format!( .with_message(
"This statement does not yield a value, you cannot assign a variable to it." "This statement does not yield a value, you cannot assign a variable to it."
)), ),
); );
} }
ValidationError::ExpectedBoolean { actual, position } => { ValidationError::ExpectedBoolean { actual, position } => {

View File

@ -30,7 +30,7 @@ pub fn parse<'src>(
.map_err(|errors| { .map_err(|errors| {
errors errors
.into_iter() .into_iter()
.map(|error| DustError::from(error)) .map(DustError::from)
.collect::<Vec<DustError>>() .collect::<Vec<DustError>>()
}) })
} }
@ -41,13 +41,13 @@ pub fn parser<'src>(
let comment = select_ref! { let comment = select_ref! {
Token::Comment(_) => {} Token::Comment(_) => {}
}; };
let identifier = select! { let identifier = select! {
Token::Identifier(text) => Identifier::from(text), Token::Identifier(text) => Identifier::from(text),
}; };
let positioned_identifier = identifier let positioned_identifier =
.clone() identifier.map_with(|identifier, state| identifier.with_position(state.span()));
.map_with(|identifier, state| identifier.with_position(state.span()));
let basic_value = select! { let basic_value = select! {
Token::Boolean(boolean) => ValueNode::Boolean(boolean), Token::Boolean(boolean) => ValueNode::Boolean(boolean),
@ -74,10 +74,13 @@ pub fn parser<'src>(
TypeConstructor::Raw(raw_constructor.with_position(state.span())) TypeConstructor::Raw(raw_constructor.with_position(state.span()))
}); });
type TypeParameters = Vec<WithPosition<Identifier>>;
type ValueParameters = Vec<(WithPosition<Identifier>, TypeConstructor)>;
type FunctionTypeParameters = (Option<TypeParameters>, ValueParameters);
let function_type = just(Token::Keyword(Keyword::Fn)) let function_type = just(Token::Keyword(Keyword::Fn))
.ignore_then( .ignore_then(
positioned_identifier positioned_identifier
.clone()
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
.at_least(1) .at_least(1)
.collect() .collect()
@ -89,7 +92,6 @@ pub fn parser<'src>(
) )
.then( .then(
positioned_identifier positioned_identifier
.clone()
.then_ignore(just(Token::Symbol(Symbol::Colon))) .then_ignore(just(Token::Symbol(Symbol::Colon)))
.then(type_constructor.clone()) .then(type_constructor.clone())
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
@ -106,10 +108,7 @@ pub fn parser<'src>(
) )
.map_with( .map_with(
|((type_parameters, value_parameters), return_type): ( |((type_parameters, value_parameters), return_type): (
( FunctionTypeParameters,
Option<Vec<WithPosition<Identifier>>>,
Vec<(WithPosition<Identifier>, TypeConstructor)>,
),
Option<TypeConstructor>, Option<TypeConstructor>,
), ),
state| { state| {
@ -123,7 +122,7 @@ pub fn parser<'src>(
FunctionTypeConstructor { FunctionTypeConstructor {
type_parameters, type_parameters,
value_parameters, value_parameters,
return_type: return_type.map(|r#type| Box::new(r#type)), return_type: return_type.map(Box::new),
} }
.with_position(state.span()), .with_position(state.span()),
) )
@ -133,7 +132,7 @@ pub fn parser<'src>(
let list_type = type_constructor let list_type = type_constructor
.clone() .clone()
.then_ignore(just(Token::Symbol(Symbol::Semicolon))) .then_ignore(just(Token::Symbol(Symbol::Semicolon)))
.then(raw_integer.clone()) .then(raw_integer)
.delimited_by( .delimited_by(
just(Token::Symbol(Symbol::SquareOpen)), just(Token::Symbol(Symbol::SquareOpen)),
just(Token::Symbol(Symbol::SquareClose)), just(Token::Symbol(Symbol::SquareClose)),
@ -159,7 +158,6 @@ pub fn parser<'src>(
}); });
let type_invokation = positioned_identifier let type_invokation = positioned_identifier
.clone()
.then( .then(
type_constructor type_constructor
.clone() .clone()
@ -181,7 +179,6 @@ pub fn parser<'src>(
}); });
let map_type = positioned_identifier let map_type = positioned_identifier
.clone()
.then_ignore(just(Token::Symbol(Symbol::Colon))) .then_ignore(just(Token::Symbol(Symbol::Colon)))
.then(type_constructor.clone()) .then(type_constructor.clone())
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
@ -210,8 +207,6 @@ pub fn parser<'src>(
just(Token::Symbol(Symbol::Colon)).ignore_then(type_constructor.clone()); just(Token::Symbol(Symbol::Colon)).ignore_then(type_constructor.clone());
let statement = recursive(|statement| { let statement = recursive(|statement| {
let allow_built_ins = allow_built_ins.clone();
let block = statement let block = statement
.clone() .clone()
.repeated() .repeated()
@ -224,14 +219,11 @@ pub fn parser<'src>(
.map_with(|statements, state| Block::new(statements).with_position(state.span())); .map_with(|statements, state| Block::new(statements).with_position(state.span()));
let expression = recursive(|expression| { let expression = recursive(|expression| {
let allow_built_ins = allow_built_ins.clone(); let identifier_expression = identifier.map_with(|identifier, state| {
let identifier_expression = identifier.clone().map_with(|identifier, state| {
Expression::Identifier(identifier.with_position(state.span())) Expression::Identifier(identifier.with_position(state.span()))
}); });
let range = raw_integer let range = raw_integer
.clone()
.then_ignore(just(Token::Symbol(Symbol::DoubleDot))) .then_ignore(just(Token::Symbol(Symbol::DoubleDot)))
.then(raw_integer) .then(raw_integer)
.map_with(|(start, end), state| { .map_with(|(start, end), state| {
@ -252,7 +244,6 @@ pub fn parser<'src>(
}); });
let map_fields = identifier let map_fields = identifier
.clone()
.then(type_specification.clone().or_not()) .then(type_specification.clone().or_not())
.then_ignore(just(Token::Symbol(Symbol::Equal))) .then_ignore(just(Token::Symbol(Symbol::Equal)))
.then(expression.clone()) .then(expression.clone())
@ -272,10 +263,13 @@ pub fn parser<'src>(
) )
}); });
type TypeParameters = Vec<Identifier>;
type ValueParameters = Vec<(Identifier, TypeConstructor)>;
type FunctionParameters = (Option<TypeParameters>, ValueParameters);
let function = just(Token::Keyword(Keyword::Fn)) let function = just(Token::Keyword(Keyword::Fn))
.ignore_then( .ignore_then(
identifier identifier
.clone()
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
.at_least(1) .at_least(1)
.allow_trailing() .allow_trailing()
@ -288,7 +282,6 @@ pub fn parser<'src>(
) )
.then( .then(
identifier identifier
.clone()
.then_ignore(just(Token::Symbol(Symbol::Colon))) .then_ignore(just(Token::Symbol(Symbol::Colon)))
.then(type_constructor.clone()) .then(type_constructor.clone())
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
@ -307,10 +300,7 @@ pub fn parser<'src>(
.then(block.clone()) .then(block.clone())
.map_with( .map_with(
|(((type_parameters, value_parameters), return_type), body): ( |(((type_parameters, value_parameters), return_type), body): (
( (FunctionParameters, Option<TypeConstructor>),
(Option<Vec<Identifier>>, Vec<(Identifier, TypeConstructor)>),
Option<TypeConstructor>,
),
WithPosition<Block>, WithPosition<Block>,
), ),
state| { state| {
@ -333,9 +323,8 @@ pub fn parser<'src>(
); );
let enum_instance = positioned_identifier let enum_instance = positioned_identifier
.clone()
.then_ignore(just(Token::Symbol(Symbol::DoubleColon))) .then_ignore(just(Token::Symbol(Symbol::DoubleColon)))
.then(positioned_identifier.clone()) .then(positioned_identifier)
.then( .then(
expression expression
.clone() .clone()
@ -427,14 +416,14 @@ pub fn parser<'src>(
); );
let atom = choice(( let atom = choice((
built_in_function.clone(), built_in_function,
enum_instance.clone(), enum_instance.clone(),
range.clone(), range,
function.clone(), function.clone(),
list.clone(), list.clone(),
map.clone(), map.clone(),
basic_value.clone(), basic_value,
identifier_expression.clone(), identifier_expression,
expression.clone().delimited_by( expression.clone().delimited_by(
just(Token::Symbol(Symbol::ParenOpen)), just(Token::Symbol(Symbol::ParenOpen)),
just(Token::Symbol(Symbol::ParenClose)), just(Token::Symbol(Symbol::ParenClose)),
@ -630,9 +619,7 @@ pub fn parser<'src>(
)) ))
}); });
let expression_statement = expression let expression_statement = expression.clone().map(Statement::Expression);
.clone()
.map(|expression| Statement::Expression(expression));
let async_block = just(Token::Keyword(Keyword::Async)) let async_block = just(Token::Keyword(Keyword::Async))
.ignore_then(statement.clone().repeated().collect().delimited_by( .ignore_then(statement.clone().repeated().collect().delimited_by(
@ -647,7 +634,6 @@ pub fn parser<'src>(
.map_with(|_, state| Statement::Break(().with_position(state.span()))); .map_with(|_, state| Statement::Break(().with_position(state.span())));
let assignment = positioned_identifier let assignment = positioned_identifier
.clone()
.then(type_specification.clone().or_not()) .then(type_specification.clone().or_not())
.then(choice(( .then(choice((
just(Token::Symbol(Symbol::Equal)).to(AssignmentOperator::Assign), just(Token::Symbol(Symbol::Equal)).to(AssignmentOperator::Assign),
@ -662,7 +648,7 @@ pub fn parser<'src>(
) )
}); });
let block_statement = block.clone().map(|block| Statement::Block(block)); let block_statement = block.clone().map(Statement::Block);
let r#loop = statement let r#loop = statement
.clone() .clone()
@ -715,7 +701,7 @@ pub fn parser<'src>(
); );
let type_alias = just(Token::Keyword(Keyword::Type)) let type_alias = just(Token::Keyword(Keyword::Type))
.ignore_then(positioned_identifier.clone()) .ignore_then(positioned_identifier)
.then_ignore(just(Token::Symbol(Symbol::Equal))) .then_ignore(just(Token::Symbol(Symbol::Equal)))
.then(type_constructor.clone()) .then(type_constructor.clone())
.map_with(|(identifier, constructor), state| { .map_with(|(identifier, constructor), state| {
@ -725,7 +711,6 @@ pub fn parser<'src>(
}); });
let enum_variant = positioned_identifier let enum_variant = positioned_identifier
.clone()
.then( .then(
type_constructor type_constructor
.clone() .clone()
@ -743,10 +728,9 @@ pub fn parser<'src>(
}); });
let enum_declaration = just(Token::Keyword(Keyword::Enum)) let enum_declaration = just(Token::Keyword(Keyword::Enum))
.ignore_then(positioned_identifier.clone()) .ignore_then(positioned_identifier)
.then( .then(
positioned_identifier positioned_identifier
.clone()
.separated_by(just(Token::Symbol(Symbol::Comma))) .separated_by(just(Token::Symbol(Symbol::Comma)))
.allow_trailing() .allow_trailing()
.collect() .collect()
@ -801,8 +785,5 @@ pub fn parser<'src>(
))) )))
}); });
statement statement.repeated().collect().map(AbstractTree::new)
.repeated()
.collect()
.map(|statements| AbstractTree::new(statements))
} }

View File

@ -16,8 +16,7 @@ use serde::{
use crate::{ use crate::{
abstract_tree::{ abstract_tree::{
AbstractNode, Block, BuiltInFunction, Evaluation, SourcePosition, Type, AbstractNode, Block, BuiltInFunction, Evaluation, SourcePosition, Type, WithPosition,
WithPosition,
}, },
context::Context, context::Context,
error::{RuntimeError, ValidationError}, error::{RuntimeError, ValidationError},
@ -157,7 +156,7 @@ impl Display for Value {
ValueInner::List(list) => { ValueInner::List(list) => {
write!(f, "[")?; write!(f, "[")?;
for (index, value) in list.into_iter().enumerate() { for (index, value) in list.iter().enumerate() {
if index == list.len() - 1 { if index == list.len() - 1 {
write!(f, "{}", value)?; write!(f, "{}", value)?;
} else { } else {
@ -170,7 +169,7 @@ impl Display for Value {
ValueInner::Map(map) => { ValueInner::Map(map) => {
write!(f, "{{ ")?; write!(f, "{{ ")?;
for (index, (key, value)) in map.into_iter().enumerate() { for (index, (key, value)) in map.iter().enumerate() {
write!(f, "{key} = {value}")?; write!(f, "{key} = {value}")?;
if index != map.len() - 1 { if index != map.len() - 1 {
@ -194,7 +193,7 @@ impl Display for Value {
if let Some(type_parameters) = type_parameters { if let Some(type_parameters) = type_parameters {
write!(f, "<")?; write!(f, "<")?;
for (index, identifier) in type_parameters.into_iter().enumerate() { for (index, identifier) in type_parameters.iter().enumerate() {
if index == type_parameters.len() - 1 { if index == type_parameters.len() - 1 {
write!(f, "{}", identifier)?; write!(f, "{}", identifier)?;
} else { } else {
@ -629,7 +628,7 @@ impl ValueInner {
ValueInner::Range(_) => Type::Range, ValueInner::Range(_) => Type::Range,
ValueInner::String(_) => Type::String, ValueInner::String(_) => Type::String,
ValueInner::Function(function) => { ValueInner::Function(function) => {
let return_type = function.return_type.clone().map(|r#type| Box::new(r#type)); let return_type = function.return_type.clone().map(Box::new);
Type::Function { Type::Function {
type_parameters: function.type_parameters().clone(), type_parameters: function.type_parameters().clone(),
@ -856,6 +855,24 @@ impl PartialOrd for Function {
impl Ord for Function { impl Ord for Function {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
todo!() let type_param_cmp = self.type_parameters().cmp(&other.type_parameters);
if type_param_cmp.is_eq() {
let value_param_cmp = self.value_parameters.cmp(&other.value_parameters);
if value_param_cmp.is_eq() {
let return_type_cmp = self.return_type.cmp(&other.return_type);
if return_type_cmp.is_eq() {
self.body.cmp(&other.body)
} else {
return_type_cmp
}
} else {
value_param_cmp
}
} else {
type_param_cmp
}
} }
} }