use super::{Run, Scope, Signature};
use crate::ast::{Expr, ExprKind, Literal};
use crate::shape::{Direction, EnumTag, Presence, TypeDesc, TypeRegistry};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) enum Ty {
Error,
Any,
Infer,
Null,
Bool,
Int,
Float,
String,
Text,
Html,
Date,
Option(Box<Ty>),
Absent(Box<Ty>),
List(Box<Ty>, Option<usize>),
ListLiteral(Vec<Ty>),
Tuple(Vec<Ty>),
Map(Box<Ty>, Box<Ty>),
Record(BTreeMap<String, Ty>),
Nominal(TypeDesc, Direction),
Union(Vec<Ty>),
Closure(Vec<Ty>, Box<Ty>),
Range,
Loop(usize),
Slot,
Attributes,
Errors,
Paginator(Box<Ty>),
PageUrls,
Service(String),
}
impl From<TypeDesc> for Ty {
fn from(desc: TypeDesc) -> Self {
Self::shape(desc, Direction::Serialize)
}
}
impl Ty {
pub(super) fn shape(desc: TypeDesc, direction: Direction) -> Self {
let sub = |ty: Box<TypeDesc>| Box::new(Self::shape(*ty, direction));
match desc {
TypeDesc::Null => Self::Null,
TypeDesc::Bool => Self::Bool,
TypeDesc::Int => Self::Int,
TypeDesc::Float => Self::Float,
TypeDesc::String | TypeDesc::Literal(_) => Self::String,
TypeDesc::Text => Self::Text,
TypeDesc::Html => Self::Html,
TypeDesc::Date => Self::Date,
TypeDesc::Any => Self::Any,
TypeDesc::Option(ty) => Self::Option(sub(ty)),
TypeDesc::List { element, length } => Self::List(sub(element), length),
TypeDesc::Tuple(elements) => Self::Tuple(
elements
.into_iter()
.map(|elt| {
let ty = Self::shape(elt.ty, direction);
if elt.omittable { ty.optional() } else { ty }
})
.collect(),
),
TypeDesc::Map { key, value } => Self::Map(sub(key), sub(value)),
TypeDesc::Union(types) => Self::Union(
types
.into_iter()
.map(|ty| Self::shape(ty, direction))
.collect(),
),
other => Self::Nominal(other, direction),
}
}
pub(super) fn list(item: Self) -> Self {
Self::List(Box::new(item), None)
}
pub(super) fn map(key: Self, value: Self) -> Self {
Self::Map(Box::new(key), Box::new(value))
}
pub(super) fn list_or_map(&self) -> Option<(Self, Self)> {
if let Self::Union(types) = self
&& let [Self::List(list_item, _), Self::Map(key, map_item)] = types.as_slice()
&& list_item == map_item
{
return Some((union(Self::Int, *key.clone()), *list_item.clone()));
}
None
}
pub(super) fn optional(self) -> Self {
match self {
Self::Option(_) | Self::Null | Self::Error => self,
_ => Self::Option(Box::new(self)),
}
}
pub(super) fn literal(literal: &Literal) -> Self {
match literal {
Literal::Null => Self::Null,
Literal::Bool(_) => Self::Bool,
Literal::Int(_) => Self::Int,
Literal::Float(_) => Self::Float,
Literal::String(_) => Self::String,
}
}
pub(super) fn unknown(&self) -> bool {
matches!(self, Self::Error | Self::Any | Self::Infer)
}
pub(super) fn label(&self) -> String {
match self {
Self::Nominal(TypeDesc::Ref(name), _) => {
name.rsplit("::").next().unwrap_or(name).into()
}
Self::Nominal(TypeDesc::Struct(_), _) | Self::Record(_) => "record".into(),
Self::Nominal(TypeDesc::Enum(_), _) => "enum".into(),
Self::Nominal(TypeDesc::Display { name, .. }, _) => (*name).into(),
Self::Option(inner) => format!("Option<{}>", inner.label()),
Self::Absent(inner) => format!("possibly absent {}", inner.label()),
Self::List(inner, _) => format!("List<{}>", inner.label()),
Self::ListLiteral(_) => "list literal".into(),
Self::Tuple(items) => format!(
"({})",
items.iter().map(Self::label).collect::<Vec<_>>().join(", ")
),
Self::Map(key, value) => format!("Map<{}, {}>", key.label(), value.label()),
Self::Union(types) => types
.iter()
.map(Self::label)
.collect::<Vec<_>>()
.join(" | "),
Self::Service(name) => name.clone(),
_ => format!("{self:?}"),
}
}
}
pub(super) fn shape_fields(
registry: &TypeRegistry,
shape: &TypeDesc,
direction: Direction,
) -> Scope {
fields(registry, shape, direction, &mut BTreeSet::new())
}
fn fields(
registry: &TypeRegistry,
shape: &TypeDesc,
direction: Direction,
seen: &mut BTreeSet<&'static str>,
) -> Scope {
match shape {
TypeDesc::Ref(name) if seen.insert(name) => {
let result = registry
.get(name, direction)
.map(|named| fields(registry, &named.ty, direction, seen))
.unwrap_or_default();
seen.remove(name);
result
}
TypeDesc::Display { ty, .. } | TypeDesc::Option(ty) => {
fields(registry, ty, direction, seen)
}
TypeDesc::Struct(members) => {
let mut result = Scope::new();
for member in members {
if member.flatten {
let nested = fields(registry, &member.ty, direction, seen);
result.absent.extend(nested.absent);
result.bindings.extend(nested.bindings);
continue;
}
result.insert(member.name.into(), member.ty.clone());
if member.presence == Presence::Absent && direction == Direction::Serialize {
result.absent.insert(member.name.into());
}
}
result
}
_ => Scope::new(),
}
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(super) struct Place {
pub name: String,
access: Vec<Access>,
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
enum Access {
Field(String),
Index(i64),
Key(String),
}
impl Place {
pub(super) fn of(expr: &Expr) -> Option<Self> {
match &expr.kind {
ExprKind::Path(path) if path.len() == 1 => Some(Self {
name: path[0].clone(),
access: Vec::new(),
}),
ExprKind::Field { receiver, name, .. } => Self::of(receiver).map(|mut p| {
p.access.push(Access::Field(name.clone()));
p
}),
ExprKind::Index {
receiver, index, ..
} => {
let name = match &index.kind {
ExprKind::Literal(Literal::String(s)) => Access::Field(s.clone()),
ExprKind::Literal(Literal::Int(i)) => Access::Index(*i),
ExprKind::Path(path) if path.len() == 1 => Access::Key(path[0].clone()),
_ => return None,
};
Self::of(receiver).map(|mut p| {
p.access.push(name);
p
})
}
_ => None,
}
}
fn depends_on(&self, name: &str) -> bool {
self.name == name
|| self
.access
.iter()
.any(|access| matches!(access, Access::Key(key) if key == name))
}
pub(super) fn is_root(&self) -> bool {
self.access.is_empty()
}
pub(super) fn writable_root(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Path(path) if path.len() == 1 => Some(&path[0]),
ExprKind::Field {
receiver,
optional: false,
..
}
| ExprKind::Index {
receiver,
optional: false,
..
} => Self::writable_root(receiver),
_ => None,
}
}
pub(super) fn root(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Path(path) if path.len() == 1 => Some(&path[0]),
ExprKind::Field { receiver, .. } | ExprKind::Index { receiver, .. } => {
Self::root(receiver)
}
_ => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct Binding {
pub ty: Ty,
pub mutable: bool,
pub middleware: bool,
pub model: bool,
id: usize,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(super) struct Environment {
pub bindings: BTreeMap<String, Binding>,
pub absent: BTreeSet<String>,
pub narrowed: BTreeSet<Place>,
pub loop_depth: usize,
pub code_loops: usize,
pub break_scopes: usize,
pub continue_scopes: usize,
pub helpers: BTreeMap<String, Signature>,
pub contract: BTreeSet<String>,
pub optional_slots: bool,
next_id: usize,
unsets: BTreeSet<usize>,
writes: BTreeMap<usize, (usize, Option<Ty>)>,
}
impl Environment {
pub(super) fn bind(&mut self, name: String, ty: Ty, mutable: bool) {
self.clear(&name);
self.absent.remove(&name);
self.next_id += 1;
self.bindings.insert(
name,
Binding {
ty,
mutable,
middleware: false,
id: self.next_id,
model: false,
},
);
}
pub(super) fn bind_model(&mut self, name: &str, ty: Ty) {
self.bind(name.into(), ty, false);
if let Some(binding) = self.bindings.get_mut(name) {
binding.model = true;
}
}
pub(super) fn mark_present(&mut self, name: &str) {
self.narrowed.insert(Place {
name: name.into(),
access: Vec::new(),
});
}
pub(super) fn mark_middleware(&mut self, name: &str) {
if let Some(binding) = self.bindings.get_mut(name) {
binding.middleware = true;
}
}
fn clear(&mut self, name: &str) {
self.narrowed.retain(|p| !p.depends_on(name));
}
pub(super) fn unset(&mut self, name: &str) {
self.clear(name);
if let Some(binding) = self.bindings.remove(name) {
self.unsets.insert(binding.id);
}
self.absent.insert(name.into());
}
pub(super) fn write(&mut self, name: &str, ty: Option<Ty>) {
self.clear(name);
if let Some(binding) = self.bindings.get_mut(name) {
let (revision, last_type) = self.writes.entry(binding.id).or_default();
*revision += 1;
if let Some(ty) = ty {
*last_type = Some(ty.clone());
binding.ty = ty;
}
}
}
pub(super) fn join(&mut self, branch: &Self) {
let mut writes = Vec::new();
for (name, binding) in &self.bindings {
if let Some((revision, ty)) = branch.writes.get(&binding.id)
&& self
.writes
.get(&binding.id)
.is_none_or(|(previous, _)| revision > previous)
{
let inferred =
matches!(&binding.ty, Ty::List(element, _) if **element == Ty::Infer);
writes.push((name.clone(), ty.clone().filter(|_| inferred)));
}
if branch.unsets.contains(&binding.id) && !self.unsets.contains(&binding.id) {
writes.push((name.clone(), Some(binding.ty.clone().optional())));
}
}
for (name, ty) in writes {
self.write(&name, ty);
}
self.unsets
.extend(branch.unsets.iter().filter(|id| **id <= self.next_id));
}
pub(super) fn forget_loop_mutations(&mut self, before: &Self, after: &Self) -> bool {
let old = self.narrowed.len();
self.narrowed.retain(|place| {
before
.bindings
.iter()
.filter(|(name, _)| place.depends_on(name))
.all(|(_, binding)| {
before.writes.get(&binding.id) == after.writes.get(&binding.id)
&& before.unsets.contains(&binding.id) == after.unsets.contains(&binding.id)
})
});
self.narrowed.len() != old
}
pub(super) fn for_include(&self) -> Self {
let mut env = Self::default();
for (name, binding) in &self.bindings {
env.bind(name.clone(), binding.ty.clone(), binding.mutable);
if binding.model
&& let Some(bound) = env.bindings.get_mut(name)
{
bound.model = true;
}
if binding.middleware {
env.mark_middleware(name);
}
}
env.narrowed = self.narrowed.clone();
env.absent = self.absent.clone();
env.loop_depth = self.loop_depth;
env.optional_slots = self.optional_slots;
env.helpers = self.helpers.clone();
env.contract = self.contract.clone();
env
}
}
impl Run<'_, '_> {
pub(super) fn resolve(&self, ty: &Ty) -> Ty {
let mut current = ty.clone();
let mut seen = BTreeSet::new();
loop {
let next = match ¤t {
Ty::Nominal(TypeDesc::Ref(name), direction) if seen.insert(*name) => {
if let Some(item) = self.config.paginators.get(*name) {
return Ty::Paginator(Box::new(Ty::from(item.clone())));
}
self.config
.types
.get(name, *direction)
.map(|named| Ty::shape(named.ty.clone(), *direction))
}
Ty::Nominal(TypeDesc::Display { ty, .. }, direction) => {
Some(Ty::shape(*ty.clone(), *direction))
}
Ty::Nominal(TypeDesc::Enum(desc), direction) if desc.tag == EnumTag::Untagged => {
let types = desc
.variants
.iter()
.map(|variant| {
variant
.payload
.clone()
.map_or(Ty::Null, |ty| Ty::shape(ty, *direction))
})
.collect();
return Ty::Union(types);
}
Ty::Nominal(TypeDesc::Enum(desc), _)
if desc.tag == EnumTag::External
&& desc
.variants
.iter()
.all(|variant| variant.payload.is_none() && !variant.untagged) =>
{
return Ty::String;
}
_ => None,
};
match next {
Some(ty) => current = ty,
None => return current,
}
}
}
pub(super) fn present_type(&self, mut ty: Ty) -> Ty {
let mut visited = Vec::new();
while !visited.contains(&ty) {
match self.resolve(&ty) {
Ty::Option(inner) | Ty::Absent(inner) => {
visited.push(ty);
ty = *inner;
}
_ => return ty,
}
}
Ty::Any
}
pub(super) fn potentially_missing(&self, ty: &Ty) -> bool {
matches!(self.resolve(ty), Ty::Option(_) | Ty::Absent(_))
}
pub(super) fn type_name(&self, ty: &Ty) -> String {
if let Ty::Nominal(TypeDesc::Ref(name), direction) = ty
&& let Some(named) = self.config.types.get(name, *direction)
{
return named.name.to_owned();
}
ty.label()
}
pub(super) fn members(&self, ty: &Ty) -> Option<BTreeMap<String, Ty>> {
match self.resolve(ty) {
Ty::Record(fields) => Some(fields),
Ty::Nominal(desc @ TypeDesc::Struct(_), direction) => {
let scope = shape_fields(self.config.types, &desc, direction);
Some(
scope
.bindings
.iter()
.map(|(name, ty)| (name.clone(), scope.binding_type(name, ty, direction)))
.collect(),
)
}
_ => None,
}
}
pub(super) fn field(&self, ty: &Ty, name: &str) -> Option<Ty> {
self.lookup_field(ty, name, &mut BTreeSet::new())
}
fn lookup_field(&self, ty: &Ty, name: &str, seen: &mut BTreeSet<&'static str>) -> Option<Ty> {
if let Ty::Nominal(TypeDesc::Ref(id), _) = ty {
if !seen.insert(id) {
return None;
}
let field = self.lookup_field(&self.resolve(ty), name, seen);
seen.remove(id);
return field;
}
match self.resolve(ty) {
Ty::Record(fields) => fields.get(name).cloned(),
Ty::Nominal(TypeDesc::Struct(members), direction) => {
for member in &members {
if !member.flatten && (member.name == name || member.aliases.contains(&name)) {
let ty = Ty::shape(member.ty.clone(), direction);
return Some(
if member.presence == Presence::Absent
&& direction == Direction::Serialize
{
ty.optional()
} else {
ty
},
);
}
}
for member in members.into_iter().filter(|m| m.flatten) {
let ty = Ty::shape(member.ty, direction);
let field = match self.resolve(&ty) {
Ty::Option(inner) => self
.lookup_field(&inner, name, seen)
.map(|ty| Ty::Absent(Box::new(ty))),
Ty::Map(key, value) if self.fits(&Ty::String, &key) => {
Some(Ty::Absent(value))
}
_ => self.lookup_field(&ty, name, seen),
};
if field.is_some() {
return field;
}
}
None
}
Ty::Nominal(TypeDesc::Enum(desc), direction) => {
let variants = desc
.variants
.into_iter()
.map(|variant| {
let payload = variant.payload.map(|ty| Ty::shape(ty, direction));
match (&desc.tag, variant.untagged) {
(_, true) | (EnumTag::Untagged, _) => {
payload.and_then(|ty| self.lookup_field(&ty, name, seen))
}
(EnumTag::External, _) if variant.name == name => payload,
(EnumTag::Internal { tag }, _) if *tag == name => Some(Ty::String),
(EnumTag::Internal { .. }, _) => {
payload.and_then(|ty| self.lookup_field(&ty, name, seen))
}
(EnumTag::Adjacent { tag, .. }, _) if *tag == name => Some(Ty::String),
(EnumTag::Adjacent { content, .. }, _) if *content == name => payload,
_ => None,
}
})
.collect::<Vec<_>>();
let partial = variants.iter().any(Option::is_none);
let found = variants.into_iter().flatten().reduce(union)?;
Some(if partial { found.optional() } else { found })
}
Ty::Union(types) => {
let mut found = Vec::new();
for ty in types {
found.push(self.lookup_field(&ty, name, seen)?);
}
found.into_iter().reduce(union)
}
Ty::Map(key, value) if self.fits(&Ty::String, &key) => Some(*value),
Ty::Loop(depth) => match name {
"index" | "iteration" | "remaining" | "count" | "depth" => Some(Ty::Int),
"first" | "last" | "even" | "odd" => Some(Ty::Bool),
"parent" if depth > 1 => Some(Ty::Loop(depth - 1)),
"parent" => Some(Ty::Null),
_ => None,
},
Ty::Slot if name == "attributes" => Some(Ty::Attributes),
Ty::Any | Ty::Error | Ty::Infer => Some(ty.clone()),
_ => None,
}
}
pub(super) fn fits(&self, actual: &Ty, expected: &Ty) -> bool {
self.fits_inner(actual, expected, &mut Vec::new())
}
fn fits_inner(&self, actual: &Ty, expected: &Ty, seen: &mut Vec<(Ty, Ty)>) -> bool {
if actual == expected || actual.unknown() || expected.unknown() {
return true;
}
let pair = (actual.clone(), expected.clone());
if seen.contains(&pair) {
return true;
}
seen.push(pair);
let actual = self.resolve(actual);
let expected = self.resolve(expected);
let result = self.fits_resolved(&actual, &expected, seen);
seen.pop();
result
}
fn fits_resolved(&self, actual: &Ty, expected: &Ty, seen: &mut Vec<(Ty, Ty)>) -> bool {
if actual == expected || actual.unknown() || expected.unknown() {
return true;
}
match (actual, expected) {
(Ty::Union(types), expected) => {
types.iter().all(|ty| self.fits_inner(ty, expected, seen))
}
(actual, Ty::Union(types)) => types.iter().any(|ty| self.fits_inner(actual, ty, seen)),
(Ty::Null, Ty::Option(_)) => true,
(Ty::Option(actual), Ty::Option(expected)) => self.fits_inner(actual, expected, seen),
(actual, Ty::Option(expected)) => self.fits_inner(actual, expected, seen),
(Ty::String | Ty::Int | Ty::Float | Ty::Null, Ty::Text) => true,
(Ty::Option(inner), Ty::Text) => self.fits_inner(inner, &Ty::Text, seen),
(Ty::ListLiteral(values), Ty::List(inner, len)) => {
len.is_none_or(|len| len == values.len())
&& values.iter().all(|v| self.fits_inner(v, inner, seen))
}
(Ty::List(a, al), Ty::List(b, bl)) => {
(bl.is_none() || al == bl) && self.fits_inner(a, b, seen)
}
(Ty::ListLiteral(a) | Ty::Tuple(a), Ty::Tuple(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| self.fits_inner(a, b, seen))
}
(Ty::Map(ak, av), Ty::Map(bk, bv)) => {
self.fits_inner(ak, bk, seen) && self.fits_inner(av, bv, seen)
}
(Ty::Record(fields), Ty::Map(key, value)) => {
self.fits_inner(&Ty::String, key, seen)
&& fields.values().all(|ty| self.fits_inner(ty, value, seen))
}
(actual, expected)
if self.members(actual).is_some() && self.members(expected).is_some() =>
{
self.members(expected)
.unwrap_or_default()
.into_iter()
.all(|(name, ty)| {
self.field(actual, &name).map_or_else(
|| matches!(self.resolve(&ty), Ty::Option(_) | Ty::Absent(_)),
|value| self.fits_inner(&value, &ty, seen),
)
})
}
_ => false,
}
}
pub(super) fn same(&self, a: &Ty, b: &Ty) -> bool {
self.fits(a, b) && self.fits(b, a)
}
pub(super) fn annotation(&self, text: &str) -> Option<Ty> {
let text = text.trim();
if let Some(inner) = text.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
return split_types(inner)
.into_iter()
.filter(|piece| !piece.trim().is_empty())
.map(|piece| self.annotation(piece))
.collect::<Option<Vec<_>>>()
.map(Ty::Tuple);
}
if let Some(inner) = text.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
return if let Some((element, length)) = inner.split_once(';') {
Some(Ty::List(
Box::new(self.annotation(element)?),
Some(length.trim().parse().ok()?),
))
} else {
Some(Ty::list(self.annotation(inner)?))
};
}
if let Some((container, args)) = text.split_once('<')
&& let Some(args) = args.strip_suffix('>')
{
let args = split_types(args);
return match (container.trim().rsplit("::").next()?, args.as_slice()) {
("Option", [inner]) => Some(self.annotation(inner)?.optional()),
("Vec" | "List", [inner]) => Some(Ty::list(self.annotation(inner)?)),
("Paginator" | "LengthAwarePaginator" | "CursorPaginator", [inner]) => {
Some(Ty::Paginator(Box::new(self.annotation(inner)?)))
}
("IndexMap" | "BTreeMap" | "Map", [key, value]) => {
Some(Ty::map(self.annotation(key)?, self.annotation(value)?))
}
_ => None,
};
}
Some(match text.rsplit("::").next()? {
"bool" | "Bool" => Ty::Bool,
"i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64"
| "u128" | "usize" | "Int" => Ty::Int,
"f32" | "f64" | "Float" => Ty::Float,
"str" | "&str" | "String" => Ty::String,
"Text" => Ty::Text,
"Html" => Ty::Html,
"Slot" => Ty::Slot,
"Attributes" | "AttributeBag" | "ComponentAttributeBag" => Ty::Attributes,
"Date" => Ty::Date,
"Any" | "Value" => Ty::Any,
_ => {
let mut found = self.config.types.iter().filter(|(id, direction, entry)| {
*direction == Direction::Serialize && (*id == text || entry.name == text)
});
let (id, direction, _) = found.next()?;
if found.next().is_some() {
return None;
}
Ty::Nominal(TypeDesc::Ref(id), direction)
}
})
}
}
pub(super) fn union(a: Ty, b: Ty) -> Ty {
if a == b || matches!(b, Ty::Error | Ty::Infer) {
return a;
}
if matches!(a, Ty::Error | Ty::Infer) {
return b;
}
match (a, b) {
(Ty::Null, other) | (other, Ty::Null) => other.optional(),
(Ty::Union(mut types), b) => {
if !types.contains(&b) {
types.push(b);
}
Ty::Union(types)
}
(a, b) => Ty::Union(vec![a, b]),
}
}
fn split_types(text: &str) -> Vec<&str> {
let mut depth = 0;
let mut start = 0;
let mut parts = Vec::new();
for (index, c) in text.char_indices() {
match c {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
parts.push(&text[start..index]);
start = index + 1;
}
_ => {}
}
}
parts.push(&text[start..]);
parts
}