use std::fmt;
use std::sync::Arc;
use flow_value::{EnumShape, RecordShape};
use crate::decode::Mode;
use crate::judge::{Judgment, Summaries, judge, summarize};
#[derive(Clone, PartialEq, Eq, Hash, 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 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 {
match self {
Type::Param(index) => args
.get(*index as usize)
.cloned()
.unwrap_or_else(|| self.clone()),
Type::List(item) => Type::list(item.subst(args)),
Type::Set(item) => Type::set(item.subst(args)),
Type::Option(item) => Type::option(item.subst(args)),
Type::Task(item) => Type::Task(Box::new(item.subst(args))),
Type::Function { params, result } => Type::Function {
params: params.iter().map(|param| param.subst(args)).collect(),
result: Box::new(result.subst(args)),
},
Type::Dict(key, value) => Type::dict(key.subst(args), value.subst(args)),
Type::Tuple(parts) => Type::Tuple(parts.iter().map(|part| part.subst(args)).collect()),
Type::Named(decl, inner) => {
Type::Named(*decl, inner.iter().map(|arg| arg.subst(args)).collect())
}
_ => self.clone(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct DeclId(pub u32);
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Origin {
Package {
package: String,
version: String,
file: String,
},
Repository {
repository: String,
version: String,
file: String,
},
File {
path: String,
},
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Identity {
pub origin: Origin,
pub name: String,
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.origin {
Origin::Package {
package,
version,
file,
} => {
write!(f, "{package}@{version}")?;
if !file.is_empty() {
write!(f, "/{file}")?;
}
write!(f, ".{}", self.name)
}
Origin::Repository {
repository,
version,
file,
} => write!(f, "{repository}@{version}/{file}.{}", self.name),
Origin::File { path } => write!(f, "{path}.{}", self.name),
}
}
}
#[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>>),
Host,
NonData,
}
#[derive(Clone, Debug)]
pub struct Catalog {
decls: Vec<Decl>,
summaries: Summaries,
option: Lang<2>,
json: Option<Lang<6>>,
}
#[derive(Clone, Debug)]
pub(crate) struct Lang<const N: usize> {
pub(crate) shape: Arc<EnumShape>,
pub(crate) at: [usize; N],
}
impl<const N: usize> Lang<N> {
fn find(shape: Arc<EnumShape>, names: [&str; N]) -> Option<Self> {
let mut at = [0; N];
for (slot, name) in at.iter_mut().zip(names) {
*slot = (0..)
.map_while(|index| shape.constructor(index))
.position(|ctor| ctor.name() == name)?;
}
Some(Lang { shape, at })
}
}
pub(crate) const JSON_CTORS: [&str; 6] = ["Null", "Bool", "Number", "Text", "List", "Object"];
impl Catalog {
pub fn new(
decls: Vec<Decl>,
option: Arc<EnumShape>,
json: Option<Arc<EnumShape>>,
) -> Option<Self> {
let option = Lang::find(option, ["None", "Some"])?;
let json = match json {
Some(shape) => Some(Lang::find(shape, JSON_CTORS)?),
None => None,
};
Some(Catalog {
summaries: summarize(&decls),
decls,
option,
json,
})
}
pub fn decl(&self, id: DeclId) -> &Decl {
&self.decls[id.0 as usize]
}
pub fn decls(&self) -> impl ExactSizeIterator<Item = (DeclId, &Decl)> {
self.decls.iter().enumerate().map(|(index, decl)| {
(
DeclId(u32::try_from(index).expect("a catalog fits 32-bit ids")),
decl,
)
})
}
pub(crate) fn judge(&self, ty: &Type, mode: Mode) -> Option<String> {
judge(&self.decls, &self.summaries, ty, mode.into())
}
pub(crate) fn crossing_problem(&self, ty: &Type) -> Option<String> {
judge(&self.decls, &self.summaries, ty, Judgment::Crossing)
}
pub(crate) fn option(&self) -> &Lang<2> {
&self.option
}
pub(crate) fn json(&self) -> &Lang<6> {
self.json
.as_ref()
.expect("a program that names json.Value has std's json module")
}
pub fn name(&self, ty: &Type) -> String {
self.written(ty, true)
}
pub(crate) fn written(&self, ty: &Type, versions: bool) -> String {
let join = |parts: &[Type]| {
parts
.iter()
.map(|part| self.written(part, versions))
.collect::<Vec<_>>()
.join(", ")
};
let one = |item: &Type| self.written(item, versions);
match ty {
Type::Int => "Int".into(),
Type::Decimal => "Decimal".into(),
Type::Bool => "Bool".into(),
Type::Text => "Text".into(),
Type::Bytes => "Bytes".into(),
Type::Duration => "Duration".into(),
Type::Instant => "Instant".into(),
Type::Unit => "Unit".into(),
Type::Never => "Never".into(),
Type::Json => "json.Value".into(),
Type::List(item) => format!("List<{}>", one(item)),
Type::Set(item) => format!("Set<{}>", one(item)),
Type::Option(item) => format!("Option<{}>", one(item)),
Type::Task(item) => format!("task.Task<{}>", one(item)),
Type::Dict(key, value) => format!("Dict<{}, {}>", one(key), one(value)),
Type::Tuple(parts) => format!("({})", join(parts)),
Type::Named(decl, args) => {
let identity = &self.decl(*decl).identity;
let base = match (&identity.origin, versions) {
(Origin::Package { package, file, .. }, false) => {
if file.is_empty() {
format!("{package}.{}", identity.name)
} else {
format!("{package}/{file}.{}", identity.name)
}
}
(
Origin::Repository {
repository, file, ..
},
false,
) => format!("{repository}/{file}.{}", identity.name),
_ => identity.to_string(),
};
if args.is_empty() {
base
} else {
format!("{base}<{}>", join(args))
}
}
Type::Param(index) => format!("${index}"),
Type::Function { params, result } => format!("({}) -> {}", join(params), one(result)),
Type::NotData => "a type that is not data".into(),
}
}
}