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

Refine comment and division operator tokenization logic #177

Merged
merged 1 commit into from
Jan 17, 2025
Merged
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
26 changes: 17 additions & 9 deletions src/lexer.c
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,10 @@ token_t lex_token_internal(bool aliasing)
error("Unknown directive");
}

/* C-style comments */
if (next_char == '/') {
read_char(false);
read_char(true);

/* C-style comments */
if (next_char == '*') {
/* in a comment, skip until end */
do {
Expand All @@ -231,14 +232,21 @@ token_t lex_token_internal(bool aliasing)
}
}
} while (next_char);
} else {
/* single '/', predict divide */
if (next_char == ' ')
read_char(true);
return T_divide;

if (!next_char)
error("Unenclosed C-style comment");
return lex_token_internal(aliasing);
}
/* TODO: check invalid cases */
error("Unexpected '/'");

/* C++-style comments */
if (next_char == '/') {
do {
read_char(false);
} while (next_char && !is_newline(next_char));
return lex_token_internal(aliasing);
}

return T_divide;
}

if (is_digit(next_char)) {
Expand Down
33 changes: 33 additions & 0 deletions tests/driver.sh
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,39 @@ items 0 "int x; for(x = 10; x > 0; x--); return x;"
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;"
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;"

# C-style comments / C++-style comments
# Start
try_ 0 << EOF
/* This is a test C-style comments */
int main() { return 0; }
EOF
try_ 0 << EOF
// This is a test C++-style comments
int main() { return 0; }
EOF
# Middle
try_ 0 << EOF
int main() {
/* This is a test C-style comments */
return 0;
}
EOF
try_ 0 << EOF
int main() {
// This is a test C++-style comments
return 0;
}
EOF
# End
try_ 0 << EOF
int main() { return 0; }
/* This is a test C-style comments */
EOF
try_ 0 << EOF
int main() { return 0; }
// This is a test C++-style comments
EOF

# functions
try_ 55 << EOF
int sum(int m, int n) {
Expand Down