diff options
| author | Tom Harley | 2023-02-01 20:53:24 +0000 |
|---|---|---|
| committer | Tom Harley | 2023-02-01 20:56:29 +0000 |
| commit | 0fcbdb1b6d4111792aa6fff4b4222652dbee47a9 (patch) | |
| tree | ebb67adc5ed2105d7dbf19da0f3d813e61bd6771 | |
| parent | Fix unit tests (diff) | |
| download | sinter-0fcbdb1b6d4111792aa6fff4b4222652dbee47a9.tar.gz sinter-0fcbdb1b6d4111792aa6fff4b4222652dbee47a9.zip | |
Add escape sequence interpretation
Sinter now has , and \ escape sequences.
| -rw-r--r-- | lex.l | 77 |
1 files changed, 73 insertions, 4 deletions
@@ -10,6 +10,8 @@ #include "sexpr.h" #include "sinc.h" #include "parse.h" +#include "error.h" +#include "debug.h" void yyerror(const char *s, ...); char *str_value(char *s); @@ -30,13 +32,80 @@ void update_yylloc() { #define YY_USER_ACTION update_yylloc(); +/** + * Calculate the size of a string value from a literal, by skipping backslashes + * and stopping at the first unescaped double quote encountered. + */ +size_t string_literal_size(char *s) { + size_t result = 0; + + for (char *c = s; *c != '"'; result++, c++) { + if (*c == '\\') { + c++; + } + } + + return result; +} + +/** + * Copy a string literal into a new buffer, removing things like escape + * sequences. + * + * n is the size of the literal, NOT the size of the buffer (the buffer should + * be one char larger for the null terminator). + */ +void deliteral_string(char *literal, char *buf, size_t n) { + char *c = literal; + + for (size_t i = 0; i < n; c++, i++) { + if (*c == '\\') { + c++; + switch (*c) { + case 'n': + buf[i] = '\n'; + break; + + case 't': + buf[i] = '\t'; + break; + + case '\\': + buf[i] = '\\'; + break; + + default: + warn("unrecognised escape sequence \\%c", *c); + buf[i] = *c; + } + + } else { + buf[i] = *c; + } + } + + buf[n] = '\0'; +} + char *str_value(char *s) { + /* + * This function is given a string literal between quotes, for example: + * + * "hello world\n" + * + * We need to do a few things here: + * 1. drop the quotes; + * 2. replace escape sequences with the character they represent. + */ + s++; - /* FIXME: strdup allocates memory! */ - char *ret = strdup(s); - ret[strlen(s) - 1] = 0; + size_t size = string_literal_size(s); + char *result = malloc(size + 1); + deliteral_string(s, result, size); + + debug("in: %s\tout: %s (size %zu)\n", s-1, result, size); - return ret; + return result; } %} |
