20 Commits

Author SHA1 Message Date
zxq5 05a25447b2 minor optimisation to reduce unnecessary allocations 2025-06-28 03:43:20 +01:00
zxq5 56d2abe17f - optimised main emulator loop, allowing updates only once every roughly 32,000 instructions.
- optimised memory access patterns, removing unecessary mutability and accesses.
- replaced the standard HashMap with an implementation that uses a faster hashing algorithm.

results:

before:
    - our benchmark program with ~4m instructions would take around for their data to make it to the UI, and a bit over 200ms to actually run

after:
    - our benchmark program with ~4m instructions can run in around 75ms, and the UI receives the update almost instantly.

conclusion:
- emulator performance should be around 2-3x faster than before.
2025-06-28 03:21:46 +01:00
zxq5 eaaefd1b07 added rule to .gitignore 2025-06-27 18:31:52 +01:00
zxq5 5302ad3876 removed junk files 2025-06-27 18:30:53 +01:00
zxq5 2280f1e5d9 updated vscode settings 2025-06-27 18:30:26 +01:00
zxq5 ae92510fb8 dsa lib bugfixes 2025-06-26 20:53:51 +01:00
zxq5 7c63340888 minor changes to assembler 2025-06-26 20:53:22 +01:00
zxq5 e9f04824ea updates to dsa libs 2025-06-26 00:51:20 +01:00
zxq5 620584488b fixed unit tests & misc changes to workspace config 2025-06-26 00:50:58 +01:00
zxq5 1101331f70 fixed a couple of emulator bugs, including fixing shift instructions. finished implementing lib/io/print/print_hex_byte and print_hex_word 2025-06-25 16:31:42 +01:00
zxq5 c171b0db89 worked on print.dsa and maths/core.dsa 2025-06-25 00:40:31 +01:00
zxq5 82b99c127c finished initial interrupts implementation 2025-06-25 00:13:55 +01:00
nullndvoid 92c4660a4d misc: get rid of some errors from Cargo lol 2025-06-24 21:55:11 +01:00
zxq5 2a6991fe4a idk, i refactored some stuff ig 2025-06-24 19:34:45 +01:00
zxq5 0fdd28aad1 finished the interpreter 2025-06-24 19:31:55 +01:00
zxq5 f639240b6c progress on debugging bf.dsa 2025-06-24 18:07:33 +01:00
zxq5 d2c1492dca added step(n) feature to emulator, allowing for stepping n instructions at a time 2025-06-24 18:07:11 +01:00
zxq5 4ef8bbdf46 updated dependencies 2025-06-24 18:06:29 +01:00
zxq5 76197fac8f finished refactor of emulator - started on loader (needs significant changes before functional in the way that I would like) 2025-06-23 23:45:47 +01:00
zxq5 bc5ddef311 added error handling to emulator 2025-06-23 21:28:38 +01:00
50 changed files with 2025 additions and 1239 deletions
+7
View File
@@ -0,0 +1,7 @@
[build]
rustc-wrapper = "sccache"
# Enable to cut unused deps.
# rustflags = ["-D", "unused-crate-dependencies"]
[future-incompat-report]
frequency = "always"
+1
View File
@@ -1,2 +1,3 @@
/target
**/*.env
book
+7 -1
View File
@@ -5,5 +5,11 @@
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"files.trimTrailingWhitespace": true
"files.trimTrailingWhitespace": true,
"gitea.owner": "LowLevelDevs",
"gitea.repo": "damn_simple_architecture",
"[markdown]": {
"editor.formatOnSave": true,
"editor.formatOnPaste": true
}
}
Generated
+31 -29
View File
@@ -424,9 +424,9 @@ dependencies = [
[[package]]
name = "autocfg"
version = "1.4.0"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "bit-set"
@@ -783,9 +783,9 @@ dependencies = [
[[package]]
name = "discord-presence"
version = "1.6.0"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91d7c2fc01ffdc327e2b66d65dd59b8bd3f31a17e88811ce0540412fa0b84c1"
checksum = "91948dab8ccaaefeb7be5f21714ed774411df66830def1f99dd74e7a85f5f111"
dependencies = [
"byteorder",
"bytes",
@@ -1027,6 +1027,7 @@ dependencies = [
"eframe",
"egui",
"egui_file",
"rustc-hash 2.1.1",
"serde",
"toml",
"winit",
@@ -1091,12 +1092,12 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.12"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -1641,9 +1642,9 @@ dependencies = [
[[package]]
name = "jpeg-decoder"
version = "0.3.1"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0"
checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
[[package]]
name = "js-sys"
@@ -1674,9 +1675,9 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "libc"
version = "0.2.173"
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8cfeafaffdbc32176b64fb251369d52ea9f0a8fbc6f8759edffef7b525d64bb"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "libloading"
@@ -1909,18 +1910,19 @@ dependencies = [
[[package]]
name = "num_enum"
version = "0.7.3"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179"
checksum = "a973b4e44ce6cad84ce69d797acf9a044532e4184c4f267913d1b546a0727b7a"
dependencies = [
"num_enum_derive",
"rustversion",
]
[[package]]
name = "num_enum_derive"
version = "0.7.3"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56"
checksum = "77e878c846a8abae00dd069496dbe8751b16ac1c3d6bd2a7283a938e8228f90d"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2435,9 +2437,9 @@ dependencies = [
[[package]]
name = "profiling"
version = "1.0.16"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afbdc74edc00b6f6a218ca6a5364d6226a259d4b8ea1af4a0ea063f27e179f4d"
checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773"
[[package]]
name = "quick-xml"
@@ -2495,9 +2497,9 @@ dependencies = [
[[package]]
name = "r-efi"
version = "5.2.0"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
@@ -2855,9 +2857,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.103"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
@@ -3046,9 +3048,9 @@ dependencies = [
[[package]]
name = "tracing-attributes"
version = "0.1.29"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b1ffbcf9c6f6b99d386e7444eb608ba646ae452a36b39737deb9663b610f662"
checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
dependencies = [
"proc-macro2",
"quote",
@@ -3987,9 +3989,9 @@ checksum = "ec107c4503ea0b4a98ef47356329af139c0a4f7750e621cf2973cd3385ebcb3d"
[[package]]
name = "xcursor"
version = "0.3.8"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ef33da6b1660b4ddbfb3aef0ade110c8b8a781a3b6382fa5f2b5b040fd55f61"
checksum = "635887f4315a33cb714eb059bdbd7c1c92bfa71bc5b9d5115460502f788c2ab5"
[[package]]
name = "xdg-home"
@@ -4151,18 +4153,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.25"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.25"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
+13
View File
@@ -1,3 +1,5 @@
cargo-features = ["codegen-backend"]
[workspace]
members = ["emulator", "common", "assembler", "dsa_editor"]
resolver = "3"
@@ -6,3 +8,14 @@ resolver = "3"
version = "0.2.0"
edition = "2024"
authors = ["zxq5", "nullndvoid"]
[profile.dev]
codegen-backend = "cranelift"
panic = "abort" # Cranelift does not support stack unwinds.
lto = false
debug = true
incremental = false # sccache does not support caching incremental crates.
[profile.release]
debug = true
lto = "fat"
+28 -33
View File
@@ -1,34 +1,29 @@
++++++++++++++++++++++++++++++++++++++++++++ c1v44 : ASCII code of comma
>++++++++++++++++++++++++++++++++ c2v32 : ASCII code of space
>++++++++++++++++ c3v11 : quantity of numbers to be calculated
> c4v0 : zeroth Fibonacci number (will not be printed)
>+ c5v1 : first Fibonacci number
<< c3 : loop counter
[ block : loop to print (i)th number and calculate next one
>> c5 : the number to be printed
block : divide c5 by 10 (preserve c5)
> c6v0 : service zero
>++++++++++ c7v10 : divisor
<< c5 : back to dividend
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] c5v0 : divmod algo; results in 0 n d_n%d n%d n/d
>[<+>-] c5 : move dividend back to c5 and clear c6
>[-] c7v0 : clear c7
>> block : c9 can have two digits; divide it by ten again
>++++++++++ c10v10: divisor
< c9 : back to dividend
[->-[>+>>]>[+[-<+>]>+>>]<<<<<] c9v0 : another divmod algo; results in 0 d_n%d n%d n/d
>[-] c10v0 : clear c10
>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]c12v0 : print nonzero n/d (first digit) and clear c12
<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]] c11v0 : print nonzero n%d (second digit) and clear c11
<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-] c8v0 : print any n%d (last digit) and clear c8
<<<<<<<.>. c1c2 : print comma and space
block : actually calculate next Fibonacci in c6
>>[>>+<<-] c4v0 : move c4 to c6 (don't need to preserve it)
>[>+<<+>-] c5v0 : move c5 to c6 and c4 (need to preserve it)
>[<+>-] c6v0 : move c6 with sum to c5
<<<- c3 : decrement loop counter
++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++
>++++++++++++++++
>
>+
<<
[
>>
>
>++++++++++
<<
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
>[<+>-]
>[-]
>>
>++++++++++
<
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
>[-]
>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]
<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]
<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]
<<<<<<<.>.
>>[>>+<<-]
>[>+<<+>-]
>[<+>-]
<<<-
]
<<++... c1 : output three dots
<<++...
Binary file not shown.
+1 -4
View File
@@ -11,10 +11,7 @@ pub fn codegen(nodes: Vec<Node>) -> Result<Vec<Instruction>, AssembleError> {
let mut instructions = vec![];
for node in nodes {
instructions.push(
build_instruction(&node)
.unwrap_or_else(|_| panic!("Failed to build instruction: {node:?}")),
);
instructions.push(build_instruction(&node)?);
}
println!("------------------------");
+10 -2
View File
@@ -7,12 +7,11 @@ use common::prelude::Register;
pub fn lexer(mut program: String, module: u64) -> Result<Vec<Token>, AssembleError> {
let mut tokens = Vec::new();
program = program.replace(',', "");
let lines = program.lines();
let mut literal = String::new();
for line in lines {
for token in line.split_whitespace() {
for (i, token) in line.split_whitespace().enumerate() {
if token.starts_with("//") {
break;
}
@@ -23,7 +22,9 @@ pub fn lexer(mut program: String, module: u64) -> Result<Vec<Token>, AssembleErr
if !literal.is_empty() {
if !token.starts_with('"') {
if i > 0 {
literal.push(' ');
}
literal.push_str(token);
}
@@ -37,6 +38,11 @@ pub fn lexer(mut program: String, module: u64) -> Result<Vec<Token>, AssembleErr
continue;
}
let token = token.trim_end_matches(',');
if token.is_empty() {
continue;
}
if let Some(token) = parse_register(token)? {
tokens.push(token);
} else if let Some(token) = parse_opcode(token)? {
@@ -59,6 +65,8 @@ pub fn lexer(mut program: String, module: u64) -> Result<Vec<Token>, AssembleErr
}
}
println!("{:#?}", tokens);
Ok(tokens)
}
pub fn parse_register(token: &str) -> Result<Option<Token>, AssembleError> {
-1
View File
@@ -1,7 +1,6 @@
//! Macros used throughout the assembler
use crate::assembler::model::{Node, Opcode, Symbol, Token};
/// Parse DSA assembly code with optional formatting
///
/// # Examples
+22 -3
View File
@@ -51,19 +51,26 @@ impl fmt::Display for Node {
.as_ref()
.map_or_else(String::new, |symbol| format!("{symbol}:\n"));
let args = self
.args()
.into_iter()
.map(|arg| arg.to_string())
.collect::<Vec<_>>()
.join(" ");
write!(
f,
"\x1b[93m{} \t\x1b[94m{} \x1b[37m{:?} \x1b[0m",
"\x1b[93m{} \t\x1b[94m{} \x1b[37m{} \x1b[0m",
symbol,
self.opcode(),
self.args()
args,
)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ( module: {})", self.name, self.module)
write!(f, "{} [ID:{}]", self.name, self.module)
}
}
@@ -174,6 +181,18 @@ pub enum Token {
Opcode(Opcode),
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Symbol(symbol) => write!(f, "{}", symbol),
Self::Register(register) => write!(f, "{}", register),
Self::Immediate(immediate) => write!(f, "{}", immediate),
Self::StringLit(string_lit) => write!(f, "{}", string_lit),
Self::Opcode(opcode) => write!(f, "{}", opcode),
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum TokenType {
Symbol,
+4 -6
View File
@@ -113,11 +113,10 @@ impl Parser {
let dest = expect_type!(self.next()?, Register)?;
let mut offset = Token::Immediate(0);
if let Ok(next) = self.peek_next() {
if expect_type!(next, Immediate).is_ok() {
if let Ok(next) = self.peek_next()
&& expect_type!(next, Immediate).is_ok() {
offset = self.next()?;
}
}
args = vec![base, dest, offset];
}
@@ -125,11 +124,10 @@ impl Parser {
let base = expect_type!(self.next()?, Register)?;
let dest = expect_type!(self.next()?, Register, Symbol)?;
let mut offset = Token::Immediate(0);
if let Ok(next) = self.peek_next() {
if expect_type!(next, Immediate).is_ok() {
if let Ok(next) = self.peek_next()
&& expect_type!(next, Immediate).is_ok() {
offset = self.next()?;
}
}
args = vec![base, dest, offset];
}
+6 -1
View File
@@ -13,11 +13,16 @@
)]
pub mod assembler;
pub mod brainf;
pub mod image_builder;
pub mod tooling;
mod util;
pub mod prelude {
pub use crate::assembler::CompilerEngine;
pub use crate::image_builder;
pub use crate::tooling::brainf;
pub use crate::tooling::project;
}
use num_cpus as _;
use threadpool as _;
+11 -4
View File
@@ -1,4 +1,11 @@
use assembler::{brainf, prelude::*};
use common as _;
use num_cpus as _;
use threadpool as _;
use assembler::{
prelude::*,
tooling::{brainf, project},
};
use std::{fs, io::Write, path::PathBuf};
fn main() {
@@ -16,7 +23,7 @@ fn main() {
let mut file = match fs::File::create("brainf.dsb") {
Err(e) => {
eprintln!("Failed to create output file: {}", e);
eprintln!("Failed to create output file: {e}");
std::process::exit(1);
}
Ok(file) => file,
@@ -24,7 +31,7 @@ fn main() {
for instruction in result {
if let Err(e) = file.write(&instruction.encode().to_be_bytes()) {
eprintln!("Failed to write to output file: {}", e);
eprintln!("Failed to write to output file: {e}");
std::process::exit(1);
}
}
@@ -50,7 +57,7 @@ fn main() {
for instruction in result {
if let Err(e) = fs::write(output_path, instruction.encode().to_be_bytes()) {
eprintln!("Failed to write to output file: {}", e);
eprintln!("Failed to write to output file: {e}");
std::process::exit(1);
}
}
+1
View File
@@ -1 +1,2 @@
pub mod brainf;
pub mod project;
+1
View File
@@ -0,0 +1 @@
disallowed-types = ["std::collections::HashMap", "std::collections::HashSet"]
+14 -6
View File
@@ -3,13 +3,19 @@ use crate::{instructions::encode::Encode, prelude::*};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Interrupt {
Software(u8),
Breakpoint,
HardFault,
}
pub type Address = u32;
impl Interrupt {
const fn as_u8(self) -> u8 {
// someone tell clippy to stfu.
#[allow(clippy::must_use_candidate)]
pub const fn as_u8(self) -> u8 {
match self {
Self::Breakpoint => 0,
Self::HardFault => 1,
Self::Software(code) => code,
}
}
@@ -19,10 +25,11 @@ impl Interrupt {
impl From<u8> for Interrupt {
#[allow(unreachable_code)]
fn from(code: u8) -> Self {
return Self::Software(code);
todo!("Implement this once a hardware interrupt convention is established.");
// Self::Software(_code)
match code {
0 => Self::Breakpoint,
1 => Self::HardFault,
_ => Self::Software(code),
}
}
}
@@ -73,7 +80,8 @@ pub enum Register {
}
impl Register {
#[must_use]
// this is here so clippy shuts up about the must_use tag.
#[allow(clippy::must_use_candidate)]
pub fn general() -> Vec<Self> {
vec![
Self::Rg0,
+5 -3
View File
@@ -54,12 +54,14 @@ impl Encode for Instruction {
],
no_args: [Nop, IntReturn, Halt],
special: [
Self::Interrupt(_) => todo!(),
Self::Data(data) => data,
Self::Interrupt(interrupt) => {
let opcode = u32::from(self.opcode());
(opcode << 26) | u32::from(interrupt.as_u8())
},
Self::Segment(segment) => {
let opcode = u32::from(self.opcode());
let segment = segment as u8;
(opcode << 26) | u32::from(segment)
(opcode << 26) | u32::from(segment as u8)
}
]
)
+6 -3
View File
@@ -17,20 +17,20 @@ required-features = ["config"]
common = { path = "../common" }
assembler = { path = "../assembler" }
dsa_editor = { path = "../dsa_editor" }
eframe = { version = "0.31.1" }
egui = "0.31.1"
dirs = "6.0.0"
discord-presence = { version = "1.6.0", optional = true }
discord-presence = { version = "2.0.0", optional = true }
toml = { version = "0.8.23", optional = true }
serde = { version = "1.0.219", features = ["derive"], optional = true }
egui_file = "0.22.1"
rustc-hash = "2.1.1"
[features]
default = ["config"]
discord-rpc = ["dep:discord-presence"]
config = ["dep:toml", "dep:serde"]
# Add support for Android for the fun of it.
# Add support for Android for the fun of it. Currently crashes lol.
[target.'cfg(target_os = "android")'.dependencies]
winit = { version = "0.30.11", features = ["android-native-activity"] }
# jni = "0.21.1"
@@ -38,3 +38,6 @@ winit = { version = "0.30.11", features = ["android-native-activity"] }
[target.'cfg(target_os = "android")'.dependencies.eframe]
version = "0.31.1"
features = ["android-native-activity"]
[target.'cfg(not(target_os = "android"))'.dependencies.eframe]
version = "0.31.1"
+119 -96
View File
@@ -1,15 +1,12 @@
use std::sync::Arc;
use std::{
sync::mpsc::{self, Receiver, Sender},
thread,
time::Duration,
};
use std::sync::mpsc::{self, Receiver, Sender};
#[allow(unused_imports)]
use crate::emulator::misc::rpc::{Activity, RpcClient};
use crate::emulator::system::model::StateUpdate;
use crate::emulator::system::{
model::{Command, PersistentState, Running, State},
model::{Command, Running},
processor::Processor,
};
@@ -19,28 +16,35 @@ use common::prelude::*;
#[allow(unused_variables)]
pub fn run_emulator(
cmd_rx: &Receiver<Command>,
state_tx: &Sender<State>,
state_tx: &Sender<StateUpdate>,
mut processor: Processor,
rpc_client: Option<&Arc<RpcClient>>,
) {
println!("INFO: Starting emulator.");
let mut running = Running::Paused;
let mut addr = 0u32;
let mut history = Vec::<(u32, Instruction)>::new();
let mut step = 0;
let mut addr;
let mut history = Vec::<(u32, Instruction)>::with_capacity(32768);
let size = 256;
let memory_view = processor.memory.read_range(addr, size);
let initial_state = state(&mut processor, running, 0, memory_view, &mut history);
let _ = state_tx.send(initial_state);
state_tx
.send(StateUpdate::Running(Running::Paused))
.expect("Failed to send initial state!");
let mut instruction_count = 0;
let mut update = false;
loop {
let cmd = if running == Running::Running {
let cmd = if step > 0 {
None
} else if running == Running::Running && step == 0 {
match cmd_rx.try_recv() {
Ok(cmd) => Some(cmd),
Err(mpsc::TryRecvError::Empty) => None,
Err(mpsc::TryRecvError::Empty) => {
update = false;
None
}
Err(mpsc::TryRecvError::Disconnected) => break,
}
} else {
@@ -50,10 +54,15 @@ pub fn run_emulator(
}
};
if running == Running::Running && step == 0 {
step = 32768;
}
if let Some(cmd) = cmd {
match cmd {
Command::Start => {
running = Running::Running;
step = 32768;
// Update RPC with current state. TODO: Make this only occur on state
// changes.
@@ -69,9 +78,11 @@ pub fn run_emulator(
}
Command::Stop => {
running = Running::Paused;
step = 0;
}
Command::Reset(x) => {
running = Running::Paused;
step = 0;
match x {
0 => {
@@ -91,8 +102,71 @@ pub fn run_emulator(
processor.reset();
}
Command::Step => {
Command::Step(x) => {
step = x;
running = Running::Paused;
}
Command::Write(offset, data) => {
update = true;
processor.memory.write_range(offset, data);
}
Command::Interrupt(_interrupt) => {
update = true;
todo!("implement interrupts")
}
Command::MemRequest(new, size) if update => {
addr = new;
let _ = state_tx.send(StateUpdate::MemoryView(
processor.memory.read_range(addr, size),
));
}
Command::DisplayRequest if update => {
let _ = state_tx.send(StateUpdate::DisplayView(
processor.display().unwrap_or_else(|_| {
report_err(
state_tx,
"Failed to read display!",
&mut processor,
);
Vec::new()
}),
));
}
Command::StackRequest if update => {
let _ = state_tx.send(StateUpdate::StackView(
processor.get_stack(32).unwrap_or_else(|_| {
report_err(state_tx, "Failed to read stack!", &mut processor);
Vec::new()
}),
));
}
Command::RegisterRequest if update => {
let _ = state_tx.send(StateUpdate::Registers(processor.registers));
}
Command::RunningRequest if update => {
let _ = state_tx.send(StateUpdate::Running(running));
}
Command::HistoryRequest if update => {
let hsc = history.clone();
history.clear();
let _ = state_tx.send(StateUpdate::InstructionHistory(hsc));
}
Command::InstructionCountRequest if update => {
let _ = state_tx.send(StateUpdate::Instructions(instruction_count));
}
Command::WriteBlock(addr, block) => {
processor.memory.write_range(addr, block.to_vec());
}
_ => {}
}
}
if running == Running::Paused && step > 0 {
step -= 1;
update = true;
// Execute one cycle.
match processor.cycle() {
@@ -100,109 +174,58 @@ pub fn run_emulator(
history.push((addr, instruction));
}
Err(why) => {
let pcx = processor.get(Register::Pcx);
eprintln!(
let pcx = processor
.get(Register::Pcx)
.expect("SPR should never be invalid");
report_err(
state_tx,
&format!(
"Could not decode instruction at {pcx:x}. Reason: {why}"
);
continue;
}
}
instruction_count += 1;
}
Command::Read(new, _size) => {
addr = new;
}
Command::Write(offset, data) => {
processor.memory.write_range(offset, data);
}
Command::Interrupt(_interrupt) => {
todo!("implement interrupts")
}
}
let memory_view = processor.memory.read_range(addr, size);
let state = state(
),
&mut processor,
running,
instruction_count,
memory_view,
&mut history,
);
println!("state");
let _ = state_tx.send(state);
}
}
instruction_count += 1;
continue;
}
if running == Running::Running {
let mut update = false;
step -= 1;
update = true;
// Execute one cycle.
let instruction = match processor.cycle() {
Ok(instruction) => instruction,
Err(why) => {
let pcx = processor.get(Register::Pcx);
eprintln!("Could not decode instruction at {pcx:x}. Reason: {why}");
continue;
let pcx = processor
.get(Register::Pcx)
.expect("PCX should never be invalid");
report_err(
state_tx,
&format!(
"Could not decode instruction at {pcx:x}. Reason: {why}"
),
&mut processor,
);
(pcx, Instruction::Nop)
}
};
history.push(instruction);
// let instruction = match Instruction::decode(cpu_lock.get(Register::Cir))
// {};
if matches!(instruction.1, Instruction::Halt) {
running = Running::Halted;
update = true;
step = 0;
}
instruction_count += 1;
// Send state updates every 100 instructions
if instruction_count % 100 == 0 {
update = true;
}
if update {
let memory_view = processor.memory.read_range(addr, size);
let state = state(
&mut processor,
running,
instruction_count,
memory_view,
&mut history,
);
println!("running state");
// println!("state!!! {:?}", state.history);
let _ = state_tx.send(state);
}
} else {
thread::sleep(Duration::from_millis(1));
}
}
}
fn state(
cpu_lock: &mut Processor,
running: Running,
instruction_count: usize,
memory_view: Vec<u8>,
history: &mut Vec<(u32, Instruction)>,
) -> State {
let hsclone = history.clone();
history.clear();
State {
// TODO: Replace with actual register access from your CPU.
reg_file: cpu_lock.registers,
running,
instructions: instruction_count,
stack_view: cpu_lock.get_stack(32),
memory_view,
display_view: cpu_lock.display(),
error: None,
persistent: PersistentState { history: hsclone },
}
fn report_err(state_tx: &Sender<StateUpdate>, why: &str, processor: &mut Processor) {
processor
.begin_interrupt(Interrupt::HardFault)
.expect("What kind of goofy ahh shenanigans did you do with your fault handler? At this point, the emulator can just crash. this is on you.");
let _ = state_tx.send(StateUpdate::Error(why.to_string()));
}
+91 -48
View File
@@ -1,23 +1,51 @@
use std::collections::HashMap;
use rustc_hash::FxHashMap;
use crate::emulator::system::model::ProcessorError;
pub trait MemoryUnit: Send + Sync {
fn reset(&mut self);
fn read_byte(&mut self, addr: u32) -> u8;
fn write_byte(&mut self, addr: u32, value: u8);
fn read_word(&mut self, addr: u32) -> u32;
fn write_word(&mut self, addr: u32, value: u32);
fn read_range(&mut self, addr: u32, size: u32) -> Vec<u8>;
fn write_range(&mut self, addr: u32, value: Vec<u8>);
fn read_word(&mut self, addr: u32) -> Result<u32, ProcessorError>;
fn write_word(&mut self, addr: u32, value: u32) -> Result<(), ProcessorError>;
fn read_range(&mut self, addr: u32, size: u32) -> Vec<u8> {
let mut data = Vec::with_capacity(size as usize);
for i in 0..size {
data.push(self.read_byte(addr + i));
}
data
}
fn write_range(&mut self, addr: u32, value: Vec<u8>) {
for (i, byte) in value.into_iter().enumerate() {
self.write_byte(addr + i as u32, byte);
}
}
fn read_block(&mut self, addr: u32) -> &[u8; 256];
fn write_block(&mut self, addr: u32, data: &[u8; 256]) {
for (i, byte) in data.iter().enumerate() {
self.write_byte(addr + i as u32, *byte);
}
}
}
pub struct MainStore {
pub data: HashMap<u32, Block>,
pub data: FxHashMap<u32, Block>,
}
pub struct Block {
data: [u8; 256],
}
impl Default for Block {
fn default() -> Self {
Self { data: [0; 256] }
}
}
impl Default for MainStore {
fn default() -> Self {
Self::new()
@@ -28,95 +56,110 @@ impl MainStore {
#[must_use]
pub fn new() -> Self {
Self {
data: HashMap::new(),
data: FxHashMap::default(),
}
}
#[inline]
const fn segment_addr(addr: u32) -> (u32, u8) {
(addr / 256, (addr % 256) as u8)
}
#[inline]
fn mut_block(&mut self, addr: u32) -> &mut Block {
self.data
.entry(addr)
.or_insert_with(|| Block { data: [0; 256] });
self.data.get_mut(&addr).map_or_else(
|| panic!("Could not fetch block with address {addr:x?}"),
|block| block,
)
self.data.entry(addr).or_default()
}
#[inline]
fn block(&mut self, addr: u32) -> &Block {
self.data
.entry(addr)
.or_insert_with(|| Block { data: [0; 256] });
self.data.get(&addr).map_or_else(
|| panic!("Could not fetch block with address {addr:x?}"),
|block| block,
)
self.data.entry(addr).or_default()
}
}
impl MemoryUnit for MainStore {
#[inline]
fn reset(&mut self) {
self.data.clear();
}
#[inline]
fn read_byte(&mut self, addr: u32) -> u8 {
let (block_addr, offset) = Self::segment_addr(addr);
let block = self.block(block_addr);
block.data[offset as usize]
}
fn read_word(&mut self, addr: u32) -> u32 {
let (block_addr, offset) = Self::segment_addr(addr);
println!("reading word from {block_addr:x?} + {offset}");
let block = self.mut_block(block_addr);
let mut bytes = [0; 4];
bytes[0] = block.data[offset as usize];
bytes[1] = block.data[(offset + 1) as usize];
bytes[2] = block.data[(offset + 2) as usize];
bytes[3] = block.data[(offset + 3) as usize];
u32::from_be_bytes(bytes)
#[inline]
fn read_word(&mut self, addr: u32) -> Result<u32, ProcessorError> {
if addr % 4 != 0 {
return Err(ProcessorError::BadMemoryAccess(addr));
}
let (block_addr, offset) = Self::segment_addr(addr);
let offset = offset as usize;
let block = self.block(block_addr);
Ok(u32::from_be_bytes(
block.data[offset..=offset + 3]
.try_into()
.expect("Failed to read word!"),
))
}
#[inline]
fn read_range(&mut self, addr: u32, size: u32) -> Vec<u8> {
let mut data = Vec::with_capacity(size as usize);
for i in 0..size {
data.push(self.read_byte(addr + i));
}
// println!("reading {data:?} from {addr:x?}");
data
}
#[inline]
fn write_byte(&mut self, addr: u32, value: u8) {
let (block_addr, offset) = Self::segment_addr(addr);
let block = self.mut_block(block_addr);
block.data[offset as usize] = value;
}
fn write_word(&mut self, addr: u32, value: u32) {
#[inline]
fn write_word(&mut self, addr: u32, value: u32) -> Result<(), ProcessorError> {
if addr % 4 != 0 {
return Err(ProcessorError::BadMemoryAccess(addr));
}
let (block_addr, offset) = Self::segment_addr(addr);
let block = self.mut_block(block_addr);
block.data[offset as usize] = (value >> 24) as u8;
block.data[(offset + 1) as usize] = (value >> 16) as u8;
block.data[(offset + 2) as usize] = (value >> 8) as u8;
block.data[(offset + 3) as usize] = value as u8;
block.data[offset as usize..=(offset + 3) as usize]
.copy_from_slice(&value.to_be_bytes());
Ok(())
}
#[inline]
fn write_range(&mut self, addr: u32, value: Vec<u8>) {
// println!("writing {value:?} to {addr:x?}");
for (i, byte) in value.into_iter().enumerate() {
let (block_addr, offset) = Self::segment_addr(addr + i as u32);
let block = self.mut_block(block_addr);
block.data[offset as usize] = byte;
let mut current_block_addr = addr / 256;
let mut current_block = self.mut_block(current_block_addr);
let mut offset = addr % 256;
for byte in value {
current_block.data[offset as usize] = byte;
offset += 1;
if offset >= 256 {
offset = 0;
current_block_addr += 1;
current_block = self.mut_block(current_block_addr);
}
}
}
#[inline]
fn read_block(&mut self, addr: u32) -> &[u8; 256] {
let (block_addr, _) = Self::segment_addr(addr);
&self.block(block_addr).data
}
#[inline]
fn write_block(&mut self, addr: u32, data: &[u8; 256]) {
let (block_addr, _) = Self::segment_addr(addr);
let _ = self.data.insert(block_addr, Block { data: *data });
}
}
+142 -56
View File
@@ -1,3 +1,5 @@
use std::sync::mpsc::{self, Receiver, Sender};
use common::prelude::*;
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
@@ -16,15 +18,143 @@ pub trait IODevice: Send + Sync {
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum Command {
// set emulator state.
Start,
Stop,
Step,
Step(usize),
Reset(usize),
Interrupt(Interrupt),
// Performs direct read/write operations on the emulator's memory.
Read(Address, u32),
Write(Address, Vec<u8>),
WriteBlock(Address, Box<[u8; 256]>),
// request emulator state.
MemRequest(Address, u32),
DisplayRequest,
StackRequest,
RegisterRequest,
RunningRequest,
HistoryRequest,
InstructionCountRequest,
}
#[derive(Debug)]
pub enum ProcessorError {
InvalidInstruction(u32),
InvalidRegister(u8),
BadMemoryAccess(u32),
}
impl std::error::Error for ProcessorError {}
impl std::fmt::Display for ProcessorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidInstruction(instruction) => {
write!(f, "Invalid instruction: {instruction}")
}
Self::InvalidRegister(register) => {
write!(f, "Invalid register: {register}")
}
Self::BadMemoryAccess(address) => {
write!(f, "Bad memory access: {address}")
}
}
}
}
pub struct State {
pub state_receiver: Receiver<StateUpdate>,
pub cmd_sender: Sender<Command>,
// Processor state
pub reg_file: RegFile,
pub running: Running,
pub instructions: usize,
// Memory access views
pub stack_view: Vec<u8>,
pub memory_view: Vec<u8>,
pub display_view: Vec<u8>,
pub error_log: Vec<String>,
pub instruction_history: Vec<(u32, Instruction)>,
}
impl State {
#[must_use]
pub fn new(sender: Sender<Command>, receiver: Receiver<StateUpdate>) -> Self {
Self {
state_receiver: receiver,
cmd_sender: sender,
reg_file: RegFile::default(),
running: Running::Paused,
instructions: 0,
stack_view: vec![],
memory_view: vec![],
display_view: vec![],
error_log: vec![],
instruction_history: vec![],
}
}
pub fn send(&mut self, cmd: Command) {
if let Err(e) = self.cmd_sender.send(cmd) {
self.error_log.push(e.to_string());
}
}
pub fn update(&mut self) -> Result<(), mpsc::TryRecvError> {
while let Ok(update) = self.state_receiver.try_recv() {
match update {
StateUpdate::Registers(reg_file) => self.reg_file = reg_file,
StateUpdate::Running(running) => self.running = running,
StateUpdate::Instructions(instructions) => {
self.instructions = instructions;
}
StateUpdate::StackView(stack_view) => self.stack_view = stack_view,
StateUpdate::MemoryView(memory_view) => self.memory_view = memory_view,
StateUpdate::DisplayView(display_view) => {
self.display_view = display_view;
}
StateUpdate::Error(err_state) => self.error_log.push(err_state),
StateUpdate::InstructionHistory(history) => {
self.instruction_history.extend(history);
}
}
if self.error_log.len() > 256 {
self.error_log.drain(0..self.error_log.len() - 256);
}
if self.instruction_history.len() > 1024 {
self.instruction_history
.drain(0..self.instruction_history.len() - 1024);
}
}
if let Err(e) = self.state_receiver.try_recv() {
match e {
mpsc::TryRecvError::Empty => {}
mpsc::TryRecvError::Disconnected => {
return Err(e);
}
}
}
Ok(())
}
}
pub enum StateUpdate {
Registers(RegFile),
Running(Running),
Instructions(usize),
StackView(Vec<u8>),
MemoryView(Vec<u8>),
DisplayView(Vec<u8>),
Error(String),
InstructionHistory(Vec<(u32, Instruction)>),
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
@@ -127,8 +257,8 @@ impl RegFile {
self.pcx = 0;
}
pub fn reg(&mut self, reg: Register) -> &mut u32 {
match reg {
pub const fn reg(&mut self, reg: Register) -> Result<&mut u32, ProcessorError> {
Ok(match reg {
Register::Rg0 => &mut self.rg0,
Register::Rg1 => &mut self.rg1,
Register::Rg2 => &mut self.rg2,
@@ -156,13 +286,13 @@ impl RegFile {
Register::Sts => &mut self.sts,
Register::Cir => &mut self.cir,
Register::Pcx => &mut self.pcx,
_ => panic!("Invalid register."),
}
_ => return Err(ProcessorError::InvalidRegister(Register::NoReg as u8)),
})
}
#[must_use]
pub fn get(&self, reg: Register) -> u32 {
match reg {
pub const fn get(&self, reg: Register) -> Result<u32, ProcessorError> {
Ok(match reg {
Register::Rg0 => self.rg0,
Register::Rg1 => self.rg1,
Register::Rg2 => self.rg2,
@@ -191,51 +321,7 @@ impl RegFile {
Register::Cir => self.cir,
Register::Pcx => self.pcx,
Register::Zero => 0,
_ => panic!("Invalid register."),
}
}
}
pub struct State {
pub reg_file: RegFile,
pub running: Running,
pub instructions: usize,
// Memory access views
pub stack_view: Vec<u8>,
pub memory_view: Vec<u8>,
pub display_view: Vec<u8>,
pub error: Option<String>,
pub persistent: PersistentState,
}
impl Default for State {
fn default() -> Self {
Self {
reg_file: RegFile::default(),
running: Running::Paused,
instructions: 0,
stack_view: vec![],
memory_view: vec![],
display_view: vec![],
persistent: PersistentState::default(),
error: None,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct PersistentState {
pub history: Vec<(u32, Instruction)>,
}
impl PersistentState {
pub fn update(&mut self, new_state: &Self) {
self.history.extend(new_state.history.clone());
if self.history.len() > 1024 {
let len = self.history.len() - 1024;
self.history.drain(..len);
}
_ => return Err(ProcessorError::InvalidRegister(Register::NoReg as u8)),
})
}
}
+140 -119
View File
@@ -5,12 +5,10 @@ use std::{
use crate::emulator::system::{
memory::MemoryUnit,
model::{IODevice, RegFile},
model::{IODevice, ProcessorError, RegFile},
};
use common::instructions::{
Instruction, Interrupt, Register, errors::InstructionDecodeError,
};
use common::instructions::{Instruction, Interrupt, Register};
pub struct Processor {
pub memory: Box<dyn MemoryUnit>,
@@ -18,14 +16,13 @@ pub struct Processor {
pub halted: bool,
pub io_devices: Vec<Arc<dyn IODevice>>,
pub dustbin: u32,
pub void: u32,
}
fn log(message: &str) {
println!("\x1b[32mINFO:\x1b[0m {message}");
}
#[allow(clippy::needless_pass_by_ref_mut)]
impl Processor {
#[must_use]
pub fn new(memory: Box<dyn MemoryUnit>, io_devices: Vec<Arc<dyn IODevice>>) -> Self {
@@ -34,7 +31,7 @@ impl Processor {
registers: RegFile::default(),
halted: false,
io_devices,
dustbin: 0,
void: 0,
}
}
@@ -48,49 +45,46 @@ impl Processor {
self.memory.reset();
}
pub fn cycle(&mut self) -> Result<(u32, Instruction), InstructionDecodeError> {
pub fn cycle(&mut self) -> Result<(u32, Instruction), ProcessorError> {
self.halted = false;
// Get value from PCX.
let addr = self.fetch();
let addr = self.fetch()?;
// Increment PCX.
self.advance();
self.advance()?;
// Set MAR to the previous value of PCX.
*self.reg(Register::Mar) = addr;
let val = self.memory.read_word(addr);
*self.reg(Register::Mar)? = addr;
let val = self.memory.read_word(addr)?;
// Set CIR to the value of RAM[MAR].
*self.reg(Register::Mar) = val;
*self.reg(Register::Mar)? = val;
// Decode and execute the instruction.
let instruction = Instruction::decode(val)?;
log(&instruction.to_string());
instruction.execute(self);
let instruction = Instruction::decode(val)
.map_err(|_| ProcessorError::InvalidInstruction(val))?;
instruction.execute(self)?;
Ok((addr, instruction))
}
fn fetch(&self) -> u32 {
const fn fetch(&self) -> Result<u32, ProcessorError> {
self.get(Register::Pcx)
}
#[must_use]
pub fn get(&self, reg: Register) -> u32 {
pub const fn get(&self, reg: Register) -> Result<u32, ProcessorError> {
self.registers.get(reg)
}
pub fn reg(&mut self, reg: Register) -> &mut u32 {
pub const fn reg(&mut self, reg: Register) -> Result<&mut u32, ProcessorError> {
match reg {
Register::Zero => &mut self.dustbin,
Register::Zero => Ok(&mut self.void),
_ => self.registers.reg(reg),
}
}
pub fn display(&mut self) -> Vec<u8> {
self.memory.read_range(0x20000, 2000)
pub fn display(&mut self) -> Result<Vec<u8>, ProcessorError> {
Ok(self.memory.read_range(0x20000, 2000))
}
pub fn cmp(&mut self, a: u32, b: u32) {
@@ -99,59 +93,80 @@ impl Processor {
self.set_flag(Flag::LessThan, a < b);
}
// stack operations
pub fn push(&mut self, value: u32) {
let stack_ptr = self.get(Register::Spr);
*self.reg(Register::Spr) += 4;
self.memory.write_word(stack_ptr, value);
}
pub fn pop(&mut self) -> u32 {
*self.reg(Register::Spr) -= 4;
self.memory.read_word(self.get(Register::Spr))
}
// functions to set new state
fn set_flag(&mut self, flag: Flag, value: bool) {
if value {
*self.reg(Register::Sts) |= flag as u32;
*self
.reg(Register::Sts)
.expect("STS should never be invalid") |= flag as u32;
} else {
*self.reg(Register::Sts) &= !(flag as u32);
*self
.reg(Register::Sts)
.expect("STS should never be invalid") &= !(flag as u32);
}
}
fn get_flag(&self, flag: Flag) -> bool {
self.get(Register::Sts) & (flag as u32) != 0
fn get_flag(&self, flag: Flag) -> Result<bool, ProcessorError> {
Ok(self.get(Register::Sts)? & (flag as u32) != 0)
}
fn advance(&mut self) {
fn advance(&mut self) -> Result<(), ProcessorError> {
// increment PCX
*self.reg(Register::Pcx) += 4;
*self.reg(Register::Pcx)? += 4;
Ok(())
}
fn jump(&mut self, reg: Register, offset: u16) {
*self.reg(Register::Pcx) = self.get(reg) + u32::from(offset);
fn jump(&mut self, reg: Register, offset: u16) -> Result<(), ProcessorError> {
*self.reg(Register::Pcx)? = self.get(reg)? + u32::from(offset);
Ok(())
}
fn begin_interrupt(&mut self, _int: Interrupt) {
// first we get the address of the interrupt descriptor table.
todo!();
pub fn begin_interrupt(
&mut self,
interrupt: Interrupt,
) -> Result<(), ProcessorError> {
let idt = self.get(Register::Idr)?;
let addr = self
.memory
.read_word(idt + u32::from(interrupt.as_u8()) * 4)?;
println!("INFO: Interrupt {interrupt:?} addr: {addr}");
self.push(self.get(Register::Pcx)?)?;
*self.reg(Register::Pcx)? = addr;
Ok(())
}
fn end_interrupt(&mut self) {
todo!();
fn push(&mut self, val: u32) -> Result<(), ProcessorError> {
*self.reg(Register::Spr)? -= 4;
let reg = *self.reg(Register::Spr)?;
self.memory.write_word(reg, val)
}
pub fn get_stack(&mut self, n: u32) -> Vec<u8> {
let addr = self.get(Register::Spr);
fn pop(&mut self) -> Result<u32, ProcessorError> {
let reg = *self.reg(Register::Spr)?;
let val = self.memory.read_word(reg)?;
*self.reg(Register::Spr)? += 4;
Ok(val)
}
// TODO: remove this once implemented
#[allow(clippy::needless_pass_by_ref_mut)]
fn end_interrupt(&mut self) -> Result<(), ProcessorError> {
let ret = self.pop()?;
*self.reg(Register::Ret)? = ret;
*self.reg(Register::Pcx)? = ret;
Ok(())
}
pub fn get_stack(&mut self, n: u32) -> Result<Vec<u8>, ProcessorError> {
let addr = self.get(Register::Spr)?;
let size = n * 4;
// returns the stack
self.memory.read_range(
Ok(self.memory.read_range(
max(addr, 0), // ensures that we cannot read from a negative address
min(size, addr), // ensures we don't read above the top of the stack
)
))
}
}
@@ -170,38 +185,40 @@ enum Flag {
}
trait Executable {
fn execute(self, cpu: &mut Processor);
fn execute(self, cpu: &mut Processor) -> Result<(), ProcessorError>;
}
impl Executable for Instruction {
#[allow(clippy::too_many_lines)]
fn execute(self, cpu: &mut Processor) {
fn execute(self, cpu: &mut Processor) -> Result<(), ProcessorError> {
match self {
// No operation - a blank line.
// Copies from SrcReg to a.drReg.
Self::Mov(a) => {
*cpu.reg(a.dr) = cpu.get(a.sr1);
*cpu.reg(a.dr)? = cpu.get(a.sr1)?;
}
// Copies from SrcReg to a.drReg, sign extending the value to take up a full
// word.
Self::MovSigned(a) => {
*cpu.reg(a.dr) = sign_extend(cpu.get(a.sr1));
*cpu.reg(a.dr)? = sign_extend(cpu.get(a.sr1)?);
}
// Loads a byte from memory address (base + offset) into a.drReg. The
// effective address must be byte-aligned.
Self::LoadByte(a) => {
*cpu.reg(a.r2) = u32::from(
cpu.memory.read_byte(cpu.get(a.r1) + u32::from(a.immediate)),
*cpu.reg(a.r2)? = u32::from(
cpu.memory
.read_byte(cpu.get(a.r1)? + u32::from(a.immediate)),
);
}
// Loads a sign-extended byte from memory address (base + offset) into
// a.drReg. The effective address must be byte-aligned.
Self::LoadByteSigned(a) => {
*cpu.reg(a.r2) = sign_extend(u32::from(
cpu.memory.read_byte(cpu.get(a.r1) + u32::from(a.immediate)),
*cpu.reg(a.r2)? = sign_extend(u32::from(
cpu.memory
.read_byte(cpu.get(a.r1)? + u32::from(a.immediate)),
));
}
@@ -210,31 +227,36 @@ impl Executable for Instruction {
Self::LoadHalfword(a) => {
// we read an entire word, then right shift so we only get the first half
// of the word
*cpu.reg(a.r2) =
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate)) >> 16;
*cpu.reg(a.r2)? = cpu
.memory
.read_word(cpu.get(a.r1)? + u32::from(a.immediate))?
>> 16;
}
// Loads a sign-extended half-word from memory address (base + offset) into
// a.drReg. The effective address must be 2-byte-aligned.
Self::LoadHalfwordSigned(a) => {
*cpu.reg(a.r2) = sign_extend(
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate)) >> 16,
*cpu.reg(a.r2)? = sign_extend(
cpu.memory
.read_word(cpu.get(a.r1)? + u32::from(a.immediate))?
>> 16,
);
}
// Loads a word from memory address (base + offset) into a.drReg. The
// effective address must be 4-byte-aligned.
Self::LoadWord(a) => {
*cpu.reg(a.r2) =
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate));
*cpu.reg(a.r2)? = cpu
.memory
.read_word(cpu.get(a.r1)? + u32::from(a.immediate))?;
}
// Stores a byte from SrcReg in memory address (base + offset) The effective
// address must be byte-aligned.
Self::StoreByte(a) => {
cpu.memory.write_byte(
cpu.get(a.r2) + u32::from(a.immediate),
cpu.get(a.r1) as u8,
cpu.get(a.r2)? + u32::from(a.immediate),
cpu.get(a.r1)? as u8,
);
}
@@ -242,149 +264,147 @@ impl Executable for Instruction {
// effective address must be 2-byte-aligned.
Self::StoreHalfword(a) => {
// split the value into bytes and then write two bytes
let bytes = (cpu.get(a.r1) as u16).to_le_bytes();
let bytes = (cpu.get(a.r1)? as u16).to_le_bytes();
cpu.memory
.write_byte(cpu.get(a.r2) + u32::from(a.immediate), bytes[0]);
.write_byte(cpu.get(a.r2)? + u32::from(a.immediate), bytes[0]);
cpu.memory
.write_byte(cpu.get(a.r2) + u32::from(a.immediate) + 1, bytes[1]);
.write_byte(cpu.get(a.r2)? + u32::from(a.immediate) + 1, bytes[1]);
}
// Stores a word from SrcReg in memory address (base + offset) The effective
// address must be 4-byte-aligned.
Self::StoreWord(a) => {
cpu.memory
.write_word(cpu.get(a.r2) + u32::from(a.immediate), cpu.get(a.r1));
cpu.memory.write_word(
cpu.get(a.r2)? + u32::from(a.immediate),
cpu.get(a.r1)?,
)?;
}
// Loads a 16-bit literal value into reg, setting the bottom 16 bits of the
// word. To populate the upper 16 bits, see LUI.
Self::LoadLowerImmediate(a) => {
*cpu.reg(a.r1) = u32::from(a.immediate);
*cpu.reg(a.r1)? = u32::from(a.immediate);
}
// Loads a 16-bit literal value into reg, setting the top 16 bits of the word.
// To populate the lower 16 bits, see LLI.
Self::LoadUpperImmediate(a) => {
*cpu.reg(a.r1) =
(cpu.get(a.r1) & 0x0000_FFFF) | (u32::from(a.immediate) << 16);
*cpu.reg(a.r1)? =
(cpu.get(a.r1)? & 0x0000_FFFF) | (u32::from(a.immediate) << 16);
}
// Unconditionally jumps to the calculated address or direct address
Self::Jump(a) => cpu.jump(a.r1, a.immediate),
Self::Jump(a) => cpu.jump(a.r1, a.immediate)?,
// Jumps to the calculated address or direct address if equal flag set.
Self::JumpEq(a) => {
if cpu.get_flag(Flag::Equal) {
cpu.jump(a.r1, a.immediate);
if cpu.get_flag(Flag::Equal)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Jumps to the calculated address or direct address if equal flag not set.
Self::JumpNeq(a) => {
if !cpu.get_flag(Flag::Equal) {
cpu.jump(a.r1, a.immediate);
if !cpu.get_flag(Flag::Equal)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Jumps to the calculated address or direct address if greater than flag set.
Self::JumpGt(a) => {
if cpu.get_flag(Flag::GreaterThan) {
cpu.jump(a.r1, a.immediate);
if cpu.get_flag(Flag::GreaterThan)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Jumps to the calculated address or direct address if greater than flag or
// equal flag set.
Self::JumpGe(a) => {
if cpu.get_flag(Flag::GreaterThan) || cpu.get_flag(Flag::Equal) {
cpu.jump(a.r1, a.immediate);
if cpu.get_flag(Flag::GreaterThan)? || cpu.get_flag(Flag::Equal)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Jumps to the calculated address or direct address if less than flag set.
Self::JumpLt(a) => {
if cpu.get_flag(Flag::LessThan) {
cpu.jump(a.r1, a.immediate);
if cpu.get_flag(Flag::LessThan)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Jumps to the calculated address or direct address if less than flag or
// equal flag set.
Self::JumpLe(a) => {
if cpu.get_flag(Flag::LessThan) || cpu.get_flag(Flag::Equal) {
cpu.jump(a.r1, a.immediate);
if cpu.get_flag(Flag::LessThan)? || cpu.get_flag(Flag::Equal)? {
cpu.jump(a.r1, a.immediate)?;
}
}
// Increments the value in the given register
Self::Increment(a) => *cpu.reg(a.sr1) = inc(cpu.get(a.sr1)),
Self::Increment(a) => *cpu.reg(a.sr1)? = inc(cpu.get(a.sr1)?),
// Decrements the value in the given register
Self::Decrement(a) => *cpu.reg(a.sr1) = dec(cpu.get(a.sr1)),
Self::Decrement(a) => *cpu.reg(a.sr1)? = dec(cpu.get(a.sr1)?),
// Left shifts the value in Reg by the given amount (either a register, or a
// literal value)
Self::ShiftLeft(a) => {
let regval = cpu.get(a.sr2);
let val = cpu.get(a.sr1);
*cpu.reg(a.sr1) =
shl(val, if regval != 0 { regval as u8 } else { a.shamt });
let reg = cpu.get(a.sr1)?;
let val = a.shamt;
*cpu.reg(a.sr1)? = shl(reg, val);
}
// Right shifts the value in Reg by the given amount (either a register, or a
// literal value).
Self::ShiftRight(a) => {
let regval = cpu.get(a.sr2);
let val = cpu.get(a.sr1);
*cpu.reg(a.sr1) =
shr(val, if regval != 0 { regval as u8 } else { a.shamt });
let regval = cpu.get(a.sr1)?;
let val = a.shamt;
*cpu.reg(a.sr1)? = shr(regval, val);
}
// Adds the value of Src2 to Src1 and writes the result to a.dr
Self::Add(a) => {
*cpu.reg(a.dr) = add(cpu.get(a.sr1), cpu.get(a.sr2));
*cpu.reg(a.dr)? = add(cpu.get(a.sr1)?, cpu.get(a.sr2)?);
}
// Subtracts the value of Src2 from Src1 and writes the result to a.dr
Self::Sub(a) => {
*cpu.reg(a.dr) = sub(cpu.get(a.sr1), cpu.get(a.sr2));
*cpu.reg(a.dr)? = sub(cpu.get(a.sr1)?, cpu.get(a.sr2)?);
}
Self::AddImmediate(a) => {
*cpu.reg(a.r2) = add(cpu.get(a.r1), u32::from(a.immediate));
*cpu.reg(a.r2)? = add(cpu.get(a.r1)?, u32::from(a.immediate));
}
Self::SubImmediate(a) => {
*cpu.reg(a.r2) = sub(cpu.get(a.r1), u32::from(a.immediate));
*cpu.reg(a.r2)? = sub(cpu.get(a.r1)?, u32::from(a.immediate));
}
// Performs bitwise AND on Src1 and Src2 storing the result in a.dr
Self::And(a) => *cpu.reg(a.dr) = and(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::And(a) => *cpu.reg(a.dr)? = and(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Performs bitwise OR on Src1 and Src2 storing the result in a.dr
Self::Or(a) => *cpu.reg(a.dr) = or(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::Or(a) => *cpu.reg(a.dr)? = or(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Performs bitwise NOT on Src storing the result in a.dr
Self::Not(a) => *cpu.reg(a.dr) = not(cpu.get(a.sr1)),
Self::Not(a) => *cpu.reg(a.dr)? = not(cpu.get(a.sr1)?),
// Performs bitwise XOR on Src1 and Src2 storing the result in a.dr
Self::Xor(a) => *cpu.reg(a.dr) = xor(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::Xor(a) => *cpu.reg(a.dr)? = xor(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Performs bitwise NAND on Src1 and Src2 storing the result in a.dr
Self::Nand(a) => *cpu.reg(a.dr) = nand(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::Nand(a) => *cpu.reg(a.dr)? = nand(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Performs bitwise NOR on Src1 and Src2 storing the result in a.dr
Self::Nor(a) => *cpu.reg(a.dr) = nor(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::Nor(a) => *cpu.reg(a.dr)? = nor(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Performs bitwise XNOR on Src1 and Src2 storing the result in a.dr
Self::Xnor(a) => *cpu.reg(a.dr) = xnor(cpu.get(a.sr1), cpu.get(a.sr2)),
Self::Xnor(a) => *cpu.reg(a.dr)? = xnor(cpu.get(a.sr1)?, cpu.get(a.sr2)?),
// Compares the value of Reg1 to the value in Reg2. The results of the
// comparisons are set in the Status register.
Self::Compare(a) => {
cpu.cmp(cpu.get(a.sr1), cpu.get(a.sr2));
cpu.cmp(cpu.get(a.sr1)?, cpu.get(a.sr2)?);
}
// Initiates an interrupt with the given 8 bit interrupt code.
@@ -392,12 +412,12 @@ impl Executable for Instruction {
// - The return address is saved to the RET register.
// - The stack base ptr is set to the kernel stack.
Self::Interrupt(interrupt_code) => {
cpu.begin_interrupt(interrupt_code);
cpu.begin_interrupt(interrupt_code)?;
}
// Returns from an interrupt,
Self::IntReturn => {
cpu.end_interrupt();
cpu.end_interrupt()?;
}
// Halts the processor.
@@ -411,6 +431,7 @@ impl Executable for Instruction {
todo!()
}
}
Ok(())
}
}
+297 -129
View File
@@ -13,22 +13,32 @@ fn test_nop_instruction() {
let mut cpu = create_test_processor();
let initial_state = cpu.registers;
Instruction::Nop.execute(&mut cpu);
Instruction::Nop.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.registers.get(Register::Rg0),
initial_state.get(Register::Rg0)
cpu.registers
.get(Register::Rg0)
.expect("Failed to get register Rg0"),
initial_state
.get(Register::Rg0)
.expect("Failed to get register Rg0")
);
assert_eq!(
cpu.registers.get(Register::Acc),
initial_state.get(Register::Acc)
cpu.registers
.get(Register::Acc)
.expect("Failed to get register Acc"),
initial_state
.get(Register::Acc)
.expect("Failed to get register Acc")
);
}
#[test]
fn test_mov_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0x1234_5678;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x1234_5678;
let mov_instr = Instruction::Mov(RTypeArgs::new(
Some(Register::Rg1),
@@ -37,14 +47,19 @@ fn test_mov_instruction() {
None,
));
mov_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0x1234_5678);
mov_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0x1234_5678
);
}
#[test]
fn test_mov_signed_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0x0000_00FF;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x0000_00FF;
let mov_signed_instr = Instruction::MovSigned(RTypeArgs::new(
Some(Register::Rg1),
@@ -53,8 +68,13 @@ fn test_mov_signed_instruction() {
None,
));
mov_signed_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0xFFFF_FFFF);
mov_signed_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0xFFFF_FFFF
);
}
#[test]
@@ -62,7 +82,7 @@ fn test_load_byte_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
cpu.memory.write_byte(addr, 0xAB);
*cpu.reg(Register::Rg1) = addr - 4;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr - 4;
let load_byte_instr = Instruction::LoadByte(ITypeArgs::new(
4,
@@ -70,8 +90,13 @@ fn test_load_byte_instruction() {
Some(Register::Rg2),
));
load_byte_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0x0000_00AB);
load_byte_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0x0000_00AB
);
}
#[test]
@@ -79,7 +104,7 @@ fn test_load_byte_signed_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
cpu.memory.write_byte(addr, 0xFF);
*cpu.reg(Register::Rg1) = addr;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr;
let load_byte_signed_instr = Instruction::LoadByteSigned(ITypeArgs::new(
0,
@@ -87,16 +112,23 @@ fn test_load_byte_signed_instruction() {
Some(Register::Rg2),
));
load_byte_signed_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0xFFFF_FFFF);
load_byte_signed_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0xFFFF_FFFF
);
}
#[test]
fn test_load_halfword_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
cpu.memory.write_word(addr, 0x1234_5678);
*cpu.reg(Register::Rg1) = addr;
cpu.memory
.write_word(addr, 0x1234_5678)
.expect("Failed to write word to memory");
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr;
let load_halfword_instr = Instruction::LoadHalfword(ITypeArgs::new(
0,
@@ -104,16 +136,23 @@ fn test_load_halfword_instruction() {
Some(Register::Rg2),
));
load_halfword_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0x0000_1234);
load_halfword_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0x0000_1234
);
}
#[test]
fn test_load_word_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
cpu.memory.write_word(addr, 0x1234_5678);
*cpu.reg(Register::Rg1) = addr;
cpu.memory
.write_word(addr, 0x1234_5678)
.expect("Failed to write word to memory");
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr;
let load_word_instr = Instruction::LoadWord(ITypeArgs::new(
0,
@@ -121,16 +160,21 @@ fn test_load_word_instruction() {
Some(Register::Rg2),
));
load_word_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0x1234_5678);
load_word_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0x1234_5678
);
}
#[test]
fn test_store_byte_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
*cpu.reg(Register::Rg1) = addr;
*cpu.reg(Register::Rg2) = 0xAB;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0xAB;
let store_byte_instr = Instruction::StoreByte(ITypeArgs::new(
0,
@@ -138,7 +182,9 @@ fn test_store_byte_instruction() {
Some(Register::Rg1),
));
store_byte_instr.execute(&mut cpu);
store_byte_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(cpu.memory.read_byte(addr), 0xAB);
}
@@ -146,8 +192,8 @@ fn test_store_byte_instruction() {
fn test_store_word_instruction() {
let mut cpu = create_test_processor();
let addr = 0x100;
*cpu.reg(Register::Rg1) = addr;
*cpu.reg(Register::Rg2) = 0x1234_5678;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = addr;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0x1234_5678;
let store_word_instr = Instruction::StoreWord(ITypeArgs::new(
0,
@@ -155,15 +201,17 @@ fn test_store_word_instruction() {
Some(Register::Rg1),
));
store_word_instr.execute(&mut cpu);
assert_eq!(cpu.memory.read_word(addr), 0x1234_5678);
store_word_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(cpu.memory.read_word(addr).expect("Emulator was slain by losing the game while attempting to execute instruction"), 0x1234_5678);
}
#[test]
fn test_add_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 15;
*cpu.reg(Register::Rg2) = 25;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 15;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 25;
let add_instr = Instruction::Add(RTypeArgs::new(
Some(Register::Rg1),
@@ -172,15 +220,20 @@ fn test_add_instruction() {
None,
));
add_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), 40);
add_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
40
);
}
#[test]
fn test_sub_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 50;
*cpu.reg(Register::Rg2) = 20;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 50;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 20;
let sub_instr = Instruction::Sub(RTypeArgs::new(
Some(Register::Rg1),
@@ -189,15 +242,20 @@ fn test_sub_instruction() {
None,
));
sub_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), 30);
sub_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
30
);
}
#[test]
fn test_and_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let and_instr = Instruction::And(RTypeArgs::new(
Some(Register::Rg1),
@@ -206,15 +264,20 @@ fn test_and_instruction() {
None,
));
and_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), 0b1000);
and_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
0b1000
);
}
#[test]
fn test_or_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let or_instr = Instruction::Or(RTypeArgs::new(
Some(Register::Rg1),
@@ -223,15 +286,20 @@ fn test_or_instruction() {
None,
));
or_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), 0b1110);
or_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
0b1110
);
}
#[test]
fn test_xor_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let xor_instr = Instruction::Xor(RTypeArgs::new(
Some(Register::Rg1),
@@ -240,14 +308,19 @@ fn test_xor_instruction() {
None,
));
xor_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), 0b0110);
xor_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
0b0110
);
}
#[test]
fn test_not_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0x0F0F_0F0F;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x0F0F_0F0F;
let not_instr = Instruction::Not(RTypeArgs::new(
Some(Register::Rg1),
@@ -256,15 +329,20 @@ fn test_not_instruction() {
None,
));
not_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg2), 0xF0F0_F0F0);
not_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg2).expect("Failed to get register Rg2"),
0xF0F0_F0F0
);
}
#[test]
fn test_compare_equal() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 42;
*cpu.reg(Register::Rg2) = 42;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 42;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 42;
let cmp_instr = Instruction::Compare(RTypeArgs::new(
Some(Register::Rg1),
@@ -273,18 +351,26 @@ fn test_compare_equal() {
None,
));
cmp_instr.execute(&mut cpu);
cmp_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert!(cpu.get_flag(Flag::Equal));
assert!(!cpu.get_flag(Flag::GreaterThan));
assert!(!cpu.get_flag(Flag::LessThan));
assert!(cpu.get_flag(Flag::Equal).expect("Failed to get flag Equal"));
assert!(
!cpu.get_flag(Flag::GreaterThan)
.expect("Failed to get flag GreaterThan")
);
assert!(
!cpu.get_flag(Flag::LessThan)
.expect("Failed to get flag LessThan")
);
}
#[test]
fn test_compare_greater_than() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 50;
*cpu.reg(Register::Rg2) = 30;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 50;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 30;
let cmp_instr = Instruction::Compare(RTypeArgs::new(
Some(Register::Rg1),
@@ -293,18 +379,26 @@ fn test_compare_greater_than() {
None,
));
cmp_instr.execute(&mut cpu);
cmp_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert!(!cpu.get_flag(Flag::Equal));
assert!(cpu.get_flag(Flag::GreaterThan));
assert!(!cpu.get_flag(Flag::LessThan));
assert!(!cpu.get_flag(Flag::Equal).expect("Failed to get flag Equal"));
assert!(
cpu.get_flag(Flag::GreaterThan)
.expect("Failed to get flag GreaterThan")
);
assert!(
!cpu.get_flag(Flag::LessThan)
.expect("Failed to get flag LessThan")
);
}
#[test]
fn test_compare_less_than() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 20;
*cpu.reg(Register::Rg2) = 30;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 20;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 30;
let cmp_instr = Instruction::Compare(RTypeArgs::new(
Some(Register::Rg1),
@@ -313,41 +407,59 @@ fn test_compare_less_than() {
None,
));
cmp_instr.execute(&mut cpu);
cmp_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert!(!cpu.get_flag(Flag::Equal));
assert!(!cpu.get_flag(Flag::GreaterThan));
assert!(cpu.get_flag(Flag::LessThan));
assert!(!cpu.get_flag(Flag::Equal).expect("Failed to get flag Equal"));
assert!(
!cpu.get_flag(Flag::GreaterThan)
.expect("Failed to get flag GreaterThan")
);
assert!(
cpu.get_flag(Flag::LessThan)
.expect("Failed to get flag LessThan")
);
}
#[test]
fn test_increment_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 42;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 42;
let inc_instr =
Instruction::Increment(RTypeArgs::new(Some(Register::Rg1), None, None, None));
inc_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 43);
inc_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
43
);
}
#[test]
fn test_decrement_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 42;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 42;
let dec_instr =
Instruction::Decrement(RTypeArgs::new(Some(Register::Rg1), None, None, None));
dec_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 41);
dec_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
41
);
}
#[test]
fn test_shift_left_with_shamt() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1010;
let shl_instr = Instruction::ShiftLeft(RTypeArgs::new(
Some(Register::Rg1),
@@ -356,14 +468,19 @@ fn test_shift_left_with_shamt() {
Some(2),
));
shl_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 0b10_1000);
shl_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
0b10_1000
);
}
#[test]
fn test_shift_right_with_shamt() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b10_1000;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b10_1000;
let shr_instr = Instruction::ShiftRight(RTypeArgs::new(
Some(Register::Rg1),
@@ -372,26 +489,32 @@ fn test_shift_right_with_shamt() {
Some(2),
));
shr_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 0b1010);
shr_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
0b1010
);
}
#[test]
fn test_shift_left_with_register() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1010;
*cpu.reg(Register::Rg2) = 3;
// #[test]
// fn test_shift_left_with_register() {
// let mut cpu = create_test_processor();
// *cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1010;
let shl_instr = Instruction::ShiftLeft(RTypeArgs::new(
Some(Register::Rg1),
Some(Register::Rg2),
None,
None,
));
// let shl_instr =
// Instruction::ShiftLeft(RTypeArgs::new(Some(Register::Rg1), None, None,
// Some(3)));
shl_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 0b101_0000);
}
// shl_instr.execute(&mut cpu).expect(
// "Emulator was slain by losing the game while attempting to execute
// instruction", );
// assert_eq!(
// cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
// 0b101_0000
// );
// }
#[test]
fn test_load_lower_immediate() {
@@ -403,14 +526,19 @@ fn test_load_lower_immediate() {
None,
));
lli_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 0x0000_1234);
lli_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
0x0000_1234
);
}
#[test]
fn test_load_upper_immediate() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0x0000_5678;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x0000_5678;
let lui_instr = Instruction::LoadUpperImmediate(ITypeArgs::new(
0x1234,
@@ -418,48 +546,71 @@ fn test_load_upper_immediate() {
None,
));
lui_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg1), 0x1234_5678);
lui_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg1).expect("Failed to get register Rg1"),
0x1234_5678
);
}
#[test]
fn test_jump_unconditional() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0x1000;
let initial_pc = cpu.get(Register::Pcx);
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x1000;
let initial_pc = cpu.get(Register::Pcx).expect("Failed to get register Pcx");
let jump_instr = Instruction::Jump(ITypeArgs::new(0x100, Some(Register::Rg1), None));
jump_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Pcx), 0x1100);
assert_ne!(cpu.get(Register::Pcx), initial_pc);
jump_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Pcx).expect("Failed to get register Pcx"),
0x1100
);
assert_ne!(
cpu.get(Register::Pcx).expect("Failed to get register Pcx"),
initial_pc
);
}
#[test]
fn test_jump_equal_when_flag_set() {
let mut cpu = create_test_processor();
cpu.set_flag(Flag::Equal, true);
*cpu.reg(Register::Rg1) = 0x1000;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x1000;
let jump_eq_instr =
Instruction::JumpEq(ITypeArgs::new(0x100, Some(Register::Rg1), None));
jump_eq_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Pcx), 0x1100);
jump_eq_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Pcx).expect("Failed to get register Pcx"),
0x1100
);
}
#[test]
fn test_jump_equal_when_flag_not_set() {
let mut cpu = create_test_processor();
cpu.set_flag(Flag::Equal, false);
*cpu.reg(Register::Rg1) = 0x1000;
let initial_pc = cpu.get(Register::Pcx);
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0x1000;
let initial_pc = cpu.get(Register::Pcx).expect("Failed to get register Pcx");
let jump_eq_instr =
Instruction::JumpEq(ITypeArgs::new(0x100, Some(Register::Rg1), None));
jump_eq_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Pcx), initial_pc);
jump_eq_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Pcx).expect("Failed to get register Pcx"),
initial_pc
);
}
#[test]
@@ -467,15 +618,17 @@ fn test_halt_instruction() {
let mut cpu = create_test_processor();
assert!(!cpu.halted);
Instruction::Halt.execute(&mut cpu);
Instruction::Halt.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert!(cpu.halted);
}
#[test]
fn test_nand_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let nand_instr = Instruction::Nand(RTypeArgs::new(
Some(Register::Rg1),
@@ -484,15 +637,20 @@ fn test_nand_instruction() {
None,
));
nand_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), !0b1000);
nand_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
!0b1000
);
}
#[test]
fn test_nor_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let nor_instr = Instruction::Nor(RTypeArgs::new(
Some(Register::Rg1),
@@ -501,15 +659,20 @@ fn test_nor_instruction() {
None,
));
nor_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), !0b1110);
nor_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
!0b1110
);
}
#[test]
fn test_xnor_instruction() {
let mut cpu = create_test_processor();
*cpu.reg(Register::Rg1) = 0b1100;
*cpu.reg(Register::Rg2) = 0b1010;
*cpu.reg(Register::Rg1).expect("Failed to get register Rg1") = 0b1100;
*cpu.reg(Register::Rg2).expect("Failed to get register Rg2") = 0b1010;
let xnor_instr = Instruction::Xnor(RTypeArgs::new(
Some(Register::Rg1),
@@ -518,6 +681,11 @@ fn test_xnor_instruction() {
None,
));
xnor_instr.execute(&mut cpu);
assert_eq!(cpu.get(Register::Rg3), !0b0110);
xnor_instr.execute(&mut cpu).expect(
"Emulator was slain by losing the game while attempting to execute instruction",
);
assert_eq!(
cpu.get(Register::Rg3).expect("Failed to get register Rg3"),
!0b0110
);
}
+64 -20
View File
@@ -1,5 +1,3 @@
use std::sync::mpsc::Sender;
use crate::emulator::{
system::model::{Command, Running, State},
ui::interface::Component,
@@ -9,19 +7,27 @@ use common::{instructions::Register, prelude::Instruction};
pub struct ControlPanel {
visible: bool,
sender: Sender<Command>,
step_amount_input: String,
step_amount: usize,
}
impl ControlPanel {
#[must_use]
pub const fn new(sender: Sender<Command>) -> Self {
#[allow(clippy::must_use_candidate)]
pub fn new() -> Self {
Self {
visible: false,
sender,
step_amount_input: String::from("1"),
step_amount: 1,
}
}
}
impl Default for ControlPanel {
fn default() -> Self {
Self::new()
}
}
impl Component for ControlPanel {
fn category(&self) -> super::interface::Category {
super::interface::Category::Control
@@ -47,46 +53,76 @@ impl Component for ControlPanel {
.clicked()
{
if state.running == Running::Running {
self.sender.send(Command::Stop).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state.cmd_sender.send(Command::Stop).unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
} else {
self.sender.send(Command::Start).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state.cmd_sender.send(Command::Start).unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
}
}
// Step
if ui.button("Step").clicked() {
self.sender.send(Command::Step).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state
.cmd_sender
.send(Command::Step(self.step_amount))
.unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
}
// Resets the emulator and all attached devices
if ui.button("Reset All").clicked() {
self.sender.send(Command::Reset(0)).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state
.cmd_sender
.send(Command::Reset(0))
.unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
}
// Resets the emulator and all attached devices
if ui.button("Clear Registers").clicked() {
self.sender.send(Command::Reset(1)).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state
.cmd_sender
.send(Command::Reset(1))
.unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
}
// Resets the emulator and all attached devices
if ui.button("Clear RAM").clicked() {
self.sender.send(Command::Reset(2)).unwrap_or_else(|_| {
state.error = Some("Failed to send command".to_string());
state
.cmd_sender
.send(Command::Reset(2))
.unwrap_or_else(|_| {
state.error_log.push("Failed to send command".to_string());
});
}
ui.separator();
state.send(Command::RegisterRequest);
state.send(Command::RunningRequest);
state.send(Command::InstructionCountRequest);
if ui
.text_edit_singleline(&mut self.step_amount_input)
.changed()
{
self.step_amount = if let Ok(amount) = self.step_amount_input.parse() {
amount
} else {
state
.error_log
.push("Unable to parse step amount".to_string());
1
}
}
// Status info
ui.label(format!(
"Status: {}",
@@ -97,13 +133,21 @@ impl Component for ControlPanel {
}
));
let pcx = state.reg_file.get(Register::Pcx);
let pcx = state
.reg_file
.get(Register::Pcx)
.expect("PCX should never be invalid");
let instructions = state.instructions;
ui.label(format!("Instructions: {instructions}"));
ui.label(format!("PC: 0x{pcx:08X}"));
let instruction = Instruction::decode(state.reg_file.get(Register::Cir))
let instruction = Instruction::decode(
state
.reg_file
.get(Register::Cir)
.expect("CIR should never be invalid"),
)
.map_or_else(
|_| "Invalid Instruction".to_string(),
|instruction| instruction.to_string(),
+3 -1
View File
@@ -1,5 +1,5 @@
use crate::emulator::{
system::model::State,
system::model::{Command, State},
ui::interface::{Category, Component},
};
@@ -40,6 +40,8 @@ impl Component for Display {
}
fn render(&mut self, state: &mut State, ui: &mut egui::Ui, _ctx: &egui::Context) {
state.send(Command::DisplayRequest);
let display: Vec<u8> = state.display_view.clone();
let font_id = FontId::monospace(12.0);
+11 -71
View File
@@ -3,7 +3,6 @@ use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
sync::mpsc::Sender,
};
use common::prelude::Instruction;
@@ -19,6 +18,7 @@ use crate::emulator::{
use assembler::prelude::*;
#[derive(Default)]
pub struct Editor {
// editor state
path: Option<PathBuf>,
@@ -41,7 +41,6 @@ pub struct Editor {
// other
visible: bool,
sender: Sender<Command>,
error: Option<String>,
}
@@ -94,14 +93,13 @@ impl Component for Editor {
impl Editor {
#[must_use]
pub const fn new(sender: Sender<Command>) -> Self {
pub const fn new() -> Self {
Self {
path: None,
text: String::new(),
buffer: String::new(),
output: Vec::new(),
unsaved: true,
sender,
cursor_col: 1,
cursor_line: 1,
visible: false,
@@ -199,38 +197,6 @@ impl Editor {
)
});
// if let Some(path) = FileDialog::new()
// .add_filter("Assembly Files or Binaries", &["dsa", "dsb"])
// .add_filter("all", &["*"])
// .set_directory(&work_dir)
// .pick_file()
// {
// match path.extension().and_then(|ext| ext.to_str()) {
// Some("dsb") => {
// let contents = match std::fs::read(&path) {
// Ok(contents) => contents,
// Err(why) => {
// self.error = Some(format!("Failed to read file: {why}"));
// return;
// }
// };
// self.path = Some(path.clone());
// self.output = contents;
// self.unsaved = false;
// self.text = String::from("Loaded Binary File!");
// self.buffer = self.text.clone();
// self.unsaved = false;
// }
// _ => {
// if let Ok(contents) = std::fs::read_to_string(&path) {
// self.path = Some(path.clone());
// self.text.clone_from(&contents);
// self.buffer = contents;
// self.unsaved = false;
// }
// }
// }
if self.save_file_dialog.is_some() {
// TODO: Flash an error stating you can only have one menu open at once.
self.save_file_dialog = None;
@@ -252,8 +218,9 @@ impl Editor {
fn handle_file_dialogs(&mut self, ctx: &egui::Context) {
// Handle open dialog
if let Some(dialog) = &mut self.open_file_dialog {
if dialog.show(ctx).selected() {
if let Some(dialog) = &mut self.open_file_dialog
&& dialog.show(ctx).selected()
{
if let Some(file) = dialog.path() {
// check if the file is a binary file
if file.extension().is_some_and(|ext| ext == "dsb") {
@@ -293,11 +260,11 @@ impl Editor {
}
self.open_file_dialog = None;
}
}
// Handle save dialog
if let Some(dialog) = &mut self.save_file_dialog {
if dialog.show(ctx).selected() {
if let Some(dialog) = &mut self.save_file_dialog
&& dialog.show(ctx).selected()
{
if let Some(file) = dialog.path() {
self.buffer = self.text.clone();
@@ -336,34 +303,6 @@ impl Editor {
self.save_file_dialog = None;
}
}
}
// fn open(&mut self) {
// let work_dir = std::env::current_dir().unwrap_or_else(|_| {
// dirs::home_dir().expect(
// "Couldn't get your current working directory or your home directory.",
// )
// });
// if let Some(path) = FileDialog::new()
// .add_filter("Assembly Files or Binaries", &["dsa", "dsb"])
// .add_filter("all", &["*"])
// .set_directory(&work_dir)
// .pick_file()
// {
// if let Ok(contents) = std::fs::read_to_string(&path) {
// self.path = Some(path.clone());
// self.text.clone_from(&contents);
// self.buffer = contents;
// self.unsaved = false;
// }
// std::env::set_current_dir(
// path.parent().expect("A file should be in a directory!"),
// )
// .expect("ERROR: Failed to set current working directory.");
// }
// }
fn render_output(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
// Output area with synchronized scrolling
@@ -526,7 +465,7 @@ impl Editor {
}
}
fn render_toolbar(&mut self, _state: &mut State, ui: &mut Ui, ctx: &Context) {
fn render_toolbar(&mut self, state: &State, ui: &mut Ui, ctx: &Context) {
self.handle_file_dialogs(ctx);
ui.horizontal(|ui| {
@@ -567,7 +506,8 @@ impl Editor {
Some("Can't load program at invalid offset!".to_string());
}
self.sender
state
.cmd_sender
.send(Command::Write(self.load_offset, self.output.clone()))
.unwrap_or_else(|_| {
self.error = Some("Failed to send command".to_string());
+8 -3
View File
@@ -1,6 +1,9 @@
use egui::{Context, Ui};
use crate::emulator::{system::model::State, ui::interface::Component};
use crate::emulator::{
system::model::{Command, State},
ui::interface::Component,
};
pub struct History {
visible: bool,
@@ -20,11 +23,13 @@ impl Component for History {
}
fn render(&mut self, state: &mut State, ui: &mut Ui, _ctx: &Context) {
state.send(Command::HistoryRequest);
egui::ScrollArea::vertical()
.id_salt("output_scroll")
.max_width(400.0)
.show(ui, |ui| {
if state.persistent.history.is_empty() {
if state.instruction_history.is_empty() {
ui.label(
egui::RichText::new("No output data")
.font(egui::FontId::monospace(12.0))
@@ -40,7 +45,7 @@ impl Component for History {
.show(ui, |ui| {
// Process bytes in chunks of 4
for (idx, instruction) in
state.persistent.history.iter().enumerate()
state.instruction_history.iter().enumerate()
{
ui.label(format!("{idx}: "));
+6 -18
View File
@@ -1,4 +1,4 @@
use crate::emulator::system::model::{Command, PersistentState, Running, State};
use crate::emulator::system::model::{Command, Running, State, StateUpdate};
use std::sync::mpsc::{Receiver, Sender};
pub trait Component {
@@ -34,21 +34,15 @@ impl Category {
}
pub struct EmulatorUI {
pub sender: Sender<Command>,
pub receiver: Receiver<State>,
pub state: State,
pub persistent: PersistentState,
pub components: Vec<Box<dyn Component>>,
}
impl EmulatorUI {
#[must_use]
pub fn new(sender: Sender<Command>, receiver: Receiver<State>) -> Self {
pub fn new(sender: Sender<Command>, receiver: Receiver<StateUpdate>) -> Self {
Self {
sender,
receiver,
state: State::default(),
persistent: PersistentState::default(),
state: State::new(sender, receiver),
components: vec![],
}
}
@@ -56,19 +50,13 @@ impl EmulatorUI {
pub fn add_component(&mut self, component: Box<dyn Component>) {
self.components.push(component);
}
fn update_state(&mut self) {
while let Ok(state) = self.receiver.try_recv() {
self.state = state;
self.persistent.update(&self.state.persistent);
self.state.persistent = self.persistent.clone();
}
}
}
impl eframe::App for EmulatorUI {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.update_state();
if let Err(e) = self.state.update() {
self.state.error_log.push(e.to_string());
}
if self.state.running == Running::Running {
ctx.request_repaint();
+294
View File
@@ -0,0 +1,294 @@
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
use common::prelude::Instruction;
use egui::{Context, Ui};
use egui_file::FileDialog;
use crate::emulator::{
system::model::{Command, State},
ui::interface::Component,
};
#[derive(Default)]
pub struct Loader {
path: Option<PathBuf>,
output: Vec<u8>,
load_offset: u32,
offset_str: String,
// file dialogs
open_file_dialog: Option<FileDialog>,
// other
visible: bool,
error: Option<String>,
}
impl Component for Loader {
fn name(&self) -> &'static str {
"Loader"
}
fn visible(&mut self) -> &mut bool {
&mut self.visible
}
fn category(&self) -> super::interface::Category {
super::interface::Category::Programming
}
fn render(&mut self, state: &mut State, ui: &mut Ui, ctx: &Context) {
ui.vertical(|ui| {
self.render_toolbar(state, ui, ctx);
ui.add_space(4.0); // Add some spacing instead of just a separator
ui.separator();
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.max_height(ui.available_height() - 100.0)
.show(ui, |ui| {
self.render_output(state, ui, ctx);
});
self.render_bottom_bar(state, ui, ctx);
});
}
}
impl Loader {
#[must_use]
pub const fn new() -> Self {
Self {
path: None,
output: Vec::new(),
visible: false,
load_offset: 0,
offset_str: String::new(),
error: None,
open_file_dialog: None,
}
}
fn filename(&self) -> &str {
if let Some(path) = &self.path {
return path
.file_name()
.unwrap_or_else(|| OsStr::new("Unnamed!"))
.to_str()
.map_or_else(
|| unreachable!("File name should be valid UTF-8."),
|ext| ext,
);
}
"Unnamed!"
}
fn open(&mut self) {
let work_dir = std::env::current_dir().unwrap_or_else(|_| {
dirs::home_dir().expect(
"Couldn't get your current working directory or your home directory.",
)
});
if self.open_file_dialog.is_some() {
// TODO: Flash an error stating you can only have one menu open at once.
self.open_file_dialog = None;
}
if self.open_file_dialog.is_none() {
if let Some(p) = &self.path {
let path = p.parent().map(Path::to_path_buf);
let mut dialog = FileDialog::open_file(path);
dialog.open();
self.open_file_dialog = Some(dialog);
} else {
let mut dialog = FileDialog::open_file(Some(work_dir));
dialog.open();
self.open_file_dialog = Some(dialog);
}
}
}
fn handle_file_dialogs(&mut self, ctx: &egui::Context) {
// Handle open dialog
if let Some(dialog) = &mut self.open_file_dialog
&& dialog.show(ctx).selected()
{
if let Some(file) = dialog.path() {
// check if the file is a binary file
if file.extension().is_some_and(|ext| ext == "dsb") {
match std::fs::read(file) {
Ok(content) => {
self.output = content;
self.error = None;
}
Err(e) => {
self.error = Some(format!("Failed to read file: {e}"));
}
}
}
}
self.open_file_dialog = None;
}
}
fn render_output(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
// Output area with synchronized scrolling
egui::ScrollArea::vertical()
.id_salt("output_scroll")
.max_width(400.0)
.show(ui, |ui| {
if self.output.is_empty() {
ui.label(
egui::RichText::new("No output data")
.font(egui::FontId::monospace(12.0))
.color(egui::Color32::GRAY),
);
return;
}
egui::Grid::new("output_grid")
.spacing([5.0, 2.0]) // Horizontal and vertical spacing
.num_columns(4)
.striped(false)
.show(ui, |ui| {
// Process bytes in chunks of 4
for (line_num, chunk) in self.output.chunks(4).enumerate() {
let address = line_num * 4;
// Convert chunk to u32 (little-endian)
let mut bytes = [0u8; 4];
for (i, &byte) in chunk.iter().enumerate() {
if i < 4 {
bytes[i] = byte;
}
}
let value = u32::from_be_bytes(bytes);
// Address column
ui.with_layout(
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
ui.set_min_width(80.0);
let style = ui.style_mut();
style.visuals.widgets.inactive.bg_fill =
egui::Color32::from_gray(30);
ui.label(
egui::RichText::new(format!("0x{address:04X}"))
.font(egui::FontId::monospace(12.0)),
);
},
);
// Individual bytes column
let byte_str = chunk
.iter()
.map(|b| format!("{b:02X}"))
.collect::<Vec<_>>()
.join(" ");
ui.label(
egui::RichText::new(format!("{byte_str:<11}"))
.font(egui::FontId::monospace(12.0))
.color(egui::Color32::from_rgb(200, 200, 255)),
);
// Hex column
ui.label(
egui::RichText::new(format!("0x{value:08X}"))
.font(egui::FontId::monospace(12.0))
.color(egui::Color32::from_rgb(255, 200, 200)),
);
// Instruction column
let instruction = Instruction::decode(value).map_or_else(
|_| format!("{value:10}"),
|instruction| instruction.to_string(),
);
ui.label(
egui::RichText::new(instruction)
.font(egui::FontId::monospace(12.0))
.color(egui::Color32::from_rgb(200, 255, 200)),
);
ui.end_row();
}
});
});
}
fn render_bottom_bar(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
ui.horizontal(|ui| {
// error display
ui.label(
egui::RichText::new(self.error.clone().unwrap_or_default())
.color(egui::Color32::RED),
);
});
}
fn render_toolbar(&mut self, state: &State, ui: &mut Ui, ctx: &Context) {
self.handle_file_dialogs(ctx);
ui.horizontal(|ui| {
ui.label(format!("Filename: {}", self.filename()));
});
ui.horizontal(|ui| {
ui.spacing_mut().button_padding = egui::vec2(8.0, 4.0);
ui.spacing_mut().item_spacing.x = 6.0;
// Opens a file
if ui.button("Open").clicked() {
self.open();
}
// Loads the generated binary into the assembler at the provided offset
if ui.button("Load").clicked() {
if self.error.is_some() {
self.error =
Some("Can't load program at invalid offset!".to_string());
}
state
.cmd_sender
.send(Command::Write(self.load_offset, self.output.clone()))
.unwrap_or_else(|_| {
self.error = Some("Failed to send command".to_string());
});
}
// Entry widget to enter a load offset
if ui.text_edit_singleline(&mut self.offset_str).changed() {
if let Some(offset) = parse_address(&self.offset_str) {
self.load_offset = offset;
self.error = None;
} else {
self.error = Some("Invalid offset".to_string());
}
}
});
}
}
fn parse_address(address: &str) -> Option<u32> {
address.strip_prefix("0x").map_or_else(
|| {
address.strip_prefix("0b").map_or_else(
|| {
address.strip_prefix("0o").map_or_else(
|| address.parse::<u32>().ok(),
|oct| u32::from_str_radix(oct, 8).ok(),
)
},
|bin| u32::from_str_radix(bin, 2).ok(),
)
},
|hex| u32::from_str_radix(hex, 16).ok(),
)
}
+24 -20
View File
@@ -1,4 +1,4 @@
use std::{num::ParseIntError, sync::mpsc::Sender};
use std::num::ParseIntError;
use common::prelude::Instruction;
@@ -7,23 +7,22 @@ use crate::emulator::{
ui::interface::Component,
};
#[derive(Default)]
pub struct MemoryInspector {
view_size: u32,
view_addr: u32,
visible: bool,
addr_input: String,
sender: Sender<Command>,
}
impl MemoryInspector {
#[must_use]
pub const fn new(sender: Sender<Command>) -> Self {
pub const fn new() -> Self {
Self {
view_size: 256,
view_addr: 0,
visible: false,
addr_input: String::new(),
sender,
}
}
}
@@ -63,28 +62,26 @@ impl Component for MemoryInspector {
let search_clicked = ui.button("🔍 Search").clicked();
// Handle Enter key in text field
let enter_pressed =
address_response.lost_focus() && ctx.input(|i| i.key_pressed(egui::Key::Enter));
let enter_pressed = address_response.lost_focus()
&& ctx.input(|i| i.key_pressed(egui::Key::Enter));
if search_clicked || enter_pressed {
if let Ok(new) = parse_address(&self.addr_input) {
self.view_addr = new;
if let Err(why) = self.sender.send(Command::Read(new, self.view_size)) {
panic!(
"Error sending message across threads -- cannot be recovered: {why}"
)
}
} else {
state.error = Some("Invalid address".to_string());
state.error_log.push("Invalid address".to_string());
}
}
let _ = state
.cmd_sender
.send(Command::MemRequest(self.view_addr, self.view_size));
ui.label("(hex or decimal)");
});
// Show input error if any
if let Some(error) = &state.error {
if let Some(error) = state.error_log.last() {
ui.colored_label(egui::Color32::RED, format!("Error: {error}"));
}
@@ -113,9 +110,12 @@ impl Component for MemoryInspector {
ui.end_row();
// Memory data (8 bytes per row)
for (row, chunk) in (0u32..).zip(state.memory_view.chunks(4)) {
for (row, chunk) in (0u32..).zip(state.memory_view.chunks(4))
{
let row_address = self.view_addr + (row * 4);
ui.monospace(format!("0x{row_address:08X} ({row_address})"));
ui.monospace(format!(
"0x{row_address:08X} ({row_address})"
));
for &byte in chunk {
ui.monospace(format!("{byte:02X}"));
}
@@ -126,12 +126,16 @@ impl Component for MemoryInspector {
}
// combine all 4 bytes in the chunk into a u32
let combined = chunk
.iter()
.fold(0u32, |acc, &byte| (acc << 8) | u32::from(byte));
let combined = chunk.iter().fold(0u32, |acc, &byte| {
(acc << 8) | u32::from(byte)
});
ui.monospace(format!("{combined}"));
ui.monospace(format!("{}", Instruction::decode(combined).unwrap_or(Instruction::Nop)));
ui.monospace(format!(
"{}",
Instruction::decode(combined)
.unwrap_or(Instruction::Nop)
));
ui.end_row();
}
+1
View File
@@ -3,6 +3,7 @@ pub mod display;
pub mod editor;
pub mod history;
pub mod interface;
pub mod loader;
pub mod memory_inspector;
pub mod menu;
pub mod stack_inspector;
+7 -2
View File
@@ -1,4 +1,7 @@
use crate::emulator::{system::model::State, ui::interface::Component};
use crate::emulator::{
system::model::{Command, State},
ui::interface::Component,
};
use common::instructions::Register;
@@ -33,6 +36,8 @@ impl Component for StackInspector {
}
fn render(&mut self, state: &mut State, ui: &mut egui::Ui, _ctx: &egui::Context) {
state.send(Command::StackRequest);
ui.vertical(|ui| {
ui.heading("Stack Inspector");
egui::ScrollArea::vertical()
@@ -56,7 +61,7 @@ impl Component for StackInspector {
ui.label(format!(
"{} [{}]",
i,
state.reg_file.get(Register::Spr) - i as u32 * 4
state.reg_file.get(Register::Spr).expect("SPR should never be invalid") - i as u32 * 4
));
ui.label(format!("0x{value:08X} ({value})"));
ui.end_row();
+10 -7
View File
@@ -30,7 +30,7 @@ use crate::emulator::{
system::{
emulator::run_emulator,
memory::MainStore,
model::{Command, State},
model::{Command, StateUpdate},
processor::Processor,
},
ui::{
@@ -86,7 +86,7 @@ pub fn android_main(app: AndroidApp) -> Result<(), Box<dyn std::error::Error>> {
pub fn setup_emulator(
cmd_receiver: Receiver<Command>,
state_sender: Sender<State>,
state_sender: Sender<StateUpdate>,
rpc_client: Option<Arc<RpcClient>>,
) {
let main_store = MainStore::new();
@@ -101,22 +101,22 @@ pub fn setup_emulator(
#[must_use]
pub fn setup_ui(
cmd_sender: Sender<Command>,
state_reciever: Receiver<State>,
state_reciever: Receiver<StateUpdate>,
) -> EmulatorUI {
let mut ui = EmulatorUI::new(cmd_sender.clone(), state_reciever);
let mut ui = EmulatorUI::new(cmd_sender, state_reciever);
// Create UI modules.
let control_unit = ControlPanel::new(cmd_sender.clone());
let control_unit = ControlPanel::new();
ui.add_component(Box::new(control_unit));
let mem_inspector = MemoryInspector::new(cmd_sender.clone());
let mem_inspector = MemoryInspector::new();
ui.add_component(Box::new(mem_inspector));
let stack_inspector = StackInspector::new();
ui.add_component(Box::new(stack_inspector));
let editor = Editor::new(cmd_sender);
let editor = Editor::new();
ui.add_component(Box::new(editor));
let display = Display::new();
@@ -125,5 +125,8 @@ pub fn setup_ui(
let history = emulator::ui::history::History::new();
ui.add_component(Box::new(history));
let loader = emulator::ui::loader::Loader::new();
ui.add_component(Box::new(loader));
ui
}
-279
View File
@@ -1,279 +0,0 @@
```rust
// src/assembler/source.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourcePosition {
pub line: u32,
pub column: u32,
pub offset: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceSpan {
pub start: SourcePosition,
pub end: SourcePosition,
pub file_id: u64, // Hash of the file path
}
impl SourceSpan {
pub fn new(start: SourcePosition, end: SourcePosition, file_id: u64) -> Self {
Self { start, end, file_id }
}
pub fn single_char(pos: SourcePosition, file_id: u64) -> Self {
Self {
start: pos,
end: pos,
file_id,
}
}
}
2. Enhanced Token with Source Information
Update the Token type to include source positions:
```rust
// src/assembler/model.rs
pub struct Token {
pub kind: TokenKind,
pub span: SourceSpan,
pub raw: String, // Original source text
}
pub enum TokenKind {
// ... existing variants ...
}
3. Enhanced CodeModule Structure
Enhance the
CodeModule
struct to track source information:
```rust
// src/assembler/mod.rs
pub struct CodeModule {
pub path: PathBuf,
pub hash: u64,
pub source: String,
pub lines: Vec<usize>, // Line start offsets for quick lookup
pub tokens: Vec<Token>,
pub nodes: Vec<Node>,
pub dependencies: Vec<CodeModule>,
}
impl CodeModule {
pub fn new(path: PathBuf, source: String) -> Self {
let hash = quick_hash(&path);
let lines = source.lines()
.scan(0, |offset, line| {
let start = *offset;
*offset += line.len() + 1; // +1 for newline
Some(start)
})
.collect();
Self {
path,
hash,
source,
lines,
tokens: Vec::new(),
nodes: Vec::new(),
dependencies: Vec::new(),
}
}
pub fn position_from_offset(&self, offset: usize) -> (u32, u32) {
match self.lines.binary_search(&offset) {
Ok(line) => (line as u32 + 1, 1),
Err(0) => (1, offset as u32 + 1),
Err(line) => {
let line_start = self.lines[line - 1];
(line as u32, (offset - line_start + 1) as u32)
}
}
}
}
4. Enhanced Lexer with Source Positions
Update the lexer to track source positions:
```rust
// src/assembler/lexer.rs
pub fn lex(module: &mut CodeModule) -> Result<(), AssembleError> {
let source = &module.source;
let mut tokens = Vec::new();
let mut pos = 0;
let mut line_start = 0;
let mut line = 1;
while pos < source.len() {
let c = source[pos..].chars().next().unwrap();
if c == '\n' {
line += 1;
line_start = pos + 1;
pos += 1;
continue;
}
if c.is_whitespace() {
pos += 1;
continue;
}
let token_start = pos;
// ... existing token parsing logic ...
// When creating a token:
let start_pos = SourcePosition {
line,
column: (token_start - line_start + 1) as u32,
offset: token_start,
};
// Update pos based on token length
let token_length = /* calculate token length */;
pos += token_length;
let end_pos = SourcePosition {
line,
column: (pos - line_start + 1) as u32,
offset: pos,
};
tokens.push(Token {
kind: token_kind,
span: SourceSpan::new(start_pos, end_pos, module.hash),
raw: source[token_start..pos].to_string(),
});
}
module.tokens = tokens;
Ok(())
}
5. Enhanced Error Reporting
Create a structured error type with source context:
```rust
// src/assembler/error.rs
#[derive(Debug)]
pub struct AssemblerError {
pub kind: ErrorKind,
pub span: SourceSpan,
pub message: String,
pub context: Vec<String>,
}
impl AssemblerError {
pub fn new(kind: ErrorKind, span: SourceSpan, message: impl Into<String>) -> Self {
Self {
kind,
span,
message: message.into(),
context: Vec::new(),
}
}
pub fn with_context(mut self, context: impl Into<String>) -> Self {
self.context.push(context.into());
self
}
pub fn format(&self, module: &CodeModule) -> String {
let (line, col) = module.position_from_offset(self.span.start.offset);
let line_content = module.source.lines().nth(line as usize - 1).unwrap_or("");
let mut output = format!(
"{}:{}:{}: {}\n",
module.path.display(),
line,
col,
self.message
);
// Add source line with caret
output.push_str(&format!("{}\n", line_content));
output.push_str(&" ".repeat(col as usize - 1));
output.push_str("^\n");
// Add context if any
for ctx in &self.context {
output.push_str(&format!(" = note: {}\n", ctx));
}
output
}
}
6. Integration with Compilation Pipeline
Update the compilation pipeline to use the enhanced types:
```rust
// src/assembler/mod.rs
pub fn assemble(src: &Path) -> Result<Vec<Instruction>, AssemblerError> {
let source = std::fs::read_to_string(src)
.map_err(|e| AssemblerError::io_error(src, e))?;
let mut module = CodeModule::new(src.to_path_buf(), source);
// Lexing
lexer::lex(&mut module)?;
// Parsing
parser::parse(&mut module)?;
// Resolution
resolver::resolve(&mut module)?;
// Code generation
codegen::generate(&module)
}
7. Logging Integration
Enhance the logging system to include source context:
```rust
// src/util/logging.rs
pub trait Loggable {
fn log(&self, level: LogLevel, message: impl std::fmt::Display);
fn log_with_span(&self, level: LogLevel, span: &SourceSpan, message: impl std::fmt::Display);
}
impl Loggable for CodeModule {
fn log_with_span(&self, level: LogLevel, span: &SourceSpan, message: impl std::fmt::Display) {
if span.file_id != self.hash {
if let Some(dep) = self.find_dependency(span.file_id) {
return dep.log_with_span(level, span, message);
}
}
let (line, col) = self.position_from_offset(span.start.offset);
let line_content = self.source.lines().nth(line as usize - 1).unwrap_or("");
log::log!(
level,
"{}:{}:{}: {}\n {}\n {}{}",
self.path.display(),
line,
col,
message,
line_content,
" ".repeat(col as usize - 1),
"^"
);
}
}
8. Usage Example
Here's how you'd use this in practice:
```rust
// In your parser or code that needs to report errors
fn parse_token(&mut self, module: &CodeModule) -> Result<Token, AssemblerError> {
// ...
if !is_valid_token(&token) {
return Err(AssemblerError::new(
ErrorKind::SyntaxError,
token.span,
"Invalid token"
).with_context("Expected a valid instruction or directive"));
}
// ...
}
```
+34 -16
View File
@@ -2,10 +2,38 @@
// a simple brainf##k interpreter,
// because I already wrote a compiler lol.
include print "./lib/print.dsa"
include print "./lib/io/print.dsa"
// "print hello world"
db program: "++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+."
db program: "++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++
>++++++++++++++++
>
>+
<<
[
>>
>
>++++++++++
<<
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
>[<+>-]
>[-]
>>
>++++++++++
<
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
>[-]
>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]
<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]
<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]
<<<<<<<.>.
>>[>>+<<-]
>[>+<<+>-]
>[<+>-]
<<<-
]
<<++..."
db error: "Invalid Instruction!"
dw stack: 0x10000
@@ -20,6 +48,7 @@ _init_stack:
start:
// load the start of the program into rg0
lwi program, rg0
lwi data, rg1
// rg0 is our instruction pointer
// rg1 is our data pointer
@@ -40,13 +69,6 @@ loop_start:
// load the current instruction into rg3
ldb rg0, rg3
// pusha 2
// push rg3
// call print::print_byte
// pop zero
// popa 2
// switch on the instruction
// all cases will return to either loop_start or loop_end
cmp rg3, rg8
@@ -69,18 +91,14 @@ loop_start:
jeq end
// if we get here, we don't know what the instruction is
lwi error, rg0
push rg0
call print::print
pop zero
end:
lwi error, rg2
pusha 2
push rg2
call print::print
pop zero
popa 2
end:
hlt
loop_end:
@@ -110,7 +128,7 @@ inc_ptr:
// ------------------------------------------
// decrement the pointer
dec_ptr:
stw rg1, rg2
stw rg2, rg1
subi rg1, 4
ldw rg1, rg2
jmp loop_end
+34
View File
@@ -0,0 +1,34 @@
include print "../io/print.dsa"
dw idt: 0xFFFF0000
setup_idt:
push bpr
mov spr, bpr
// load the IDT into the IDR
ldw idt, idr
mov bpr, spr
pop bpr
irt
setup_hard_fault_handler:
push bpr
mov spr, bpr
lwi handle_hard_fault, rg0
stw rg0, idr, 4
mov bpr, spr
pop bpr
irt
dw hard_fault_err: "FATAL: Illegal Instruction or Memory Access!"
handle_hard_fault:
call print::reset
lwi hard_fault_err, rg0
push rg0
call print::print
pop zero
hlt
-18
View File
@@ -1,18 +0,0 @@
fib_n:
pop ret
pop rg0 // n
lli 0, rg1
lli 1, rg2
start:
add rg1, rg2, acc
push rg1
mov rg2, rg1
mov acc, rg2
cmp rg0, zero
dec rg0
jgt start
jmp 4, ret
+244
View File
@@ -0,0 +1,244 @@
// lib:
// print.dsa
// usage:
//
// include print "<relative path>""
//
// usage for print:
// push (register containing address of string)
// push pcx
// jmp print::print
//
// usage for reset:
// push pcx
// jmp print::reset
//
// usage for clear:
// push pcx
// jmp print::clear
//
// usage for print_byte:
// push (register containing byte)
// push pcx
// jmp print::print_byte
//
// usage for print_word:
// push (register containing word)
// push pcx
// jmp print::print_word
//
include maths "../maths/core.dsa"
dw display: 0x20000
dw current: 0x20000
// ------------------------------------------
// prints the string at addr(arg[0]) to the screen.
print:
push bpr
mov spr, bpr
ldw bpr, rg0, 8
ldw current, rg1
_print_loop:
ldb rg0, acc
stb acc, rg1
addi rg0, 1
addi rg1, 1
cmp acc, zero
jne _print_loop
jmp _end
// ------------------------------------------
// prints the value of arg[0] to the screen.
print_word:
// initialise
push bpr
mov spr, bpr
// load byte into acc
ldw bpr, rg0, 8
ldw current, rg1
addi rg1, 3
stb rg0, rg1
subi rg1, 1
shr rg0, 8
stb rg0, rg1
subi rg1, 1
shr rg0, 8
stb rg0, rg1
subi rg1, 1
shr rg0, 8
stb rg0, rg1
addi rg1, 4
jmp _end
// ------------------------------------------
// prints the last byte of arg[0] to the screen.
print_byte:
push bpr
mov spr, bpr
ldw bpr, rg0, 8
ldw current, rg1
stb rg0, rg1
addi rg1, 1
jmp _end
// ------------------------------------------
// prints the value of arg[0] to the screen in hex.
print_hex_word:
push bpr
mov spr, bpr
ldw current, rg1
ldb bpr, rg0, 8
push rg0
call _print_hex_byte
addi spr, 4
ldb bpr, rg0, 9
push rg0
call _print_hex_byte
addi spr, 4
ldb bpr, rg0, 10
push rg0
call _print_hex_byte
addi spr, 4
ldb bpr, rg0, 11
push rg0
call _print_hex_byte
addi spr, 4
jmp _end
// ------------------------------------------
// prints the last byte of arg[0] to the screen in hex.
print_hex_byte:
push bpr
mov spr, bpr
ldw bpr, rg0, 8
ldw current, rg1
call _print_hex_byte
jmp _end
// function body
_print_hex_byte:
// mask to get lower nibble
lli 0xF, rg2
// save rg0 state
push rg0
shr rg0, 4
and rg0, rg2, rg0
call _print_hex_nibble
pop rg0
and rg0, rg2, rg0
call _print_hex_nibble
return
// print a hex digit
_print_hex_nibble:
lli 10, rg3
cmp rg0, rg3
jlt _print_hex_nibble_number
addi rg0, 0x37, rg0
stb rg0, rg1
addi rg1, 1
return
// helper function.
_print_hex_nibble_number:
addi rg0, 0x30, rg0
stb rg0, rg1
addi rg1, 1
return
// ------------------------------------------
// print whitespace
print_whitespace:
push bpr
mov spr, bpr
ldw current, rg1
lli 0x20, rg0
stb rg0, rg1
addi rg1, 1
jmp _end
// ------------------------------------------
// print newline
print_newline:
push bpr
mov spr, bpr
// load variables into registers
ldw display, rg0
ldw current, rg1
// get the offset from the display base
sub rg1, rg0, rg0
lwi 80, rg2
pusha 3
push rg0
push rg2
call maths::divmod
pop zero // result
pop rg3 // remainder
popa 3
sub rg1, rg3, rg2
addi rg2, 80, rg1
// _end saves the display state
jmp _end
// ------------------------------------------
// resets the cursor position on the screen to 0x20000. (0,0)
reset:
push bpr
mov spr, bpr
ldw display, rg1
jmp _end
// ------------------------------------------
// clears the screen
clear:
push bpr
mov spr, bpr
// display size = 2000 bytes / 500 words
lli 500 rg0
ldw display, rg1
_clear_loop:
dec rg0
stw zero, rg1
addi rg1, 4
cmp rg0, zero
jgt _clear_loop
jmp _end
// ------------------------------------------
// return
_end:
stw rg1, current
mov bpr, spr
pop bpr
return
+60
View File
@@ -0,0 +1,60 @@
// multiply.dsa
// usage:
//
// include multiply "<relative path>"
//
// usage for multiply:
// push (arg1)
// push (arg0)
// call multiply::multiply
// pop (arg0)
// pop (arg1)
multiply:
push bpr
mov spr, bpr
ldw bpr, rg0, 8 // load op 2
ldw bpr, rg1, 12 // load op 1
_multiply_loop:
add rg2, rg0, rg2
dec rg1
cmp rg1, zero
jgt _multiply_loop
_multiply_end:
stw rg2, bpr, 8
mov bpr, spr
pop bpr
return
divmod:
push bpr
mov spr, bpr
ldw bpr, rg1, 8 // load op 2
ldw bpr, rg0, 12 // load op 1
lli 0, rg3
_divmod_loop:
cmp rg0, rg1
jlt _divmod_end
sub rg0, rg1, rg0
inc rg3
jmp _divmod_loop
_divmod_end:
// store div in first arg
// store mod in second arg
stw rg3, bpr, 8
stw rg0, bpr, 12
mov bpr, spr
pop bpr
return
+31
View File
@@ -0,0 +1,31 @@
include print "../io/print.dsa"
fib_n:
push bpr
mov spr, bpr
ldw bpr, rg0, 8 // load arg
mov rg1, rg2
lwi 1, rg1
start:
add rg1, rg2, rg3
pusha 4
push rg1
call print::print_hex_byte
call print::print_newline
pop zero
popa 4
mov rg2, rg1
mov rg3, rg2
dec rg0
cmp rg0, zero
jgt start
stw rg1, bpr, 8
mov bpr, spr
pop bpr
return
-30
View File
@@ -1,30 +0,0 @@
// multiply.dsa
// usage:
//
// include multiply "<relative path>"
//
// usage for multiply:
// push (arg1)
// push (arg0)
// call multiply::multiply
// pop (arg0)
// pop (arg1)
multiply:
push bpr
mov spr, bpr
ldw bpr, rg0, 8 // load op 1
ldw bpr, rg1, 12 // load op 2
start:
add acc, rg0, acc
dec rg1
cmp rg1, zero
jgt start
end:
mov bpr, spr
pop bpr
return
-115
View File
@@ -1,115 +0,0 @@
// lib:
// print.dsa
// usage:
//
// include print "<relative path>""
//
// usage for print:
// push (register containing address of string)
// push pcx
// jmp print::print
//
// usage for reset:
// push pcx
// jmp print::reset
//
// usage for clear:
// push pcx
// jmp print::clear
//
// usage for print_byte:
// push (register containing byte)
// push pcx
// jmp print::print_byte
//
// usage for print_word:
// push (register containing word)
// push pcx
// jmp print::print_word
//
dw display: 0x20000
dw current: 0x20000
// ------------------------------------------
// prints the string at addr(arg[0]) to the screen.
print:
push bpr
mov spr, bpr
ldw bpr, rg0, 8
ldw current, rg1
_print_loop:
ldb rg0, acc
stb acc, rg1
addi rg0, 1
addi rg1, 1
cmp acc, zero
jne _print_loop
jmp _end
// ------------------------------------------
// prints the value of arg[0] to the screen.
print_word:
// initialise
push bpr
mov spr, bpr
// load byte into acc
ldw bpr, rg0, 8
ldw current, rg1
stw rg0, rg1
addi rg1, 4
jmp _end
// ------------------------------------------
// prints the last byte of arg[0] to the screen.
print_byte:
push bpr
mov spr, bpr
ldw bpr, rg0, 8
ldw current, rg1
stb rg0, rg1
addi rg1, 1
jmp _end
// ------------------------------------------
// resets the cursor position on the screen to 0x20000. (0,0)
reset:
push bpr
mov spr, bpr
ldw display, rg1
jmp _end
// ------------------------------------------
// clears the screen
clear:
push bpr
mov spr, bpr
// display size = 2000 bytes / 500 words
lli 500 rg0
ldw display, rg1
_clear_loop:
dec rg0
stw zero, rg1
addi rg1, 4
cmp rg0, zero
jgt _clear_loop
jmp _end
// ------------------------------------------
// return
_end:
stw rg1, current
mov bpr, spr
pop bpr
return
+80
View File
@@ -0,0 +1,80 @@
include fib: "./lib/maths/fib.dsa"
include maths: "./lib/maths/core.dsa"
include print: "./lib/io/print.dsa"
dw idt: 0xFFFF0000
dw stack: 0x10000
init:
// setup interrupt handlers
ldw idt, idr
lwi handle_hard_fault, rg0
stw rg0, idr, 4
// set up a stack.
ldw stack, bpr
mov bpr, spr
dw string: "hello world"
start:
lwi 37, rg0
lwi 12, rg1
push rg0
push rg1
call maths::divmod
pop rg0 // result
pop rg1 // remainder
push rg1
push rg0
call print::print_hex_byte
call print::print_whitespace
pop zero
call print::print_hex_byte
call print::print_newline
lwi string, rg0
//lwi 10, rg0
pusha 4
push rg0
call print::print
//call fib::fib_n
pop zero
call print::print_newline
popa 4
pusha 4
push rg0
call print::print
//call fib::fib_n
pop zero
call print::print_newline
popa 4
pusha 4
push rg0
call print::print
//call fib::fib_n
pop zero
call print::print_newline
popa 4
pusha 4
push rg0
call print::print
//call fib::fib_n
pop zero
call print::print_newline
popa 4
hlt
// fault handler in case we fail DSA.
dw hard_fault_err: "FATAL: Illegal Instruction or Memory Access!"
handle_hard_fault:
call print::clear
call print::reset
lwi hard_fault_err, rg0
push rg0
call print::print
pop zero
hlt
-18
View File
@@ -1,18 +0,0 @@
include print "./lib/print.dsa"
dw stack: 0x10000
db string: "Hello world"
init:
// set up a stack.
ldw stack, bpr
mov bpr, spr
start:
lwi string, rg1
push rg1
call print::print
pop rg1
hlt
+80
View File
@@ -0,0 +1,80 @@
include print "./lib/io/print.dsa"
dw idt: 0xFFFF0000
dw stack: 0x10000
init:
// setup interrupt handlers
ldw idt, idr
lwi handle_hard_fault, rg0
stw rg0, idr, 4
// set up a stack.
ldw stack, bpr
mov bpr, spr
db string: "I won, the game!"
db hexbyte: 0xab
dw hexword: 0x1234abcd
db replace: "I lost"
start:
// test print string
lwi string, rg0
push rg0
call print::print
pop zero
// test print hex byte.
ldb hexbyte, rg0
push rg0
call print::print_hex_byte
pop zero
// test print hex word.
ldw hexword, rg0
push rg0
call print::print_hex_word
pop zero
// test print char
lli 0x40, rg0 // print @
push rg0
call print::print_byte
pop zero
// test newline
call print::print_newline
lwi string rg0
push rg0
call print::print
// test print word
lwi 0x31323334, rg0 // print 1234
push rg0
call print::print_word
pop zero
// test reset cursor pos
call print::reset
// test print string at reset pos
lwi replace, rg0
push rg0
call print::print
pop zero
hlt
// fault handler in case we fail DSA.
dw hard_fault_err: "FATAL: Illegal Instruction or Memory Access!"
handle_hard_fault:
call print::clear
call print::reset
lwi hard_fault_err, rg0
push rg0
call print::print
pop zero
hlt
Binary file not shown.