Compare commits

...

2 commits

Author SHA1 Message Date
1ad13b2693
main.rs: simplify tokenizer, add test 2025-03-27 09:33:33 +01:00
7842cb4b84
flake.nix: add bacon 2025-03-27 09:33:19 +01:00
2 changed files with 18 additions and 28 deletions

View file

@ -23,6 +23,7 @@
cargo cargo
rustc rustc
rustfmt rustfmt
bacon
; ;
inherit inherit
(pkgsFor.${system}.rustPackages) (pkgsFor.${system}.rustPackages)

View file

@ -1,6 +1,6 @@
use std::io; use std::io;
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
enum Symbol { enum Symbol {
Number, Number,
@ -44,38 +44,27 @@ fn get_user_input() -> io::Result<String> {
Ok(buffer) Ok(buffer)
} }
#[test]
fn try_tokenizing() {
let tokenized_input = tokenize("1 + 1").unwrap();
let result = vec![Symbol::Number, Symbol::Add, Symbol::Number];
assert!(tokenized_input == result, "1 + 1 not working");
}
fn tokenize(input: &str) -> Result<Vec<Symbol>, ParseError> { fn tokenize(input: &str) -> Result<Vec<Symbol>, ParseError> {
let mut tokens: Vec<Symbol> = vec![]; let mut tokens: Vec<Symbol> = vec![];
for (i, c) in input.chars().enumerate() { for (i, c) in input.chars().enumerate() {
match c { match c {
' ' => { ' ' => continue,
continue; '(' => tokens.push(Symbol::LeftBracket),
} ')' => tokens.push(Symbol::RightBracket),
'(' => { '+' => tokens.push(Symbol::Add),
tokens.push(Symbol::LeftBracket); '-' => tokens.push(Symbol::Sub),
} '*' => tokens.push(Symbol::Mul),
')' => { '/' => tokens.push(Symbol::Div),
tokens.push(Symbol::RightBracket); '0'..='9' => tokens.push(Symbol::Number),
} '\n' => break,
'+' => {
tokens.push(Symbol::Add);
}
'-' => {
tokens.push(Symbol::Sub);
}
'*' => {
tokens.push(Symbol::Mul);
}
'/' => {
tokens.push(Symbol::Div);
}
'0'..='9' => {
tokens.push(Symbol::Number);
}
'\n' => {
break;
}
_ => return Err(ParseError::WrongTokenError { pos: i }), _ => return Err(ParseError::WrongTokenError { pos: i }),
} }
} }