Skip to main content

lichtung_plot/recipe/
schema.rs

1//! JSON Schema is projected from the native declaration field and mode tables.
2
3use std::collections::BTreeMap;
4
5use serde_json::{json, Map, Value};
6use toml_edit::{Item, TableLike};
7
8use crate::Result;
9
10use super::codec::Codec;
11
12pub(crate) struct Schema {
13    definitions: BTreeMap<String, Value>,
14    names: BTreeMap<String, String>,
15}
16
17impl Schema {
18    pub(crate) fn new() -> Self {
19        Self {
20            definitions: BTreeMap::new(),
21            names: BTreeMap::new(),
22        }
23    }
24
25    pub(crate) fn reference<T: Codec>(&mut self) -> Value {
26        self.named(std::any::type_name::<T>(), T::schema)
27    }
28
29    pub(crate) fn named(&mut self, name: &str, make: impl FnOnce(&mut Self) -> Value) -> Value {
30        if let Some(key) = self.names.get(name) {
31            return json!({"$ref":format!("#/$defs/{key}")});
32        }
33        let base = short_name(name);
34        let mut key = base.clone();
35        let mut suffix = 2;
36        while self.definitions.contains_key(&key) {
37            key = format!("{base}_{suffix}");
38            suffix += 1;
39        }
40        // Reserve the name before descending into recursive types.
41        self.names.insert(name.to_owned(), key.clone());
42        self.definitions.insert(key.clone(), Value::Bool(true));
43        let schema = make(self);
44        self.definitions.insert(key.clone(), schema);
45        json!({"$ref":format!("#/$defs/{key}")})
46    }
47
48    pub(crate) fn document(self, root: Value) -> Value {
49        let mut document = json!({
50            "$schema":"https://json-schema.org/draft/2020-12/schema",
51            "$id":format!("urn:lichtung-plot:recipe:{}",super::RECIPE_VERSION),
52            "title":format!("lichtung-plot Recipe {}",super::RECIPE_VERSION),
53        });
54        document["$defs"] = Value::Object(self.definitions.into_iter().collect());
55        document["allOf"] = Value::Array(vec![root]);
56        document
57    }
58}
59
60fn short_name(name: &str) -> String {
61    // The full Rust type name still identifies each definition. Short schema
62    // names make references readable, including ordinary containers.
63    let (base, parameter) = name.split_once('<').unwrap_or((name, ""));
64    let mut name = base.rsplit("::").next().expect("type name").to_owned();
65    if let Some(parameter) = parameter.strip_suffix('>') {
66        name.push('_');
67        name.push_str(&short_name(parameter));
68    }
69    name.replace(
70        |character: char| !character.is_ascii_alphanumeric() && character != '_',
71        "_",
72    )
73}
74
75pub(crate) fn primitive(name: &str) -> Value {
76    json!({"type":name})
77}
78
79pub(crate) fn choices(values: &[&str]) -> Value {
80    json!({"enum":values})
81}
82
83pub(crate) fn literal(value: impl Into<Value>) -> Value {
84    json!({"const":value.into()})
85}
86
87pub(crate) fn any_of(values: impl IntoIterator<Item = Value>) -> Value {
88    json!({"anyOf":values.into_iter().collect::<Vec<_>>()})
89}
90
91pub(crate) fn one_of(values: impl IntoIterator<Item = Value>) -> Value {
92    json!({"oneOf":values.into_iter().collect::<Vec<_>>()})
93}
94
95pub(crate) fn array(items: Value) -> Value {
96    let mut schema = primitive("array");
97    schema["items"] = items;
98    schema
99}
100
101pub(crate) fn pair(items: Value) -> Value {
102    let mut schema = array(items);
103    schema["minItems"] = 2.into();
104    schema["maxItems"] = 2.into();
105    schema
106}
107
108pub(crate) fn dictionary(items: Value) -> Value {
109    let mut schema = primitive("object");
110    schema["additionalProperties"] = items;
111    schema
112}
113
114pub(crate) fn object(
115    fields: impl IntoIterator<Item = (&'static str, Value)>,
116    required: &[&str],
117) -> Value {
118    json!({
119        "type":"object",
120        "properties":fields.into_iter().map(|(name,value)|(name.to_owned(),value)).collect::<Map<_,_>>(),
121        "required":required,
122        "additionalProperties":false,
123    })
124}
125
126pub(crate) fn required(names: &[&str]) -> Value {
127    json!({"required":names})
128}
129
130pub(crate) fn with(mut shape: Value, constraint: Value) -> Value {
131    let fields = shape.as_object_mut().expect("schema object");
132    fields
133        .entry("allOf")
134        .or_insert_with(|| json!([]))
135        .as_array_mut()
136        .expect("schema conditions")
137        .push(constraint);
138    shape
139}
140
141pub(crate) fn exclusive(names: &[&str]) -> Value {
142    one_of(names.iter().map(|name| required(&[name])))
143}
144
145pub(crate) fn forbidden(names: &[&str]) -> Value {
146    if names.is_empty() {
147        return json!({});
148    }
149    json!({"propertyNames":{"not":{"enum":names}}})
150}
151
152pub(crate) fn at_most_one(names: &[&str]) -> Value {
153    any_of([
154        exclusive(names),
155        json!({"not":{"anyOf":names.iter().map(|name|required(&[name])).collect::<Vec<_>>()}}),
156    ])
157}
158
159pub(crate) fn exact_values(names: &[&str], selected: &[&str]) -> Value {
160    let requirements = names
161        .iter()
162        .map(|name| {
163            let active = json!({"required":[name],"properties":{(*name):{"not":{"const":false}}}});
164            if selected.contains(name) {
165                active
166            } else {
167                json!({"not":active})
168            }
169        })
170        .collect::<Vec<_>>();
171    json!({"allOf":requirements})
172}
173
174/// One field in the actual declaration admission table. The schema factory
175/// is never evaluated during ordinary parsing or scientific preparation.
176#[derive(Clone, Copy)]
177pub(crate) struct Field {
178    pub(crate) name: &'static str,
179    pub(crate) needed: bool,
180    shape: fn(&mut Schema) -> Value,
181    pub(crate) example: Option<Example>,
182}
183
184/// Examples attached to the actual input fields, for commented templates.
185#[derive(Clone, Copy)]
186pub(crate) enum Example {
187    Column(&'static str),
188    Variables,
189    Grid,
190    Literal(&'static str),
191    Group(&'static [Field]),
192}
193
194impl Field {
195    pub(crate) const fn example(mut self, example: Example) -> Self {
196        self.example = Some(example);
197        self
198    }
199}
200
201pub(crate) const fn optional<T: Codec>(name: &'static str) -> Field {
202    custom(name, false, Schema::reference::<T>)
203}
204
205pub(crate) const fn mandatory<T: Codec>(name: &'static str) -> Field {
206    custom(name, true, Schema::reference::<T>)
207}
208
209pub(crate) const fn custom(
210    name: &'static str,
211    needed: bool,
212    shape: fn(&mut Schema) -> Value,
213) -> Field {
214    Field {
215        name,
216        needed,
217        shape,
218        example: None,
219    }
220}
221
222pub(crate) fn record(ctx: &mut Schema, fields: &[Field]) -> Value {
223    let required = fields
224        .iter()
225        .filter(|field| field.needed)
226        .map(|field| field.name)
227        .collect::<Vec<_>>();
228    object(
229        fields.iter().map(|field| (field.name, (field.shape)(ctx))),
230        &required,
231    )
232}
233
234pub(crate) fn record_fields<'a>(item: &'a Item, spec: &[Field]) -> Result<&'a dyn TableLike> {
235    super::codec::table_checked(item, |name| spec.iter().any(|field| field.name == name))
236}
237
238pub(crate) fn getter<T, U: Codec>(ctx: &mut Schema, _: impl FnOnce(&T) -> U) -> Value {
239    ctx.reference::<U>()
240}
241
242pub(crate) fn borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> &U) -> Value {
243    ctx.reference::<U>()
244}
245
246pub(crate) fn optional_borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> Option<&U>) -> Value {
247    ctx.reference::<Option<U>>()
248}
249
250pub(crate) fn inherited_getter<T, U: Codec>(ctx: &mut Schema, _: impl FnOnce(&T) -> U) -> Value {
251    U::schema_with_default(ctx)
252}
253
254pub(crate) fn inherited_borrowed<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> &U) -> Value {
255    U::schema_with_default(ctx)
256}
257
258pub(crate) fn inherited_optional<T, U: Codec>(ctx: &mut Schema, _: fn(&T) -> Option<&U>) -> Value {
259    Option::<U>::schema_with_default(ctx)
260}
261
262pub(crate) fn declare_property(shape: &mut Value, name: &str, value: Value) {
263    let Some(properties) = shape.get_mut("properties").and_then(Value::as_object_mut) else {
264        unreachable!("record schema");
265    };
266    assert!(properties.contains_key(name), "unknown schema field {name}");
267    properties.insert(name.to_owned(), value);
268}
269
270pub(crate) const fn role(name: &'static str, needed: bool) -> Field {
271    custom(name, needed, super::resolve::DataReference::schema)
272}
273
274pub(crate) fn names(fields: &[Field]) -> Vec<&'static str> {
275    fields.iter().map(|field| field.name).collect()
276}
277
278pub(crate) fn group(ctx: &mut Schema, fields: &[Field]) -> Value {
279    let mut fields = fields.to_vec();
280    fields.push(optional::<String>("binding"));
281    record(ctx, &fields)
282}
283
284pub(crate) fn dependent_pair(shape: Value, first: &str, second: &str) -> Value {
285    with(
286        shape,
287        json!({"dependentRequired":{(first):[second],(second):[first]}}),
288    )
289}
290
291impl super::Recipe {
292    /// Generate the machine-readable schema for the current native Recipe
293    /// grammar. Additional source, reference and scientific constraints are
294    /// enforced by the ordinary declaration reader and check operation.
295    pub fn schema() -> String {
296        let mut schema = Schema::new();
297        let root = super::document::schema(&mut schema);
298        serde_json::to_string_pretty(&schema.document(root)).expect("static recipe schema")
299    }
300}