1
0
Fork 0
forked from fun/fun

Built-ins: Maps and more... ;)

This commit is contained in:
Johannes Findeisen 2025-09-15 04:41:11 +02:00
commit d1bbd2e501
9 changed files with 663 additions and 36 deletions

2
.gitignore vendored
View file

@ -6,7 +6,7 @@ out/
src/*.o src/*.o
tmp/ tmp/
.aiignore .aiignore
dev.txt *.txt
fun fun
fun_test fun_test
test_opcodes test_opcodes

View file

@ -0,0 +1,60 @@
#!/usr/bin/env fun
// Maps, map/filter/reduce, labeled break/continue (depth), and file I/O
// Map literal and indexing
m = { "a": 1, "b": 2 }
print(m) // -> {"a": 1, "b": 2} (order may vary)
print(m["a"]) // -> 1
m["c"] = 5
print(has(m, "c")) // -> 1
print(keys(m)) // -> ["a", "b", "c"] (order may vary)
print(values(m)) // -> [1, 2, 5] (order may vary)
// map/filter/reduce
nums = [1, 2, 3, 4]
fun double(x)
return x + x
fun is_odd(x)
return x % 2 == 1
fun sum2(a, b)
return a + b
print(map(nums, double)) // -> [2, 4, 6, 8]
print(filter(nums, is_odd)) // -> [1, 3]
print(reduce(nums, 0, sum2)) // -> 10
// labeled break/continue by depth using nested loops
for i in range(0, 3)
for j in range(0, 5)
if j == 1
continue 1 // skip to next j
if i == 1 && j == 2
break 2 // break outer and inner
print(i * 10 + j)
// file I/O (writes then reads)
path = "tmp_io_example.txt"
ok = write_file(path, "hello-io")
print(ok) // -> 1
content = read_file(path)
print(content) // -> hello-io
/* Expected output:
{"a": 1, "b": 2}
1
1
["a", "b", "c"]
[1, 2, 5]
[2, 4, 6, 8]
[1, 3]
10
0
2
3
1
hello-io
*/

View file

@ -100,6 +100,12 @@ static const char *opcode_name(OpCode op) {
case OP_POW: return "POW"; case OP_POW: return "POW";
case OP_RANDOM_SEED: return "RANDOM_SEED"; case OP_RANDOM_SEED: return "RANDOM_SEED";
case OP_RANDOM_INT: return "RANDOM_INT"; case OP_RANDOM_INT: return "RANDOM_INT";
case OP_MAKE_MAP: return "MAKE_MAP";
case OP_KEYS: return "KEYS";
case OP_VALUES: return "VALUES";
case OP_HAS_KEY: return "HAS_KEY";
case OP_READ_FILE: return "READ_FILE";
case OP_WRITE_FILE: return "WRITE_FILE";
default: return "???"; default: return "???";
} }
} }

View file

