Skip to main content

predicator_rs/
instructions.rs

1//! An instruction list: the program the evaluator runs.
2
3use crate::{Error, ParseError, Value, tagged};
4
5/// An instruction list: a flat list of instructions, each a list whose first
6/// member names the opcode and whose other members are its operands, as the
7/// reference's instruction-set text defines it.
8///
9/// One is made by compiling a source ([`compile`](crate::compile),
10/// [`compile_program`](crate::compile_program)) or by reading its JSON
11/// form ([`Instructions::from_json`]), and written back to that form by
12/// [`Instructions::to_json`].
13///
14/// An instruction is read when the evaluator reaches it, as the reference
15/// reads it: an instruction that is not a list, names no opcode the build
16/// runs or carries operands of the wrong shape is refused then, with the
17/// reason `unknown_instruction`, and an opcode the instruction set has
18/// retired with the reason `retired_opcode`. An instruction a jump skips is
19/// never read.
20///
21/// ```
22/// use predicator_rs::{Context, Instructions, Options, Value, evaluate};
23///
24/// let instructions = Instructions::from_json(r#"[["lit",3],["lit",5],["compare","LT"]]"#)?;
25/// assert_eq!(evaluate(&instructions, &Context::new(), &Options::new())?, Value::from(true));
26/// # Ok::<(), predicator_rs::Error>(())
27/// ```
28#[derive(Debug, Clone, PartialEq)]
29pub struct Instructions {
30    pub(crate) list: Vec<Value>,
31}
32
33impl Instructions {
34    /// Reads an instruction list from JSON text in the conformance corpus's
35    /// tagged-value encoding (the [`tagged`] module), which carries an
36    /// undefined, a date, an instant or a duration operand as a tagged
37    /// object.
38    ///
39    /// Every refusal is an [`Error::Parse`]: the reasons
40    /// [`tagged::decode`] gives for a text that does not decode, and
41    /// `not_an_instruction_list` for a text that decodes to anything but a
42    /// list. The instructions themselves are read when they run.
43    ///
44    /// ```
45    /// use predicator_rs::Instructions;
46    ///
47    /// assert!(Instructions::from_json(r#"[["lit",{"$type":"undefined"}]]"#).is_ok());
48    /// let refused = Instructions::from_json(r#"{"lit":1}"#).unwrap_err();
49    /// assert_eq!(refused.reason(), "not_an_instruction_list");
50    /// ```
51    pub fn from_json(text: &str) -> Result<Instructions, Error> {
52        // Value implements Drop, so the list is taken out rather than moved.
53        match &mut tagged::decode(text)? {
54            Value::List(list) => Ok(Instructions {
55                list: core::mem::take(list),
56            }),
57            _ => Err(ParseError::new(
58                "not_an_instruction_list",
59                "an instruction list is a JSON array",
60            )
61            .into()),
62        }
63    }
64
65    /// Writes the instruction list as JSON text in the conformance corpus's
66    /// tagged-value encoding (the [`tagged`] module), the text
67    /// [`Instructions::from_json`] reads back: no whitespace, an undefined,
68    /// a date, an instant or a duration operand carried as its tag. It needs
69    /// no feature.
70    ///
71    /// A list this crate compiled or read is always written. The refusals
72    /// are [`tagged::encode`]'s, each an [`Error::Evaluation`].
73    ///
74    /// ```
75    /// use predicator_rs::{Instructions, compile};
76    ///
77    /// let instructions = compile("x == undefined")?;
78    /// let text = instructions.to_json()?;
79    /// assert_eq!(text, r#"[["load","x"],["lit",{"$type":"undefined"}],["compare","EQ"]]"#);
80    /// assert_eq!(Instructions::from_json(&text)?, instructions);
81    /// # Ok::<(), predicator_rs::Error>(())
82    /// ```
83    pub fn to_json(&self) -> Result<String, Error> {
84        tagged::encode(&Value::List(self.list.clone()))
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    // Sabotage: with from_json accepting a map as an empty list, this test
93    // fails.
94    #[test]
95    fn only_a_list_is_an_instruction_list() {
96        let read = Instructions::from_json(r#"[["load","x"],5,[]]"#).unwrap();
97        assert_eq!(read.list.len(), 3);
98        for text in [r#"{"a":1}"#, "5", "null", r#""x""#] {
99            let refused = Instructions::from_json(text)
100                .err()
101                .map(|error| (error.type_name().to_owned(), error.reason().to_owned()));
102            assert_eq!(
103                refused,
104                Some((
105                    "ParseError".to_owned(),
106                    "not_an_instruction_list".to_owned()
107                )),
108                "{text}"
109            );
110        }
111        assert_eq!(
112            Instructions::from_json("[").unwrap_err().reason(),
113            "malformed_json"
114        );
115    }
116
117    // to_json writes the tagged encoding from_json reads, every tag included,
118    // so a list read and written comes back as the same text.
119    // Sabotage: with to_json leaving out the list's last instruction, this
120    // test fails on the round trip.
121    #[test]
122    fn to_json_writes_what_from_json_reads() {
123        let text = r#"[["lit",{"$type":"undefined"}],["lit",[{"$type":"date","value":"2026-01-02"},{"$type":"datetime","value":"2026-01-02T03:04:05.500000Z"},1.5]],["lit",{"$type":"duration","value":{"days":3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0,"years":0}}],["call","f",2]]"#;
124        let read = Instructions::from_json(text).unwrap();
125        assert_eq!(read.to_json().unwrap(), text);
126        assert_eq!(
127            Instructions::from_json("[]").unwrap().to_json().unwrap(),
128            "[]"
129        );
130    }
131}