use std::collections::{HashMap, HashSet};
use crate::names::{NameIndex, Spelling};
use crate::nested::{Fold, Nested};
use crate::types::{Body, Decl, DeclId, Type};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum Crossing {
#[default]
Stays,
Crosses,
HeldByOption,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Settings {
pub data: bool,
pub host_ok: bool,
pub no_opaque: bool,
pub crossing: Crossing,
pub names: Spelling,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Reason {
Function,
Host,
Task,
NotData,
Opaque,
JsonValue,
OptionalJson,
SharedKey,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Step {
Field {
decl: DeclId,
index: usize,
},
Payload {
decl: DeclId,
ctor: usize,
index: usize,
},
Base(DeclId),
Index(usize),
Element,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Refusal {
pub part: Type,
pub reason: Reason,
pub path: Vec<Step>,
}
pub fn judge(
decls: &[Decl],
ty: &Type,
settings: Settings,
on_param: &mut dyn FnMut(u32, Settings),
) -> Option<Refusal> {
Walk::new(decls, on_param).judge(ty, settings)
}
struct Walk<'a> {
decls: &'a [Decl],
on_param: &'a mut dyn FnMut(u32, Settings),
nodes: Vec<Node>,
ids: HashMap<Node, Id>,
walked: HashSet<(Id, Crossing)>,
#[cfg(test)]
steps: usize,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Id(usize);
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Node {
Leaf(Type),
List(Id),
Set(Id),
Option(Id),
Task(Id),
Dict(Id, Id),
Tuple(Vec<Id>),
Named(DeclId, Vec<Id>),
Param(u32),
Function(Vec<Id>, Id),
}
type Part = (Option<Step>, Id, Settings);
struct Found {
part: Id,
reason: Reason,
path: Vec<Step>,
}
enum Entered {
Refused(Found),
Parts(Vec<Part>, OnRefusal),
}
enum OnRefusal {
Through,
Optional(Id),
}
struct Open {
parts: std::vec::IntoIter<Part>,
step: Option<Step>,
on_refusal: OnRefusal,
}
impl Open {
fn refused(self, mut found: Found) -> Found {
found.path.splice(0..0, self.step);
match self.on_refusal {
OnRefusal::Optional(part) if found.reason == Reason::JsonValue => Found {
part,
reason: Reason::OptionalJson,
path: Vec::new(),
},
OnRefusal::Optional(_) | OnRefusal::Through => found,
}
}
}
impl<'a> Walk<'a> {
fn new(decls: &'a [Decl], on_param: &'a mut dyn FnMut(u32, Settings)) -> Self {
Walk {
decls,
on_param,
nodes: Vec::new(),
ids: HashMap::new(),
walked: HashSet::new(),
#[cfg(test)]
steps: 0,
}
}
fn judge(&mut self, ty: &Type, settings: Settings) -> Option<Refusal> {
let root = self.intern(ty, &[]);
let mut open: Vec<Open> = Vec::new();
let mut entered = self.enter(root, settings);
loop {
match entered {
Entered::Refused(mut found) => {
while let Some(left) = open.pop() {
found = left.refused(found);
}
return Some(Refusal {
part: self.render(found.part),
reason: found.reason,
path: found.path,
});
}
Entered::Parts(parts, on_refusal) => open.push(Open {
parts: parts.into_iter(),
step: None,
on_refusal,
}),
}
entered = loop {
let top = open.last_mut()?;
if let Some((step, part, settings)) = top.parts.next() {
top.step = step;
break self.enter(part, settings);
}
open.pop();
};
}
}
fn intern(&mut self, ty: &Type, args: &[Id]) -> Id {
ty.fold(&mut Interning { walk: self, args })
}
fn render(&self, id: Id) -> Type {
let mut todo = vec![(id, false)];
let mut done: Vec<Type> = Vec::new();
while let Some((id, parts_done)) = todo.pop() {
let node = &self.nodes[id.0];
let parts = node.parts();
if parts_done || parts.is_empty() {
let built = done.split_off(done.len() - parts.len());
done.push(node.ty(built));
} else {
todo.push((id, true));
todo.extend(parts.into_iter().rev().map(|part| (part, false)));
}
}
done.pop().expect("rendering a type yields it")
}
fn enter(&mut self, id: Id, settings: Settings) -> Entered {
#[cfg(test)]
{
self.steps += 1;
}
let inner = inner(settings);
match self.nodes[id.0].clone() {
Node::Param(index) => {
(self.on_param)(index, settings);
through(Vec::new(), inner)
}
Node::Leaf(Type::NotData) if settings.data => refused(id, Reason::NotData),
Node::Task(_) if settings.data => refused(id, Reason::Task),
Node::Leaf(Type::Json) if settings.crossing == Crossing::HeldByOption => {
refused(id, Reason::JsonValue)
}
Node::Function(..) if settings.data => refused(id, Reason::Function),
Node::Function(..)
| Node::Task(_)
| Node::List(_)
| Node::Set(_)
| Node::Option(_)
| Node::Dict(..)
| Node::Tuple(_)
if !self.walked.insert((id, inner.crossing)) =>
{
through(Vec::new(), inner)
}
Node::Leaf(_) | Node::Function(..) | Node::Task(_) => through(Vec::new(), inner),
Node::List(item) | Node::Set(item) => through(vec![(Some(Step::Element), item)], inner),
Node::Dict(key, value) => through(
vec![(Some(Step::Element), key), (Some(Step::Element), value)],
inner,
),
Node::Tuple(parts) => through(
parts
.into_iter()
.enumerate()
.map(|(position, part)| (Some(Step::Index(position)), part))
.collect(),
inner,
),
Node::Option(held) if settings.crossing != Crossing::Stays => {
let held_by = Settings {
crossing: Crossing::HeldByOption,
..settings
};
Entered::Parts(vec![(None, held, held_by)], OnRefusal::Optional(id))
}
Node::Option(held) => through(vec![(None, held)], inner),
Node::Named(decl, args) => self.declared(id, decl, &args, settings),
}
}
fn declared(&mut self, id: Id, decl: DeclId, args: &[Id], settings: Settings) -> Entered {
let inner = inner(settings);
let declared = &self.decls[crate::index(decl.0)];
match &declared.body {
Body::Host if !settings.host_ok => refused(id, Reason::Host),
Body::NonData if settings.data => refused(id, Reason::NotData),
Body::Record(..) | Body::Enum(..) | Body::Newtype(_)
if settings.no_opaque && declared.opaque =>
{
refused(id, Reason::Opaque)
}
Body::Record(..) | Body::Enum(..)
if settings.names == Spelling::Relaxed
&& NameIndex::of(&declared.body, Spelling::Relaxed).is_err() =>
{
refused(id, Reason::SharedKey)
}
Body::Newtype(_) if !self.walked.insert((id, settings.crossing)) => {
through(Vec::new(), inner)
}
Body::Host | Body::NonData | Body::Record(..) | Body::Enum(..)
if !self.walked.insert((id, inner.crossing)) =>
{
through(Vec::new(), inner)
}
Body::Host => through(
args.iter().map(|arg| (Some(Step::Element), *arg)).collect(),
inner,
),
Body::NonData => through(Vec::new(), inner),
Body::Newtype(base) => {
let base = self.intern(base, args);
Entered::Parts(
vec![(Some(Step::Base(decl)), base, settings)],
OnRefusal::Through,
)
}
Body::Record(_, fields) => {
let mut parts = Vec::with_capacity(fields.len());
for (index, field) in fields.iter().enumerate() {
parts.push((Some(Step::Field { decl, index }), self.intern(field, args)));
}
through(parts, inner)
}
Body::Enum(_, ctors) => {
let mut parts = Vec::new();
for (ctor, payload) in ctors.iter().enumerate() {
for (index, part) in payload.iter().enumerate() {
let step = Step::Payload { decl, ctor, index };
parts.push((Some(step), self.intern(part, args)));
}
}
through(parts, inner)
}
}
}
}
impl Node {
fn parts(&self) -> Vec<Id> {
match self {
Node::Leaf(_) | Node::Param(_) => Vec::new(),
Node::List(item) | Node::Set(item) | Node::Option(item) | Node::Task(item) => {
vec![*item]
}
Node::Dict(key, value) => vec![*key, *value],
Node::Tuple(parts) | Node::Named(_, parts) => parts.clone(),
Node::Function(params, result) => params
.iter()
.copied()
.chain(std::iter::once(*result))
.collect(),
}
}
fn ty(&self, mut parts: Vec<Type>) -> Type {
let mut part = || Box::new(parts.remove(0));
match self {
Node::Leaf(leaf) => leaf.clone(),
Node::Param(index) => Type::Param(*index),
Node::List(_) => Type::List(part()),
Node::Set(_) => Type::Set(part()),
Node::Option(_) => Type::Option(part()),
Node::Task(_) => Type::Task(part()),
Node::Dict(..) => Type::Dict(part(), part()),
Node::Tuple(_) => Type::Tuple(parts),
Node::Named(decl, _) => Type::Named(*decl, parts),
Node::Function(..) => {
let result = Box::new(parts.pop().expect("a function has a result"));
Type::Function {
params: parts,
result,
}
}
}
}
}
struct Interning<'w, 'a> {
walk: &'w mut Walk<'a>,
args: &'w [Id],
}
impl Fold<Type> for Interning<'_, '_> {
type Made = Id;
fn open(&mut self, ty: &Type) -> Option<Id> {
let Type::Param(index) = ty else {
return None;
};
self.args.get(crate::index(*index)).copied()
}
fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Id) -> Id {
let parts = ty.parts().map(|ty| part(self, ty)).collect();
let walk = &mut *self.walk;
let next = Id(walk.nodes.len());
*walk.ids.entry(node(ty, parts)).or_insert_with_key(|node| {
walk.nodes.push(node.clone());
next
})
}
}
fn node(ty: &Type, mut parts: Vec<Id>) -> Node {
match ty {
Type::List(_) => Node::List(parts[0]),
Type::Set(_) => Node::Set(parts[0]),
Type::Option(_) => Node::Option(parts[0]),
Type::Task(_) => Node::Task(parts[0]),
Type::Dict(..) => Node::Dict(parts[0], parts[1]),
Type::Tuple(_) => Node::Tuple(parts),
Type::Named(decl, _) => Node::Named(*decl, parts),
Type::Function { .. } => {
let result = parts.pop().expect("a function has a result");
Node::Function(parts, result)
}
Type::Param(index) => Node::Param(*index),
Type::Int
| Type::Decimal
| Type::Bool
| Type::Text
| Type::Bytes
| Type::Duration
| Type::Instant
| Type::Unit
| Type::Never
| Type::Json
| Type::NotData => Node::Leaf(ty.clone()),
}
}
fn inner(settings: Settings) -> Settings {
Settings {
crossing: settings.crossing.min(Crossing::Crosses),
..settings
}
}
fn refused(id: Id, reason: Reason) -> Entered {
Entered::Refused(Found {
part: id,
reason,
path: Vec::new(),
})
}
fn through(parts: Vec<(Option<Step>, Id)>, inner: Settings) -> Entered {
let parts = parts
.into_iter()
.map(|(step, part)| (step, part, inner))
.collect();
Entered::Parts(parts, OnRefusal::Through)
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::{Crossing, Settings, Spelling, Walk};
use crate::{Body, Decl, DeclId, Identity, ModulePath, RecordShape, Segments, Tree, Type};
fn doubling(n: u32) -> Vec<Decl> {
(0..n)
.map(|at| {
let field = if at + 1 == n {
Type::Param(0)
} else {
Type::Named(
DeclId(at + 1),
vec![Type::Tuple(vec![Type::Param(0), Type::Param(0)])],
)
};
Decl {
lexical_ordinal: 1,
identity: Identity {
origin: ModulePath::new(
Tree::Local,
None,
Segments::from_names(["main"]).expect("a test path is a path"),
),
version: None,
name: format!("D{at}"),
},
doc: None,
params: vec!["T".into()],
members: Vec::new(),
opaque: false,
body: Body::Record(RecordShape::new(&format!("D{at}"), ["x"]), vec![field]),
}
})
.collect()
}
fn steps(n: u32) -> usize {
let decls = doubling(n);
let mut on_param = |_, _| {};
let mut walk = Walk::new(&decls, &mut on_param);
let settings = Settings {
data: true,
host_ok: true,
no_opaque: true,
crossing: Crossing::Crosses,
names: Spelling::Exact,
};
assert!(
walk.judge(&Type::Named(DeclId(0), vec![Type::Int]), settings)
.is_none()
);
walk.steps
}
#[test]
fn a_chain_doubling_its_argument_is_judged_in_steps_linear_in_its_length() {
for n in 1..=30 {
let steps = steps(n);
assert!(
steps <= 8 * crate::index(n),
"{n} declarations took {steps} steps"
);
}
}
}