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
use super::*;
use rle;

/// Program forms that can be compiled to the peephole AST.
pub trait PeepholeCompilable {
    /// Compile the given program into RLE AST to prepare for peephole optimization.
    fn with_rle<F, R>(&self, k: F) -> R
        where F: FnOnce(&rle::Program) -> R;

    /// Peephole optimize the given program.
    fn peephole_compile(&self) -> Box<Program> {
        self.with_rle(compile)
    }
}

/// Peephole-optimizes run-length encoded AST.
///
/// See [`Instruction`](struct.Instruction.html) for descriptions of the peepholes.
pub fn compile(src: &[rle::Statement]) -> Box<Program> {
    let mut compiler = Compiler::new();
    compiler.compile(src);
    compiler.into_program()
}

pub struct Compiler {
    instructions: Vec<Statement>,
}

macro_rules! or_else {
    ($x:expr) => ($x);
    ($x:expr, $($y:expr),+) => ($x.or_else(|| or_else!($($y),+)))
}

impl Compiler {
    pub fn new() -> Self {
        Compiler {
            instructions: Vec::new(),
        }
    }

    pub fn compile(&mut self, src: &[rle::Statement]) {
        use rle::Statement::*;
        use common::Command::*;
        use common::Instruction as Obj;

        for instruction in src {
            match *instruction {
                Cmd(Right, count) =>
                    self.push(Obj::Right(count)),
                Cmd(Left, count) =>
                    self.push(Obj::Left(count)),
                Cmd(Up, count) => {
                    let amount = (count % 256) as u8;
                    self.push(Obj::Add(amount));
                }
                Cmd(Down, count) => {
                    let amount = (256 - count % 256) as u8;
                    self.push(Obj::Add(amount));
                }
                Cmd(In, count) => {
                    for _ in 0 .. count {
                        self.push(Obj::In);
                    }
                }
                Cmd(Out, count) => {
                    for _ in 0 .. count {
                        self.push(Obj::Out);
                    }
                }
                Cmd(Begin, _) | Cmd(End, _) =>
                    panic!("bad opcode"),

                Loop(ref body) => {
                    let body = compile(&*body);

                    let peephole = or_else!(
                        set_zero_peephole(&body),
                        find_zero_peephole(&body),
                        offset_add_peephole(&body)
                    );

                    if let Some(instr) = peephole {
                        self.push(instr);
                    } else {
                        self.instructions.push(Statement::Loop(body))
                    }
                }
            }
        }
    }

    pub fn into_program(self) -> Box<Program> {
        self.instructions.into_boxed_slice()
    }

    fn push(&mut self, instr: common::Instruction) {
        self.instructions.push(Statement::Instr(instr));
    }
}

pub fn set_zero_peephole(body: &[Statement]) -> Option<common::Instruction> {
    use self::Statement::*;
    use common::Instruction::*;

    if body.len() == 1 && (body[0] == Instr(Add(1)) || body[0] == Instr(Add(255))) {
        Some(SetZero)
    } else {
        None
    }
}

pub fn find_zero_peephole(body: &[Statement]) -> Option<common::Instruction> {
    use self::Statement::*;
    use common::Instruction::*;

    if body.len() == 1 {
        match body[0] {
            Instr(Right(count)) =>
                Some(FindZeroRight(count)),
            Instr(Left(count)) =>
                Some(FindZeroLeft(count)),
            _ => None,
        }
    } else {
        None
    }
}

pub fn offset_add_peephole(body: &[Statement]) -> Option<common::Instruction> {
    use self::Statement::*;
    use common::Instruction::*;

    if body.len() == 4 {
        match (&body[0], &body[1], &body[2], &body[3]) {
            (&Instr(Add(255)), &Instr(Right(count_l)), &Instr(Add(1)), &Instr(Left(count_r)))
            if count_l == count_r => {
                Some(OffsetAddRight(count_l))
            }

            (&Instr(Add(255)), &Instr(Left(count_l)), &Instr(Add(1)), &Instr(Right(count_r)))
            if count_l == count_r => {
                Some(OffsetAddLeft(count_l))
            }

            _ => None,
        }
    } else {
        None
    }
}

impl PeepholeCompilable for rle::Program {
    fn with_rle<F, R>(&self, k: F) -> R
        where F: FnOnce(&rle::Program) -> R
    {
        k(self)
    }
}

impl<T: rle::RleCompilable + ?Sized> PeepholeCompilable for T {
    fn with_rle<F, R>(&self, k: F) -> R
        where F: FnOnce(&rle::Program) -> R
    {
        k(&self.rle_compile())
    }
}