inital commit

This commit is contained in:
nora 2021-09-17 14:13:16 +02:00
commit 103068c96e
5 changed files with 94 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
.idea
*.iml

7
Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "m8ni-rs"
version = "0.1.0"

8
Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "m8ni-rs"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

54
src/main.rs Normal file
View file

@ -0,0 +1,54 @@
enum Stmt {
Inc(usize),
Dec(usize),
IsZero(usize, usize),
Jump(usize),
Stop
}
fn main() {
let filename = match std::env::args().skip(1).next() {
Some(name) => name,
None => eprintln!("error: no file provided.\nUsage: <filename>"),
};
let program = std::fs::read_to_string(filename).unwrap();
let statements = parse(&program);
}
fn parse(text: &str) -> Result<Vec<Stmt>, String> {
text.lines().map(parse_line).collect()
}
fn parse_line(line: &str) -> Result<Stmt, String> {
const NO_REGISTER: fn() -> String = || "No register".to_string();
const NO_LINE_NUMBER: fn() -> String = || "No line number".to_string();
const EMPTY_LINE: fn() -> String = || "Empty line not allowed".to_string();
let mut iter = line.split_ascii_whitespace();
let first = iter.next().ok_or_else(EMPTY_LINE)?;
Ok(match first {
"INC" => {
let register = iter.next().ok_or_else(NO_REGISTER)?.parse()?;
Stmt::Inc(register)
}
"DEC" => {
let register = iter.next().ok_or_else(NO_REGISTER)?.parse()?;
Stmt::Dec(register)
}
"IS_ZERO" => {
let register = iter.next().ok_or_else(NO_REGISTER)?.parse()?;
let line_number = iter.next().ok_or_else(NO_LINE_NUMBER)?.parse()?;
Stmt::IsZero(register, line_number)
}
"JUMP" => {
let line_number = iter.next().ok_or_else(NO_LINE_NUMBER)?.parse()?;
Stmt::Jump(line_number)
}
"STOP" => Stmt::Stop,
stmt => return Err(format!("Illegal instruction: '{}'", stmt)),
})
}

22
test.m8 Normal file
View file

@ -0,0 +1,22 @@
INC 1
INC 1
INC 1
INC 2
INC 2
IS_ZERO 1 22
DEC 1
IS_ZERO 2 13
INC 4
INC 5
DEC 2
JUMP 8
IS_ZERO 4 17
INC 3
DEC 4
JUMP 13
IS_ZERO 5 21
INC 2
DEC 5
JUMP 17
JUMP 6
STOP