summaryrefslogtreecommitdiff
path: root/src/core.rs
blob: f46fd5417d58b7b76526d72e3ea7720125039445 (plain)
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
// Copyright (c) 2025 taitep
// SPDX-License-Identifier: MIT
//
// This file is part of TRVE (https://gitea.taitep.se/taitep/trve)
// See LICENSE file in the project root for full license text.

use std::fmt::format;

use crate::{
    consts::{Addr, RegId, RegValue},
    decode::Instruction,
    exceptions::ExceptionType,
    instructions::find_and_exec,
    mem::MemConfig,
};

pub struct Core {
    pub(crate) x_regs: [RegValue; 32],
    pub(crate) pc: Addr,
    pub(crate) mem: MemConfig,
}

impl Core {
    pub fn new(mem: MemConfig) -> Self {
        Self {
            x_regs: [0; 32],
            pc: 0,
            mem,
        }
    }

    pub fn run(&mut self) {
        loop {
            if !self.pc.is_multiple_of(4) {
                self.throw_exception(ExceptionType::InstructionAddressMisaligned);
                break;
            }

            let instr = match self.mem.read_word(self.pc) {
                Ok(i) => i,
                Err(e) => {
                    self.throw_exception(e.to_exception_instr());
                    break;
                }
            };

            if instr == 0 {
                self.throw_exception(ExceptionType::IllegalInstruction);
                break;
            }

            if instr & 3 != 3 {
                // Compressed instruction - (currently) unsupported
                self.throw_exception(ExceptionType::IllegalInstruction);
                break;
            }

            let instr = Instruction(instr);

            if let Err(e) = find_and_exec(instr, self) {
                self.throw_exception(e);
                eprintln!("instr: {:08x}", instr.0);
                break;
            }
        }
    }

    fn throw_exception(&mut self, exception_type: ExceptionType) {
        eprintln!("Exception: {exception_type:?}");
        dbg!(self.pc, self.x_regs);
    }

    pub fn reset(&mut self, pc: Addr) {
        self.pc = pc;
    }

    pub(crate) fn reg_read(&self, id: RegId) -> RegValue {
        self.x_regs[id as usize]
    }

    pub(crate) fn reg_write(&mut self, id: RegId, value: RegValue) {
        if id == 0 {
            return;
        }
        self.x_regs[id as usize] = value;
    }

    pub(crate) fn advance_pc(&mut self) {
        self.pc = self.pc.wrapping_add(4);
    }
}