#![allow(dead_code)]
use std::error::Error;
use std::str::FromStr;
use std::string::String;
use std::vec::Vec;
#[derive(Default, Debug, PartialEq, Eq, Hash, Clone)]
pub enum Punct {
#[default]
None,
Comma,
Colon,
Semicolon,
Exclamation,
Dot,
Hash,
Dollar,
Percent,
Ampersand,
OpenRound,
CloseRound,
OpenSquare,
CloseSquare,
OpenCurly,
CloseCutly,
Asterisk,
Plus,
Minus,
Slash,
BackSlash,
Less,
Equals,
Greater,
QuestionMark,
At,
Tilde,
Pipe,
Arrow,
PlusPlus,
MinusMinus,
LessEqual,
GreaterEqual,
EqualEqual,
Comment,
OpenMultilineComment,
CloseMultilineComment,
}
#[derive(Default, Debug, PartialEq, Eq, Hash, Clone)]
pub enum Keyword {
#[default]
None,
If,
Else,
Return,
}
#[derive(Default, Debug, PartialEq)]
pub enum Token {
#[default]
None,
Symbol(String),
Integer(i32),
Float(f32),
Punct(Punct),
Keyword(Keyword),
}
pub struct JustLex {
pub keywords: Vec<(Keyword, String)>,
pub puncts: Vec<(Punct, String)>,
pub input: Option<String>,
pub position: usize,
}
impl Default for JustLex {
fn default() -> Self {
let keywords = vec![
(Keyword::If, String::from("if")),
(Keyword::Else, String::from("else")),
(Keyword::Return, String::from("return"))];
let puncts = vec![
(Punct::Arrow, String::from("->")),
(Punct::PlusPlus, String::from("++")),
(Punct::MinusMinus, String::from("--")),
(Punct::LessEqual, String::from("<=")),
(Punct::GreaterEqual, String::from(">=")),
(Punct::EqualEqual, String::from("==")),
(Punct::Comment, String::from("//")),
(Punct::OpenMultilineComment, String::from("/*")),
(Punct::CloseMultilineComment, String::from("*/")),
(Punct::Comma, String::from(",")),
(Punct::Colon, String::from(":")),
(Punct::Semicolon, String::from(";")),
(Punct::Dot, String::from(".")),
(Punct::Exclamation, String::from("!")),
(Punct::Hash, String::from("#")),
(Punct::Dollar, String::from("$")),
(Punct::Percent, String::from("%")),
(Punct::Ampersand, String::from("&")),
(Punct::OpenRound, String::from("(")),
(Punct::CloseRound, String::from(")")),
(Punct::OpenSquare, String::from("[")),
(Punct::CloseSquare, String::from("]")),
(Punct::OpenCurly, String::from("{")),
(Punct::CloseCutly, String::from("}")),
(Punct::Asterisk, String::from("*")),
(Punct::Plus, String::from("+")),
(Punct::Minus, String::from("-")),
(Punct::Slash, String::from("/")),
(Punct::BackSlash, String::from("\\")),
(Punct::Less, String::from("<")),
(Punct::Equals, String::from("=")),
(Punct::Greater, String::from(">")),
(Punct::QuestionMark, String::from("?")),
(Punct::At, String::from("@")),
(Punct::Tilde, String::from("~")),
(Punct::Pipe, String::from("|")),
];
Self {
keywords,
puncts,
input: None,
position: 0,
}
}
}
impl JustLex {
pub fn new(keywords: Vec<(Keyword, String)>, puncts: Vec<(Punct, String)>) -> Self {
Self {
keywords,
puncts,
input: None,
position: 0,
}
}
pub fn set_input(&mut self, input: String) {
self.input = Some(input);
}
pub fn next_token(&mut self) -> Result<Token, Box<dyn Error>> {
if self.input.is_none() {
return Ok(Token::None);
}
let input: &str = self.input.as_ref().unwrap();
while self.position < input.len() && is_space(input.as_bytes()[self.position] as char) {
self.position += 1
}
if self.position >= input.len() {
return Ok(Token::None);
}
for (keyword, string) in &self.keywords {
if input[self.position..].starts_with(string) {
self.position += string.len();
return Ok(Token::Keyword(keyword.clone()));
}
}
for (punct, string) in &self.puncts {
if input[self.position..].starts_with(string) {
self.position += string.len();
return Ok(Token::Punct(punct.clone()));
}
}
if is_numeric(input.as_bytes()[self.position] as char) {
if self.position + 1 >= input.len() {
self.position += 1;
return Ok(Token::Integer(
input.as_bytes()[self.position] as i32 - ('0' as i32),
));
}
if input.as_bytes()[self.position + 1] == b'x' {
self.position += 2;
let hex_len = numeric_len(&input[self.position..]);
let hex_number =
i32::from_str_radix(&input[self.position..self.position + hex_len], 16)?;
self.position += hex_len;
return Ok(Token::Integer(hex_number));
}
if input.as_bytes()[self.position + 1] == b'b' {
self.position += 2;
let bin_len = numeric_len(&input[self.position..]);
let bin_number =
i32::from_str_radix(&input[self.position..self.position + bin_len], 2)?;
self.position += bin_len;
return Ok(Token::Integer(bin_number));
}
let len = numeric_len(&input[self.position..]);
let number = (input[self.position..self.position + len]).parse::<i32>()?;
self.position += len;
if self.position >= input.len() {
return Ok(Token::Integer(number));
}
if input.as_bytes()[self.position] != b'.' {
return Ok(Token::Integer(number));
}
if self.position + 1 >= input.len() {
return Ok(Token::Integer(number));
}
if !is_numeric(input.as_bytes()[self.position + 1] as char) {
return Ok(Token::Integer(number));
}
let fractional_len = numeric_len(&input[self.position + 1..]);
let float_number =
f32::from_str(&input[self.position - len..self.position + fractional_len + 1])?;
self.position += fractional_len + 1;
return Ok(Token::Float(float_number));
}
let symbol_len = alphanumeric_len(&input[self.position..]);
let symbol = String::from(&input[self.position..self.position + symbol_len]);
self.position += symbol_len;
Ok(Token::Symbol(symbol.clone()))
}
pub fn reset(&mut self) {
self.position = 0;
}
}
impl Iterator for JustLex {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
if let Ok(token) = self.next_token() {
if token != Token::None {
return Some(token);
}
}
None
}
}
pub fn is_space(c: char) -> bool {
c == ' ' || c == '\t' || c == '\r' || c == '\n'
}
pub fn is_alpha(c: char) -> bool {
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
pub fn is_numeric(c: char) -> bool {
c.is_ascii_digit()
}
pub fn is_alphanumeric(c: char) -> bool {
is_alpha(c) || is_numeric(c)
}
pub fn numeric_len(input: &str) -> usize {
let mut len: usize = 0;
while len < input.len() && is_numeric(input.as_bytes()[len] as char) {
len += 1;
}
len
}
pub fn alphanumeric_len(input: &str) -> usize {
let mut len: usize = 0;
while len < input.len() && is_alphanumeric(input.as_bytes()[len] as char) {
len += 1;
}
len
}