Skip to main content

shape/
discriminated.rs

1//! A discriminated union: the branch is chosen by the value of a tag
2//! property and the value validated against that branch alone, so the
3//! errors are its own rather than a list of every alternative.
4
5use crate::builders::{buildize, fault_node};
6use crate::context::{State, Update, UpdateErr};
7use crate::error::ValidationError;
8use crate::node::{Kind, Node, Validator};
9use crate::normalize::literal_node;
10use crate::spec::Spec;
11use crate::validate::{validate_node, Cur, Walk};
12use crate::value::{json_render, Value};
13use std::sync::Arc;
14
15/// The tag of a discriminated union and its branch names, sorted. The
16/// branches themselves are the node's list, in that order.
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct Disc {
19    pub tag: String,
20    pub tags: Vec<String>,
21}
22
23/// A union choosing its branch by the value of the tag property. An
24/// object-shaped branch without the tag property has it added, as the
25/// literal it is keyed by.
26pub fn discriminated<I, K, S>(tag: impl Into<String>, branches: I) -> Node
27where
28    I: IntoIterator<Item = (K, S)>,
29    K: Into<String>,
30    S: Into<Spec>,
31{
32    let tag = tag.into();
33    let mut pairs: Vec<(String, Spec)> = branches
34        .into_iter()
35        .map(|(k, s)| (k.into(), s.into()))
36        .collect();
37    if tag.is_empty() || pairs.is_empty() {
38        return fault_node("Discriminated needs a tag property name and at least one branch");
39    }
40    pairs.sort_by(|a, b| a.0.cmp(&b.0));
41
42    let mut n = Node::of(Kind::List);
43    n.required = true;
44    n.required_set = true;
45    let mut tags = Vec::with_capacity(pairs.len());
46    for (name, spec) in pairs {
47        let mut bn = buildize(spec);
48        if bn.kind == Kind::Object && !bn.obj_children.contains_key(&tag) {
49            bn.obj_children
50                .insert(tag.clone(), literal_node(Value::Str(name.clone())));
51        }
52        tags.push(name);
53        n.list.push(bn);
54    }
55    n.disc = Some(Disc {
56        tag: tag.clone(),
57        tags,
58    });
59    let chosen = tag.clone();
60    n.befores.push(Validator {
61        name: "Discriminated".to_string(),
62        func: Arc::new(move |state: &mut State<'_>, update: &mut Update| {
63            choose(&chosen, state, update)
64        }),
65        args: vec![Value::Str(tag)],
66        suffix: None,
67        inner: None,
68    });
69    n
70}
71
72fn choose(tag: &str, state: &mut State<'_>, update: &mut Update) -> bool {
73    // Required or optional is for the structural check to say.
74    if state.absent {
75        return true;
76    }
77    let Some(tv) = state.value.as_obj().and_then(|m| m.get(tag)) else {
78        update.err = Some(UpdateErr::Text(format!(
79            "Value \"$VALUE\" for property \"$PATH\" is not an object with a \"{}\" property.",
80            tag
81        )));
82        update.why = Some("Discriminated".to_string());
83        return false;
84    };
85    let disc = state.node.disc.as_ref();
86    let found = match (tv, disc) {
87        (Value::Str(name), Some(d)) => d.tags.iter().position(|t| t == name),
88        _ => None,
89    };
90    let Some(i) = found else {
91        let names = disc.map(|d| d.tags.join(", ")).unwrap_or_default();
92        update.err = Some(UpdateErr::Text(format!(
93            "Value \"$VALUE\" for property \"$PATH\" has unknown \"{}\" {}, expected one of: {}.",
94            tag,
95            json_render(tv),
96            names
97        )));
98        update.why = Some("Discriminated".to_string());
99        return false;
100    };
101    let bn = &state.node.list[i];
102    let mut val = state.value.clone();
103    let mut sub = ValidationError::default();
104    let mut w = Walk {
105        ctx: state.ctx,
106        is_match: state.is_match,
107        path: state.path_arr.to_vec(),
108        paths: true,
109    };
110    validate_node(
111        bn,
112        Cur::Mut(&mut val),
113        state.key,
114        state.parent_is_array,
115        &mut w,
116        &mut sub,
117    );
118    if sub.has_any() {
119        update.err = Some(UpdateErr::Fields(sub.issues));
120        return false;
121    }
122    update.val = Some(val);
123    true
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::builders::optional;
130    use crate::node::Token;
131    use crate::spec::obj;
132    use crate::stringify::stringify_node;
133    use crate::Schema;
134
135    fn j(s: &str) -> Value {
136        Value::from(serde_json::from_str::<serde_json::Value>(s).unwrap())
137    }
138
139    fn run(s: &Schema, input: &str) -> String {
140        match s.validate(j(input)) {
141            Ok(v) => serde_json::Value::from(v).to_string(),
142            Err(e) => format!("ERR {}", e),
143        }
144    }
145
146    fn pet() -> Node {
147        discriminated(
148            "kind",
149            [
150                ("fish", obj([("fins", Spec::from(Token::Number))])),
151                ("dog", obj([("bark", Spec::from(Token::Boolean))])),
152            ],
153        )
154    }
155
156    #[test]
157    fn chooses_the_branch_by_tag() {
158        let s = Schema::new(obj([("p", Spec::from(pet()))]));
159        assert_eq!(
160            run(&s, r#"{"p":{"bark":true,"kind":"dog"}}"#),
161            r#"{"p":{"bark":true,"kind":"dog"}}"#
162        );
163        assert_eq!(
164            run(&s, r#"{"p":{"fins":"x","kind":"fish"}}"#),
165            "ERR Validation failed for property \"p.fins\" with string \"x\" because the string is not of type number."
166        );
167        assert_eq!(
168            run(&s, r#"{"p":{"kind":"dog"}}"#),
169            "ERR Validation failed for property \"p.bark\" because the property is missing."
170        );
171        assert_eq!(
172            run(&s, r#"{"p":{"bark":true}}"#),
173            "ERR Value \"{bark:true}\" for property \"p\" is not an object with a \"kind\" property."
174        );
175        assert_eq!(
176            run(&s, r#"{"p":{"kind":"cat"}}"#),
177            "ERR Value \"{kind:cat}\" for property \"p\" has unknown \"kind\" \"cat\", expected one of: dog, fish."
178        );
179        assert_eq!(
180            run(&s, r#"{"p":{"kind":1}}"#),
181            "ERR Value \"{kind:1}\" for property \"p\" has unknown \"kind\" 1, expected one of: dog, fish."
182        );
183        assert_eq!(
184            run(&s, r#"{"p":1}"#),
185            "ERR Value \"1\" for property \"p\" is not an object with a \"kind\" property."
186        );
187        assert_eq!(
188            run(&s, "{}"),
189            "ERR Validation failed for property \"p\" because the property is missing."
190        );
191        assert_eq!(
192            run(
193                &Schema::new(obj([("p", Spec::from(optional(pet())))])),
194                "{}"
195            ),
196            "{}"
197        );
198        assert!(s.valid(&j(r#"{"p":{"bark":true,"kind":"dog"}}"#)));
199        assert!(!s.valid(&j(r#"{"p":{"kind":"cat"}}"#)));
200        assert_eq!(
201            s.error(&j(r#"{"p":{"kind":"cat"}}"#))[0].why,
202            "Discriminated"
203        );
204        assert_eq!(
205            stringify_node(&pet(), false),
206            "Discriminated(kind,dog,fish)"
207        );
208        // A branch that is not an object carries no tag of its own.
209        let s = Schema::new(discriminated("k", [("n", Spec::from(Token::Number))]));
210        assert_eq!(
211            run(&s, r#"{"k":"n"}"#),
212            "ERR Validation failed for object \"{k:n}\" because the object is not of type number."
213        );
214        assert_eq!(
215            run(&Schema::new(discriminated("", [("a", Spec::from(1))])), "1"),
216            "ERR Discriminated needs a tag property name and at least one branch"
217        );
218        assert_eq!(
219            run(
220                &Schema::new(discriminated::<[(&str, Spec); 0], &str, Spec>("k", [])),
221                "1"
222            ),
223            "ERR Discriminated needs a tag property name and at least one branch"
224        );
225        // A branch that declares the tag keeps its own declaration.
226        let s = Schema::new(discriminated(
227            "k",
228            [("a", obj([("k", Spec::from(Token::String))]))],
229        ));
230        assert_eq!(run(&s, r#"{"k":"a"}"#), r#"{"k":"a"}"#);
231    }
232}