use std::sync::Arc;
use flow_types::{EnumShape, RecordShape};
use flow_value::{Dict, Record, Set, Text, Tuple, Value, Variant};
use crate::catalog::StdForm;
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::json::quote;
use crate::limits::Limits;
#[derive(Debug)]
pub(crate) enum Begun<P, M = Make, V = Value> {
Done(V),
Open(Frame<P, M, V>),
}
#[derive(Debug)]
pub(crate) struct Frame<P, M = Make, V = Value> {
pub(crate) parts: P,
pub(crate) make: M,
pub(crate) values: Vec<V>,
pub(crate) level: usize,
}
impl<P, M, V> Frame<P, M, V> {
pub(crate) fn open(make: M, parts: P, room: usize, level: usize) -> Begun<P, M, V> {
Begun::Open(Frame {
parts,
make,
values: Vec::with_capacity(room),
level,
})
}
}
pub(crate) enum Make {
List,
Set,
Tuple,
Dict,
Record(Arc<RecordShape>),
Variant(Arc<EnumShape>, usize),
Unwritten(Arc<EnumShape>, usize),
Newtype(Option<StdForm>),
}
pub(crate) trait Source<P> {
fn path(&mut self) -> &mut Place;
fn next(&mut self, frame: &mut Frame<P>) -> Result<Option<Begun<P>>, DecodeError>;
fn steps(frame: &Frame<P>) -> usize;
fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError>;
fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError>;
fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError>;
}
pub(crate) trait Walk<P, M, V> {
type Error;
fn path(&mut self) -> &mut Place;
fn next(&mut self, frame: &mut Frame<P, M, V>) -> Result<Option<Begun<P, M, V>>, Self::Error>;
fn steps(frame: &Frame<P, M, V>) -> usize;
fn finish(&mut self, frame: Frame<P, M, V>) -> Result<V, Self::Error>;
}
impl<P, S: Source<P>> Walk<P, Make, Value> for S {
type Error = DecodeError;
fn path(&mut self) -> &mut Place {
Source::path(self)
}
fn next(&mut self, frame: &mut Frame<P>) -> Result<Option<Begun<P>>, DecodeError> {
Source::next(self, frame)
}
fn steps(frame: &Frame<P>) -> usize {
<S as Source<P>>::steps(frame)
}
fn finish(&mut self, frame: Frame<P>) -> Result<Value, DecodeError> {
finish(self, frame)
}
}
const NATIVE_DEPTH: usize = 8;
pub(crate) fn build<P, M, V, W: Walk<P, M, V>>(
walk: &mut W,
root: Begun<P, M, V>,
) -> Result<V, W::Error> {
match root {
Begun::Done(value) => Ok(value),
Begun::Open(frame) => build_within(walk, frame, NATIVE_DEPTH),
}
}
fn build_within<P, M, V, W: Walk<P, M, V>>(
walk: &mut W,
mut frame: Frame<P, M, V>,
room: usize,
) -> Result<V, W::Error> {
let Some(room) = room.checked_sub(1) else {
return build_on_heap(walk, frame);
};
while let Some(part) = walk.next(&mut frame)? {
let value = match part {
Begun::Done(value) => value,
Begun::Open(part) => build_within(walk, part, room)?,
};
made(walk, &mut frame, value);
}
walk.finish(frame)
}
fn build_on_heap<P, M, V, W: Walk<P, M, V>>(
walk: &mut W,
root: Frame<P, M, V>,
) -> Result<V, W::Error> {
let mut open = vec![root];
loop {
let frame = open
.last_mut()
.expect("a frame is open until the root is made");
let value = match walk.next(frame)? {
Some(Begun::Open(part)) => {
open.push(part);
continue;
}
Some(Begun::Done(value)) => value,
None => {
let frame = open.pop().expect("the frame just read");
let value = walk.finish(frame)?;
let Some(frame) = open.last_mut() else {
return Ok(value);
};
made(walk, frame, value);
continue;
}
};
made(walk, frame, value);
}
}
fn made<P, M, V, W: Walk<P, M, V>>(walk: &mut W, frame: &mut Frame<P, M, V>, value: V) {
frame.values.push(value);
for _ in 0..W::steps(frame) {
walk.path().pop();
}
}
fn finish<P, S: Source<P>>(source: &mut S, frame: Frame<P>) -> Result<Value, DecodeError> {
let mut values = frame.values.into_iter();
Ok(match frame.make {
Make::List => Value::List(values.collect()),
Make::Set => Value::Set(source.set(values.collect())?),
Make::Tuple => Value::Tuple(Tuple::new(values)),
Make::Dict => {
let entries = std::iter::from_fn(|| Some((values.next()?, values.next()?)));
Value::Dict(source.dict(entries.collect())?)
}
Make::Record(shape) => {
Value::Record(Record::new(shape, values.collect()).expect("one value per field"))
}
Make::Variant(shape, index) => {
source.path().pop();
Value::Variant(
Variant::new(shape, index, values.collect()).expect("one value per part"),
)
}
Make::Unwritten(shape, index) => Value::Variant(
Variant::new(shape, index, values.collect()).expect("one value per part"),
),
Make::Newtype(form) => match (form, values.next().expect("a newtype's one value")) {
(Some(form), Value::Text(text)) => source.form(form, text)?,
(_, value) => value,
},
})
}
pub(crate) fn normal(
form: StdForm,
text: &Text,
limits: &Limits,
path: &Place,
) -> Result<Value, DecodeError> {
let Some(normal) = form.normal(text.as_str()) else {
return Err(DecodeError::of(
path,
DecodeErrorKind::Mismatch,
format!("is {}, which is not {}", quote(text.as_str()), form.noun()),
));
};
if normal.len() > limits.text_bytes {
return Err(DecodeError::of(
path,
DecodeErrorKind::TooLarge,
format!("is longer than {} bytes", limits.text_bytes),
));
}
Ok(Value::Text(Text::new(&normal)))
}
pub(crate) fn distinct_set(items: Vec<Value>, path: &Place) -> Result<Set, DecodeError> {
let count = items.len();
let set = Set::from_items(items).expect("values read at a set's type are data");
if set.len() != count {
return Err(DecodeError::of(
path,
DecodeErrorKind::Duplicate,
"has two equal elements".to_owned(),
));
}
Ok(set)
}
pub(crate) fn distinct_dict(
entries: Vec<(Value, Value)>,
path: &Place,
) -> Result<Dict, DecodeError> {
let count = entries.len();
let dict = Dict::from_entries(entries).expect("keys read at a dictionary's type are data");
if dict.len() != count {
return Err(DecodeError::of(
path,
crate::error::DecodeErrorKind::Duplicate,
"has two equal keys".to_owned(),
));
}
Ok(dict)
}