Refactor TupleTyple

This commit is contained in:
Pranav Gaddamadugu 2023-10-10 08:55:59 -04:00 committed by Pranav Gaddamadugu
parent 072ab7b930
commit 5b2e73d419
5 changed files with 25 additions and 15 deletions

View File

@ -18,7 +18,6 @@ use crate::{GroupLiteral, IntegerType};
use super::*;
// TODO: Refactor integer literals to use `IntegerType`.
/// A literal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Literal {

View File

@ -53,7 +53,7 @@ impl Finalize {
let output_type = match output.len() {
0 => Type::Unit,
1 => output[0].type_(),
_ => Type::Tuple(TupleType(output.iter().map(|output| output.type_()).collect())),
_ => Type::Tuple(TupleType::new(output.iter().map(|output| output.type_()).collect())),
};
Self { identifier, input, output, output_type, block, span, id }

View File

@ -100,7 +100,7 @@ impl Function {
let output_type = match output.len() {
0 => Type::Unit,
1 => get_output_type(&output[0]),
_ => Type::Tuple(TupleType(output.iter().map(get_output_type).collect())),
_ => Type::Tuple(TupleType::new(output.iter().map(get_output_type).collect())),
};
Function { annotations, variant, identifier, input, output, output_type, block, finalize, span, id }

View File

@ -17,24 +17,33 @@
use crate::Type;
use serde::{Deserialize, Serialize};
use std::{fmt, ops::Deref};
// TODO: Consider defining a safe interface for constructing a tuple type.
use std::fmt;
/// A type list of at least two types.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TupleType(pub Vec<Type>);
pub struct TupleType {
elements: Vec<Type>,
}
impl Deref for TupleType {
type Target = Vec<Type>;
impl TupleType {
/// Creates a new tuple type.
pub fn new(elements: Vec<Type>) -> Self {
Self { elements }
}
fn deref(&self) -> &Self::Target {
&self.0
/// Returns the elements of the tuple type.
pub fn elements(&self) -> &[Type] {
&self.elements
}
/// Returns the length of the tuple type.
pub fn length(&self) -> usize {
self.elements.len()
}
}
impl fmt::Display for TupleType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({})", self.0.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(","))
write!(f, "({})", self.elements.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(","))
}
}

View File

@ -78,9 +78,11 @@ impl Type {
(Type::Mapping(left), Type::Mapping(right)) => {
left.key.eq_flat(&right.key) && left.value.eq_flat(&right.value)
}
(Type::Tuple(left), Type::Tuple(right)) if left.len() == right.len() => {
left.iter().zip_eq(right.iter()).all(|(left_type, right_type)| left_type.eq_flat(right_type))
}
(Type::Tuple(left), Type::Tuple(right)) if left.length() == right.length() => left
.elements()
.iter()
.zip_eq(right.elements().iter())
.all(|(left_type, right_type)| left_type.eq_flat(right_type)),
_ => false,
}
}