Skip to content

Commit

Permalink
Fix: Built-in output serve now correctly handles strings in the out…
Browse files Browse the repository at this point in the history
…put buffer

#208
  • Loading branch information
KennyOliver committed Jan 15, 2025
1 parent ceb6e81 commit b22d9d9
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions src/interpreter/builtins.c
Original file line number Diff line number Diff line change
Expand Up @@ -374,9 +374,18 @@ InterpretResult builtin_output(ASTNode *node, Environment *env) {
snprintf(temp_buffer, sizeof(temp_buffer), "%lld",
lv.data.integer);
break;
case TYPE_STRING:
print_formatted_string(lv.data.string);
case TYPE_STRING: {
char *processed = process_escape_sequences(lv.data.string);
if (processed) {
snprintf(temp_buffer, sizeof(temp_buffer), "%s", processed);
free(processed);
} else {
// Fallback
snprintf(temp_buffer, sizeof(temp_buffer), "%s",
lv.data.string);
}
break;
}
case TYPE_BOOLEAN:
snprintf(temp_buffer, sizeof(temp_buffer), "%s",
lv.data.boolean ? "True" : "False");
Expand Down Expand Up @@ -651,18 +660,19 @@ InterpretResult builtin_time(void) {

char *process_escape_sequences(const char *input) {
size_t length = strlen(input);

char *processed = malloc(length + 1);
if (!processed) {
perror("Failed to allocate memory for processed string");
return NULL;
}

char *dst = processed;
const char *src = input;
char *dst = processed; // destination
const char *src = input; // source

while (*src) {
if (*src == '\\' && *(src + 1)) {
src++;
src++; // skip backslash
switch (*src) {
case 'n':
*dst++ = '\n';
Expand All @@ -676,12 +686,27 @@ char *process_escape_sequences(const char *input) {
case 'r':
*dst++ = '\r';
break;
case '\"':
case '"':
*dst++ = '\"';
break;
case '\'':
*dst++ = '\'';
break;
case 'x': {
// Look ahead two characters; if they are hex digits, decode
// them.
if (isxdigit(*(src + 1)) && isxdigit(*(src + 2))) {
char hex[3] = {*(src + 1), *(src + 2), '\0'};
long value = strtol(hex, NULL, 16);
*dst++ = (char)value;
src += 2; // Skip past the two hex digits
} else {
// If the two characters after \x aren’t hex, just output
// "x"
*dst++ = 'x';
}
break;
}
default:
*dst++ = '\\';
*dst++ = *src;
Expand All @@ -692,7 +717,8 @@ char *process_escape_sequences(const char *input) {
}
src++;
}
*dst = '\0'; // NULL-terminate the string

*dst = '\0'; // NULL-termination
return processed;
}

Expand Down

0 comments on commit b22d9d9

Please sign in to comment.