From 6d7c58a512f821aabed87b61f2777568e1b3aab1 Mon Sep 17 00:00:00 2001 From: overflowerror Date: Sat, 27 Apr 2024 17:08:12 +0200 Subject: [PATCH] fix: newline escapes in char literal --- compiler/src/lexer.l | 15 +++++++++++++-- compiler/test/cases/001a-bug-newline-in-char.in | 1 + compiler/test/cases/001a-bug-newline-in-char.out | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 compiler/test/cases/001a-bug-newline-in-char.in create mode 100644 compiler/test/cases/001a-bug-newline-in-char.out diff --git a/compiler/src/lexer.l b/compiler/src/lexer.l index 361ae4a..b52b345 100644 --- a/compiler/src/lexer.l +++ b/compiler/src/lexer.l @@ -10,7 +10,7 @@ if "if" else "else" while "while" -char "'"."'" +char "'"([^\\]|[\\]n|[\\]t|[\\]{2})"'" id [a-zA-Z_][a-zA-Z0-9_]* %option noyywrap @@ -34,6 +34,17 @@ id [a-zA-Z_][a-zA-Z0-9_]* #include "y.tab.h" +char char_escape(const char* yytext) { + if (yytext[1] == '\\') { + if (yytext[2] == '\\') return '\\'; + else if (yytext[2] == 'n') return '\n'; + else if (yytext[2] == 't') return '\t'; + else lex_panic("unknown escape sequence: %s\n", yytext); + } else { + return yytext[1]; + } +} + %} %% @@ -106,7 +117,7 @@ strbuf_t strbuf = NULL; {dec} { yylval.number = strtol(yytext, NULL, 10); return NUM; } {oct} { yylval.number = strtol(yytext + 1, NULL, 8); return NUM; } {bin} { yylval.number = strtol(yytext + 2, NULL, 2); return NUM; } -{char} { yylval.ch = yytext[1]; return CHAR; } +{char} { yylval.ch = char_escape(yytext); return CHAR; } {id} { yylval.id = strdup(yytext); return ID; } {whitespace}+ { } diff --git a/compiler/test/cases/001a-bug-newline-in-char.in b/compiler/test/cases/001a-bug-newline-in-char.in new file mode 100644 index 0000000..0a74cff --- /dev/null +++ b/compiler/test/cases/001a-bug-newline-in-char.in @@ -0,0 +1 @@ +print('\n'); \ No newline at end of file diff --git a/compiler/test/cases/001a-bug-newline-in-char.out b/compiler/test/cases/001a-bug-newline-in-char.out new file mode 100644 index 0000000..34f0ecc --- /dev/null +++ b/compiler/test/cases/001a-bug-newline-in-char.out @@ -0,0 +1 @@ +[-]++++++++++.