@ -85,7 +85,17 @@ typedef enum {
OP_ABS, // pops x; pushes |x| OP_ABS, // pops x; pushes |x|
OP_POW, // pops b, a; pushes a^b OP_POW, // pops b, a; pushes a^b
OP_RANDOM_SEED, // pops seed; sets RNG seed; pushes nothing (we'll push 0) OP_RANDOM_SEED, // pops seed; sets RNG seed; pushes nothing (we'll push 0)
OP_RANDOM_INT // pops hi, lo; pushes random int in [lo, hi) OP_RANDOM_INT, // pops hi, lo; pushes random int in [lo, hi)
// maps
OP_MAKE_MAP, // operand = pair count; pops 2*n (key,value)..., pushes map
OP_KEYS, // pops map; pushes array of keys
OP_VALUES, // pops map; pushes array of values
OP_HAS_KEY, // pops key, map; pushes 1/0
// file I/O
OP_READ_FILE, // pops path string; pushes content string (or "")
OP_WRITE_FILE // pops data string, path string; pushes 1/0
} OpCode; } OpCode;
typedef struct { typedef struct {

View file

@ -401,6 +401,37 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos)
return 1; return 1;
} }
/* map literal: { "key": expr, ... } */
skip_spaces(src, len, pos);
if (*pos < len && src[*pos] == '{') {
(*pos)++; /* '{' */
int pairs = 0;
skip_spaces(src, len, pos);
if (*pos < len && src[*pos] != '}') {
for (;;) {
/* key must be a string literal */
char *k = parse_string_literal_any_quote(src, len, pos);
if (!k) { parser_fail(*pos, "Expected string key in map literal"); return 0; }
int kci = bytecode_add_constant(bc, make_string(k));
free(k);
bytecode_add_instruction(bc, OP_LOAD_CONST, kci);
skip_spaces(src, len, pos);
if (!consume_char(src, len, pos, ':')) { parser_fail(*pos, "Expected ':' after map key"); return 0; }
if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "Expected value expression in map literal"); return 0; }
pairs++;
skip_spaces(src, len, pos);
if (*pos < len && src[*pos] == ',') { (*pos)++; skip_spaces(src, len, pos); continue; }
break;
}
}
if (!consume_char(src, len, pos, '}')) {
parser_fail(*pos, "Expected '}' to close map literal");
return 0;
}
bytecode_add_instruction(bc, OP_MAKE_MAP, pairs);
return 1;
}
/* number */ /* number */
int ok = 0; int ok = 0;
size_t save = *pos; size_t save = *pos;
@ -535,6 +566,43 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos)
free(name); free(name);
return 1; return 1;
} }
if (strcmp(name, "keys") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "keys expects 1 arg"); free(name); return 0; }
bytecode_add_instruction(bc, OP_KEYS, 0);
free(name);
return 1;
}
if (strcmp(name, "values") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "values expects 1 arg"); free(name); return 0; }
bytecode_add_instruction(bc, OP_VALUES, 0);
free(name);
return 1;
}
if (strcmp(name, "has") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "has expects (map, key)"); free(name); return 0; }
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "has expects (map, key)"); free(name); return 0; }
bytecode_add_instruction(bc, OP_HAS_KEY, 0);
free(name);
return 1;
}
if (strcmp(name, "read_file") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "read_file expects 1 arg"); free(name); return 0; }
bytecode_add_instruction(bc, OP_READ_FILE, 0);
free(name);
return 1;
}
if (strcmp(name, "write_file") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "write_file expects 2 args"); free(name); return 0; }
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "write_file expects 2 args"); free(name); return 0; }
bytecode_add_instruction(bc, OP_WRITE_FILE, 0);
free(name);
return 1;
}
/* string ops */ /* string ops */
if (strcmp(name, "split") == 0) { if (strcmp(name, "split") == 0) {
(*pos)++; /* '(' */ (*pos)++; /* '(' */
@ -616,6 +684,238 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos)
free(name); free(name);
return 1; return 1;
} }
if (strcmp(name, "map") == 0) {
(*pos)++; /* '(' */
/* arr */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "map expects (array, function)"); free(name); return 0; }
/* store arr -> __map_arr */
char tarr[64]; snprintf(tarr, sizeof(tarr), "__map_arr_%d", g_temp_counter++);
int larr = -1, garr = -1;
if (g_locals) { larr = local_add(tarr); bytecode_add_instruction(bc, OP_STORE_LOCAL, larr); }
else { garr = sym_index(tarr); bytecode_add_instruction(bc, OP_STORE_GLOBAL, garr); }
/* func */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "map expects (array, function)"); free(name); return 0; }
char tfn[64]; snprintf(tfn, sizeof(tfn), "__map_fn_%d", g_temp_counter++);
int lfn = -1, gfn = -1;
if (g_locals) { lfn = local_add(tfn); bytecode_add_instruction(bc, OP_STORE_LOCAL, lfn); }
else { gfn = sym_index(tfn); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gfn); }
/* res array */
bytecode_add_instruction(bc, OP_MAKE_ARRAY, 0);
char tres[64]; snprintf(tres, sizeof(tres), "__map_res_%d", g_temp_counter++);
int lres = -1, gres = -1;
if (g_locals) { lres = local_add(tres); bytecode_add_instruction(bc, OP_STORE_LOCAL, lres); }
else { gres = sym_index(tres); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gres); }
/* i=0 */
int c0 = bytecode_add_constant(bc, make_int(0));
bytecode_add_instruction(bc, OP_LOAD_CONST, c0);
char ti[64]; snprintf(ti, sizeof(ti), "__map_i_%d", g_temp_counter++);
int li = -1, gi = -1;
if (g_locals) { li = local_add(ti); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { gi = sym_index(ti); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
/* loop start */
int loop_start = bc->instr_count;
/* i < len(arr) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); }
bytecode_add_instruction(bc, OP_LEN, 0);
bytecode_add_instruction(bc, OP_LT, 0);
int jf = bytecode_add_instruction(bc, OP_JUMP_IF_FALSE, 0);
/* elem = arr[i] */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_INDEX_GET, 0);
/* call fn(elem) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lfn); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gfn); }
/* reorder: we need fn below arg -> push fn first then arg already on stack? We currently have elem on stack; push fn now results top=fn. We want top args then function; OP_CALL expects fn then pops args? Our OP_CALL pops function after args; earlier compile of calls: they push function then args then OP_CALL. So we need to swap: push fn, then swap to make function below arg */
bytecode_add_instruction(bc, OP_SWAP, 0);
bytecode_add_instruction(bc, OP_CALL, 1);
/* Append to result via indexed assignment: res[len(res)] = value */
/* Store computed value to a temp */
char tv[64]; snprintf(tv, sizeof(tv), "__map_v_%d", g_temp_counter++);
int lv = -1, gv = -1;
if (g_locals) { lv = local_add(tv); bytecode_add_instruction(bc, OP_STORE_LOCAL, lv); }
else { gv = sym_index(tv); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gv); }
/* Push array (for INDEX_SET we need stack: value, index, array; we will build array, index, then value) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
/* Compute index = len(res) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
bytecode_add_instruction(bc, OP_LEN, 0);
/* Load value back on top */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lv); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gv); }
/* Append via insert: res.insert(index=len(res), value) */
bytecode_add_instruction(bc, OP_ARR_INSERT, 0);
/* discard returned new length */
bytecode_add_instruction(bc, OP_POP, 0);
/* i++ */
int c1 = bytecode_add_constant(bc, make_int(1));
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_JUMP, loop_start);
bytecode_set_operand(bc, jf, bc->instr_count);
/* result value on stack */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
free(name);
return 1;
}
if (strcmp(name, "filter") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "filter expects (array, function)"); free(name); return 0; }
char tarr[64]; snprintf(tarr, sizeof(tarr), "__flt_arr_%d", g_temp_counter++);
int larr = -1, garr = -1;
if (g_locals) { larr = local_add(tarr); bytecode_add_instruction(bc, OP_STORE_LOCAL, larr); }
else { garr = sym_index(tarr); bytecode_add_instruction(bc, OP_STORE_GLOBAL, garr); }
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "filter expects (array, function)"); free(name); return 0; }
char tfn[64]; snprintf(tfn, sizeof(tfn), "__flt_fn_%d", g_temp_counter++);
int lfn = -1, gfn = -1;
if (g_locals) { lfn = local_add(tfn); bytecode_add_instruction(bc, OP_STORE_LOCAL, lfn); }
else { gfn = sym_index(tfn); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gfn); }
bytecode_add_instruction(bc, OP_MAKE_ARRAY, 0);
char tres[64]; snprintf(tres, sizeof(tres), "__flt_res_%d", g_temp_counter++);
int lres = -1, gres = -1;
if (g_locals) { lres = local_add(tres); bytecode_add_instruction(bc, OP_STORE_LOCAL, lres); }
else { gres = sym_index(tres); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gres); }
int c0 = bytecode_add_constant(bc, make_int(0));
bytecode_add_instruction(bc, OP_LOAD_CONST, c0);
char ti[64]; snprintf(ti, sizeof(ti), "__flt_i_%d", g_temp_counter++);
int li = -1, gi = -1;
if (g_locals) { li = local_add(ti); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { gi = sym_index(ti); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
int loop_start = bc->instr_count;
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); }
bytecode_add_instruction(bc, OP_LEN, 0);
bytecode_add_instruction(bc, OP_LT, 0);
int jf = bytecode_add_instruction(bc, OP_JUMP_IF_FALSE, 0);
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_INDEX_GET, 0);
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lfn); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gfn); }
bytecode_add_instruction(bc, OP_SWAP, 0);
bytecode_add_instruction(bc, OP_CALL, 1);
/* if truthy then push elem to res */
int jskip = bytecode_add_instruction(bc, OP_JUMP_IF_FALSE, 0);
/* Append element to result: res[len(res)] = elem */
/* Reload element into a temp */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_INDEX_GET, 0);
char tvf[64]; snprintf(tvf, sizeof(tvf), "__flt_v_%d", g_temp_counter++);
int lvf = -1, gvf = -1;
if (g_locals) { lvf = local_add(tvf); bytecode_add_instruction(bc, OP_STORE_LOCAL, lvf); }
else { gvf = sym_index(tvf); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gvf); }
/* Push array */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
/* index = len(res) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
bytecode_add_instruction(bc, OP_LEN, 0);
/* value */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lvf); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gvf); }
/* Append via insert: res.insert(index=len(res), value) */
bytecode_add_instruction(bc, OP_ARR_INSERT, 0);
/* discard returned new length */
bytecode_add_instruction(bc, OP_POP, 0);
int c1 = bytecode_add_constant(bc, make_int(1));
/* patch skip over append */
bytecode_set_operand(bc, jskip, bc->instr_count);
/* i++ */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_JUMP, loop_start);
bytecode_set_operand(bc, jf, bc->instr_count);
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lres); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gres); }
free(name);
return 1;
}
if (strcmp(name, "reduce") == 0) {
(*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "reduce expects (array, init, function)"); free(name); return 0; }
char tarr[64]; snprintf(tarr, sizeof(tarr), "__red_arr_%d", g_temp_counter++);
int larr = -1, garr = -1;
if (g_locals) { larr = local_add(tarr); bytecode_add_instruction(bc, OP_STORE_LOCAL, larr); }
else { garr = sym_index(tarr); bytecode_add_instruction(bc, OP_STORE_GLOBAL, garr); }
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ',')) { parser_fail(*pos, "reduce expects (array, init, function)"); free(name); return 0; }
char tacc[64]; snprintf(tacc, sizeof(tacc), "__red_acc_%d", g_temp_counter++);
int lacc = -1, gacc = -1;
if (g_locals) { lacc = local_add(tacc); bytecode_add_instruction(bc, OP_STORE_LOCAL, lacc); }
else { gacc = sym_index(tacc); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gacc); }
if (!emit_expression(bc, src, len, pos) || !consume_char(src, len, pos, ')')) { parser_fail(*pos, "reduce expects (array, init, function)"); free(name); return 0; }
char tfn[64]; snprintf(tfn, sizeof(tfn), "__red_fn_%d", g_temp_counter++);
int lfn = -1, gfn = -1;
if (g_locals) { lfn = local_add(tfn); bytecode_add_instruction(bc, OP_STORE_LOCAL, lfn); }
else { gfn = sym_index(tfn); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gfn); }
/* loop */
int c0 = bytecode_add_constant(bc, make_int(0));
bytecode_add_instruction(bc, OP_LOAD_CONST, c0);
char ti[64]; snprintf(ti, sizeof(ti), "__red_i_%d", g_temp_counter++);
int li = -1, gi = -1;
if (g_locals) { li = local_add(ti); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { gi = sym_index(ti); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
int loop_start = bc->instr_count;
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); }
bytecode_add_instruction(bc, OP_LEN, 0);
bytecode_add_instruction(bc, OP_LT, 0);
int jf = bytecode_add_instruction(bc, OP_JUMP_IF_FALSE, 0);
/* elem */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, larr); bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, garr); bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_INDEX_GET, 0);
/* Store elem to a temp so we can build stack as: fn, acc, elem */
char telem[64]; snprintf(telem, sizeof(telem), "__red_elem_%d", g_temp_counter++);
int lelem = -1, gelem = -1;
if (g_locals) { lelem = local_add(telem); bytecode_add_instruction(bc, OP_STORE_LOCAL, lelem); }
else { gelem = sym_index(telem); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gelem); }
/* push function */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lfn); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gfn); }
/* push accumulator (arg1) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lacc); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gacc); }
/* push element (arg2) */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lelem); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gelem); }
/* call fn(acc, elem) -> result */
bytecode_add_instruction(bc, OP_CALL, 2);
/* store to acc */
if (g_locals) { bytecode_add_instruction(bc, OP_STORE_LOCAL, lacc); }
else { bytecode_add_instruction(bc, OP_STORE_GLOBAL, gacc); }
int c1 = bytecode_add_constant(bc, make_int(1));
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, li); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_LOCAL, li); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gi); bytecode_add_instruction(bc, OP_LOAD_CONST, c1); bytecode_add_instruction(bc, OP_ADD, 0); bytecode_add_instruction(bc, OP_STORE_GLOBAL, gi); }
bytecode_add_instruction(bc, OP_JUMP, loop_start);
bytecode_set_operand(bc, jf, bc->instr_count);
/* result = acc on stack */
if (g_locals) { bytecode_add_instruction(bc, OP_LOAD_LOCAL, lacc); }
else { bytecode_add_instruction(bc, OP_LOAD_GLOBAL, gacc); }
free(name);
return 1;
}
if (strcmp(name, "zip") == 0) { if (strcmp(name, "zip") == 0) {
(*pos)++; /* '(' */ (*pos)++; /* '(' */
if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "zip expects first array"); free(name); return 0; } if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "zip expects first array"); free(name); return 0; }

