From 0fcbdb1b6d4111792aa6fff4b4222652dbee47a9 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 1 Feb 2023 20:53:24 +0000 Subject: Add escape sequence interpretation Sinter now has \n, \t, and \\ escape sequences. --- lex.l | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 73 insertions(+), 4 deletions(-) diff --git a/lex.l b/lex.l index a548576..2a07507 100644 --- a/lex.l +++ b/lex.l @@ -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; } %} -- cgit v1.2.1