Skip to main content

predicator_rs/
tagged.rs

1//! The conformance corpus's tagged-value encoding, as text.
2//!
3//! JSON carries most predicator values as themselves: null, booleans,
4//! integers, floats, strings, lists and maps (objects). Four do not fit, and
5//! the encoding carries each as an object with a `$type` key:
6//!
7//! ```text
8//! {"$type":"undefined"}
9//! {"$type":"date","value":"2026-08-06"}
10//! {"$type":"datetime","value":"2026-08-06T12:00:00Z"}
11//! {"$type":"duration","value":{"days":3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0,"years":0}}
12//! ```
13//!
14//! The encoding is the corpus's apparatus, specified by the reference's
15//! `conformance/README.md` at the tag this crate's vendored corpus names. It
16//! is offered for a host that keeps values or instruction lists as JSON.
17//!
18//! [`encode`] writes the text the reference writes: no whitespace, the keys
19//! of every object in codepoint order, floats in the reference's spelling, a
20//! datetime's fraction left out when it is zero and six digits when it is
21//! not, and a duration's `milliseconds` written only when it is not zero.
22//! [`decode`] reads any JSON text, which may also name an instant with an
23//! offset or a fraction of any length; an integer stays an integer and a
24//! float a float.
25//!
26//! ```
27//! use predicator_rs::{tagged, Value};
28//!
29//! let value = tagged::decode(r#"{"x":{"$type":"undefined"},"y":[1,1.0]}"#).unwrap();
30//! let Value::Map(map) = &value else { panic!() };
31//! assert_eq!(map.get(&"x".into()), Some(&Value::Undefined));
32//! assert_eq!(map.get(&"y".into()), Some(&Value::List(vec![1.into(), 1.0.into()])));
33//! assert_eq!(tagged::encode(&value).unwrap(), r#"{"x":{"$type":"undefined"},"y":[1,1.0]}"#);
34//! ```
35
36use crate::boundary;
37use crate::json::{self, Extension, Refusal};
38use crate::{
39    Date, DateTime, Duration, Error, EvaluationError, Key, Map, ParseError, Position, Value,
40};
41
42/// The units a duration's tag always carries; `milliseconds` is carried
43/// only when it is not zero.
44const REQUIRED_UNITS: [&str; 7] = [
45    "years", "months", "weeks", "days", "hours", "minutes", "seconds",
46];
47
48/// Reads a text in the tagged encoding into a value.
49///
50/// Every refusal is an [`Error::Parse`] at the position of the fault, with
51/// one of these reasons:
52///
53/// - `malformed_json`: the text is not JSON;
54/// - `depth_limit_exceeded`: lists and objects nest past 100 levels, a
55///   tag's own braces counted;
56/// - `integer_out_of_range`: an integer (a number with neither a fraction
57///   nor an exponent) outside the 64-bit signed range;
58/// - `non_finite_number`: a number too large for a finite float;
59/// - `invalid_tagged_value`: an object with a `$type` key that is not one of
60///   the four tags, or a tag whose value is not what the tag carries.
61///
62/// ```
63/// use predicator_rs::{tagged, Value};
64///
65/// assert_eq!(tagged::decode("[1,null]").unwrap(), Value::from(vec![1.into(), Value::Null]));
66/// let refused = tagged::decode("[1, 99999999999999999999]").unwrap_err();
67/// assert_eq!(refused.type_name(), "ParseError");
68/// assert_eq!(refused.reason(), "integer_out_of_range");
69/// assert_eq!(refused.position().map(|at| at.column), Some(5));
70/// ```
71pub fn decode(text: &str) -> Result<Value, Error> {
72    json::read(text, &untag).map_err(|fault| {
73        ParseError::new(fault.refusal.reason, fault.refusal.message)
74            .with_position(position_of(text, fault.offset))
75            .into()
76    })
77}
78
79/// Writes a value as text in the tagged encoding.
80///
81/// Every refusal is an [`Error::Evaluation`], with one of these reasons:
82///
83/// - `non_finite_number`: a float that is not finite;
84/// - `depth_limit_exceeded`: lists and maps nested past 100 levels, or a
85///   text that would, a tag's own braces counted;
86/// - `reserved_map_key`: a map with a `$type` key, which would read back as
87///   a tag;
88/// - `non_string_map_key`: a map key that is not a string (an integer, a
89///   boolean or undefined), for which a JSON object has no form;
90/// - `invalid_tagged_value`: a date or an instant outside the years 0 to
91///   9999 the encoding carries.
92///
93/// ```
94/// use predicator_rs::{tagged, Date, Map, Value};
95///
96/// let date = Date::new(2026, 8, 6).unwrap();
97/// let value = Value::from(vec![Value::from(1), Value::from(1.0), Value::from(date)]);
98/// assert_eq!(
99///     tagged::encode(&value).unwrap(),
100///     r#"[1,1.0,{"$type":"date","value":"2026-08-06"}]"#
101/// );
102/// let reserved: Map = [("$type", Value::from("x"))].into_iter().collect();
103/// assert_eq!(tagged::encode(&reserved.into()).unwrap_err().reason(), "reserved_map_key");
104/// ```
105pub fn encode(value: &Value) -> Result<String, Error> {
106    boundary::check(value)?;
107    json::write(value, &Tagged)
108        .map_err(|refusal| EvaluationError::new(refusal.reason, refusal.message).into())
109}
110
111/// The line and column of a byte offset into `text`, both from 1.
112fn position_of(text: &str, offset: usize) -> Position {
113    let before = text.get(..offset).unwrap_or(text);
114    let line_start = before.rfind('\n').map_or(0, |at| at + 1);
115    Position {
116        line: before.matches('\n').count() + 1,
117        column: before.get(line_start..).unwrap_or_default().chars().count() + 1,
118    }
119}
120
121fn invalid(message: String) -> Refusal {
122    Refusal::new("invalid_tagged_value", message)
123}
124
125/// The value an object stands for: the tag it carries, or the map itself
126/// when it has no `$type` key.
127pub(crate) fn untag(map: Map) -> Result<Value, Refusal> {
128    let Some(tag) = map.get_str("$type") else {
129        return Ok(Value::Map(map));
130    };
131    let Value::String(tag) = tag else {
132        return Err(invalid(
133            "a $type that is not a string is not a tag".to_owned(),
134        ));
135    };
136    let refused = || {
137        let keys: Vec<&Key> = map.keys().collect();
138        invalid(format!(
139            "a {tag:?} tag with the keys {keys:?} is not a tagged value"
140        ))
141    };
142    let value = map.get_str("value");
143    let tagged = match (tag.as_str(), map.len(), value) {
144        ("undefined", 1, _) => Some(Value::Undefined),
145        ("date", 2, Some(Value::String(text))) => Date::parse(text).map(Value::Date),
146        ("datetime", 2, Some(Value::String(text))) => DateTime::parse(text).map(Value::DateTime),
147        ("duration", 2, Some(Value::Map(units))) => duration(units).map(Value::Duration),
148        _ => None,
149    };
150    tagged.ok_or_else(refused)
151}
152
153/// The duration a tag's value map carries: the seven units always written,
154/// `milliseconds` when it is there, each an integer, and nothing else.
155pub(crate) fn duration(units: &Map) -> Option<Duration> {
156    let mut duration = Duration::default();
157    for (name, amount) in units.iter() {
158        let (Key::String(name), Value::Integer(amount)) = (name, amount) else {
159            return None;
160        };
161        *duration.unit_mut(name)? = *amount;
162    }
163    REQUIRED_UNITS
164        .iter()
165        .all(|unit| units.get_str(unit).is_some())
166        .then_some(duration)
167}
168
169/// The text a date or an instant's year allows the encoding to carry.
170pub(crate) fn carried(year: i32, text: String) -> Result<String, Refusal> {
171    if (0..=9999).contains(&year) {
172        Ok(text)
173    } else {
174        Err(invalid(format!(
175            "{text} is outside the years 0 to 9999 the encoding carries"
176        )))
177    }
178}
179
180/// The refusal of a map with a `$type` key.
181pub(crate) fn check_map(map: &Map) -> Result<(), Refusal> {
182    if map.get_str("$type").is_some() {
183        return Err(Refusal::new(
184            "reserved_map_key",
185            "a map with a \"$type\" key would read back as a tag",
186        ));
187    }
188    Ok(())
189}
190
191/// A duration's tag value, its units in key order, `milliseconds` only when
192/// it is not zero.
193fn duration_text(duration: &Duration, out: &mut String) {
194    let mut units: Vec<(&str, i64)> = duration
195        .units()
196        .into_iter()
197        .filter(|(name, _, amount)| *name != "milliseconds" || *amount != 0)
198        .map(|(name, _, amount)| (name, amount))
199        .collect();
200    units.sort_unstable_by_key(|(name, _)| *name);
201    out.push('{');
202    for (index, (name, amount)) in units.into_iter().enumerate() {
203        if index > 0 {
204            out.push(',');
205        }
206        out.push_str(&format!("\"{name}\":{amount}"));
207    }
208    out.push('}');
209}
210
211/// The tagged encoding's writing of the four values JSON has no form for.
212struct Tagged;
213
214impl Extension for Tagged {
215    fn write_other(&self, value: &Value, depth: usize, out: &mut String) -> Result<(), Refusal> {
216        json::depth_check(depth)?;
217        match value {
218            Value::Date(date) => {
219                let text = carried(date.year(), date.to_string())?;
220                out.push_str(&format!("{{\"$type\":\"date\",\"value\":\"{text}\"}}"));
221            }
222            Value::DateTime(instant) => {
223                let text = carried(instant.date().year(), instant.to_string())?;
224                out.push_str(&format!("{{\"$type\":\"datetime\",\"value\":\"{text}\"}}"));
225            }
226            Value::Duration(duration) => {
227                json::depth_check(depth + 1)?;
228                out.push_str("{\"$type\":\"duration\",\"value\":");
229                duration_text(duration, out);
230                out.push('}');
231            }
232            _ => out.push_str("{\"$type\":\"undefined\"}"),
233        }
234        Ok(())
235    }
236
237    fn check_map(&self, map: &Map) -> Result<(), Refusal> {
238        check_map(map)
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn reason(text: &str) -> String {
247        decode(text).unwrap_err().reason().to_owned()
248    }
249
250    fn date(year: i32, month: u32, day: u32) -> Date {
251        Date::new(year, month, day).unwrap()
252    }
253
254    // Sabotage: with untag answering Null for an undefined tag, this test
255    // fails.
256    #[test]
257    fn each_kind_round_trips_through_its_text() {
258        let instant = DateTime::new(date(2026, 8, 9), 10, 30, 0, 500_000).unwrap();
259        let pairs = [
260            (Value::Null, "null"),
261            (Value::Undefined, r#"{"$type":"undefined"}"#),
262            (Value::from(true), "true"),
263            (Value::from(-7), "-7"),
264            (Value::from(3.0), "3.0"),
265            (Value::from("x"), r#""x""#),
266            (Value::from(vec![1.into(), 1.0.into()]), "[1,1.0]"),
267            (
268                Value::from(
269                    [("b", Value::Null), ("a", Value::from(1))]
270                        .into_iter()
271                        .collect::<Map>(),
272                ),
273                r#"{"a":1,"b":null}"#,
274            ),
275            (
276                Value::from(date(2026, 8, 9)),
277                r#"{"$type":"date","value":"2026-08-09"}"#,
278            ),
279            (
280                Value::from(instant),
281                r#"{"$type":"datetime","value":"2026-08-09T10:30:00.500000Z"}"#,
282            ),
283            (
284                Value::from(DateTime::from_unix(0, 0).unwrap()),
285                r#"{"$type":"datetime","value":"1970-01-01T00:00:00Z"}"#,
286            ),
287            (
288                Value::from(Duration {
289                    weeks: 2,
290                    days: 3,
291                    ..Duration::default()
292                }),
293                r#"{"$type":"duration","value":{"days":3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":2,"years":0}}"#,
294            ),
295            (
296                Value::from(Duration {
297                    seconds: 1,
298                    milliseconds: 500,
299                    ..Duration::default()
300                }),
301                r#"{"$type":"duration","value":{"days":0,"hours":0,"milliseconds":500,"minutes":0,"months":0,"seconds":1,"weeks":0,"years":0}}"#,
302            ),
303            (
304                Value::from(Duration {
305                    days: -3,
306                    ..Duration::default()
307                }),
308                r#"{"$type":"duration","value":{"days":-3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0,"years":0}}"#,
309            ),
310        ];
311        for (value, text) in pairs {
312            assert_eq!(encode(&value).unwrap(), text);
313            assert_eq!(decode(text).unwrap(), value, "{text}");
314        }
315    }
316
317    // Sabotage: with duration accepting a value map that lacks a required
318    // unit, this test fails.
319    #[test]
320    fn a_tag_that_does_not_carry_its_value_is_refused() {
321        let units = r#""days":0,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0"#;
322        for text in [
323            r#"{"$type":"nope"}"#,
324            r#"{"$type":1}"#,
325            r#"{"$type":"undefined","value":1}"#,
326            r#"{"$type":"date","value":"2026-02-30"}"#,
327            r#"{"$type":"date","value":20260806}"#,
328            r#"{"$type":"date"}"#,
329            r#"{"$type":"datetime","value":"2026-08-06"}"#,
330            r#"{"$type":"datetime","value":"2026-08-06T12:00:00Z","x":1}"#,
331            &format!(r#"{{"$type":"duration","value":{{{units}}}}}"#),
332            &format!(r#"{{"$type":"duration","value":{{{units},"years":0.5}}}}"#),
333            &format!(r#"{{"$type":"duration","value":{{{units},"years":0,"decades":0}}}}"#),
334            r#"{"$type":"duration","value":[]}"#,
335        ] {
336            assert_eq!(reason(text), "invalid_tagged_value", "{text}");
337        }
338        let decoded = decode(&format!(
339            r#"{{"$type":"duration","value":{{{units},"years":0}}}}"#
340        ));
341        assert_eq!(decoded.unwrap(), Value::from(Duration::default()));
342        let offset = decode(r#"{"$type":"datetime","value":"2026-08-06T12:00:00+01:30"}"#);
343        assert_eq!(
344            encode(&offset.unwrap()).unwrap(),
345            r#"{"$type":"datetime","value":"2026-08-06T10:30:00Z"}"#
346        );
347    }
348
349    // Sabotage: with decode's error left at no position, this test fails.
350    #[test]
351    fn a_decode_refusal_is_a_parse_error_at_its_position() {
352        let refused = decode("[1,\n  {\"$type\":\"nope\"}]").unwrap_err();
353        assert_eq!(refused.type_name(), "ParseError");
354        assert_eq!(refused.position(), Some(Position { line: 2, column: 3 }));
355        assert_eq!(reason("[1e400]"), "non_finite_number");
356        assert_eq!(reason("[9223372036854775808]"), "integer_out_of_range");
357        assert_eq!(reason("{"), "malformed_json");
358        let refused = decode("\"é\" x").unwrap_err();
359        assert_eq!(refused.position(), Some(Position { line: 1, column: 5 }));
360    }
361
362    // Sabotage: with write_other's depth check removed, this test fails.
363    #[test]
364    fn a_tag_counts_toward_the_depth_limit() {
365        let wrap = |mut value: Value, levels: usize| {
366            for _ in 0..levels {
367                value = Value::from(vec![value]);
368            }
369            value
370        };
371        assert!(encode(&wrap(Value::Undefined, 99)).is_ok());
372        assert_eq!(
373            encode(&wrap(Value::Undefined, 100)).unwrap_err().reason(),
374            "depth_limit_exceeded"
375        );
376        let duration = Value::from(Duration::default());
377        assert!(encode(&wrap(duration.clone(), 98)).is_ok());
378        assert_eq!(
379            encode(&wrap(duration, 99)).unwrap_err().reason(),
380            "depth_limit_exceeded"
381        );
382        let text = encode(&wrap(Value::from(Duration::default()), 98)).unwrap();
383        assert!(decode(&text).is_ok());
384        assert_eq!(reason(&format!("[{text}]")), "depth_limit_exceeded");
385    }
386
387    // Sabotage: with the writer writing a non-string key as a string key,
388    // this test fails.
389    #[test]
390    fn a_map_key_that_is_not_a_string_has_no_tagged_form() {
391        for key in [Key::from(1), Key::from(true), Key::Undefined] {
392            let map: Map = [(key, Value::Null)].into_iter().collect();
393            let refused = encode(&Value::from(vec![map.into()]))
394                .map_err(|error| (error.type_name(), error.reason().to_owned()));
395            assert_eq!(
396                refused,
397                Err(("EvaluationError", "non_string_map_key".to_owned()))
398            );
399        }
400        let decoded = decode(r#"{"1":1,"true":2,"undefined":3}"#).unwrap();
401        let Value::Map(map) = &decoded else {
402            panic!("{decoded:?}")
403        };
404        assert_eq!(map.get(&"1".into()), Some(&Value::from(1)));
405        assert_eq!(map.get(&Key::from(1)), None);
406        assert_eq!(map.get(&Key::from(true)), None);
407        assert_eq!(map.get(&Key::Undefined), None);
408    }
409
410    // Sabotage: with carried admitting the year 10000, this test fails.
411    #[test]
412    fn an_encode_refusal_is_an_evaluation_error() {
413        let refused = |value: Value| {
414            let error = encode(&value).unwrap_err();
415            assert_eq!(error.type_name(), "EvaluationError");
416            error.reason().to_owned()
417        };
418        assert_eq!(refused(Value::from(f64::NAN)), "non_finite_number");
419        assert_eq!(
420            refused(Value::from(date(10_000, 1, 1))),
421            "invalid_tagged_value"
422        );
423        assert_eq!(
424            refused(Value::from(date(-1, 12, 31))),
425            "invalid_tagged_value"
426        );
427        let far = DateTime::new(date(10_000, 1, 1), 0, 0, 0, 0).unwrap();
428        assert_eq!(refused(Value::from(far)), "invalid_tagged_value");
429        let inner: Map = [("$type", Value::from("date"))].into_iter().collect();
430        assert_eq!(refused(Value::from(vec![inner.into()])), "reserved_map_key");
431        assert!(encode(&Value::from(date(0, 1, 1))).is_ok());
432        assert!(encode(&Value::from(date(9999, 12, 31))).is_ok());
433    }
434}