1use serde_json::Value;
21
22#[derive(Debug, Clone)]
24pub struct Assertion {
25 source: String,
26 path: Vec<Step>,
27 length: bool,
28 op: Op,
29 literal: Value,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33enum Step {
34 Key(String),
35 Elements,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq)]
39enum Op {
40 Eq,
41 Ne,
42 Gt,
43 Ge,
44 Lt,
45 Le,
46 Exists,
47}
48
49impl Assertion {
50 pub fn parse(line: &str) -> Result<Assertion, String> {
52 let mut parts = line.split_whitespace();
53 let path_text = parts.next().ok_or("empty assertion")?;
54 let op_text = parts
55 .next()
56 .ok_or_else(|| format!("`{line}`: missing operator"))?;
57 let op = match op_text {
58 "==" => Op::Eq,
59 "!=" => Op::Ne,
60 ">" => Op::Gt,
61 ">=" => Op::Ge,
62 "<" => Op::Lt,
63 "<=" => Op::Le,
64 "exists" => Op::Exists,
65 other => return Err(format!("`{line}`: unknown operator `{other}`")),
66 };
67 let literal = if op == Op::Exists {
68 if parts.next().is_some() {
69 return Err(format!("`{line}`: `exists` takes no operand"));
70 }
71 Value::Null
72 } else {
73 let rest = parts.collect::<Vec<_>>().join(" ");
74 serde_json::from_str(&rest)
75 .map_err(|_| format!("`{line}`: operand `{rest}` is not a JSON literal"))?
76 };
77 let (path_text, length) = match path_text.strip_suffix("#len") {
78 Some(stripped) => (stripped, true),
79 None => (path_text, false),
80 };
81 let mut path = Vec::new();
82 for segment in path_text.split('.').filter(|s| !s.is_empty()) {
83 match segment.strip_suffix("[]") {
84 Some("") => path.push(Step::Elements),
85 Some(key) => {
86 path.push(Step::Key(key.to_string()));
87 path.push(Step::Elements);
88 }
89 None => path.push(Step::Key(segment.to_string())),
90 }
91 }
92 Ok(Assertion {
93 source: line.to_string(),
94 path,
95 length,
96 op,
97 literal,
98 })
99 }
100
101 pub fn source(&self) -> &str {
103 &self.source
104 }
105
106 pub fn check(&self, value: &Value) -> Result<(), String> {
108 let mut targets = vec![value];
109 for step in &self.path {
110 let mut next = Vec::new();
111 for target in targets {
112 match step {
113 Step::Key(key) => next.push(target.get(key).unwrap_or(&Value::Null)),
114 Step::Elements => match target.as_array() {
115 Some(items) => next.extend(items.iter()),
116 None => next.push(&Value::Null),
117 },
118 }
119 }
120 targets = next;
121 }
122 if targets.is_empty() {
123 return Ok(());
125 }
126 for target in targets {
127 self.check_one(target)?;
128 }
129 Ok(())
130 }
131
132 fn check_one(&self, target: &Value) -> Result<(), String> {
133 let length_value;
134 let target = if self.length {
135 let len = match target {
136 Value::Array(items) => items.len(),
137 Value::String(s) => s.len(),
138 other => return Err(format!("{}: {} has no length", self.source, kind(other))),
139 };
140 length_value = Value::from(len);
141 &length_value
142 } else {
143 target
144 };
145 let holds = match self.op {
146 Op::Exists => !target.is_null(),
147 Op::Eq => target == &self.literal,
148 Op::Ne => target != &self.literal,
149 Op::Gt | Op::Ge | Op::Lt | Op::Le => {
150 let (Some(actual), Some(expected)) = (target.as_f64(), self.literal.as_f64())
151 else {
152 return Err(format!("{}: got {}", self.source, short(target)));
153 };
154 match self.op {
155 Op::Gt => actual > expected,
156 Op::Ge => actual >= expected,
157 Op::Lt => actual < expected,
158 _ => actual <= expected,
159 }
160 }
161 };
162 if holds {
163 Ok(())
164 } else {
165 Err(format!("{}: got {}", self.source, short(target)))
166 }
167 }
168}
169
170fn kind(value: &Value) -> &'static str {
171 match value {
172 Value::Null => "null",
173 Value::Bool(_) => "boolean",
174 Value::Number(_) => "number",
175 Value::String(_) => "string",
176 Value::Array(_) => "array",
177 Value::Object(_) => "object",
178 }
179}
180
181fn short(value: &Value) -> String {
182 let text = value.to_string();
183 if text.len() > 60 {
184 format!("{}…", &text[..60])
185 } else {
186 text
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use serde_json::json;
194
195 fn assert_holds(line: &str, value: &Value) {
196 Assertion::parse(line).unwrap().check(value).unwrap();
197 }
198
199 fn assert_fails(line: &str, value: &Value) {
200 assert!(Assertion::parse(line).unwrap().check(value).is_err());
201 }
202
203 #[test]
204 fn scalar_comparisons() {
205 let value = json!({"meta": {"price": 12.5, "currency": "USD"}});
206 assert_holds("meta.price > 0", &value);
207 assert_holds("meta.currency == \"USD\"", &value);
208 assert_fails("meta.price < 1", &value);
209 assert_fails("meta.currency == \"EUR\"", &value);
210 }
211
212 #[test]
213 fn missing_and_null_fail_comparisons_but_exist_checks_say_why() {
214 let value = json!({"meta": {"price": null}});
215 assert_fails("meta.price > 0", &value);
216 assert_fails("meta.gone > 0", &value);
217 assert_fails("meta.price exists", &value);
218 assert_holds("meta.price != 3", &value);
219 }
220
221 #[test]
222 fn length_of_arrays_and_strings() {
223 let value = json!({"candles": [1, 2, 3], "symbol": "AAPL"});
224 assert_holds("candles#len >= 1", &value);
225 assert_holds("symbol#len == 4", &value);
226 assert_fails("candles#len > 3", &value);
227 assert_fails("candles.0#len > 0", &value);
228 }
229
230 #[test]
231 fn element_descent_must_hold_for_every_element() {
232 let value = json!({"candles": [{"close": 1.0}, {"close": 0.0}]});
233 assert_fails("candles[].close > 0", &value);
234 assert_holds("candles[].close >= 0", &value);
235 assert_holds("empty[].close > 0", &json!({"empty": []}));
236 }
237
238 #[test]
239 fn parse_rejects_malformed_lines() {
240 assert!(Assertion::parse("price >").is_err());
241 assert!(Assertion::parse("price ~ 3").is_err());
242 assert!(Assertion::parse("price exists 3").is_err());
243 assert!(Assertion::parse("price == not-json").is_err());
244 }
245}