use std::collections::BTreeMap;
use serde_json::{json, Map, Value};
use toml_edit::{Item, TableLike};
use crate::Result;
use super::codec::Codec;
pub(crate) struct Schema {
definitions: BTreeMap<String, Value>,
names: BTreeMap<String, String>,
}
impl Schema {
pub(crate) fn new() -> Self {
Self {
definitions: BTreeMap::new(),
names: BTreeMap::new(),
}
}
pub(crate) fn reference<T: Codec>(&mut self) -> Value {
self.named(std::any::type_name::<T>(), T::schema)
}
pub(crate) fn named(&mut self, name: &str, make: impl FnOnce(&mut Self) -> Value) -> Value {
if let Some(key) = self.names.get(name) {
return json!({"$ref":format!("#/$defs/{key}")});
}
let base = short_name(name);
let mut key = base.clone();
let mut suffix = 2;
while self.definitions.contains_key(&key) {
key = format!("{base}_{suffix}");
suffix += 1;
}
self.names.insert(name.to_owned(), key.clone());
self.definitions.insert(key.clone(), Value::Bool(true));
let schema = make(self);
self.definitions.insert(key.clone(), schema);
json!({"$ref":format!("#/$defs/{key}")})
}
pub(crate) fn document(self, root: Value) -> Value {
let mut document = json!({
"$schema":"https://json-schema.org/draft/2020-12/schema",
"$id":format!("urn:lichtung-plot:recipe:{}",super::RECIPE_VERSION),
"title":format!("lichtung-plot Recipe {}",super::RECIPE_VERSION),
});
document["$defs"] = Value::Object(self.definitions.into_iter().collect());
document["allOf"] = Value::Array(vec![root]);
document
}
}
fn short_name(name: &str) -> String {
let (base, parameter) = name.split_once('<').unwrap_or((name, ""));
let mut name = base.rsplit("::").next().expect("type name").to_owned();
if let Some(parameter) = parameter.strip_suffix('>') {
name.push('_');
name.push_str(&short_name(parameter));
}
name.replace(
|character: char| !character.is_ascii_alphanumeric() && character != '_',
"_",
)
}
pub(crate) fn primitive(name: &str) -> Value {
json!({"type":name})
}
pub(crate) fn choices(values: &[&str]) -> Value {
json!({"enum":values})
}
pub(crate) fn literal(value: impl Into<Value>) -> Value {
json!({"const":value.into()})
}
pub(crate) fn any_of(values: impl IntoIterator<Item = Value>) -> Value {
json!({"anyOf":values.into_iter().collect::<Vec<_>>()})
}
pub(crate) fn one_of(values: impl IntoIterator<Item = Value>) -> Value {
json!({"oneOf":values.into_iter().collect::<Vec<_>>()})
}
pub(crate) fn array(items: Value) -> Value {
let mut schema = primitive("array");
schema["items"] = items;
schema
}
pub(crate) fn pair(items: Value) -> Value {
let mut schema = array(items);
schema["minItems"] = 2.into();
schema["maxItems"] = 2.into();
schema
}
pub(crate) fn dictionary(items: Value) -> Value {
let mut schema = primitive("object");
schema["additionalProperties"] = items;
schema
}
pub(crate) fn object(
fields: impl IntoIterator<Item = (&'static str, Value)>,
required: &[&str],
) -> Value {
json!({
"type":"object",
"properties":fields.into_iter().map(|(name,value)|(name.to_owned(),value)).collect::<Map<_,_>>(),
"required":required,
"additionalProperties":false,
})
}
pub(crate) fn required(names: &[&str]) -> Value {
json!({"required":names})
}
pub(crate) fn with(mut shape: Value, constraint: Value) -> Value {
let fields = shape.as_object_mut().expect("schema object");
fields
.entry("allOf")
.or_insert_with(|| json!([]))
.as_array_mut()
.expect("schema conditions")
.push(constraint);
shape
}
pub(crate) fn exclusive(names: &[&str]) -> Value {
one_of(names.iter().map(|name| required(&[name])))
}
pub(crate) fn forbidden(names: &[&str]) -> Value {
if names.is_empty() {
return json!({});
}
json!({"propertyNames":{"not":{"enum":names}}})
}
pub(crate) fn at_most_one(names: &[&str]) -> Value {
any_of([
exclusive(names),
json!({"not":{"anyOf":names.iter().map(|name|required(&[name])).collect::<Vec<_>>()}}),
])
}
pub(crate) fn exact_values(names: &[&str], selected: &[&str]) -> Value {
let requirements = names
.iter()
.map(|name| {
let active = json!({"required":[name],"properties":{(*name):{"not":{"const":false}}}});
if selected.contains(name) {
active
} else {
json!({"not":active})
}
})
.collect::<Vec<_>>();
json!({"allOf":requirements})
}
#[derive(Clone, Copy)]
pub(crate) struct Field {
pub(crate) name: &'static str,
pub(crate) needed: bool,
shape: fn(&mut Schema) -> Value,
pub(crate) example: Option<Example>,
}
#[derive(Clone, Copy)]
pub(crate) enum Example {
Column(&'static str),
Variables,
Grid,
Literal(&'static str),
Group(&'static [Field]),
}
impl Field {
pub(crate) const fn example(mut self, example: Example) -> Self {
self.example = Some(example);
self
}
}
pub(crate) const fn optional<T: Codec>(name: &'static str) -> Field {
custom(name, false, Schema::reference::<T>)
}
pub(crate) const fn mandatory<T: Codec>(name: &'static str) -> Field {
custom(name, true, Schema::reference::<T>)
}
pub(crate) const fn custom(
name: &'static str,
needed: bool,
shape: fn(&mut Schema) -> Value,
) -> Field {
Field {
name,
needed,
shape,
example: None,
}
}
pub(crate) fn record(ctx: &mut Schema, fields: &[Field]) -> Value {
let required = fields
.iter()
.filter(|field| field.needed)
.map(|field| field.name)
.collect::<Vec<_>>();
object(
fields.iter().map(|field| (field.name, (field.shape)(ctx))),
&required,
)
}
pub(crate) fn record_fields<'a>(item: &'a Item, spec: &[Field]) -> Result<&'a dyn TableLike> {
super::codec::table_checked(item, |name| spec.iter().any(|field| field.name == name))
}
pub(crate) fn getter<T, U: Codec>(ctx: &mut Schema, _: impl FnOnce(&T) -> U) -> Value {
ctx.reference::<U>()
}
pub(crate) fn borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> &U) -> Value {
ctx.reference::<U>()
}
pub(crate) fn optional_borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> Option<&U>) -> Value {
ctx.reference::<Option<U>>()
}
pub(crate) fn inherited_getter<T, U: Codec>(ctx: &mut Schema, _: impl FnOnce(&T) -> U) -> Value {
U::schema_with_default(ctx)
}
pub(crate) fn inherited_borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> &U) -> Value {
U::schema_with_default(ctx)
}
pub(crate) fn inherited_optional<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> Option<&U>) -> Value {
Option::<U>::schema_with_default(ctx)
}
pub(crate) fn declare_property(shape: &mut Value, name: &str, value: Value) {
let Some(properties) = shape.get_mut("properties").and_then(Value::as_object_mut) else {
unreachable!("record schema");
};
assert!(properties.contains_key(name), "unknown schema field {name}");
properties.insert(name.to_owned(), value);
}
pub(crate) const fn role(name: &'static str, needed: bool) -> Field {
custom(name, needed, super::resolve::DataReference::schema)
}
pub(crate) fn names(fields: &[Field]) -> Vec<&'static str> {
fields.iter().map(|field| field.name).collect()
}
pub(crate) fn group(ctx: &mut Schema, fields: &[Field]) -> Value {
let mut fields = fields.to_vec();
fields.push(optional::<String>("binding"));
record(ctx, &fields)
}
pub(crate) fn dependent_pair(shape: Value, first: &str, second: &str) -> Value {
with(
shape,
json!({"dependentRequired":{(first):[second],(second):[first]}}),
)
}
impl super::Recipe {
pub fn schema() -> String {
let mut schema = Schema::new();
let root = super::document::schema(&mut schema);
serde_json::to_string_pretty(&schema.document(root)).expect("static recipe schema")
}
}