justlex 0.1.0

Configurable lexer with no dependencies
Documentation
// SPDX-License-Identifier: MIT
// Author:  Giovanni Santini
// Mail:    giovanni.santini@proton.me
// Github:  @San7o
//
// justlex.rs
// ==========
//
// Configurable lexer with no dependencies in rust.
//

#![allow(dead_code)]

//
// Imports
//

use std::error::Error;
use std::str::FromStr;
use std::string::String;
use std::vec::Vec;

//
// Enums
//

#[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),
}

//
// Structs
//

/// You can set the keywords, punctuation and input to the lexer via
/// the functions `new` and `set_input`. Then, you can keep
/// calling `next_token` or `next` to receive all the tokens.
pub struct JustLex {
    /// A vector of [`Keyword`] enum and its string value
    pub keywords: Vec<(Keyword, String)>,
    /// A vector of [`Punct`] enum and its string value
    pub puncts: Vec<(Punct, String)>,
    /// The input string to lex
    pub input: Option<String>,
    /// Current lexer position relative to the start of the input
    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 {
    /// Initialize a new lexer with specified keywords and punctuation
    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();

        // Ignore spaces
        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);
        }

        // Check keywords
        for (keyword, string) in &self.keywords {
            if input[self.position..].starts_with(string) {
                self.position += string.len();
                return Ok(Token::Keyword(keyword.clone()));
            }
        }

        // Check puncts
        for (punct, string) in &self.puncts {
            if input[self.position..].starts_with(string) {
                self.position += string.len();
                return Ok(Token::Punct(punct.clone()));
            }
        }

        // Check int
        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;

            // Check float
            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));
        }

        // Symbol
        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()))
    }

    /// Reset the position counter back to the beginning of the input.
    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
    }
}

//
// Functions
//

/// Returns true if `c` is considered a white-space character
pub fn is_space(c: char) -> bool {
    c == ' ' || c == '\t' || c == '\r' || c == '\n'
}

/// Returns true if `c` is a letter of the alphabet (ASCII)
pub fn is_alpha(c: char) -> bool {
    (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}

/// Returns true if `c` is a digit (0 to 9)
pub fn is_numeric(c: char) -> bool {
    c.is_ascii_digit()
}

/// Returns true if `c` is a letter or a digit
pub fn is_alphanumeric(c: char) -> bool {
    is_alpha(c) || is_numeric(c)
}

/// Returns the number of numeric characters that occur from the start
/// of `input`
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
}

/// Returns the number of alphanumeric characters that occur from the
/// start of `input`
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
}