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::ir::immediates::{Ieee32, Ieee64, Imm64};
10 use cranelift_codegen::ir::{self, types, ConstantData, Type};
11 use std::convert::TryInto;
12 use std::fmt::{self, Display, Formatter};
13 use thiserror::Error;
14 
15 /// A run command appearing in a test file.
16 ///
17 /// For parsing, see `Parser::parse_run_command`
18 #[derive(PartialEq, Debug)]
19 pub enum RunCommand {
20     /// Invoke a function and print its result.
21     Print(Invocation),
22     /// Invoke a function and compare its result to a value sequence.
23     Run(Invocation, Comparison, Vec<DataValue>),
24 }
25 
26 impl RunCommand {
27     /// Run the [RunCommand]:
28     ///  - for [RunCommand::Print], print the returned values from invoking the function.
29     ///  - for [RunCommand::Run], compare the returned values from the invoked function and
30     ///    return an `Err` with a descriptive string if the comparison fails.
31     ///
32     /// Accepts a function used for invoking the actual execution of the command. This function,
33     /// `invoked_fn`, is passed the _function name_ and _function arguments_ of the [Invocation].
34     pub fn run<F>(&self, invoke_fn: F) -> Result<(), String>
35     where
36         F: FnOnce(&str, &[DataValue]) -> Result<Vec<DataValue>, String>,
37     {
38         match self {
39             RunCommand::Print(invoke) => {
40                 let actual = invoke_fn(&invoke.func, &invoke.args)?;
41                 println!("{} -> {}", invoke, DisplayDataValues(&actual))
42             }
43             RunCommand::Run(invoke, compare, expected) => {
44                 let actual = invoke_fn(&invoke.func, &invoke.args)?;
45                 let matched = match compare {
46                     Comparison::Equals => *expected == actual,
47                     Comparison::NotEquals => *expected != actual,
48                 };
49                 if !matched {
50                     let actual = DisplayDataValues(&actual);
51                     return Err(format!("Failed test: {}, actual: {}", self, actual));
52                 }
53             }
54         }
55         Ok(())
56     }
57 }
58 
59 impl Display for RunCommand {
60     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
61         match self {
62             RunCommand::Print(invocation) => write!(f, "print: {}", invocation),
63             RunCommand::Run(invocation, comparison, expected) => {
64                 let expected = DisplayDataValues(expected);
65                 write!(f, "run: {} {} {}", invocation, comparison, expected)
66             }
67         }
68     }
69 }
70 
71 /// Represent a function call; [RunCommand]s invoke a CLIF function using an [Invocation].
72 #[derive(Debug, PartialEq)]
73 pub struct Invocation {
74     /// The name of the function to call. Note: this field is for mostly included for informational
75     /// purposes and may not always be necessary for identifying which function to call.
76     pub func: String,
77     /// The arguments to be passed to the function when invoked.
78     pub args: Vec<DataValue>,
79 }
80 
81 impl Invocation {
82     pub(crate) fn new(func: &str, args: Vec<DataValue>) -> Self {
83         let func = func.to_string();
84         Self { func, args }
85     }
86 }
87 
88 impl Display for Invocation {
89     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
90         write!(f, "%{}(", self.func)?;
91         write_data_value_list(f, &self.args)?;
92         write!(f, ")")
93     }
94 }
95 
96 /// Represent a data value. Where [Value] is an SSA reference, [DataValue] is the type + value
97 /// that would be referred to by a [Value].
98 ///
99 /// [Value]: cranelift_codegen::ir::Value
100 #[allow(missing_docs)]
101 #[derive(Clone, Debug, PartialEq)]
102 pub enum DataValue {
103     B(bool),
104     I8(i8),
105     I16(i16),
106     I32(i32),
107     I64(i64),
108     F32(f32),
109     F64(f64),
110     V128([u8; 16]),
111 }
112 
113 impl DataValue {
114     /// Try to cast an immediate integer ([Imm64]) to the given Cranelift [Type].
115     pub fn from_integer(imm: Imm64, ty: Type) -> Result<DataValue, DataValueCastFailure> {
116         match ty {
117             types::I8 => Ok(DataValue::I8(imm.bits() as i8)),
118             types::I16 => Ok(DataValue::I16(imm.bits() as i16)),
119             types::I32 => Ok(DataValue::I32(imm.bits() as i32)),
120             types::I64 => Ok(DataValue::I64(imm.bits())),
121             _ => Err(DataValueCastFailure::FromImm64(imm, ty)),
122         }
123     }
124 
125     /// Return the Cranelift IR [Type] for this [DataValue].
126     pub fn ty(&self) -> Type {
127         match self {
128             DataValue::B(_) => ir::types::B8, // A default type.
129             DataValue::I8(_) => ir::types::I8,
130             DataValue::I16(_) => ir::types::I16,
131             DataValue::I32(_) => ir::types::I32,
132             DataValue::I64(_) => ir::types::I64,
133             DataValue::F32(_) => ir::types::F32,
134             DataValue::F64(_) => ir::types::F64,
135             DataValue::V128(_) => ir::types::I8X16, // A default type.
136         }
137     }
138 
139     /// Return true if the value is a vector (i.e. `DataValue::V128`).
140     pub fn is_vector(&self) -> bool {
141         match self {
142             DataValue::V128(_) => true,
143             _ => false,
144         }
145     }
146 }
147 
148 /// Record failures to cast [DataValue].
149 #[derive(Error, Debug, PartialEq)]
150 #[allow(missing_docs)]
151 pub enum DataValueCastFailure {
152     #[error("unable to cast data value of type {0} to type {1}")]
153     TryInto(Type, Type),
154     #[error("unable to cast Imm64({0}) to a data value of type {1}")]
155     FromImm64(Imm64, Type),
156 }
157 
158 /// Helper for creating conversion implementations for [DataValue].
159 macro_rules! build_conversion_impl {
160     ( $rust_ty:ty, $data_value_ty:ident, $cranelift_ty:ident ) => {
161         impl From<$rust_ty> for DataValue {
162             fn from(data: $rust_ty) -> Self {
163                 DataValue::$data_value_ty(data)
164             }
165         }
166 
167         impl TryInto<$rust_ty> for DataValue {
168             type Error = DataValueCastFailure;
169             fn try_into(self) -> Result<$rust_ty, Self::Error> {
170                 if let DataValue::$data_value_ty(v) = self {
171                     Ok(v)
172                 } else {
173                     Err(DataValueCastFailure::TryInto(
174                         self.ty(),
175                         types::$cranelift_ty,
176                     ))
177                 }
178             }
179         }
180     };
181 }
182 build_conversion_impl!(bool, B, B8);
183 build_conversion_impl!(i8, I8, I8);
184 build_conversion_impl!(i16, I16, I16);
185 build_conversion_impl!(i32, I32, I32);
186 build_conversion_impl!(i64, I64, I64);
187 build_conversion_impl!(f32, F32, F32);
188 build_conversion_impl!(f64, F64, F64);
189 build_conversion_impl!([u8; 16], V128, I8X16);
190 
191 impl Display for DataValue {
192     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
193         match self {
194             DataValue::B(dv) => write!(f, "{}", dv),
195             DataValue::I8(dv) => write!(f, "{}", dv),
196             DataValue::I16(dv) => write!(f, "{}", dv),
197             DataValue::I32(dv) => write!(f, "{}", dv),
198             DataValue::I64(dv) => write!(f, "{}", dv),
199             // Use the Ieee* wrappers here to maintain a consistent syntax.
200             DataValue::F32(dv) => write!(f, "{}", Ieee32::from(*dv)),
201             DataValue::F64(dv) => write!(f, "{}", Ieee64::from(*dv)),
202             // Again, for syntax consistency, use ConstantData, which in this case displays as hex.
203             DataValue::V128(dv) => write!(f, "{}", ConstantData::from(&dv[..])),
204         }
205     }
206 }
207 
208 /// Helper structure for printing bracket-enclosed vectors of [DataValue]s.
209 /// - for empty vectors, display `[]`
210 /// - for single item vectors, display `42`, e.g.
211 /// - for multiple item vectors, display `[42, 43, 44]`, e.g.
212 struct DisplayDataValues<'a>(&'a [DataValue]);
213 
214 impl<'a> Display for DisplayDataValues<'a> {
215     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
216         if self.0.len() == 1 {
217             write!(f, "{}", self.0[0])
218         } else {
219             write!(f, "[")?;
220             write_data_value_list(f, &self.0)?;
221             write!(f, "]")
222         }
223     }
224 }
225 
226 /// Helper function for displaying `Vec<DataValue>`.
227 fn write_data_value_list(f: &mut Formatter<'_>, list: &[DataValue]) -> fmt::Result {
228     match list.len() {
229         0 => Ok(()),
230         1 => write!(f, "{}", list[0]),
231         _ => {
232             write!(f, "{}", list[0])?;
233             for dv in list.iter().skip(1) {
234                 write!(f, ", {}", dv)?;
235             }
236             Ok(())
237         }
238     }
239 }
240 
241 /// A CLIF comparison operation; e.g. `==`.
242 #[allow(missing_docs)]
243 #[derive(Debug, PartialEq)]
244 pub enum Comparison {
245     Equals,
246     NotEquals,
247 }
248 
249 impl Display for Comparison {
250     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
251         match self {
252             Comparison::Equals => write!(f, "=="),
253             Comparison::NotEquals => write!(f, "!="),
254         }
255     }
256 }
257 
258 #[cfg(test)]
259 mod test {
260     use super::*;
261     use crate::parse_run_command;
262     use cranelift_codegen::ir::{types, AbiParam, Signature};
263     use cranelift_codegen::isa::CallConv;
264 
265     #[test]
266     fn run_a_command() {
267         let mut signature = Signature::new(CallConv::Fast);
268         signature.returns.push(AbiParam::new(types::I32));
269         let command = parse_run_command(";; run: %return42() == 42 ", &signature)
270             .unwrap()
271             .unwrap();
272 
273         assert!(command.run(|_, _| Ok(vec![DataValue::I32(42)])).is_ok());
274         assert!(command.run(|_, _| Ok(vec![DataValue::I32(43)])).is_err());
275     }
276 
277     #[test]
278     fn type_conversions() {
279         assert_eq!(DataValue::B(true).ty(), types::B8);
280         assert_eq!(
281             TryInto::<bool>::try_into(DataValue::B(false)).unwrap(),
282             false
283         );
284         assert_eq!(
285             TryInto::<i32>::try_into(DataValue::B(false)).unwrap_err(),
286             DataValueCastFailure::TryInto(types::B8, types::I32)
287         );
288 
289         assert_eq!(DataValue::V128([0; 16]).ty(), types::I8X16);
290         assert_eq!(
291             TryInto::<[u8; 16]>::try_into(DataValue::V128([0; 16])).unwrap(),
292             [0; 16]
293         );
294         assert_eq!(
295             TryInto::<i32>::try_into(DataValue::V128([0; 16])).unwrap_err(),
296             DataValueCastFailure::TryInto(types::I8X16, types::I32)
297         );
298     }
299 }
300