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
// Copyright (c) 2021 Saadi Save
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::{
    collections::BTreeMap,
    fmt::{Debug, Display, Formatter, Result as FmtResult},
};

/// # Arithmetic
/// Module for arithmetic operations
#[allow(clippy::needless_pass_by_value, clippy::enum_glob_use)]
pub mod arith;

/// # I/O
/// Module for input, output and debugging
#[allow(clippy::needless_pass_by_value, clippy::enum_glob_use)]
pub mod io;

/// # Data movement
/// Module for moving data between registers and memory locations
#[allow(clippy::needless_pass_by_value, clippy::enum_glob_use)]
pub mod mov;

/// # Comparison
/// Module for making logical comparisons
#[allow(clippy::needless_pass_by_value, clippy::enum_glob_use)]
pub mod cmp;

/// # Bit manipulation
/// Module for logical bit manipulation
#[allow(clippy::needless_pass_by_value, clippy::enum_glob_use)]
pub mod bitman;

#[allow(clippy::enum_glob_use)]
mod error;

mod memory;

#[allow(clippy::enum_glob_use)]
mod inst;

pub use error::{PasmError, PasmResult, Source};

pub use memory::{MemEntry, Memory};

pub use inst::{Inst, Op, OpFun};

#[derive(Debug, Default)]
pub struct Context {
    pub cmp: bool,
    pub mar: usize,
    pub acc: usize,
    pub ix: usize,
    pub flow_override_reg: bool,
    pub mem: Memory,
    pub ret: usize,
    pub gprs: [usize; 30],
    pub end: bool,
}

impl Context {
    pub fn new(mem: Memory) -> Self {
        Self {
            mem,
            ..Context::default()
        }
    }

    #[inline]
    pub fn override_flow_control(&mut self) {
        self.flow_override_reg = true;
    }

    /// # Panics
    /// If `op` is not a `usize` register. To avoid this, check `op` using [`Op::is_register`].
    #[inline]
    pub fn get_mut_register(&mut self, op: &Op) -> &mut usize {
        match op {
            Op::Acc => &mut self.acc,
            Op::Ix => &mut self.ix,
            Op::Ar => &mut self.ret,
            Op::Gpr(x) => &mut self.gprs[*x],
            _ => unreachable!(),
        }
    }

    /// # Panics
    /// If `op` is not a `usize` register. To avoid this, check `op` using [`Op::is_register`].
    #[inline]
    pub fn get_register(&self, op: &Op) -> usize {
        match op {
            Op::Acc => self.acc,
            Op::Ix => self.ix,
            Op::Ar => self.ret,
            Op::Gpr(x) => self.gprs[*x],
            _ => unreachable!(),
        }
    }

    /// # Panics
    /// If `op` is not writable. To avoid this, check `op` using [`Op::is_read_write`].
    #[inline]
    pub fn modify(&mut self, op: &Op, f: impl Fn(&mut usize)) -> PasmResult {
        match op {
            Op::Loc(x) => {
                let mut res = self.mem.get(x)?;
                f(&mut res);
                self.mem.write(x, res)?;
            }
            op if op.is_register() => f(self.get_mut_register(op)),
            _ => unreachable!(),
        }

        Ok(())
    }
}

impl Display for Context {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("Context {\n")?;
        f.write_fmt(format_args!("{:>6}: {}\n", "mar", self.mar))?;
        f.write_fmt(format_args!("{:>6}: {}\n", "acc", self.acc))?;
        f.write_fmt(format_args!("{:>6}: {}\n", "ix", self.ix))?;
        f.write_fmt(format_args!("{:>6}: {}\n", "cmp", self.cmp))?;
        f.write_fmt(format_args!(
            "{:>6}: {}\n",
            "gprs",
            self.gprs
                .iter()
                .enumerate()
                .fold(String::from("["), |s, (num, val)| {
                    if num == self.gprs.len() - 1 {
                        format!("{s}r{num} = {val}]")
                    } else {
                        format!("{s}r{num} = {val}, ")
                    }
                })
        ))?;
        f.write_fmt(format_args!("{:>6}: Memory {{\n", "mem"))?;

        for (addr, entry) in self.mem.iter() {
            f.write_fmt(format_args!("{addr:>8}: {entry},\n"))?;
        }

        f.write_fmt(format_args!("{:>3}}}\n", ""))?;

        f.write_str("}")
    }
}

pub type ExTree = BTreeMap<usize, Inst>;

pub struct Executor {
    pub source: Source,
    pub prog: ExTree,
    pub ctx: Context,
    count: u64,
}

impl Executor {
    pub fn new(source: impl Into<Source>, prog: ExTree, ctx: Context) -> Self {
        Self {
            source: source.into(),
            prog,
            ctx,
            count: 0,
        }
    }

    pub fn exec(&mut self) {
        loop {
            if self.ctx.mar == self.prog.len() || self.ctx.end {
                break;
            }

            self.count += 1;

            trace!("Executing line {}", self.ctx.mar + 1);

            let inst = if let Some(inst) = self.prog.get(&self.ctx.mar) {
                inst
            } else {
                panic!("Unable to fetch instruction. Please report this as a bug with full debug logs attached.")
            };

            match (inst.opfun)(&mut self.ctx, &inst.op) {
                Ok(_) => (),
                Err(e) => {
                    self.source.handle_err(&e, self.ctx.mar);
                    return;
                }
            }

            if self.ctx.flow_override_reg {
                self.ctx.flow_override_reg = false;
            } else {
                self.ctx.mar += 1;
            }
        }

        debug!("Total instructions executed: {}", self.count);
    }
}

impl Display for Executor {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("Executor {\n")?;
        for (addr, Inst { op, .. }) in &self.prog {
            f.write_fmt(format_args!("{addr:>6}: {op}\n", op = op.to_string()))?;
        }
        f.write_str("}")
    }
}

impl Debug for Executor {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.debug_struct("Executor")
            .field("source", &self.source)
            .field(
                "prog",
                &self
                    .prog
                    .iter()
                    .map(|(addr, Inst { op, .. })| (addr, op))
                    .collect::<Vec<_>>(),
            )
            .field("ctx", &self.ctx)
            .field("count", &self.count)
            .finish()
    }
}

#[cfg(test)]
#[test]
fn exec() {
    use std::collections::BTreeMap;

    let prog: BTreeMap<usize, Inst> = BTreeMap::from(
        // Division algorithm from pg 101 of textbook
        [
            (0, Inst::new(mov::ldd, "200".into())),
            (1, Inst::new(mov::sto, "202".into())),
            (2, Inst::new(mov::sto, "203".into())),
            (3, Inst::new(mov::ldd, "202".into())),
            (4, Inst::new(arith::inc, "ACC".into())),
            (5, Inst::new(mov::sto, "202".into())),
            (6, Inst::new(mov::ldd, "203".into())),
            (7, Inst::new(arith::add, "201".into())),
            (8, Inst::new(mov::sto, "203".into())),
            (9, Inst::new(cmp::cmp, "204".into())),
            (10, Inst::new(cmp::jpn, "3".into())),
            (11, Inst::new(mov::ldd, "202".into())),
            (12, Inst::new(io::out, "".into())),
            (13, Inst::new(io::end, "".into())),
        ],
    );

    let mem: BTreeMap<usize, MemEntry> = BTreeMap::from([
        (200, 0.into()),
        (201, 5.into()),
        (202, 0.into()),
        (203, 0.into()),
        (204, 75.into()),
    ]);

    let mut exec = Executor::new("None", prog, Context::new(Memory::new(mem)));

    exec.exec();

    assert_eq!(exec.ctx.acc, 15);
}