View file

@ -9,6 +9,14 @@ typedef struct Array {
Value *items; /* owns items; each item owned by array */ Value *items; /* owns items; each item owned by array */
} Array; } Array;
typedef struct Map {
int refcount;
int count;
int cap;
char **keys; /* each key owned here */
Value *vals; /* each value owned here */
} Map;
Value make_int(int64_t v) { Value make_int(int64_t v) {
Value val; Value val;
val.type = VAL_INT; val.type = VAL_INT;
@ -37,6 +45,100 @@ Value make_nil(void) {
return v; return v;
} }
Value make_map_empty(void) {
Map *m = (Map*)malloc(sizeof(Map));
if (!m) return make_nil();
m->refcount = 1;
m->count = 0;
m->cap = 0;
m->keys = NULL;
m->vals = NULL;
Value v;
v.type = VAL_MAP;
v.map = (struct Map*)m;
return v;
}
static int map_ensure_cap(Map *m, int need) {
if (m->cap >= need) return 1;
int ncap = m->cap == 0 ? 4 : m->cap * 2;
while (ncap < need) ncap *= 2;
char **nkeys = (char**)realloc(m->keys, sizeof(char*) * ncap);
Value *nvals = (Value*)realloc(m->vals, sizeof(Value) * ncap);
if (!nkeys || !nvals) return 0;
m->keys = nkeys;
m->vals = nvals;
m->cap = ncap;
return 1;
}
int map_set(Value *vm, const char *key, Value v) {
if (!vm || vm->type != VAL_MAP || !vm->map || !key) { free_value(v); return 0; }
Map *m = (Map*)vm->map;
/* replace if exists */
for (int i = 0; i < m->count; ++i) {
if (strcmp(m->keys[i], key) == 0) {
free_value(m->vals[i]);
m->vals[i] = v;
return 1;
}
}
if (!map_ensure_cap(m, m->count + 1)) { free_value(v); return 0; }
m->keys[m->count] = strdup(key);
m->vals[m->count] = v;
m->count++;
return 1;
}
int map_get_copy(const Value *vm, const char *key, Value *out) {
if (!vm || vm->type != VAL_MAP || !vm->map || !key) return 0;
Map *m = (Map*)vm->map;
for (int i = 0; i < m->count; ++i) {
if (strcmp(m->keys[i], key) == 0) {
if (out) *out = copy_value(&m->vals[i]);
return 1;
}
}
return 0;
}
int map_has(const Value *vm, const char *key) {
if (!vm || vm->type != VAL_MAP || !vm->map || !key) return 0;
Map *m = (Map*)vm->map;
for (int i = 0; i < m->count; ++i) {
if (strcmp(m->keys[i], key) == 0) return 1;
}
return 0;
}
Value map_keys_array(const Value *vm) {
if (!vm || vm->type != VAL_MAP || !vm->map) return make_array_from_values(NULL, 0);
Map *m = (Map*)vm->map;
if (m->count <= 0) return make_array_from_values(NULL, 0);
Value *tmp = (Value*)malloc(sizeof(Value) * m->count);
for (int i = 0; i < m->count; ++i) {
tmp[i] = make_string(m->keys[i]);
}
Value arr = make_array_from_values(tmp, m->count);
for (int i = 0; i < m->count; ++i) free_value(tmp[i]);
free(tmp);
return arr;
}
Value map_values_array(const Value *vm) {
if (!vm || vm->type != VAL_MAP || !vm->map) return make_array_from_values(NULL, 0);
Map *m = (Map*)vm->map;
if (m->count <= 0) return make_array_from_values(NULL, 0);
Value *tmp = (Value*)malloc(sizeof(Value) * m->count);
for (int i = 0; i < m->count; ++i) {
tmp[i] = copy_value(&m->vals[i]);
}
Value arr = make_array_from_values(tmp, m->count);
for (int i = 0; i < m->count; ++i) free_value(tmp[i]);
free(tmp);
return arr;
}
Value make_array_from_values(const Value *vals, int count) { Value make_array_from_values(const Value *vals, int count) {
if (count < 0) count = 0; if (count < 0) count = 0;
Array *arr = (Array*)malloc(sizeof(Array)); Array *arr = (Array*)malloc(sizeof(Array));
@ -212,6 +314,12 @@ Value copy_value(const Value *v) {
if (a) a->refcount++; if (a) a->refcount++;
break; break;
} }
case VAL_MAP: {
Map *m = (Map*)v->map;
out.map = (struct Map*)m;
if (m) m->refcount++;
break;
}
case VAL_NIL: case VAL_NIL:
default: default:
break; break;
@ -240,13 +348,22 @@ Value deep_copy_value(const Value *v) {
tmp[i] = deep_copy_value(&a->items[i]); tmp[i] = deep_copy_value(&a->items[i]);
} }
Value out = make_array_from_values(tmp, a->count); Value out = make_array_from_values(tmp, a->count);
/* free temporaries (we created new deep copies already moved into out) */
for (int i = 0; i < a->count; ++i) { for (int i = 0; i < a->count; ++i) {
free_value(tmp[i]); free_value(tmp[i]);
} }
free(tmp); free(tmp);
return out; return out;
} }
case VAL_MAP: {
const Map *m = (const Map*)v->map;
if (!m || m->count <= 0) return make_map_empty();
Value out = make_map_empty();
for (int i = 0; i < m->count; ++i) {
Value dv = deep_copy_value(&m->vals[i]);
map_set(&out, m->keys[i], dv);
}
return out;
}
case VAL_NIL: case VAL_NIL:
default: default:
return make_nil(); return make_nil();
@ -265,6 +382,17 @@ void free_value(Value v) {
free(a->items); free(a->items);
free(a); free(a);
} }
} else if (v.type == VAL_MAP && v.map) {
Map *m = (Map*)v.map;
if (--m->refcount == 0) {
for (int i = 0; i < m->count; ++i) {
if (m->keys[i]) free(m->keys[i]);
free_value(m->vals[i]);
}
free(m->keys);
free(m->vals);
free(m);
}
} }
/* VAL_FUNCTION: we *do not* free the Bytecode here (caller frees it) */ /* VAL_FUNCTION: we *do not* free the Bytecode here (caller frees it) */
} }
@ -292,6 +420,19 @@ void print_value(const Value *v) {
printf("]"); printf("]");
break; break;
} }
case VAL_MAP: {
const Map *m = (const Map*)v->map;
printf("{");
if (m) {
for (int i = 0; i < m->count; ++i) {
if (i > 0) printf(", ");
printf("\"%s\": ", m->keys[i] ? m->keys[i] : "");
print_value(&m->vals[i]);
}
}
printf("}");
break;
}
case VAL_NIL: case VAL_NIL:
default: default:
printf("nil"); printf("nil");

