From ef77378ab43e644225561ac23b38d2634e15d3cd Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 14 Sep 2025 15:58:50 +0200 Subject: [PATCH] String concatination. --- examples/strings_test.fun | 34 ++++++++++++++++++++++++++++++++++ src/vm.c | 32 ++++++++++++++++++++++++++------ 2 files changed, 60 insertions(+), 6 deletions(-) create mode 100755 examples/strings_test.fun diff --git a/examples/strings_test.fun b/examples/strings_test.fun new file mode 100755 index 0000000..4130285 --- /dev/null +++ b/examples/strings_test.fun @@ -0,0 +1,34 @@ +#!/usr/bin/env fun +// Strings test: concatenation with variables and literals, functions returning strings + +print("=== strings test start ===") + +string a = "Hello" +string b = "World" +string sep = ", " +string excl = "!" + +// Basic concatenations +print(a + sep + b + excl) // expect: Hello, World! +print("Hi" + " " + "there") // expect: Hi there + +// Empty strings +string empty = "" +print(empty + "x") // expect: x +print("x" + empty) // expect: x + +// Function returning concatenated string +fun greet(name) + return "Hello, " + name + +print(greet("Fun")) // expect: Hello, Fun + +// Using a variable prefix with a function result +string prefix = "Hi, " +print(prefix + greet("You")) // expect: Hi, Hello, You + +// Non-empty check (string comparison) +if (a != "") + print("a is non-empty") + +print("=== strings test end ===") diff --git a/src/vm.c b/src/vm.c index bbd7911..df53528 100644 --- a/src/vm.c +++ b/src/vm.c @@ -153,15 +153,35 @@ void vm_run(VM *vm, Bytecode *entry) { case OP_ADD: { Value b = pop_value(vm); Value a = pop_value(vm); - if (a.type != VAL_INT || b.type != VAL_INT) { - fprintf(stderr, "Runtime type error: ADD expects ints, got %s and %s\n", + if (a.type == VAL_INT && b.type == VAL_INT) { + Value res = make_int(a.i + b.i); + free_value(a); + free_value(b); + push_value(vm, res); + } else if (a.type == VAL_STRING && b.type == VAL_STRING) { + const char *sa = a.s ? a.s : ""; + const char *sb = b.s ? b.s : ""; + size_t la = strlen(sa); + size_t lb = strlen(sb); + char *buf = (char*)malloc(la + lb + 1); + if (!buf) { + fprintf(stderr, "Runtime error: out of memory during string concatenation\n"); + exit(1); + } + memcpy(buf, sa, la); + memcpy(buf + la, sb, lb); + buf[la + lb] = '\0'; + Value res; + res.type = VAL_STRING; + res.s = buf; + free_value(a); + free_value(b); + push_value(vm, res); + } else { + fprintf(stderr, "Runtime type error: ADD expects both ints or both strings, got %s and %s\n", value_type_name(a.type), value_type_name(b.type)); exit(1); } - Value res = make_int(a.i + b.i); - free_value(a); - free_value(b); - push_value(vm, res); break; }