Skip to content

Commit 853663f

Browse files
authored
Merge pull request #177 from ChAoSUnItY/refactor/comment-div
Refine comment and division operator tokenization logic
2 parents 4ebc0bb + fefe803 commit 853663f

File tree

2 files changed

+50
-9
lines changed

2 files changed

+50
-9
lines changed

src/lexer.c

+17-9
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,10 @@ token_t lex_token_internal(bool aliasing)
216216
error("Unknown directive");
217217
}
218218

219-
/* C-style comments */
220219
if (next_char == '/') {
221-
read_char(false);
220+
read_char(true);
221+
222+
/* C-style comments */
222223
if (next_char == '*') {
223224
/* in a comment, skip until end */
224225
do {
@@ -231,14 +232,21 @@ token_t lex_token_internal(bool aliasing)
231232
}
232233
}
233234
} while (next_char);
234-
} else {
235-
/* single '/', predict divide */
236-
if (next_char == ' ')
237-
read_char(true);
238-
return T_divide;
235+
236+
if (!next_char)
237+
error("Unenclosed C-style comment");
238+
return lex_token_internal(aliasing);
239239
}
240-
/* TODO: check invalid cases */
241-
error("Unexpected '/'");
240+
241+
/* C++-style comments */
242+
if (next_char == '/') {
243+
do {
244+
read_char(false);
245+
} while (next_char && !is_newline(next_char));
246+
return lex_token_internal(aliasing);
247+
}
248+
249+
return T_divide;
242250
}
243251

244252
if (is_digit(next_char)) {

tests/driver.sh

+33
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,39 @@ items 0 "int x; for(x = 10; x > 0; x--); return x;"
233233
items 30 "int i; int acc; i = 0; acc = 0; do { i = i + 1; if (i - 1 < 5) continue; acc = acc + i; if (i == 9) break; } while (i < 10); return acc;"
234234
items 26 "int acc; acc = 0; int i; for (i = 0; i < 100; i++) { if (i < 5) continue; if (i == 9) break; acc = acc + i; } return acc;"
235235

236+
# C-style comments / C++-style comments
237+
# Start
238+
try_ 0 << EOF
239+
/* This is a test C-style comments */
240+
int main() { return 0; }
241+
EOF
242+
try_ 0 << EOF
243+
// This is a test C++-style comments
244+
int main() { return 0; }
245+
EOF
246+
# Middle
247+
try_ 0 << EOF
248+
int main() {
249+
/* This is a test C-style comments */
250+
return 0;
251+
}
252+
EOF
253+
try_ 0 << EOF
254+
int main() {
255+
// This is a test C++-style comments
256+
return 0;
257+
}
258+
EOF
259+
# End
260+
try_ 0 << EOF
261+
int main() { return 0; }
262+
/* This is a test C-style comments */
263+
EOF
264+
try_ 0 << EOF
265+
int main() { return 0; }
266+
// This is a test C++-style comments
267+
EOF
268+
236269
# functions
237270
try_ 55 << EOF
238271
int sum(int m, int n) {

0 commit comments

Comments
 (0)