use std::fmt;
use std::sync::Arc;
use crate::module::{ModulePath, Tree};
use crate::nested::{Fold, Nested};
use crate::shape::{EnumShape, RecordShape};
#[derive(Debug)]
pub enum Type {
Int,
Decimal,
Bool,
Text,
Bytes,
Duration,
Instant,
Unit,
Never,
Json,
List(Box<Type>),
Set(Box<Type>),
Dict(Box<Type>, Box<Type>),
Option(Box<Type>),
Tuple(Vec<Type>),
Named(DeclId, Vec<Type>),
Param(u32),
Task(Box<Type>),
Function {
params: Vec<Type>,
result: Box<Type>,
},
NotData,
}
impl Type {
pub fn args(&self) -> &[Type] {
if let Type::Named(_, args) = self {
args
} else {
&[]
}
}
pub fn list(item: Type) -> Type {
Type::List(Box::new(item))
}
pub fn set(item: Type) -> Type {
Type::Set(Box::new(item))
}
pub fn dict(key: Type, value: Type) -> Type {
Type::Dict(Box::new(key), Box::new(value))
}
pub fn option(item: Type) -> Type {
Type::Option(Box::new(item))
}
#[must_use]
pub fn subst(&self, args: &[Type]) -> Type {
self.fold(&mut Substitution(args))
}
#[must_use]
pub fn map_parts(&self, mut part: impl FnMut(&Type) -> Type) -> Type {
match self {
Type::List(item) => Type::List(Box::new(part(item))),
Type::Set(item) => Type::Set(Box::new(part(item))),
Type::Option(item) => Type::Option(Box::new(part(item))),
Type::Task(item) => Type::Task(Box::new(part(item))),
Type::Dict(key, value) => {
let key = Box::new(part(key));
Type::Dict(key, Box::new(part(value)))
}
Type::Tuple(parts) => Type::Tuple(parts.iter().map(part).collect()),
Type::Named(decl, args) => Type::Named(*decl, args.iter().map(part).collect()),
Type::Function { params, result } => {
let params = params.iter().map(&mut part).collect();
Type::Function {
params,
result: Box::new(part(result)),
}
}
Type::Int => Type::Int,
Type::Decimal => Type::Decimal,
Type::Bool => Type::Bool,
Type::Text => Type::Text,
Type::Bytes => Type::Bytes,
Type::Duration => Type::Duration,
Type::Instant => Type::Instant,
Type::Unit => Type::Unit,
Type::Never => Type::Never,
Type::Json => Type::Json,
Type::Param(index) => Type::Param(*index),
Type::NotData => Type::NotData,
}
}
fn same_node(&self, other: &Type) -> bool {
match (self, other) {
(Type::Named(a, xs), Type::Named(b, ys)) => a == b && xs.len() == ys.len(),
(Type::Tuple(xs), Type::Tuple(ys))
| (Type::Function { params: xs, .. }, Type::Function { params: ys, .. }) => {
xs.len() == ys.len()
}
(Type::Param(a), Type::Param(b)) => a == b,
_ => std::mem::discriminant(self) == std::mem::discriminant(other),
}
}
}
impl Nested for Type {
const LEAF: Type = Type::NotData;
fn parts(&self) -> impl DoubleEndedIterator<Item = &Type> {
let (list, boxed): (&[Type], [Option<&Type>; 2]) = match self {
Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
(&[], [Some(item), None])
}
Type::Dict(key, value) => (&[], [Some(key), Some(value)]),
Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
Type::Function { params, result } => (params, [Some(result), None]),
Type::Int
| Type::Decimal
| Type::Bool
| Type::Text
| Type::Bytes
| Type::Duration
| Type::Instant
| Type::Unit
| Type::Never
| Type::Json
| Type::Param(_)
| Type::NotData => (&[], [None, None]),
};
list.iter().chain(boxed.into_iter().flatten())
}
fn parts_mut(&mut self) -> impl Iterator<Item = &mut Type> {
let (list, boxed): (&mut [Type], [Option<&mut Box<Type>>; 2]) = match self {
Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
(&mut [], [Some(item), None])
}
Type::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
Type::Function { params, result } => (params, [Some(result), None]),
Type::Int
| Type::Decimal
| Type::Bool
| Type::Text
| Type::Bytes
| Type::Duration
| Type::Instant
| Type::Unit
| Type::Never
| Type::Json
| Type::Param(_)
| Type::NotData => (&mut [], [None, None]),
};
list.iter_mut()
.chain(boxed.into_iter().flatten().map(|part| &mut **part))
}
}
struct Substitution<'a>(&'a [Type]);
impl Fold<Type> for Substitution<'_> {
type Made = Type;
fn open(&mut self, ty: &Type) -> Option<Type> {
let Type::Param(index) = ty else {
return None;
};
Some(self.0.get(crate::index(*index)).unwrap_or(ty).clone())
}
fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
ty.map_parts(|ty| part(self, ty))
}
}
struct Cloning;
impl Fold<Type> for Cloning {
type Made = Type;
fn open(&mut self, _: &Type) -> Option<Type> {
None
}
fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
ty.map_parts(|ty| part(self, ty))
}
}
impl Clone for Type {
fn clone(&self) -> Type {
self.fold(&mut Cloning)
}
}
impl PartialEq for Type {
fn eq(&self, other: &Type) -> bool {
self.same_tree(other, Type::same_node)
}
}
impl Eq for Type {}
impl std::hash::Hash for Type {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.fold(&mut Hashing(state));
}
}
struct Hashing<'h, H>(&'h mut H);
impl<H: std::hash::Hasher> Fold<Type> for Hashing<'_, H> {
type Made = ();
fn open(&mut self, ty: &Type) -> Option<()> {
use std::hash::Hash as _;
std::mem::discriminant(ty).hash(self.0);
if let Type::Named(DeclId(number), _) | Type::Param(number) = ty {
number.hash(self.0);
}
ty.parts().next().is_none().then_some(())
}
fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type)) {
for ty in ty.parts() {
part(self, ty);
}
}
}
impl Drop for Type {
fn drop(&mut self) {
self.free_parts();
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct DeclId(pub u32);
#[derive(Clone, Debug)]
pub struct Identity {
pub origin: ModulePath,
pub version: Option<String>,
pub name: String,
}
impl Identity {
pub fn shown(&self) -> String {
let versions = match self.origin.tree() {
Tree::Std => Versions::Shown,
Tree::Repository(_) | Tree::Local => Versions::Hidden,
};
self.written(versions)
}
pub fn written(&self, versions: Versions) -> String {
let version = match versions {
Versions::Shown => self.version.as_deref(),
Versions::Hidden => None,
};
let module = self.origin.written(version);
if module.is_empty() {
self.name.clone()
} else {
format!("{module}.{}", self.name)
}
}
}
impl PartialEq for Identity {
fn eq(&self, other: &Self) -> bool {
self.written(Versions::Shown) == other.written(Versions::Shown)
}
}
impl Eq for Identity {}
impl std::hash::Hash for Identity {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.written(Versions::Shown).hash(state);
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.written(Versions::Shown))
}
}
#[derive(Clone, Debug)]
pub struct Decl {
pub lexical_ordinal: u32,
pub identity: Identity,
pub doc: Option<String>,
pub members: Vec<MemberDoc>,
pub params: Vec<String>,
pub opaque: bool,
pub body: Body,
}
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub struct MemberDoc {
pub doc: Option<String>,
pub fields: Vec<Option<String>>,
}
#[derive(Clone, Debug)]
pub enum Body {
Record(Arc<RecordShape>, Vec<Type>),
Enum(Arc<EnumShape>, Vec<Vec<Type>>),
Newtype(Type),
Host,
NonData,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Versions {
Shown,
Hidden,
}