Skip to content

Commit 51014cc

Browse files
committed
fix: lexer parse comment bug
1 parent 085cf9d commit 51014cc

File tree

3 files changed

+78
-2
lines changed

3 files changed

+78
-2
lines changed

lexer/lexer_test.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,15 @@ mod tests {
6464
fn test_lexer_bool() {
6565
test_lexer_common("bool", "let y=true");
6666
}
67+
68+
#[test]
69+
fn test_comments_then_blank_line() {
70+
// Ensure comments followed by a blank line are skipped correctly
71+
// and do not yield ILLEGAL tokens.
72+
test_lexer_common("comments_then_blank_line", "// comment\n\nlet x = 5");
73+
}
74+
75+
6776

6877
#[test]
6978
fn test_lexer_complex() {

lexer/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ impl<'a> Lexer<'a> {
4747

4848
pub fn next_token(&mut self) -> Token {
4949
// println!("self ch {}, position {} read_position {}", self.ch, self.position, self.read_position);
50-
self.skip_whitespace();
51-
self.skip_comments();
50+
// Skip any whitespace and successive line comments before producing a token.
51+
self.skip_ignorable();
5252
let t = match self.ch {
5353
'=' => {
5454
if self.peek_char() == '=' {
@@ -115,6 +115,18 @@ impl<'a> Lexer<'a> {
115115
}
116116
}
117117

118+
fn skip_ignorable(&mut self) {
119+
loop {
120+
self.skip_whitespace();
121+
if self.ch == '/' && self.peek_char() == '/' {
122+
self.skip_comments();
123+
// Continue the loop, in case there are more comments or whitespace
124+
continue;
125+
}
126+
break;
127+
}
128+
}
129+
118130
fn skip_comments(&mut self) {
119131
if self.ch == '/' && self.peek_char() == '/' {
120132
self.read_char();
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
source: lexer/lexer_test.rs
3+
expression: "// comment\n\nlet x = 5"
4+
---
5+
[
6+
{
7+
"kind": {
8+
"type": "LET"
9+
},
10+
"span": {
11+
"start": 12,
12+
"end": 15
13+
}
14+
},
15+
{
16+
"kind": {
17+
"type": "IDENTIFIER",
18+
"value": {
19+
"name": "x"
20+
}
21+
},
22+
"span": {
23+
"start": 16,
24+
"end": 17
25+
}
26+
},
27+
{
28+
"kind": {
29+
"type": "ASSIGN"
30+
},
31+
"span": {
32+
"start": 18,
33+
"end": 19
34+
}
35+
},
36+
{
37+
"kind": {
38+
"type": "INT",
39+
"value": 5
40+
},
41+
"span": {
42+
"start": 20,
43+
"end": 21
44+
}
45+
},
46+
{
47+
"kind": {
48+
"type": "EOF"
49+
},
50+
"span": {
51+
"start": 21,
52+
"end": 22
53+
}
54+
}
55+
]

0 commit comments

Comments
 (0)