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
use num_bigint::BigInt;

use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;

use label::Label;

pub use ::Program;

#[derive(Debug, Clone)]
pub struct SourceLoc {
    pub line: usize,
    pub column: usize,
    pub span: Range<usize>,
    pub label: Option<Rc<Label>>
}

#[derive(Debug, Clone)]
pub enum Command {
    Push {value: Integer},
    PushBig {value: BigInteger},
    Duplicate,
    Copy {index: usize},
    Swap,
    Discard,
    Slide {amount: usize},
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Set,
    Get,
    Label,
    Call {index: usize},
    Jump {index: usize},
    JumpIfZero {index: usize},
    JumpIfNegative {index: usize},
    EndSubroutine,
    EndProgram,
    PrintChar,
    PrintNum,
    InputChar,
    InputNum
}

pub type Integer = isize;

pub type BigInteger = BigInt;

#[derive(Debug, Clone)]
pub enum SizedInteger {
    Big(BigInteger),
    Small(Integer)
}

impl Program {
    /// Remove source location information from the program.
    pub fn strip(&mut self) {
        self.source = None;
        self.locs = None;
    }

    /// Rewrites labels to ensure the resulting program is as small as possible.
    pub fn minify(&mut self) {
        // get the source locs, otherwise, invent some new sourcelocs.
        let locs = if let Some(ref mut locs) = self.locs {
            locs
        } else {
            self.locs = Some(self.commands.iter().map(|_| SourceLoc {line: 0, column: 0, span: 0..0, label: None}).collect());
            self.locs.as_mut().unwrap()
        };

        // create an index => times_used map
        let mut label_count = HashMap::new();
        for (i, op) in self.commands.iter().enumerate() {
            match *op {
                Command::Label => *label_count.entry(i + 1).or_insert(0) += 1,
                Command::Call {index}
                | Command::Jump {index}
                | Command::JumpIfZero {index}
                | Command::JumpIfNegative {index} => *label_count.entry(index).or_insert(0) += 1,
                _ => ()
            }
        }

        // turn the map into a list of (index, times_used) that is sorted by times_used
        let mut label_count: Vec<_> = label_count.into_iter().collect();
        label_count.sort_by_key(|&(_, w)| w);

        // create an allocator that produces unique labels, starting from the smallest possible label
        let mut length = 0usize;
        let mut value = 0usize;
        let mut new_label = || {
            // create label
            let mut label = Label::new();
            for i in 0..length {
                label.push(value & (1 << i) != 0);
            }
            // increment state
            value += 1;
            if value == (1 << length) {
                length += 1;
                value = 0;
            }
            Rc::new(label)
        };

        // from the sorted list, create a map of index => new_label
        let label_map: HashMap<_, _> = label_count.iter().rev().map(|&(i, _)| (i, new_label())).collect();

        // and edit locs using them.
        for ((i, op), loc) in self.commands.iter().enumerate().zip(locs) {
            match *op {
                Command::Label => loc.label = Some(label_map[&(i + 1)].clone()),
                Command::Call {index}
                | Command::Jump {index}
                | Command::JumpIfZero {index}
                | Command::JumpIfNegative {index} => loc.label = Some(label_map[&index].clone()),
                _ => ()
            }
        }
    }
}