Initial commit

This commit is contained in:
2021-11-28 23:08:27 +01:00
commit 3bed67c2b6
16 changed files with 460 additions and 0 deletions

7
src/errors.rs Normal file
View File

@ -0,0 +1,7 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum CalculatorErrors {
#[error("IOError")]
IOError,
}

13
src/lexer/errors.rs Normal file
View File

@ -0,0 +1,13 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum LexerErrors {
#[error("unexpected character {char} at position {pos} in context {context}")]
UnexpectedCharacter {
char: char,
pos: u32,
context: String,
},
#[error("cannot lex an empty text sequence")]
EmptyTextSequenceError,
}

42
src/lexer/mod.rs Normal file
View File

@ -0,0 +1,42 @@
mod errors;
mod tokens;
use std::collections::VecDeque;
use std::fs::File;
use std::path::Path;
use std::str::Chars;
use tokens::Token;
use crate::lexer::errors::LexerErrors;
use crate::lexer::errors::LexerErrors::EmptyTextSequenceError;
pub type Result<T> = std::result::Result<T, errors::LexerErrors>;
pub struct Lexer<'a> {
input: String,
chars: Chars<'a>,
}
impl Lexer<'_> {
/// Create a new Lexer for the given String
/// Example:
/// ```
/// use cb_calculator::lexer;
/// let text = "some text";
/// lexer::Lexer::new(String::from(text));
/// ```
#[inline]
pub fn new(input: String) -> Lexer {
Lexer { input, chars: input.chars() }
}
// Get the next token
pub fn next(&mut self) -> Result<Option<Token>> {
let mut buffer: Vec<char> = Vec::new();
loop {
if let Some(c) = self.chars.next() {
buffer.push(c);
}
}
}
}

42
src/lexer/tokens.rs Normal file
View File

@ -0,0 +1,42 @@
/// # Token Metadata
/// Data contained is:
/// * File that the token was parsed in
/// * Line that the token was parsed in
/// * Position of the *first character making up the token* in said line
#[derive(Debug)]
pub struct TokenMeta {
file: String,
line: u32,
pos: u32,
}
#[derive(Debug)]
pub enum OpType {
MUL,
DIV,
ADD,
SUB,
POW,
}
/// Bracket types, either OPEN or CLOSE.
#[derive(Debug)]
pub enum BrType {
OPEN,
CLOSE,
}
/// # Tokens
/// The tokens all contain [metadata](TokenMeta).
/// 1. `ID`: A number, parsed into 64 bit floating-point.
/// 1. `OBR`: An opening bracket (`(`).
/// 1. `CBR`: A closing bracket (`)`).
/// 1. `OP`: An operation. Containing an [Operation Type](OpType).
#[derive(Debug)]
pub enum Token {
ID (TokenMeta, f64),
OBR (TokenMeta),
CBR (TokenMeta),
OP (TokenMeta, OpType),
}

6
src/lib.rs Normal file
View File

@ -0,0 +1,6 @@
pub mod lexer;
pub mod errors;
pub fn test() {
println!("{}", "hi there");
}

6
src/main.rs Normal file
View File

@ -0,0 +1,6 @@
use cb_calculator::lexer::Lexer;
fn main() {
let lexer = Lexer::new("15+(30^2-5)*2/4".chars().collect());
println!("Hello, world!");
}