1 //! Run commands.
2 //!
3 //! Functions in a `.clif` file can have *run commands* appended that control how a function is
4 //! invoked and tested within the `test run` context. The general syntax is:
5 //!
6 //! - `; run`: this assumes the function has a signature like `() -> b*`.
7 //! - `; run: %fn(42, 4.2) == false`: this syntax specifies the parameters and return values.
8 
9 use cranelift_codegen::data_value::{self, DataValue, DisplayDataValues};
10 use std::fmt::{self, Display, Formatter};
11 
12 /// A run command appearing in a test file.
13 ///
14 /// For parsing, see `Parser::parse_run_command`
15 #[derive(PartialEq, Debug)]
16 pub enum RunCommand {
17     /// Invoke a function and print its result.
18     Print(Invocation),
19     /// Invoke a function and compare its result to a value sequence.
20     Run(Invocation, Comparison, Vec<DataValue>),
21 }
22 
23 impl RunCommand {
24     /// Run the [RunCommand]:
25     ///  - for [RunCommand::Print], print the returned values from invoking the function.
26     ///  - for [RunCommand::Run], compare the returned values from the invoked function and
27     ///    return an `Err` with a descriptive string if the comparison fails.
28     ///
29     /// Accepts a function used for invoking the actual execution of the command. This function,
30     /// `invoked_fn`, is passed the _function name_ and _function arguments_ of the [Invocation].
31     pub fn run<F>(&self, invoke_fn: F) -> Result<(), String>
32     where
33         F: FnOnce(&str, &[DataValue]) -> Result<Vec<DataValue>, String>,
34     {
35         match self {
36             RunCommand::Print(invoke) => {
37                 let actual = invoke_fn(&invoke.func, &invoke.args)?;
38                 println!("{} -> {}", invoke, DisplayDataValues(&actual))
39             }
40             RunCommand::Run(invoke, compare, expected) => {
41                 let actual = invoke_fn(&invoke.func, &invoke.args)?;
42                 let matched = match compare {
43                     Comparison::Equals => *expected == actual,
44                     Comparison::NotEquals => *expected != actual,
45                 };
46                 if !matched {
47                     let actual = DisplayDataValues(&actual);
48                     return Err(format!("Failed test: {}, actual: {}", self, actual));
49                 }
50             }
51         }
52         Ok(())
53     }
54 }
55 
56 impl Display for RunCommand {
57     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
58         match self {
59             RunCommand::Print(invocation) => write!(f, "print: {}", invocation),
60             RunCommand::Run(invocation, comparison, expected) => {
61                 let expected = DisplayDataValues(expected);
62                 write!(f, "run: {} {} {}", invocation, comparison, expected)
63             }
64         }
65     }
66 }
67 
68 /// Represent a function call; [RunCommand]s invoke a CLIF function using an [Invocation].
69 #[derive(Debug, PartialEq)]
70 pub struct Invocation {
71     /// The name of the function to call. Note: this field is for mostly included for informational
72     /// purposes and may not always be necessary for identifying which function to call.
73     pub func: String,
74     /// The arguments to be passed to the function when invoked.
75     pub args: Vec<DataValue>,
76 }
77 
78 impl Invocation {
79     pub(crate) fn new(func: &str, args: Vec<DataValue>) -> Self {
80         let func = func.to_string();
81         Self { func, args }
82     }
83 }
84 
85 impl Display for Invocation {
86     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
87         write!(f, "%{}(", self.func)?;
88         data_value::write_data_value_list(f, &self.args)?;
89         write!(f, ")")
90     }
91 }
92 
93 /// A CLIF comparison operation; e.g. `==`.
94 #[allow(missing_docs)]
95 #[derive(Debug, PartialEq)]
96 pub enum Comparison {
97     Equals,
98     NotEquals,
99 }
100 
101 impl Display for Comparison {
102     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
103         match self {
104             Comparison::Equals => write!(f, "=="),
105             Comparison::NotEquals => write!(f, "!="),
106         }
107     }
108 }
109 
110 #[cfg(test)]
111 mod test {
112     use super::*;
113     use crate::parse_run_command;
114     use cranelift_codegen::ir::{types, AbiParam, Signature};
115     use cranelift_codegen::isa::CallConv;
116 
117     #[test]
118     fn run_a_command() {
119         let mut signature = Signature::new(CallConv::Fast);
120         signature.returns.push(AbiParam::new(types::I32));
121         let command = parse_run_command(";; run: %return42() == 42 ", &signature)
122             .unwrap()
123             .unwrap();
124 
125         assert!(command.run(|_, _| Ok(vec![DataValue::I32(42)])).is_ok());
126         assert!(command.run(|_, _| Ok(vec![DataValue::I32(43)])).is_err());
127     }
128 }
129