rabbitizer 2.0.0-alpha.8

MIPS instruction decoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/* SPDX-FileCopyrightText: © 2024-2025 Decompollaborate */
/* SPDX-License-Identifier: MIT */

#![allow(clippy::uninlined_format_args)]

use rabbitizer::display_flags::InstructionDisplayFlags;
use rabbitizer::instr::{Instruction, InstructionFlags};
#[cfg(any(feature = "RSP", feature = "R4000ALLEGREX"))]
use rabbitizer::isa::IsaExtension;
use rabbitizer::opcodes::Opcode;
use rabbitizer::operands::OPERAND_COUNT_MAX;
use rabbitizer::vram::Vram;

#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct TestEntry {
    pub instr: Instruction,
    pub imm_override: Option<&'static str>,
    pub display_flags: InstructionDisplayFlags,

    pub valid: bool,

    pub expected: &'static str,
    pub expected_opcode: Opcode,
    pub opcode_str: &'static str,
    pub operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],

    pub test_encoder: bool,
}

impl TestEntry {
    #[allow(dead_code)]
    const fn new_impl(
        word: u32,
        vram: Vram,
        flags: InstructionFlags,
        expected: &'static str,
        expected_opcode: Opcode,
        opcode_str: &'static str,
        operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],
    ) -> Self {
        Self {
            instr: Instruction::new(word, vram, flags),
            imm_override: None,
            display_flags: InstructionDisplayFlags::new(),
            valid: true,
            expected,
            expected_opcode,
            opcode_str,
            operands_str,
            test_encoder: true,
        }
    }

    #[allow(dead_code)]
    pub const fn new(
        word: u32,
        flags: InstructionFlags,
        expected: &'static str,
        expected_opcode: Opcode,
        opcode_str: &'static str,
        operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],
    ) -> Self {
        Self::new_impl(
            word,
            Vram::new(0x80000000),
            flags,
            expected,
            expected_opcode,
            opcode_str,
            operands_str,
        )
    }

    #[cfg(feature = "RSP")]
    #[allow(dead_code)]
    pub const fn new_rsp(
        word: u32,
        flags: InstructionFlags,
        expected: &'static str,
        expected_opcode: Opcode,
        opcode_str: &'static str,
        operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],
    ) -> Self {
        Self::new_impl(
            word,
            Vram::new(0xA4000000),
            flags,
            expected,
            expected_opcode,
            opcode_str,
            operands_str,
        )
    }

    #[cfg(feature = "RSP")]
    #[allow(dead_code)]
    pub const fn new_rsp_invalid(
        word: u32,
        flags: InstructionFlags,
        expected: &'static str,
    ) -> Self {
        Self {
            instr: Instruction::new(
                word,
                Vram::new(0xA4000000),
                flags.with_isa_extension(Some(IsaExtension::RSP)),
            ),
            imm_override: None,
            display_flags: InstructionDisplayFlags::default(),
            valid: false,
            expected,
            expected_opcode: Opcode::ALL_INVALID,
            opcode_str: "INVALID",
            operands_str: [None, None, None, None, None],
            test_encoder: false,
        }
    }

    #[cfg(feature = "R4000ALLEGREX")]
    #[allow(dead_code)]
    pub const fn new_r4000allegrex(
        word: u32,
        expected: &'static str,
        expected_opcode: Opcode,
        opcode_str: &'static str,
        operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],
    ) -> Self {
        use rabbitizer::abi::Abi;

        Self::new(
            word,
            InstructionFlags::new_extension(IsaExtension::R4000ALLEGREX).with_abi(Abi::EABI64),
            expected,
            expected_opcode,
            opcode_str,
            operands_str,
        )
    }

    #[allow(dead_code)]
    pub const fn new_full_invalid(
        word: u32,
        flags: InstructionFlags,
        expected: &'static str,
    ) -> Self {
        Self {
            instr: Instruction::new(word, Vram::new(0x80000000), flags),
            imm_override: None,
            display_flags: InstructionDisplayFlags::default(),
            valid: false,
            expected,
            expected_opcode: Opcode::ALL_INVALID,
            opcode_str: "INVALID",
            operands_str: [None, None, None, None, None],
            test_encoder: false,
        }
    }

    #[allow(dead_code)]
    pub const fn new_semi_invalid(
        word: u32,
        flags: InstructionFlags,
        expected: &'static str,
        expected_opcode: Opcode,
        opcode_str: &'static str,
        operands_str: [Option<&'static str>; OPERAND_COUNT_MAX],
    ) -> Self {
        Self {
            instr: Instruction::new(word, Vram::new(0x80000000), flags),
            imm_override: None,
            display_flags: InstructionDisplayFlags::default(),
            valid: false,
            expected,
            expected_opcode,
            opcode_str,
            operands_str,
            test_encoder: false,
        }
    }

    #[allow(dead_code)]
    pub const fn with_display_flags(self, display_flags: InstructionDisplayFlags) -> Self {
        Self {
            display_flags,
            ..self
        }
    }

    pub fn compare_source_info(&self, other: &Self) -> bool {
        self.instr.word() == other.instr.word()
            && self.instr.flags() == other.instr.flags()
            && self.imm_override == other.imm_override
            && self.display_flags == other.display_flags
            && self.valid == other.valid
    }

    pub fn check_validity(&self) -> u32 {
        let mut errors = 0;

        if self.instr.is_valid() != self.valid {
            println!(
                "'{}' ({:08X}) has incorrect validity. Expected '{}', got '{}'",
                self.opcode_str,
                self.instr.word(),
                self.valid,
                self.instr.is_valid()
            );
            errors += 1;
        }
        if self.instr.opcode() != self.expected_opcode {
            println!(
                "'{}' ({:08X}) has incorrect decoded opcode. Expected '{:?}', got '{:?}'",
                self.opcode_str,
                self.instr.word(),
                self.expected_opcode,
                self.instr.opcode()
            );
            errors += 1;
        }
        let generated_mnemonic = self.instr.mnemonic_display(&self.display_flags).to_string();
        if generated_mnemonic != self.opcode_str {
            println!(
                "'{}' ({:08X}) has incorrect mnemonic. Expected '{}', got '{}'",
                self.opcode_str,
                self.instr.word(),
                self.opcode_str,
                generated_mnemonic,
            );
            errors += 1;
        }

        if self.instr.opcode().is_branch() {
            if self.instr.get_branch_offset_generic().is_none() {
                println!(
                    "'{}' ({:08X}) is a branch opcode but `get_branch_offset_generic` returned `None`.",
                    self.opcode_str,
                    self.instr.word()
                );
                errors += 1;
            }
            if self.instr.get_branch_vram_generic().is_none() {
                println!(
                    "'{}' ({:08X}) is a branch but `get_branch_vram_generic` returned `None`.",
                    self.opcode_str,
                    self.instr.word()
                );
                errors += 1;
            }
        }

        if self.instr.opcode() == Opcode::core_j {
            if self.instr.flags().j_as_branch() {
                if self.instr.get_branch_offset_generic().is_none() {
                    println!(
                        "'{}' ({:08X}) is the `j` opcode but `get_branch_offset_generic` returned `None`.",
                        self.opcode_str,
                        self.instr.word()
                    );
                    errors += 1;
                }
                if self.instr.get_branch_vram_generic().is_none() {
                    println!(
                        "'{}' ({:08X}) is the `j` but `get_branch_vram_generic` returned `None`.",
                        self.opcode_str,
                        self.instr.word()
                    );
                    errors += 1;
                }
            } else {
                if self.instr.get_branch_offset_generic().is_some() {
                    println!(
                        "'{}' ({:08X}) is the `j` opcode but `get_branch_offset_generic` returned `Some` when `j_as_branch` is turned off.",
                        self.opcode_str,
                        self.instr.word()
                    );
                    errors += 1;
                }
                if self.instr.get_branch_vram_generic().is_some() {
                    println!(
                        "'{}' ({:08X}) is the `j` opcode but `get_branch_vram_generic` returned `Some` when `j_as_branch` is turned off.",
                        self.opcode_str,
                        self.instr.word()
                    );
                    errors += 1;
                }
            }
        }

        errors
    }

    pub fn check_disassembly(&self) -> u32 {
        let mut errors = 0;
        let display_flags = self.display_flags.with_debug_word_comment_info(true);

        let disasm = self
            .instr
            .display(&display_flags, self.imm_override, 0)
            .to_string();
        // println!("    {}", disasm);
        if disasm != self.expected {
            println!(
                "'{}' ({:08X}) did not match the expected string.",
                self.opcode_str,
                self.instr.word(),
            );
            println!("    Expected: '{}'", self.expected,);
            println!("    Got:      '{}'", disasm,);
            errors += 1;
        }

        // Check disassembling specific operands
        {
            let mut j = 0;
            for (i, operand) in self.instr.operands_iter().enumerate() {
                let operand_str = operand
                    .display(&self.instr, &display_flags, self.imm_override)
                    .to_string();
                let maybe_expected_str = self.operands_str[i];

                if let Some(expected_str) = maybe_expected_str {
                    if operand_str != expected_str {
                        println!(
                            "'{}' ({:08X}) has incorrect disassembled operand. Expected '{}', got '{}'",
                            self.opcode_str,
                            self.instr.word(),
                            expected_str,
                            operand_str
                        );
                        errors += 1;
                    }
                } else {
                    println!(
                        "'{}' ({:08X}) has an unexpected operand at index {}. Got: '{}'",
                        self.opcode_str,
                        self.instr.word(),
                        i,
                        operand_str,
                    );
                    errors += 1;
                }
                j = i;
            }

            if !self.operands_str[j + 1..].iter().all(|x| x.is_none()) {
                println!(
                    "'{}' ({:08X}) has unhandled expected operands. Values: '{:?}'",
                    self.opcode_str,
                    self.instr.word(),
                    &self.operands_str[j..]
                );
                errors += 1;
            }
        }

        errors
    }

    #[cfg(feature = "encoder")]
    pub fn check_encoding(&self) -> u32 {
        use rabbitizer::encoder::{EncoderFlags, EncoderIterator};

        if !self.valid {
            return 0;
        }
        if self.expected.starts_with(".word") {
            return 0;
        }
        if self.imm_override.is_some() {
            // TODO: We don't support `imm_override`s yet while encoding.
            return 0;
        }

        let mut encoder_flags = EncoderFlags::new(*self.instr.flags());
        if !self.display_flags.use_dollar() {
            *encoder_flags.allow_dollarless_mut() = true;
        }
        #[cfg(feature = "R5900EE")]
        {
            *encoder_flags.r5900ee_prodg_sn_as_inverted_regs_mut() =
                self.display_flags.r5900ee_prodg_sn_as_inverted_regs();
        }

        let mut errors = 0;
        let mut encoder = EncoderIterator::new(self.expected, self.instr.vram(), encoder_flags);
        let display_flags = self.display_flags.with_debug_word_comment_info(true);

        match encoder.next() {
            None => {
                println!("Unable to encode? '{}'", self.expected);
                errors += 1;
            }
            Some(Err(e)) => {
                // TODO: add error
                println!(
                    "Unable to encode '{}' due to error:\n    {}",
                    self.expected, e
                );
                errors += 1;
            }
            Some(Ok((instr, raw))) => {
                let disasm = instr
                    .display(&display_flags, self.imm_override, 0)
                    .to_string();
                if !instr.is_valid() {
                    println!(
                        "Encoded instruction '{}' (encoded '{}') is not valid?",
                        self.expected, disasm
                    );
                    errors += 1;
                }
                if instr.word() != self.instr.word() {
                    println!("Encoded instruction does not match the expected word.");
                    println!(
                        "    Expected: '0x{:08X}' '{}'",
                        self.instr.word(),
                        self.expected
                    );
                    println!("    Got:      '0x{:08X}' '{}'", instr.word(), disasm);
                    errors += 1;
                }
                if raw.trim() != self.expected.trim() {
                    println!("The returned raw range of the instruction '{}' does not match the expected text '{}'", raw, self.expected);
                    errors += 1;
                }
            }
        }

        match encoder.next() {
            None => {}
            Some(_) => {
                println!(
                    "What? A second instruction was tried to be encoded while encoding '{}'?",
                    self.expected
                );
                errors += 1;
            }
        }

        errors
    }
}

pub fn entries_sanity_check(entries: &[TestEntry]) {
    for (i, x) in entries.iter().enumerate() {
        for y in entries[i + 1..].iter() {
            assert!(
                !x.compare_source_info(y),
                "Duplicated entry. Word: '0x{:08X}'. imm_override: '{:?}'",
                x.instr.word(),
                x.imm_override
            );
        }
    }
}

pub fn check_test_entries(entries: &[TestEntry]) -> (u32, u32) {
    let mut instructions_with_errors = 0;
    let mut individual_errors = 0;

    entries_sanity_check(entries);

    for entry in entries {
        let mut errors = entry.check_validity();
        errors += entry.check_disassembly();
        #[cfg(feature = "encoder")]
        if entry.test_encoder {
            errors += entry.check_encoding();
        }

        individual_errors += errors;
        if errors != 0 {
            instructions_with_errors += 1;
            println!();
        }
    }

    (instructions_with_errors, individual_errors)
}