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
use std::collections::HashMap;
use std::rc::Rc;

pub mod commands;

#[derive(Debug, Clone)]
pub struct Operation {
  trigger: [bool; 2],
  force: [bool; 2],
  cont: [bool; 4],
  op: String,
  args: Vec<String>
}

impl Operation {
  pub fn op(&self) -> &str {
    &self.op
  }

  pub fn trigger(&self) -> [bool; 2] {
    self.trigger
  }
}

#[derive(Debug)]
struct StackFrame {
  store_load: Vec<Status>, // TODO move out
  ops: *const Operation,
  len: usize,
  pos: usize,
}

struct FrameHolder<'a, 'b> where 'b: 'a {
  frame: Option<StackFrame>,
  _lt: std::marker::PhantomData<&'a [Operation]>,
  state: &'b mut State,
}

impl<'a, 'b> FrameHolder<'a, 'b> where 'b: 'a  {
  fn new(state: &'b mut State, ops: &'a [Operation]) -> FrameHolder<'a, 'b> where 'b: 'a {
    FrameHolder {
      frame: Some(StackFrame { store_load: Vec::new(), ops: ops.as_ptr(), len: ops.len(), pos: 0 }),
      _lt: std::marker::PhantomData,
      state: state
    }
  }

  fn with<F, R>(mut self, f: F) -> R where F: FnOnce(&mut State) -> R {
    let frame = self.frame.take().unwrap();
    self.state.frames.push(frame);
    f(self.state)
  }
}

impl<'a, 'b> Drop for FrameHolder<'a, 'b> where 'b: 'a  {
  fn drop(&mut self) {
    self.state.frames.pop();
  }
}

#[derive(Debug)]
pub struct State {
  frames: Vec<StackFrame>,
  commands: HashMap<&'static str, Rc<Command>>,
}

impl State {
  pub fn new() -> State {
    State { frames: Vec::new(), commands: HashMap::new() }
  }

  pub fn register_command<T: 'static + Command>(&mut self, command: T) {
    self.commands.insert(command.get_name(), Rc::new(command));
  }

  pub fn get_op<F, R>(&self, f: F) -> R where F: FnOnce(&Operation) -> R {
    let op = unsafe {
      let frame = self.frames.last().unwrap();
      &std::slice::from_raw_parts(frame.ops, frame.len)[frame.pos]
    };
    f(op)
  }

  pub fn get_pos(&self) -> usize {
    self.frames.last().unwrap().pos
  }

  pub fn call(&mut self, prog: &[Operation]) -> Status {
    FrameHolder::new(self, prog).with(|x| x.run(0))
  }

  pub fn run(&mut self, from: usize) -> Status {
    let mut status = Status::Success;
    // `unsafe` means we're holding both an immutable and a mutable reference to `self` here
    // but it works
    let oldpos = self.frames.last_mut().unwrap().pos;
    let ops = unsafe {
      let frame = self.frames.last().unwrap();
      std::slice::from_raw_parts(frame.ops, frame.len)
    };
    for (pos, op) in ops.iter().enumerate().skip(from) {
      self.frames.last_mut().unwrap().pos = pos;
      status = if op.trigger[*status] {
        let newstatus = {
          if let Some(x) = self.commands.get(op.op.as_str()).map(|x| x.clone()) {
            x.run(self, status, &op.args)
          } else {
            Status::Failure
          }
        };
        if newstatus.is_return() {
          self.frames.last_mut().unwrap().pos = oldpos;
          return newstatus;
        }
        if op.cont[*status * 2 + *newstatus] {
          Status::Success
        } else {
          Status::Failure
        }
      } else if op.force[*status] {
        status
      } else {
        self.frames.last_mut().unwrap().pos = oldpos;
        return status;
      }
    }
    self.frames.last_mut().unwrap().pos = oldpos;
    status
  }
}

#[derive(Debug, Copy, Clone)]
pub enum Status {
  Failure,
  Success,
  ReturnFailure,
  ReturnSuccess,
}

impl Status {
  pub fn is_return(&self) -> bool {
    use Status::*;

    match *self {
      Failure | Success => false,
      ReturnFailure | ReturnSuccess => true,
    }
  }
}

impl std::ops::Deref for Status {
  type Target = usize;

  fn deref(&self) -> &usize {
    use Status::*;

    static ONE: usize = 1;
    static ZERO: usize = 0;
    match *self {
      Failure | ReturnFailure => &ZERO,
      Success | ReturnSuccess => &ONE,
    }
  }
}

impl std::ops::Not for Status {
  type Output = Status;

  fn not(self) -> Self::Output {
    use Status::*;

    match self {
      Failure => Success,
      Success => Failure,
      ReturnFailure => ReturnSuccess,
      ReturnSuccess => ReturnFailure,
    }
  }
}

impl std::ops::Neg for Status {
  type Output = Status;

  fn neg(self) -> Self::Output {
    use Status::*;

    match self {
      Failure => ReturnFailure,
      Success => ReturnSuccess,
      ReturnFailure => Failure,
      ReturnSuccess => Success,
    }
  }
}

impl From<bool> for Status {
  fn from(b: bool) -> Status {
    if b {
      Status::Success
    } else {
      Status::Failure
    }
  }
}

pub trait Command {
  fn get_name(&self) -> &'static str;

  fn run(&self, state: &mut State, status: Status, args: &[String]) -> Status;
}

impl std::fmt::Debug for Command {
  fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
    write!(fmt, "Command: {}", self.get_name())
  }
}


pub fn parse<I>(program: I) -> Vec<Operation> where I: Iterator<Item=char> {
  program.chain("\n".chars()).scan(String::new(), |state, x| {
    if x == '\r' || x == '\n' {
      let s = state.clone();
      state.clear();
      Some(Some(s))
    } else {
      state.push(x);
      Some(None)
    }
  }).flat_map(|x| x) // flatten
    .filter(|x| !x.is_empty())
    .filter(|x| !x.starts_with("#"))
    .map(|x| {
      let mut itr = x.chars();
      let trigger = itr.next().and_then(|c| c.to_digit(16)).unwrap();
      let cont = itr.next().and_then(|c| c.to_digit(16)).unwrap();
      if itr.next().unwrap() != ' ' { panic!(); }
      let mut parts = itr.as_str().split(' ');
      let op = parts.next().unwrap().to_owned();
      let args = parts.map(|x| x.to_owned()).collect();
      Operation {
        trigger: [trigger & 1 != 0, trigger & 2 != 0],
        force: [trigger & 4 != 0, trigger & 8 != 0],
        cont: [cont & 1 != 0, cont & 2 != 0, cont & 4 != 0, cont & 8 != 0],
        op: op,
        args: args
      }
    })
    .collect()
}