This commit is contained in:
Schrottkatze 2022-01-28 22:38:44 +01:00
parent 72a8791111
commit 7c6ea56df4
3 changed files with 42 additions and 10 deletions

View file

@ -0,0 +1,28 @@
pub struct Position {
pub line: u32,
pub character: usize
}
pub struct IllegalCharacterError {
pub pos: Position,
pub cause: char,
}
trait Error {
fn make_msg(&self) -> String;
}
impl IllegalCharacterError {
pub fn new(pos: Position, chara: char) -> IllegalCharacterError {
IllegalCharacterError {
pos,
cause: chara
}
}
}
impl Error for IllegalCharacterError {
fn make_msg(&self) -> String {
String::from(format!("IllegalCharacterError at {}, {}: Unknown character '{}'", self.pos.line, self.pos.character % self.pos.line as usize, self.cause))
}
}

View file

@ -3,6 +3,7 @@ use std::fs;
pub mod shell; pub mod shell;
pub mod parsing; pub mod parsing;
pub mod error;
use parsing::preprocessor::preprocess; use parsing::preprocessor::preprocess;

View file

@ -1,5 +1,6 @@
use super::preprocessor::preprocess; use super::preprocessor::preprocess;
use super::token::Token; use super::token::Token;
use crate::error::{IllegalCharacterError, Position};
const DIGITS: &str = "0123456789"; const DIGITS: &str = "0123456789";
const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz"; const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";
@ -7,26 +8,28 @@ const ALPHABET_C: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub struct Lexer { pub struct Lexer {
code: String, code: String,
pos: usize, pos: Position,
current: Option<char>, current: char,
} }
impl Lexer { impl Lexer {
pub fn new(code: String) -> Lexer { pub fn new(code: String) -> Lexer {
Lexer { Lexer {
code: code.clone(), code: code.clone(),
pos: 0, pos: Position { line: 0, character: 0 },
current: code.chars().nth(0), current: code.chars().nth(0),
} }
} }
pub fn next(&mut self) { pub fn next(&mut self) {
self.pos += 1; self.pos.character += 1;
self.current = if self.pos < self.code.len() { self.current = switch self.code.chars().nth(self.pos.character) {
self.code.chars().nth(self.pos) Some(c) => {
} else { let chara = ;
None if chara == '\n' { self.pos.line += 1; };
}; chara
},
None => {}
} }
pub fn tokenize(&mut self) -> Vec<Token> { pub fn tokenize(&mut self) -> Vec<Token> {
@ -55,7 +58,7 @@ impl Lexer {
jump_next = true; jump_next = true;
Some(self.make_nr_token()) Some(self.make_nr_token())
} else { } else {
None IllegalCharacterError::new()
} }
}, },
}; };