use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::{Arc, Mutex, PoisonError};
use flow_span::{RunId, TaskPath};
use flow_types::{
Body, Decl, DeclId, EnumShape, JsonValueCtor, Members, Mismatch, NameIndex, Nested, OptionCtor,
Reason, Role, Settings, Shape, Spelling, StdEnum, Tree, Type, Versions, judge,
};
use flow_value::{Value, Variant};
use crate::DecodeError;
use crate::decode::{CROSSING, Mode};
use crate::form::{Form, form};
use crate::json::quote;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StdForm {
Path,
Url,
MediaType,
RunId,
TaskPath,
}
impl StdForm {
pub fn of(decl: &Decl) -> Option<StdForm> {
let identity = &decl.identity;
if *identity.origin.tree() != Tree::Std || identity.version.as_deref() != Some("v1") {
return None;
}
let role = Role::of(identity.origin.module().as_str(), identity.name.as_str())?;
[
StdForm::Path,
StdForm::Url,
StdForm::MediaType,
StdForm::RunId,
StdForm::TaskPath,
]
.into_iter()
.find(|form| form.role() == role)
}
pub fn role(self) -> Role {
match self {
StdForm::Path => Role::Path,
StdForm::Url => Role::Url,
StdForm::MediaType => Role::MediaType,
StdForm::RunId => Role::RunId,
StdForm::TaskPath => Role::TaskPath,
}
}
pub fn normal(self, text: &str) -> Option<String> {
match self {
StdForm::Path => Some(flow_types::normal_path(text)),
StdForm::Url => crate::url::normal_url(text),
StdForm::MediaType => crate::media::normal_media_type(text),
StdForm::RunId => RunId::parse(text).ok().map(|run| run.to_string()),
StdForm::TaskPath => TaskPath::parse(text).ok().map(|task| task.to_string()),
}
}
pub fn make(self, text: &str) -> Option<Value> {
self.normal(text).map(|normal| Value::Text(normal.into()))
}
pub fn refusal(self, text: &str) -> Option<String> {
match self.normal(text) {
Some(normal) if normal == text => None,
Some(normal) => Some(format!(
"is {} written {}, which is not its normal form {}",
self.noun(),
quote(text),
quote(&normal)
)),
None => Some(format!("is {}, which is not {}", quote(text), self.noun())),
}
}
pub fn out_of(form: Option<StdForm>, value: &Value) -> Option<String> {
match (form, value) {
(Some(form), Value::Text(text)) => form.refusal(text.as_str()),
_ => None,
}
}
pub fn first_out_of(catalog: &Catalog, ty: &Type, value: &Value) -> Option<String> {
let mut pending: Vec<(Type, &Value)> = vec![(ty.clone(), value)];
while let Some((ty, value)) = pending.pop() {
match (form(catalog, &ty), value) {
(Form::Newtype(base, held), _) => {
if let Some(problem) = StdForm::out_of(held, value) {
return Some(problem);
}
pending.push((base, value));
}
(Form::List(item), Value::List(items)) => {
pending.extend(items.iter().map(|part| (item.clone(), part)));
}
(Form::Set(item), Value::Set(items)) => {
pending.extend(items.iter().map(|part| (item.clone(), part)));
}
(Form::Dict(key, item), Value::Dict(entries)) => {
for (k, v) in entries.iter() {
pending.push((key.clone(), k));
pending.push((item.clone(), v));
}
}
(Form::Tuple(parts), Value::Tuple(tuple)) => {
pending.extend(parts.iter().cloned().zip(tuple.parts()));
}
(Form::Record(record), Value::Record(fields)) => {
pending.extend(record.fields.into_iter().zip(fields.fields()));
}
(Form::Enum(shape), Value::Variant(variant)) => {
let parts = shape.parts(variant.index()).unwrap_or_default();
pending.extend(
parts
.into_iter()
.map(Cow::into_owned)
.zip(variant.payload()),
);
}
_ => {}
}
}
None
}
pub(crate) fn noun(self) -> &'static str {
match self {
StdForm::Path => "a path",
StdForm::Url => "a URL",
StdForm::MediaType => "a media type",
StdForm::RunId => "a run's id",
StdForm::TaskPath => "a task's id",
}
}
}
#[derive(Clone, Debug)]
pub struct Catalog {
decls: Vec<Decl>,
judged: Judged,
names: Vec<Names>,
option: Bound<OptionCtor>,
json: Option<Bound<JsonValueCtor>>,
}
#[derive(Debug, Default)]
struct Judged(Mutex<HashMap<(Type, Settings), Option<String>>>);
impl Clone for Judged {
fn clone(&self) -> Self {
Judged(Mutex::new(self.entries().clone()))
}
}
impl Judged {
fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(Type, Settings), Option<String>>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Clone, Debug)]
struct Names {
exact: NameIndex,
relaxed: Option<NameIndex>,
}
impl Names {
fn of(decls: &[Decl]) -> Vec<Names> {
decls
.iter()
.map(|decl| Names {
exact: NameIndex::of(&decl.body, Spelling::Exact)
.expect("a declaration's names are distinct"),
relaxed: NameIndex::of(&decl.body, Spelling::Relaxed).ok(),
})
.collect()
}
}
#[derive(Clone, Debug)]
pub(crate) struct Bound<C> {
pub(crate) shape: Arc<EnumShape>,
pub(crate) ctors: StdEnum<C>,
}
impl<C: Members> Bound<C> {
fn of(shape: Arc<EnumShape>) -> Result<Self, Mismatch> {
Ok(Bound {
ctors: StdEnum::of(&shape)?,
shape,
})
}
}
pub fn std_enum(role: Role) -> Arc<EnumShape> {
match role.shape() {
Some(Shape::Enum(shape)) => shape,
_ => panic!("std declares no enum for {role:?}"),
}
}
pub trait Params {
fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool;
}
#[derive(Clone, Copy, Debug)]
pub struct Exact;
impl Params for Exact {
fn matches(&mut self, index: u32, _: &Catalog, other_ty: &Type) -> bool {
matches!(other_ty, Type::Param(other_index) if *other_index == index)
}
}
#[derive(Clone, Debug, Default)]
pub struct Fixing {
fixed: std::collections::BTreeMap<u32, Type>,
}
impl Params for Fixing {
fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool {
match self.fixed.entry(index) {
std::collections::btree_map::Entry::Occupied(fixed) => {
other.same(fixed.get(), other, other_ty)
}
std::collections::btree_map::Entry::Vacant(free) => {
free.insert(other_ty.clone());
true
}
}
}
}
impl Catalog {
pub fn new(
decls: Vec<Decl>,
option: Arc<EnumShape>,
json: Option<Arc<EnumShape>>,
) -> Result<Self, DecodeError> {
let lacking = |mismatch: Mismatch| crate::metadata::fail(mismatch.to_string());
let option = Bound::of(option).map_err(lacking)?;
let json = json.map(Bound::of).transpose().map_err(lacking)?;
crate::metadata::regular(&decls)?;
Ok(Catalog {
names: Names::of(&decls),
decls,
judged: Judged::default(),
option,
json,
})
}
pub fn std(decls: Vec<Decl>) -> Result<Catalog, DecodeError> {
Catalog::new(
decls,
std_enum(Role::Option),
Some(std_enum(Role::JsonValue)),
)
}
pub(crate) fn extended(&self, more: Vec<Decl>) -> Catalog {
let mut decls = self.decls.clone();
decls.extend(more);
Catalog {
names: Names::of(&decls),
decls,
judged: Judged::default(),
option: self.option.clone(),
json: self.json.clone(),
}
}
pub fn decl(&self, id: DeclId) -> &Decl {
&self.decls[crate::bytes::index(id.0)]
}
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 fn same(&self, ty: &Type, other: &Catalog, other_ty: &Type) -> bool {
self.matches(ty, other, other_ty, &mut Exact)
}
pub fn matches(
&self,
ty: &Type,
other: &Catalog,
other_ty: &Type,
params: &mut impl Params,
) -> bool {
let mut todo = vec![(ty, other_ty)];
while let Some((ty, other_ty)) = todo.pop() {
if let Type::Param(index) = ty {
if !params.matches(*index, other, other_ty) {
return false;
}
continue;
}
let named_alike = match (ty, other_ty) {
(Type::Named(decl, _), Type::Named(other_decl, _)) => {
let (declared, other_declared) = (self.decl(*decl), other.decl(*other_decl));
declared.identity == other_declared.identity
&& declared.lexical_ordinal == other_declared.lexical_ordinal
}
(Type::NotData, _) => false,
_ => true,
};
let alike = named_alike
&& std::mem::discriminant(ty) == std::mem::discriminant(other_ty)
&& ty.parts().count() == other_ty.parts().count();
if !alike {
return false;
}
todo.extend(ty.parts().rev().zip(other_ty.parts().rev()));
}
true
}
pub fn erase<'t>(&self, ty: &'t Type) -> Cow<'t, Type> {
let mut current = Cow::Borrowed(ty);
for _ in 0..=self.decls.len() {
let Type::Named(decl, args) = &*current else {
return current;
};
let Body::Newtype(base) = &self.decl(*decl).body else {
return current;
};
current = Cow::Owned(base.subst(args));
}
Cow::Owned(Type::NotData)
}
pub fn std_form(&self, ty: &Type) -> Option<StdForm> {
let mut current = Cow::Borrowed(ty);
for _ in 0..=self.decls.len() {
let Type::Named(decl, args) = &*current else {
break;
};
let decl = self.decl(*decl);
if let Some(form) = StdForm::of(decl) {
return Some(form);
}
let Body::Newtype(base) = &decl.body else {
break;
};
current = Cow::Owned(base.subst(args));
}
None
}
pub(crate) fn problem(&self, ty: &Type, settings: Settings) -> Option<String> {
let key = (ty.clone(), settings);
if let Some(problem) = self.judged.entries().get(&key) {
return problem.clone();
}
let mut unbound = false;
let problem = match judge(&self.decls, ty, settings, &mut |_, _| unbound = true) {
Some(refusal) => Some(match refusal.reason {
Reason::Opaque => format!(
"has the type {}, which is opaque, so it can't be decoded",
self.declared(&refusal.part)
),
Reason::Host => format!(
"has the host type {}, which a run's input can't carry",
self.declared(&refusal.part)
),
Reason::SharedKey => {
let decl = self.decl_of(&refusal.part);
let shared = NameIndex::of(&decl.body, Spelling::Relaxed).expect_err(
"the judge refuses only a declaration whose relaxed keys collide",
);
format!(
"has the type {}, whose names `{}` and `{}` share the relaxed key `{}`",
decl.identity, shared.first, shared.second, shared.key
)
}
Reason::JsonValue | Reason::OptionalJson => {
"has an Option<json.Value> part, which cannot cross a boundary".into()
}
Reason::Function | Reason::Task | Reason::NotData => no_encoding(),
}),
None => unbound.then(no_encoding),
};
self.judged.entries().insert(key, problem.clone());
problem
}
pub(crate) fn names(&self, decl: DeclId, mode: Mode) -> &NameIndex {
let names = &self.names[crate::bytes::index(decl.0)];
match mode.spelling() {
Spelling::Exact => &names.exact,
Spelling::Relaxed => names
.relaxed
.as_ref()
.expect("judging refuses a declaration whose relaxed keys collide"),
}
}
fn declared(&self, part: &Type) -> &flow_types::Identity {
&self.decl_of(part).identity
}
fn decl_of(&self, part: &Type) -> &Decl {
let Type::Named(decl, _) = part else {
unreachable!("only a declared type is refused for what it declares")
};
self.decl(*decl)
}
pub(crate) fn option(&self) -> &Bound<OptionCtor> {
&self.option
}
pub fn none(&self) -> Value {
Value::Variant(
Variant::new(
Arc::clone(&self.option.shape),
self.option.ctors.index(OptionCtor::None),
Vec::new(),
)
.expect("None carries nothing"),
)
}
pub fn some(&self, value: Value) -> Value {
Value::Variant(
Variant::new(
Arc::clone(&self.option.shape),
self.option.ctors.index(OptionCtor::Some),
vec![value],
)
.expect("Some carries one value"),
)
}
pub(crate) fn json(&self) -> &Bound<JsonValueCtor> {
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, Versions::Shown)
}
pub(crate) fn written(&self, ty: &Type, versions: Versions) -> String {
enum Next<'t> {
Type(&'t Type),
Text(&'static str),
}
let mut out = String::new();
let mut todo = vec![Next::Type(ty)];
while let Some(next) = todo.pop() {
let ty = match next {
Next::Text(text) => {
out.push_str(text);
continue;
}
Next::Type(ty) => ty,
};
let (open, close) = match ty {
Type::Int => ("Int", ""),
Type::Decimal => ("Decimal", ""),
Type::Bool => ("Bool", ""),
Type::Text => ("Text", ""),
Type::Bytes => ("Bytes", ""),
Type::Duration => ("Duration", ""),
Type::Instant => ("Instant", ""),
Type::Unit => ("Unit", ""),
Type::Never => ("Never", ""),
Type::Json => ("json.Value", ""),
Type::List(_) => ("List<", ">"),
Type::Set(_) => ("Set<", ">"),
Type::Option(_) => ("Option<", ">"),
Type::Task(_) => ("task.Task<", ">"),
Type::Dict(..) => ("Dict<", ">"),
Type::Tuple(_) | Type::Function { .. } => ("(", ""),
Type::Named(decl, args) => {
let declared = self.decl(*decl);
out.push_str(&declared.identity.written(versions));
if declared.lexical_ordinal > 1 {
write!(out, "#{}", declared.lexical_ordinal).expect("writing to a string");
}
if args.is_empty() {
("", "")
} else {
("<", ">")
}
}
Type::Param(index) => {
write!(out, "${index}").expect("writing to a string");
("", "")
}
Type::NotData => ("a type that is not data", ""),
};
out.push_str(open);
todo.push(Next::Text(close));
let mut parts: Vec<&Type> = ty.parts().collect();
if let Type::Function { .. } = ty {
let result = parts.pop().expect("a function type has a result");
todo.push(Next::Type(result));
todo.push(Next::Text(") -> "));
} else if let Type::Tuple(_) = ty {
todo.push(Next::Text(")"));
}
for (at, part) in parts.into_iter().enumerate().rev() {
todo.push(Next::Type(part));
if at > 0 {
todo.push(Next::Text(", "));
}
}
}
out
}
}
fn no_encoding() -> String {
"has a type with no encoding".into()
}
pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
crate::decodable(catalog, ty, CROSSING)
}