summaryrefslogtreecommitdiff
path: root/src/core.rs
blob: 162821607430e087ceb3cf2baabacf5c91222a27 (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
92
93
94
95
96
97
// 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 crate::{
    consts::{Addr, RegId, RegValue},
    decode::Instruction,
    instructions::find_runner,
    mem::MemConfig,
};

// placeholder - change when exception system is in place
pub(crate) type Exception = ();

pub(crate) enum InstructionResult {
    Normal,
    Exception(Exception),
    Pause,
}

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 {
            let page = (self.pc / 4096) as usize;
            let offset = (self.pc / 4) as u16;
            if !self.pc.is_multiple_of(4) {
                //replace eprint with logging, replace break with exception
                eprintln!("PC not aligned");
                break;
            }

            let instr = match self.mem.read_word(page, offset) {
                Ok(i) => i,
                Err(_) => {
                    eprintln!("Memory access fault while fetching instruction");
                    break;
                }
            };

            assert_eq!(instr & 3, 3, "Compressed instructions not supported");

            let instr = Instruction(instr);

            let runner = find_runner(instr);

            if let Some(runner) = runner {
                let res = runner(self, instr);

                match res {
                    InstructionResult::Normal => {}
                    InstructionResult::Exception(_e) => {
                        eprintln!("Exception from instruction");
                        break;
                    }
                    InstructionResult::Pause => {
                        eprintln!("Instruction asked for pause");
                        break;
                    }
                }
            } else {
                eprintln!("Invalid Instruction 0x{:08x} 0b{:032b}", instr.0, instr.0);
                break;
            }
        }
    }

    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;
    }
}