Skip to content

Commit 043e2cb

Browse files
committed
feat: add comment support
close #52
1 parent e3305c4 commit 043e2cb

File tree

4 files changed

+190
-150
lines changed

4 files changed

+190
-150
lines changed

lexer/lexer_test.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ mod tests {
3535
test_lexer_common("let", "let x=5");
3636
}
3737

38+
#[test]
39+
fn test_comments() {
40+
test_lexer_common("comments", "// I am comments");
41+
}
42+
3843
#[test]
3944
fn test_lexer_let_with_space() {
4045
test_lexer_common("let_with_space", "let x = 5");
@@ -62,7 +67,9 @@ mod tests {
6267

6368
#[test]
6469
fn test_lexer_complex() {
65-
test_lexer_common("complex", "let five = 5;
70+
test_lexer_common("complex", "
71+
// welcome to monkeylang
72+
let five = 5;
6673
let ten = 10;
6774
6875
let add = fn(x, y) {

lexer/lib.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ impl<'a> Lexer<'a> {
5353
pub fn next_token(&mut self) -> Token {
5454
// println!("self ch {}, position {} read_position {}", self.ch, self.position, self.read_position);
5555
self.skip_whitespace();
56+
self.skip_comments();
5657
let t = match self.ch {
5758
'=' => {
5859
if self.peek_char() == '=' {
@@ -113,6 +114,23 @@ impl<'a> Lexer<'a> {
113114
}
114115
}
115116

117+
fn skip_comments(&mut self) {
118+
if self.ch == '/' && self.peek_char() == '/' {
119+
self.read_char();
120+
self.read_char();
121+
loop {
122+
self.read_char();
123+
if self.ch == '\n' || self.ch == '\u{0}' {
124+
// consume the comments end
125+
if self.ch == '\n' {
126+
self.read_char();
127+
}
128+
break
129+
}
130+
}
131+
}
132+
}
133+
116134
fn read_identifier(&mut self) -> (usize, usize, String) {
117135
let pos = self.position;
118136
while is_letter(self.ch) {
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
source: lexer/lexer_test.rs
3+
expression: // I am comments
4+
---
5+
[
6+
{
7+
"kind": {
8+
"type": "EOF"
9+
},
10+
"span": {
11+
"start": 16,
12+
"end": 17
13+
}
14+
}
15+
]

0 commit comments

Comments
 (0)