cranelift_fuzzgen/
print.rs

1use cranelift::codegen::data_value::DataValue;
2use cranelift::codegen::ir::Function;
3use cranelift::prelude::settings::SettingKind;
4use cranelift::prelude::*;
5use std::fmt;
6
7use crate::TestCaseInput;
8
9#[derive(Debug)]
10enum TestCaseKind {
11    Compile,
12    Run,
13}
14
15/// Provides a way to format a `TestCase` in the .clif format.
16pub struct PrintableTestCase<'a> {
17    kind: TestCaseKind,
18    isa: &'a isa::OwnedTargetIsa,
19    functions: &'a [Function],
20    // Only applicable for run test cases
21    inputs: &'a [TestCaseInput],
22}
23
24impl<'a> PrintableTestCase<'a> {
25    /// Emits a `test compile` test case.
26    pub fn compile(isa: &'a isa::OwnedTargetIsa, functions: &'a [Function]) -> Self {
27        Self {
28            kind: TestCaseKind::Compile,
29            isa,
30            functions,
31            inputs: &[],
32        }
33    }
34
35    /// Emits a `test run` test case. These also include a `test interpret`.
36    ///
37    /// By convention the first function in `functions` will be considered the main function.
38    pub fn run(
39        isa: &'a isa::OwnedTargetIsa,
40        functions: &'a [Function],
41        inputs: &'a [TestCaseInput],
42    ) -> Self {
43        Self {
44            kind: TestCaseKind::Run,
45            isa,
46            functions,
47            inputs,
48        }
49    }
50
51    /// Returns the main function of this test case.
52    pub fn main(&self) -> &Function {
53        &self.functions[0]
54    }
55}
56
57impl<'a> fmt::Debug for PrintableTestCase<'a> {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self.kind {
60            TestCaseKind::Compile => {
61                writeln!(f, ";; Compile test case\n")?;
62                writeln!(f, "test compile")?;
63            }
64            TestCaseKind::Run => {
65                writeln!(f, ";; Run test case\n")?;
66                writeln!(f, "test interpret")?;
67                writeln!(f, "test run")?;
68            }
69        };
70
71        write_non_default_flags(f, self.isa.flags())?;
72
73        write!(f, "target {} ", self.isa.triple().architecture)?;
74        write_non_default_isa_flags(f, &self.isa)?;
75        write!(f, "\n\n")?;
76
77        // Print the functions backwards, so that the main function is printed last
78        // and near the test inputs for run test cases.
79        for func in self.functions.iter().rev() {
80            writeln!(f, "{func}\n")?;
81        }
82
83        if !self.inputs.is_empty() {
84            writeln!(f, "; Note: the results in the below test cases are simply a placeholder and probably will be wrong\n")?;
85        }
86
87        for input in self.inputs.iter() {
88            // TODO: We don't know the expected outputs, maybe we can run the interpreter
89            // here to figure them out? Should work, however we need to be careful to catch
90            // panics in case its the interpreter that is failing.
91            // For now create a placeholder output consisting of the zero value for the type
92            let returns = &self.main().signature.returns;
93            let placeholder_output = returns
94                .iter()
95                .map(|param| DataValue::read_from_slice_ne(&[0; 16][..], param.value_type))
96                .map(|val| format!("{val}"))
97                .collect::<Vec<_>>()
98                .join(", ");
99
100            // If we have no output, we don't need the == condition
101            let test_condition = match returns.len() {
102                0 => String::new(),
103                1 => format!(" == {placeholder_output}"),
104                _ => format!(" == [{placeholder_output}]"),
105            };
106
107            let args = input
108                .iter()
109                .map(|val| format!("{val}"))
110                .collect::<Vec<_>>()
111                .join(", ");
112
113            writeln!(f, "; run: {}({}){}", self.main().name, args, test_condition)?;
114        }
115
116        Ok(())
117    }
118}
119
120/// Print only non default flags.
121fn write_non_default_flags(f: &mut fmt::Formatter<'_>, flags: &settings::Flags) -> fmt::Result {
122    let default_flags = settings::Flags::new(settings::builder());
123    for (default, flag) in default_flags.iter().zip(flags.iter()) {
124        assert_eq!(default.name, flag.name);
125
126        if default.value_string() != flag.value_string() {
127            writeln!(f, "set {}={}", flag.name, flag.value_string())?;
128        }
129    }
130
131    Ok(())
132}
133
134/// Print non default ISA flags in a single line, as used in `target` declarations.
135fn write_non_default_isa_flags(
136    f: &mut fmt::Formatter<'_>,
137    isa: &isa::OwnedTargetIsa,
138) -> fmt::Result {
139    let default_isa = isa::lookup(isa.triple().clone())
140        .unwrap()
141        .finish(isa.flags().clone())
142        .unwrap();
143
144    for (default, flag) in default_isa.isa_flags().iter().zip(isa.isa_flags()) {
145        assert_eq!(default.name, flag.name);
146
147        // Skip default flags, putting them all out there is too verbose.
148        if default.value_string() == flag.value_string() {
149            continue;
150        }
151
152        // On boolean flags we can use the shorthand syntax instead of just specifying the flag name.
153        // This is slightly neater than the full syntax.
154        if flag.kind() == SettingKind::Bool && flag.value_string() == "true" {
155            write!(f, "{} ", flag.name)?;
156        } else {
157            write!(f, "{}={} ", flag.name, flag.value_string())?;
158        }
159    }
160
161    Ok(())
162}