use crate::DecodeError;
use crate::decode::Mode;
use crate::types::{Body, Catalog, Decl, Type};
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub(crate) struct Summary {
problem: Option<String>,
uses: Vec<bool>,
option_uses: Vec<bool>,
}
pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
match catalog.crossing_problem(ty) {
Some(problem) => Err(DecodeError {
path: String::new(),
problem,
kind: crate::DecodeErrorKind::Invalid,
}),
None => Ok(()),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Judgment {
Reply,
Input,
Rebuild,
Crossing,
}
impl From<Mode> for Judgment {
fn from(mode: Mode) -> Self {
match mode {
Mode::Reply => Self::Reply,
Mode::Input => Self::Input,
Mode::Rebuild => Self::Rebuild,
}
}
}
pub(crate) type Summaries = Vec<[Summary; 4]>;
const MODES: [Judgment; 4] = [
Judgment::Reply,
Judgment::Input,
Judgment::Rebuild,
Judgment::Crossing,
];
fn slot(mode: Judgment) -> usize {
match mode {
Judgment::Reply => 0,
Judgment::Input => 1,
Judgment::Rebuild => 2,
Judgment::Crossing => 3,
}
}
pub(crate) fn summarize(decls: &[Decl]) -> Summaries {
let mut summaries: Summaries = decls
.iter()
.map(|decl| {
let blank = Summary {
problem: None,
uses: vec![false; decl.params.len()],
option_uses: vec![false; decl.params.len()],
};
[blank.clone(), blank.clone(), blank.clone(), blank]
})
.collect();
let facts: usize = decls.iter().map(|decl| 2 * decl.params.len() + 1).sum();
for _ in 0..=facts {
if !round(decls, &mut summaries) {
break;
}
}
summaries
}
fn round(decls: &[Decl], summaries: &mut Summaries) -> bool {
let mut changed = false;
for (index, decl) in decls.iter().enumerate() {
for mode in MODES {
let fields: Vec<&Type> = match &decl.body {
Body::Record(_, fields) => fields.iter().collect(),
Body::Enum(_, ctors) => ctors.iter().flatten().collect(),
Body::Host | Body::NonData => Vec::new(),
};
let mut next = summaries[index][slot(mode)].clone();
for field in fields {
let problem = walk(
decls,
summaries,
mode,
field,
&mut |param, option_operand| {
if let Some(used) = next.uses.get_mut(param as usize) {
*used = true;
}
if option_operand
&& let Some(used) = next.option_uses.get_mut(param as usize)
{
*used = true;
}
},
);
if next.problem.is_none() {
next.problem = problem;
}
}
if next != summaries[index][slot(mode)] {
summaries[index][slot(mode)] = next;
changed = true;
}
}
}
changed
}
pub(crate) fn judge(
decls: &[Decl],
summaries: &Summaries,
ty: &Type,
mode: Judgment,
) -> Option<String> {
let mut unbound = false;
let problem = walk(decls, summaries, mode, ty, &mut |_, _| unbound = true);
problem.or_else(|| unbound.then(no_encoding))
}
fn no_encoding() -> String {
"has a type with no encoding".into()
}
fn walk(
decls: &[Decl],
summaries: &Summaries,
mode: Judgment,
ty: &Type,
on_param: &mut dyn FnMut(u32, bool),
) -> Option<String> {
match ty {
Type::Option(item) if mode == Judgment::Crossing => {
option_operand(item, on_param).or_else(|| walk(decls, summaries, mode, item, on_param))
}
Type::List(item) | Type::Set(item) | Type::Option(item) => {
walk(decls, summaries, mode, item, on_param)
}
Type::Dict(key, value) => walk(decls, summaries, mode, key, on_param)
.or_else(|| walk(decls, summaries, mode, value, on_param)),
Type::Tuple(parts) => parts
.iter()
.find_map(|part| walk(decls, summaries, mode, part, on_param)),
Type::Named(id, args) => {
let decl = &decls[id.0 as usize];
if decl.opaque && matches!(mode, Judgment::Reply | Judgment::Input) {
return Some(format!(
"has the type {}, which is opaque, so it can't be decoded",
decl.identity
));
}
if matches!(decl.body, Body::Host) && mode == Judgment::Input {
return Some(format!(
"has the host type {}, which a run's input can't carry",
decl.identity
));
}
if matches!(decl.body, Body::NonData) && mode != Judgment::Rebuild {
return Some(no_encoding());
}
let summary = &summaries[id.0 as usize][slot(mode)];
if let Some(problem) = &summary.problem {
return Some(problem.clone());
}
if mode == Judgment::Crossing {
for (arg, used) in args.iter().zip(&summary.option_uses) {
if *used && let Some(problem) = option_operand(arg, on_param) {
return Some(problem);
}
}
}
args.iter()
.zip(&summary.uses)
.filter(|(_, used)| **used)
.find_map(|(arg, _)| walk(decls, summaries, mode, arg, on_param))
}
Type::Param(index) => {
on_param(*index, false);
None
}
Type::Task(_) | Type::Function { .. } | Type::NotData if mode == Judgment::Rebuild => None,
Type::Task(_) | Type::Function { .. } | Type::NotData => Some(no_encoding()),
Type::Int
| Type::Decimal
| Type::Bool
| Type::Text
| Type::Bytes
| Type::Duration
| Type::Instant
| Type::Unit
| Type::Never
| Type::Json => None,
}
}
fn option_operand(ty: &Type, on_param: &mut dyn FnMut(u32, bool)) -> Option<String> {
match ty {
Type::Json => Some("has an Option<json.Value> part, which cannot cross a boundary".into()),
Type::Param(index) => {
on_param(*index, true);
None
}
_ => None,
}
}