Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lexer: add floats #56

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ pub enum TokenKind {
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Value {
Int,
Float,
Copy link
Collaborator

@YerinAlexey YerinAlexey Oct 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should keep floats and integers inside Value like we do with strings?

Str(String),
}

Expand Down Expand Up @@ -371,24 +372,27 @@ impl Cursor<'_> {
}

fn number(&mut self) -> TokenKind {
match self.first() {
let value_kind = match self.first() {
'b' => {
self.bump();
self.eat_binary_digits();
Value::Int
}
'o' => {
self.bump();
self.eat_octal_digits();
Value::Int
}
'x' => {
self.bump();
self.eat_hex_digits();
Value::Int
}
_ => {
self.eat_digits();
self.eat_digits()
}
};
TokenKind::Literal(Value::Int)
TokenKind::Literal(value_kind)
}

fn string(&mut self, end: char) -> Result<TokenKind, String> {
Expand Down Expand Up @@ -434,21 +438,21 @@ impl Cursor<'_> {
TokenKind::Comment
}

fn eat_digits(&mut self) -> bool {
let mut has_digits = false;
fn eat_digits(&mut self) -> Value {
let mut value_kind = Value::Int;
loop {
match self.first() {
'_' => {
'0'..='9' | '_' => {
self.bump();
}
'0'..='9' => {
has_digits = true;
'.' => {
value_kind = Value::Float;
self.bump();
}
_ => break,
}
}
has_digits
value_kind
}

fn eat_binary_digits(&mut self) -> bool {
Expand Down
39 changes: 39 additions & 0 deletions src/lexer/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,42 @@ fn fib() {}
}
);
}

#[test]
fn test_floats() {
let mut tokens = tokenize("1.23").unwrap().into_iter();

assert_eq!(
tokens.next().unwrap(),
Token {
len: 4,
kind: TokenKind::Literal(Value::Float),
raw: "1.23".to_owned(),
pos: Position {
raw: 3,
line: 1,
offset: 3
}
}
);
}

#[test]
#[ignore]
fn test_negative_floats() {
let mut tokens = tokenize("-1.23").unwrap().into_iter();

assert_eq!(
tokens.next().unwrap(),
Token {
len: 4,
kind: TokenKind::Literal(Value::Float),
raw: "-1.23".to_owned(),
pos: Position {
raw: 4,
line: 1,
offset: 4
}
}
);
}