Added string concatenation

This commit is contained in:
2022-08-20 22:58:50 +01:00
parent 80ccd119ff
commit c64d451287
6 changed files with 27 additions and 8 deletions

View File

@@ -230,6 +230,22 @@ static bool execArithmetic(Interpreter* interpreter, Opcode opcode) {
parseIdentifierToValue(interpreter, &rhs);
parseIdentifierToValue(interpreter, &lhs);
//special case for string concatenation ONLY
if (IS_STRING(lhs) && IS_STRING(rhs)) {
//check for overflow
if (STRLEN(lhs) + STRLEN(rhs) > MAX_STRING_LENGTH) {
printf("Can't concatenate these strings (result is too long)\n");
return false;
}
//concat the strings
char buffer[MAX_STRING_LENGTH];
snprintf(buffer, MAX_STRING_LENGTH, "%s%s", AS_STRING(lhs), AS_STRING(rhs));
pushLiteralArray(&interpreter->stack, TO_STRING_LITERAL(buffer));
return true;
}
//type coersion
if (IS_FLOAT(lhs) && IS_INTEGER(rhs)) {
rhs = TO_FLOAT_LITERAL(AS_INTEGER(rhs));

View File

@@ -81,12 +81,12 @@ void printLiteralCustom(Literal literal, void (printFn)(const char*)) {
break;
case LITERAL_STRING: {
char buffer[4096];
char buffer[MAX_STRING_LENGTH];
if (!quotes) {
snprintf(buffer, 4096, "%.*s", STRLEN(literal), AS_STRING(literal));
snprintf(buffer, MAX_STRING_LENGTH, "%.*s", STRLEN(literal), AS_STRING(literal));
}
else {
snprintf(buffer, 4096, "%c%.*s%c", quotes, STRLEN(literal), AS_STRING(literal), quotes);
snprintf(buffer, MAX_STRING_LENGTH, "%c%.*s%c", quotes, STRLEN(literal), AS_STRING(literal), quotes);
}
printFn(buffer);
}

View File

@@ -92,6 +92,7 @@ void freeLiteral(Literal literal);
#define IS_TRUTHY(x) _isTruthy(x)
#define MAX_STRING_LENGTH 4096
#define STRLEN(lit) ((lit).as.string.length)
#define STRLEN_I(lit) ((lit).as.identifier.length)
#define HASH_I(lit) ((lit).as.identifier.hash)

View File

@@ -241,9 +241,11 @@ static Opcode string(Parser* parser, Node** nodeHandle) {
int length = parser->previous.length;
//for safety
if (length > 4096) {
length = 4096;
error(parser, parser->previous, "Strings can only be a maximum of 4096 characters long");
if (length > MAX_STRING_LENGTH) {
length = MAX_STRING_LENGTH;
char buffer[256];
snprintf(buffer, 256, "Strings can only be a maximum of %d characters long", MAX_STRING_LENGTH);
error(parser, parser->previous, buffer);
}
emitNodeLiteral(nodeHandle, TO_STRING_LITERAL(copyString(parser->previous.lexeme, length)));