View file

@ -5,12 +5,14 @@
struct Bytecode; /* forward */ struct Bytecode; /* forward */
struct Array; /* forward */ struct Array; /* forward */
struct Map; /* forward */
typedef enum { typedef enum {
VAL_INT, VAL_INT,
VAL_STRING, VAL_STRING,
VAL_FUNCTION, VAL_FUNCTION,
VAL_ARRAY, VAL_ARRAY,
VAL_MAP,
VAL_NIL VAL_NIL
} ValueType; } ValueType;
@ -21,6 +23,7 @@ typedef struct {
char *s; char *s;
struct Bytecode *fn; struct Bytecode *fn;
struct Array *arr; struct Array *arr;
struct Map *map;
}; };
} Value; } Value;
@ -42,9 +45,17 @@ int array_remove(Value *v, int index, Value *out); /* returns 1 on suc
Value array_slice(const Value *v, int start, int end); /* negative end means till end */ Value array_slice(const Value *v, int start, int end); /* negative end means till end */
Value array_concat(const Value *a, const Value *b); /* returns new array */ Value array_concat(const Value *a, const Value *b); /* returns new array */
/* maps (string keys) */
Value make_map_empty(void); /* new empty map */
int map_set(Value *m, const char *key, Value v); /* 1 on ok (takes ownership of v) */
int map_get_copy(const Value *m, const char *key, Value *out);/* 1 on found, out=copy */
int map_has(const Value *m, const char *key); /* 1/0 */
Value map_keys_array(const Value *m); /* array of strings */
Value map_values_array(const Value *m); /* array of values (copies) */
/* copy/free */ /* copy/free */
Value copy_value(const Value *v); /* deep for strings, RC for arrays, shallow fn */ Value copy_value(const Value *v); /* deep for strings, RC for arrays/maps, shallow fn */
Value deep_copy_value(const Value *v); /* deep copy including arrays */ Value deep_copy_value(const Value *v); /* deep copy including arrays/maps */
void free_value(Value v); /* frees owned resources */ void free_value(Value v); /* frees owned resources */
/* utilities */ /* utilities */

