From 7c6ea56df454739bf750a076c17c643f686cd875 Mon Sep 17 00:00:00 2001 From: Gabriel <68819302+obsidianical@users.noreply.github.com> Date: Fri, 28 Jan 2022 22:38:44 +0100 Subject: [PATCH] aaa --- src/error.rs | 28 ++++++++++++++++++++++++++++ src/main.rs | 1 + src/parsing/lexer.rs | 23 +++++++++++++---------- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/error.rs b/src/error.rs index e69de29..2559f8e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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)) + } +} diff --git a/src/main.rs b/src/main.rs index 60a9c2c..77cb940 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ use std::fs; pub mod shell; pub mod parsing; +pub mod error; use parsing::preprocessor::preprocess; diff --git a/src/parsing/lexer.rs b/src/parsing/lexer.rs index cf779f1..66d1e5e 100644 --- a/src/parsing/lexer.rs +++ b/src/parsing/lexer.rs @@ -1,5 +1,6 @@ use super::preprocessor::preprocess; use super::token::Token; +use crate::error::{IllegalCharacterError, Position}; const DIGITS: &str = "0123456789"; const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz"; @@ -7,26 +8,28 @@ const ALPHABET_C: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub struct Lexer { code: String, - pos: usize, - current: Option, + pos: Position, + current: char, } impl Lexer { pub fn new(code: String) -> Lexer { Lexer { code: code.clone(), - pos: 0, + pos: Position { line: 0, character: 0 }, current: code.chars().nth(0), } } pub fn next(&mut self) { - self.pos += 1; - self.current = if self.pos < self.code.len() { - self.code.chars().nth(self.pos) - } else { - None - }; + self.pos.character += 1; + self.current = switch self.code.chars().nth(self.pos.character) { + Some(c) => { + let chara = ; + if chara == '\n' { self.pos.line += 1; }; + chara + }, + None => {} } pub fn tokenize(&mut self) -> Vec { @@ -55,7 +58,7 @@ impl Lexer { jump_next = true; Some(self.make_nr_token()) } else { - None + IllegalCharacterError::new() } }, };