use std::collections::BTreeMap;
use std::fmt::Display;
use crate::names::folded;
use crate::path::Path;
use crate::problems::{Kind, Problems};
use crate::raw::{Raw, RawKey};
use crate::variant::Variant;
macro_rules! replaced {
() => {
fn overlay(
&mut self,
raw: &Raw,
path: &Path,
problems: &mut Problems,
) -> Result<(), Unbuilt> {
*self = Self::read(raw, path, problems)?;
Ok(())
}
};
}
macro_rules! sampled {
($sample:expr) => {
fn sample() -> Option<Self> {
$sample
}
};
}
pub(crate) use replaced;
pub(crate) use sampled;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Unbuilt;
pub trait Node {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt>
where
Self: Sized;
fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt>;
fn shape(&self) -> Shape<'_>;
fn variants(&self) -> Vec<Variant> {
Vec::new()
}
fn empty() -> Option<Self>
where
Self: Sized,
{
None
}
fn sample() -> Option<Self>
where
Self: Sized,
{
Self::empty()
}
fn fill(&mut self) {}
fn check(&self, path: &Path, problems: &mut Problems) {
check_children!(self, path, problems);
}
}
pub fn check_inner(node: &dyn Node, path: &Path, problems: &mut Problems) {
check_children!(node, path, problems);
}
macro_rules! check_children {
($node:expr, $path:expr, $problems:expr) => {
match $node.shape() {
Shape::Scalar(_) | Shape::Optional(None) => {}
Shape::Optional(Some(inner)) => inner.check($path, $problems),
Shape::Section(fields) => {
for field in fields {
field.node.check(&$path.field(field.name), $problems);
}
}
Shape::Sequence(items) => {
for (index, item) in items.into_iter().enumerate() {
item.check(&$path.index(index), $problems);
}
}
Shape::Dictionary(entries) => {
for (key, value) in entries {
value.check(&$path.field(key), $problems);
}
}
}
};
}
use check_children;
pub enum Shape<'a> {
Scalar(String),
Optional(Option<&'a dyn Node>),
Section(Vec<Field<'a>>),
Sequence(Vec<&'a dyn Node>),
Dictionary(Vec<(&'a str, &'a dyn Node)>),
}
pub struct Field<'a> {
pub name: &'static str,
pub doc: &'static str,
pub obsolete: Option<&'static str>,
pub required: bool,
pub node: &'a dyn Node,
}
pub fn section_entries<'a>(
raw: &'a Raw,
path: &Path,
problems: &mut Problems,
) -> Option<&'a [(RawKey, Raw)]> {
match raw.entries() {
Some(entries) => Some(entries),
None => {
wrong_shape(raw, path, problems, "a section");
None
}
}
}
pub fn deprecated_field(problems: &mut Problems, key: &RawKey, path: &Path, note: &str) {
let name = key.text();
let message = if note.is_empty() {
format!("deprecated name {name:?}")
} else {
format!("deprecated name {name:?}: {note}")
};
problems.warning(Kind::Obsolete, key.mark(), path.clone(), message);
}
pub fn required_is_missing(problems: &mut Problems, path: &Path, doc: &str) {
problems.error(
Kind::Validation,
&crate::mark::Mark::Model,
path.clone(),
format!("the field is required, but the value is not set — {doc}"),
);
}
pub fn read_enum<T>(
raw: &Raw,
path: &Path,
problems: &mut Problems,
variants: &'static [&'static str],
variant: impl FnOnce(&str) -> Option<T>,
) -> Result<T, Unbuilt> {
read_scalar(raw, path, problems, "a value of the enumeration", |text| {
let read = folded(text);
variant(&read)
.ok_or_else(|| format!("unknown value; possible values: {}", variants.join(", ")))
})
}
pub(crate) fn read_scalar<T, E>(
raw: &Raw,
path: &Path,
problems: &mut Problems,
what: &str,
parse: impl FnOnce(&str) -> Result<T, E>,
) -> Result<T, Unbuilt>
where
E: Display,
{
let Some(text) = raw.text() else {
return Err(wrong_shape(raw, path, problems, what));
};
match parse(text) {
Ok(value) => Ok(value),
Err(error) => {
problems.error(
Kind::InvalidValue,
raw.mark(),
path.clone(),
format!("{text:?} is not {what}: {error}"),
);
Err(Unbuilt)
}
}
}
pub(crate) fn wrong_shape(
raw: &Raw,
path: &Path,
problems: &mut Problems,
expected: &str,
) -> Unbuilt {
let got = raw.describe();
problems.error(
Kind::InvalidValue,
raw.mark(),
path.clone(),
format!("expected {expected}, got {got}"),
);
Unbuilt
}
impl<T: Node> Node for Option<T> {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
if raw.is_null() {
return Ok(None);
}
T::read(raw, path, problems).map(Some)
}
fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
if raw.is_null() {
*self = None;
return Ok(());
}
match self {
Some(inner) => T::overlay(inner, raw, path, problems),
None => {
*self = Some(T::read(raw, path, problems)?);
Ok(())
}
}
}
fn shape(&self) -> Shape<'_> {
Shape::Optional(self.as_ref().map(|inner| inner as &dyn Node))
}
fn variants(&self) -> Vec<Variant> {
match self {
Some(inner) => inner.variants(),
None => T::sample().map_or_else(Vec::new, |sample| sample.variants()),
}
}
fn fill(&mut self) {
if self.is_none()
&& let Some(empty) = T::empty()
{
*self = Some(empty);
}
if let Some(inner) = self {
inner.fill();
}
}
}
impl<T: Node> Node for Vec<T> {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
let mut value = Vec::new();
Self::overlay(&mut value, raw, path, problems)?;
Ok(value)
}
fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
if raw.is_empty() {
self.clear();
return Ok(());
}
if let Some(items) = raw.items() {
*self = read_items(items, path, problems);
return Ok(());
}
if raw.entries().is_some() {
return overlay_items(self, raw, path, problems);
}
Err(wrong_shape(raw, path, problems, "a sequence"))
}
fn shape(&self) -> Shape<'_> {
Shape::Sequence(self.iter().map(|item| item as &dyn Node).collect())
}
fn empty() -> Option<Self> {
Some(Vec::new())
}
fn fill(&mut self) {
if self.is_empty()
&& let Some(sample) = T::sample()
{
self.push(sample);
if let Some(sample) = T::sample() {
self.push(sample);
}
}
for item in self.iter_mut() {
item.fill();
}
}
}
fn read_items<T: Node>(items: &[Raw], path: &Path, problems: &mut Problems) -> Vec<T> {
let mut value = Vec::with_capacity(items.len());
for (index, item) in items.iter().enumerate() {
if let Ok(element) = T::read(item, &path.index(index), problems) {
value.push(element);
}
}
value
}
fn overlay_items<T: Node>(
value: &mut Vec<T>,
raw: &Raw,
path: &Path,
problems: &mut Problems,
) -> Result<(), Unbuilt> {
let entries = raw.entries().unwrap_or_default();
let mut patches: Vec<(usize, &Raw)> = Vec::with_capacity(entries.len());
for (key, item) in entries {
match key.text().parse::<usize>() {
Ok(index) => patches.push((index, item)),
Err(_) => {
let message = format!("expected an index of an element, got {:?}", key.text());
problems.error(Kind::InvalidValue, key.mark(), path.clone(), message);
return Err(Unbuilt);
}
}
}
patches.sort_by_key(|(index, _)| *index);
for (index, item) in patches {
let item_path = path.index(index);
if let Some(existing) = value.get_mut(index) {
T::overlay(existing, item, &item_path, problems).ok();
} else if value.len() == index {
if let Ok(element) = T::read(item, &item_path, problems) {
value.push(element);
}
} else {
let message =
"the element is out of turn: elements are numbered from 0 without gaps".to_owned();
problems.error(Kind::InvalidValue, item.mark(), item_path, message);
return Err(Unbuilt);
}
}
Ok(())
}
impl<T: Node> Node for BTreeMap<String, T> {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
let mut value = BTreeMap::new();
Self::overlay(&mut value, raw, path, problems)?;
Ok(value)
}
fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
if raw.is_empty() {
self.clear();
return Ok(());
}
let Some(entries) = raw.entries() else {
return Err(wrong_shape(raw, path, problems, "a mapping"));
};
if !raw.is_from_environment() {
self.clear();
}
for (key, item) in entries {
let item_path = path.field(key.text());
if key.text().is_empty() {
let message = "a dictionary key must not be empty".to_owned();
problems.error(Kind::InvalidValue, key.mark(), item_path, message);
continue;
}
if let Some(existing) = self.get_mut(key.text()) {
T::overlay(existing, item, &item_path, problems).ok();
} else if let Ok(element) = T::read(item, &item_path, problems) {
self.insert(key.text().to_owned(), element);
}
}
Ok(())
}
fn shape(&self) -> Shape<'_> {
Shape::Dictionary(
self.iter()
.map(|(key, value)| (key.as_str(), value as &dyn Node))
.collect(),
)
}
fn empty() -> Option<Self> {
Some(BTreeMap::new())
}
fn fill(&mut self) {
if self.is_empty() {
for key in ["key1", "key2"] {
if let Some(sample) = T::sample() {
self.insert(key.to_owned(), sample);
}
}
}
for value in self.values_mut() {
value.fill();
}
}
}