155
src/vm.c
View file

@ -517,45 +517,56 @@ void vm_run(VM *vm, Bytecode *entry) {
case OP_INDEX_GET: { case OP_INDEX_GET: {
Value idx = pop_value(vm); Value idx = pop_value(vm);
Value arr = pop_value(vm); Value container = pop_value(vm);
if (arr.type != VAL_ARRAY) { if (container.type == VAL_ARRAY) {
fprintf(stderr, "Runtime type error: INDEX_GET expects array\n"); if (idx.type != VAL_INT) { fprintf(stderr, "INDEX_GET index must be int for array\n"); exit(1); }
Value elem;
if (!array_get_copy(&container, (int)idx.i, &elem)) {
fprintf(stderr, "Runtime error: index out of range\n"); exit(1);
}
free_value(container);
free_value(idx);
push_value(vm, elem);
} else if (container.type == VAL_MAP) {
if (idx.type != VAL_STRING) { fprintf(stderr, "INDEX_GET key must be string for map\n"); exit(1); }
Value out;
if (!map_get_copy(&container, idx.s ? idx.s : "", &out)) {
/* missing -> nil */
out = make_nil();
}
free_value(container);
free_value(idx);
push_value(vm, out);
} else {
fprintf(stderr, "Runtime type error: INDEX_GET expects array or map\n");
exit(1); exit(1);
} }
if (idx.type != VAL_INT) {
fprintf(stderr, "Runtime type error: INDEX_GET index must be int\n");
exit(1);
}
Value elem;
if (!array_get_copy(&arr, (int)idx.i, &elem)) {
fprintf(stderr, "Runtime error: index out of range\n");
exit(1);
}
free_value(arr);
free_value(idx);
push_value(vm, elem);
break; break;
} }
case OP_INDEX_SET: { case OP_INDEX_SET: {
Value v = pop_value(vm); Value v = pop_value(vm);
Value idx = pop_value(vm); Value idx = pop_value(vm);
Value arr = pop_value(vm); Value container = pop_value(vm);
if (arr.type != VAL_ARRAY) { if (container.type == VAL_ARRAY) {
fprintf(stderr, "Runtime type error: INDEX_SET expects array\n"); if (idx.type != VAL_INT) { fprintf(stderr, "INDEX_SET index must be int for array\n"); exit(1); }
if (!array_set(&container, (int)idx.i, v)) {
fprintf(stderr, "Runtime error: index out of range\n"); exit(1);
}
/* v moved into array */
free_value(container);
free_value(idx);
} else if (container.type == VAL_MAP) {
if (idx.type != VAL_STRING) { fprintf(stderr, "INDEX_SET key must be string for map\n"); exit(1); }
if (!map_set(&container, idx.s ? idx.s : "", v)) {
fprintf(stderr, "Runtime error: map set failed\n"); exit(1);
}
free_value(container);
free_value(idx);
} else {
fprintf(stderr, "Runtime type error: INDEX_SET expects array or map\n");
exit(1); exit(1);
} }
if (idx.type != VAL_INT) {
fprintf(stderr, "Runtime type error: INDEX_SET index must be int\n");
exit(1);
}
if (!array_set(&arr, (int)idx.i, v)) {
fprintf(stderr, "Runtime error: index out of range\n");
exit(1);
}
/* arr modified in place; do not free v (ownership moved) */
free_value(arr);
free_value(idx);
break; break;
} }
@ -970,6 +981,92 @@ void vm_run(VM *vm, Bytecode *entry) {
break; break;
} }
case OP_MAKE_MAP: {
int pairs = inst.operand;
if (pairs < 0) { fprintf(stderr, "MAKE_MAP invalid pair count\n"); exit(1); }
Value m = make_map_empty();
for (int i = 0; i < pairs; ++i) {
Value val = pop_value(vm);
Value key = pop_value(vm);
if (key.type != VAL_STRING) { fprintf(stderr, "Map literal keys must be strings\n"); exit(1); }
if (!map_set(&m, key.s ? key.s : "", val)) {
fprintf(stderr, "Map literal set failed\n"); exit(1);
}
free_value(key);
/* val ownership moved */
}
push_value(vm, m);
break;
}
case OP_KEYS: {
Value m = pop_value(vm);
if (m.type != VAL_MAP) { fprintf(stderr, "KEYS expects map\n"); exit(1); }
Value arr = map_keys_array(&m);
free_value(m);
push_value(vm, arr);
break;
}
case OP_VALUES: {
Value m = pop_value(vm);
if (m.type != VAL_MAP) { fprintf(stderr, "VALUES expects map\n"); exit(1); }
Value arr = map_values_array(&m);
free_value(m);
push_value(vm, arr);
break;
}
case OP_HAS_KEY: {
Value key = pop_value(vm);
Value m = pop_value(vm);
if (m.type != VAL_MAP || key.type != VAL_STRING) { fprintf(stderr, "HAS_KEY expects (map, string)\n"); exit(1); }
int ok = map_has(&m, key.s ? key.s : "");
free_value(m); free_value(key);
push_value(vm, make_int(ok ? 1 : 0));
break;
}
case OP_READ_FILE: {
Value path = pop_value(vm);
if (path.type != VAL_STRING) { fprintf(stderr, "READ_FILE expects string\n"); exit(1); }
const char *p = path.s ? path.s : "";
FILE *f = fopen(p, "rb");
if (!f) { free_value(path); push_value(vm, make_string("")); break; }
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); free_value(path); push_value(vm, make_string("")); break; }
long sz = ftell(f);
if (sz < 0) { fclose(f); free_value(path); push_value(vm, make_string("")); break; }
rewind(f);
char *buf = (char*)malloc((size_t)sz + 1);
size_t n = buf ? fread(buf, 1, (size_t)sz, f) : 0;
fclose(f);
if (!buf) { free_value(path); push_value(vm, make_string("")); break; }
buf[n] = '\0';
Value out = make_string(buf);
free(buf);
free_value(path);
push_value(vm, out);
break;
}
case OP_WRITE_FILE: {
Value data = pop_value(vm);
Value path = pop_value(vm);
if (path.type != VAL_STRING || data.type != VAL_STRING) { fprintf(stderr, "WRITE_FILE expects (string, string)\n"); exit(1); }
const char *p = path.s ? path.s : "";
FILE *f = fopen(p, "wb");
int ok = 0;
if (f) {
size_t len = data.s ? strlen(data.s) : 0;
ok = (fwrite(data.s ? data.s : "", 1, len, f) == len);
fclose(f);
}
free_value(path);
free_value(data);
push_value(vm, make_int(ok ? 1 : 0));
break;
}
case OP_LOAD_GLOBAL: { case OP_LOAD_GLOBAL: {
int idx = inst.operand; int idx = inst.operand;
if (idx < 0 || idx >= VM_MAX_GLOBALS) { if (idx < 0 || idx >= VM_MAX_GLOBALS) {

View file

@ -21,7 +21,9 @@ static const char *opcode_names[] = {
"SPLIT","JOIN","SUBSTR","FIND", "SPLIT","JOIN","SUBSTR","FIND",
"CONTAINS","INDEX_OF","CLEAR", "CONTAINS","INDEX_OF","CLEAR",
"ENUMERATE","ZIP", "ENUMERATE","ZIP",
"MIN","MAX","CLAMP","ABS","POW","RANDOM_SEED","RANDOM_INT" "MIN","MAX","CLAMP","ABS","POW","RANDOM_SEED","RANDOM_INT",
"MAKE_MAP","KEYS","VALUES","HAS_KEY",
"READ_FILE","WRITE_FILE"
}; };
typedef struct { typedef struct {
@ -62,7 +64,7 @@ void vm_dump_globals(VM *vm);
void vm_run(VM *vm, Bytecode *entry); void vm_run(VM *vm, Bytecode *entry);
static inline int opcode_is_valid(int op) { static inline int opcode_is_valid(int op) {
return op >= OP_NOP && op <= OP_RANDOM_INT; // all current opcodes return op >= OP_NOP && op <= OP_WRITE_FILE; // all current opcodes
} }
#endif #endif