Skip to content

Commit

Permalink
Merge pull request #17 from rozukke/add/traps-usability
Browse files Browse the repository at this point in the history
Add traps and usability fixes
  • Loading branch information
rozukke authored Sep 15, 2024
2 parents 80aec79 + f3258f5 commit bb76b55
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 34 deletions.
54 changes: 45 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,51 @@
[![Creator rozukke](https://img.shields.io/badge/Creator-rozukke-f497af.svg)](https://github.com/rozukke)
[![Made with Rust](https://img.shields.io/badge/Made%20with-Rust-b7410e.svg)](https://www.rust-lang.org)

`lace` is an all-in-one **LC3** (Little Computer 3) assembly toolchain. It will support fancy convenience features like `watch`ing,
interpreting files directly from `.asm`, a formatter and (probably) running with a copy of the original OS.
`lace` is an all-in-one **LC3** (Little Computer 3) assembly toolchain. `lace` currently supports compiling, checking and
running LC3 assembly files. It will support fancy convenience features like `watch`ing, a formatter and (probably) running
with a copy of the original OS. **Some features are missing!**

## Current features
- It assembles! The `compile` command is minimally functional. You may need an LC3 VM in order to run the resulting file.
## Commands
- `run`: assemble and run a file - all in one command.
- `compile`: creates a binary file with a `.lc3` extension. Note that `lace` cannot currently run these files, so you may need
a different LC3 virtual machine to test them out until that is implemented.
- `check`: verifies that your file is correct without outputting it or running it.
- `watch`: **(work in progress)** runs `check` for a specified file while you develop. Neat!
- `fmt`: **(planned)** formats your `.asm` file to fit my arbitrary style guide.
- `clean`: **(planned)** used to clean debug artifacts that will be implemented in the future.

## MacOS/Linux
TODO: Proper installation instructions
For now, please use `cargo` to get set up. Many features are missing, so watch out!
## Traps
There are a few extra traps that should make debugging a lot nicer! Please note that they will not perform as expected when you run
your binaries with other virtual machines.
- `putn`: print the contents of `r0` to console. This isn't supposed to be easy, and you should probably learn why!
- `reg`: print the contents of every register to console. Currently only supports u16 formatting.

## Windows
TODO: figure out how Windows would work at all
## Work in progress
There are several features and fixes under development:
- Input traps
- Showing multiple errors per compilation
- Watching a file
- File formatting
- Debug symbols
- A step-through debugger (big one!)
Check the repo for updates as it is under active development.

## Installation
For now, please use `cargo` to get set up, as there are no official releases. Check in often for the latest updates! If you are
unsure what `cargo` is, check out [this help page](https://doc.rust-lang.org/cargo/getting-started/installation.html).
To install, follow the steps below:
```sh
git clone https://github.com/rozukke/lace.git
cd lace
cargo install --path .
```
You should, as a result, have the `lace` binary available in your PATH.

## License
Copyright (c) 2024 Artemis Rosman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 changes: 4 additions & 2 deletions src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub fn tokenize(input: &'static str) -> impl Iterator<Item = Result<Token>> + '_

/// Test if a character is considered to be whitespace, including commas.
pub(crate) fn is_whitespace(c: char) -> bool {
char::is_ascii_whitespace(&c) || c == ','
char::is_ascii_whitespace(&c) || matches!(c, ',' | ':')
}

pub(crate) fn is_reg_num(c: char) -> bool {
Expand Down Expand Up @@ -340,13 +340,15 @@ impl Cursor<'_> {
use TokenKind::Trap;
use TrapKind::*;
match ident {
"trap" => Trap(Generic),
"getc" => Trap(Getc),
"out" => Trap(Out),
"puts" => Trap(Puts),
"in" => Trap(In),
"putsp" => Trap(Putsp),
"halt" => Trap(Halt),
"trap" => Trap(Generic),
"putn" => Trap(Putn),
"reg" => Trap(Reg),
_ => TokenKind::Label,
}
}
Expand Down
43 changes: 29 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ enum Command {
/// Destination to output .lc3 file
dest: Option<PathBuf>,
},
/// Check a `.asm` file without running or outputting binary
Check {
/// File to check
name: PathBuf,
},
/// Remove compilation artifacts for specified source
Clean {
/// `.asm` file to try remove artifacts for
Expand All @@ -63,7 +68,7 @@ fn main() -> miette::Result<()> {
let contents: &'static str =
Box::leak(Box::new(fs::read_to_string(&name).into_diagnostic()?));
println!(
"{:>12} {}",
"{:>12} target {}",
"Assembling".green().bold(),
name.to_str().unwrap()
);
Expand All @@ -72,16 +77,12 @@ fn main() -> miette::Result<()> {
let mut air = parser.parse()?;
air.backpatch()?;
// Run file
println!(
"{:>12} {}",
"Running".green().bold(),
name.to_str().unwrap()
);
println!("{:>12} binary", "Running".green().bold());
let mut program = RunState::try_from(air)?;
program.run();
println!(
"{:>12} {}",
"Finished".green().bold(),
"{:>12} target {}",
"Completed".green().bold(),
name.to_str().unwrap()
);
Ok(())
Expand All @@ -91,7 +92,7 @@ fn main() -> miette::Result<()> {
let contents: &'static str =
Box::leak(Box::new(fs::read_to_string(&name).into_diagnostic()?));
println!(
"{:>12} {}",
"{:>12} target {}",
"Assembling".green().bold(),
name.to_str().unwrap()
);
Expand All @@ -114,18 +115,32 @@ fn main() -> miette::Result<()> {
for i in 0..air.len() {
file.write(&air.get(i).emit()?.to_be_bytes());
}
println!(
"{:>12} {}",
"Finished".green().bold(),
name.to_str().unwrap()
);
println!("{:>12} binary", "Finished".green().bold(),);
println!(
"{:>12} {}",
"Saved to".green().bold(),
out_file_name.to_str().unwrap()
);
Ok(())
}
Command::Check { name } => {
let contents: &'static str =
Box::leak(Box::new(fs::read_to_string(&name).into_diagnostic()?));
println!(
"{:>12} target {}",
"Checking".green().bold(),
name.to_str().unwrap()
);
// Process asm
let parser = lace::AsmParser::new(&contents)?;
let mut air = parser.parse()?;
air.backpatch()?;
for stmt in air {
let _ = stmt.emit()?;
}
println!("{:>12} with 0 errors", "Finished".green().bold(),);
Ok(())
}
Command::Clean { name } => todo!(),
Command::Watch { name } => todo!(),
Command::Fmt { name } => todo!(),
Expand Down
2 changes: 2 additions & 0 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ impl AsmParser {
TrapKind::In => 0x23,
TrapKind::Putsp => 0x24,
TrapKind::Halt => 0x25,
TrapKind::Putn => 0x26,
TrapKind::Reg => 0x27,
} as u8;

Ok(AirStmt::Trap { trap_vect })
Expand Down
32 changes: 23 additions & 9 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl RunState {
// imm
Self::s_ext(instr, 5)
};
let res = val1 + val2;
let res = val1.wrapping_add(val2);
self.set_flags(res);
*self.reg(dr) = res;
}
Expand All @@ -161,7 +161,7 @@ impl RunState {
// imm
Self::s_ext(instr, 5)
};
let res = val1 + val2;
let res = val1 & val2;
self.set_flags(res);
*self.reg(dr) = res;
}
Expand Down Expand Up @@ -192,14 +192,14 @@ impl RunState {

fn ld(&mut self, instr: u16) {
let dr = (instr >> 9) & 0b111;
let val = *self.mem(self.pc + Self::s_ext(instr, 9));
let val = *self.mem(self.pc.wrapping_add(Self::s_ext(instr, 9)));
*self.reg(dr) = val;
self.set_flags(val);
}

fn ldi(&mut self, instr: u16) {
let dr = (instr >> 9) & 0b111;
let ptr = *self.mem(self.pc + Self::s_ext(instr, 9));
let ptr = *self.mem(self.pc.wrapping_add(Self::s_ext(instr, 9)));
let val = *self.mem(ptr);
*self.reg(dr) = val;
self.set_flags(val);
Expand All @@ -209,14 +209,14 @@ impl RunState {
let dr = (instr >> 9) & 0b111;
let br = (instr >> 6) & 0b111;
let ptr = *self.reg(br);
let val = *self.mem(ptr + Self::s_ext(instr, 6));
let val = *self.mem(ptr.wrapping_add(Self::s_ext(instr, 6)));
*self.reg(dr) = val;
self.set_flags(val);
}

fn lea(&mut self, instr: u16) {
let dr = (instr >> 9) & 0b111;
let val = self.pc + Self::s_ext(instr, 9);
let val = self.pc.wrapping_add(Self::s_ext(instr, 9));
*self.reg(dr) = val;
self.set_flags(val);
}
Expand All @@ -236,21 +236,21 @@ impl RunState {
fn st(&mut self, instr: u16) {
let sr = (instr >> 9) & 0b111;
let val = *self.reg(sr);
*self.mem(self.pc + Self::s_ext(instr, 9)) = val;
*self.mem(self.pc.wrapping_add(Self::s_ext(instr, 9))) = val;
}

fn sti(&mut self, instr: u16) {
let sr = (instr >> 9) & 0b111;
let val = *self.reg(sr);
let ptr = *self.mem(self.pc + Self::s_ext(instr, 9));
let ptr = *self.mem(self.pc.wrapping_add(Self::s_ext(instr, 9)));
*self.mem(ptr) = val;
}

fn str(&mut self, instr: u16) {
let sr = (instr >> 9) & 0b111;
let br = (instr >> 6) & 0b111;
let ptr = *self.reg(br);
*self.mem(ptr + Self::s_ext(instr, 6));
*self.mem(ptr.wrapping_add(Self::s_ext(instr, 6)));
}

fn trap(&mut self, instr: u16) {
Expand Down Expand Up @@ -297,6 +297,20 @@ impl RunState {
self.pc = u16::MAX;
println!("\n{:>12}", "Halted".cyan());
}
// putn
0x26 => {
let val = *self.reg(0);
println!("{val}");
}
// reg
0x27 => {
println!("\n------ Registers ------");
for (i, reg) in self.reg.iter().enumerate() {
println!("r{i}: {reg:.>#19}");
// println!("r{i}: {reg:.>#19b}");
}
println!("-----------------------");
}
// unknown
_ => panic!("You called a trap with an unknown vector of {}", trap_vect),
}
Expand Down
2 changes: 2 additions & 0 deletions src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ pub enum TrapKind {
Puts,
Out,
Getc,
Putn,
Reg,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
Expand Down

0 comments on commit bb76b55

Please sign in to comment.