]> Witch of Git - jade-rose/blob - toolchain/src/inst/encode.rs
Add the wait state to the state machine
[jade-rose] / toolchain / src / inst / encode.rs
1 use super::{AluI, Data, Inst, Reg, Special, U3};
2 use std::io::{self, Write};
3
4 pub trait Encode {
5 fn encode(&self, writer: &mut impl Write) -> io::Result<()>;
6 }
7
8 fn reg(Reg(U3(x)): Reg) -> u8 {
9 x
10 }
11
12 fn sp(s: Special) -> u8 {
13 match s {
14 Special::Data(Data::D1) => 0b00,
15 Special::Data(Data::D2) => 0b01,
16 Special::Code => 0b10,
17 }
18 }
19
20 impl Encode for Inst {
21 fn encode(&self, writer: &mut impl Write) -> io::Result<()> {
22 match *self {
23 Inst::Stop => writer.write(&[0x00])?,
24 Inst::Nope => writer.write(&[0x01])?,
25 Inst::Prnt => writer.write(&[0x02])?,
26 Inst::CAbA => writer.write(&[0x06])?,
27 Inst::COfA => writer.write(&[0x07])?,
28 Inst::Alu1(op) => writer.write(&[0x08 | op as u8])?,
29 Inst::Get(s) => writer.write(&[0x10 | sp(s)])?,
30 Inst::Set(s) => writer.write(&[0x18 | sp(s)])?,
31 Inst::GetR(r) => writer.write(&[0x20 | reg(r)])?,
32 Inst::SetR(r) => writer.write(&[0x28 | reg(r)])?,
33 Inst::Swap(r) => writer.write(&[0x30 | reg(r)])?,
34 Inst::IsLt(r) => writer.write(&[0x38 | reg(r)])?,
35 Inst::AluR(op, r) => writer.write(&[0x40 | (op as u8) << 3 | reg(r)])?,
36 Inst::Mem(op, d, r, inc) => writer.write(&[0x80
37 | (d as u8) << 5
38 | (inc as u8) << 4
39 | (op as u8) << 3
40 | reg(r)])?,
41 Inst::AluI(alu) => match alu {
42 AluI::And(imm) => writer.write(&[0xf0, imm])?,
43 AluI::Ior(imm) => writer.write(&[0xf1, imm])?,
44 AluI::Xor(imm) => writer.write(&[0xf2, imm])?,
45 AluI::Add(imm) => writer.write(&[0xf3, imm.0 as u8])?,
46 AluI::Compact(op, imm) => writer.write(&[0xf3, 0x80 | (op as u8) << 3 | imm.0])?,
47 },
48 Inst::BEzI(off) => writer.write(&[0xf4, off as u8])?,
49 Inst::JOfI(off) => writer.write(&[0xf5, off as u8])?,
50 Inst::CAbI(imm) => writer.write(&[0xf6, imm])?,
51 Inst::COfI(off) => writer.write(&[0xf7, off as u8])?,
52 Inst::GetI(imm) => writer.write(&[0xfe, imm])?,
53 };
54 Ok(())
55 }
56 }