Repository navigation
Expand file tree
/
Copy patheval.c
More file actions
1620 lines (1567 loc) · 63.1 KB
/
Copy patheval.c
File metadata and controls
1620 lines (1567 loc) · 63.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "eval.h"
#include "kanren.h"
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
StigiStr name;
StigiVal val;
bool is_handler_var;
StigiVal *handler_var_ptr; /* when non-NULL, reads/writes mutate handler state directly */
} EvalBinding;
typedef struct {
EvalBinding *items;
uint32_t count;
uint32_t cap;
} EvalEnv;
typedef struct {
StigiStr binder;
int32_t cap_unit_idx;
int32_t handler_unit_idx;
StigiStr *param_names;
StigiVal *param_vals;
uint32_t param_count;
StigiStr *var_names;
StigiVal *var_vals;
uint32_t var_count;
} EvalHandlerFrame;
typedef struct {
const StigiImage *img;
Arena *arena;
uint64_t fuel_left;
uint64_t fuel_max;
uint32_t call_depth;
EvalHandlerFrame *handlers;
uint32_t handler_count;
uint32_t handler_cap;
StigiEvalResult res;
bool failed;
} EvalCtx;
static void eval_fail(EvalCtx *ctx, const char *code, const char *fmt, ...) {
if (ctx->failed) return;
ctx->failed = true;
ctx->res.status = STIGI_ERR_INVALID;
ctx->res.diag_code = code;
va_list ap;
va_start(ap, fmt);
(void)vsnprintf(ctx->res.msg, sizeof ctx->res.msg, fmt, ap);
va_end(ap);
}
static bool burn_fuel(EvalCtx *ctx) {
if (ctx->fuel_left == 0) {
eval_fail(ctx, "evaluation-fuel", "evaluation exceeded fuel budget (%llu)",
(unsigned long long)ctx->fuel_max);
return false;
}
ctx->fuel_left--;
return true;
}
static bool str_eq_lit(StigiStr s, const char *lit) {
size_t n = strlen(lit);
return s.len == n && memcmp(s.ptr, lit, n) == 0;
}
static bool str_eq_s(StigiStr a, StigiStr b) {
return a.len == b.len && (a.len == 0 || memcmp(a.ptr, b.ptr, a.len) == 0);
}
static StigiStr case_short_name(StigiStr s) {
if (s.ptr == NULL) return s;
for (size_t i = s.len; i > 0; i--) {
if (s.ptr[i - 1] == '.') {
StigiStr r;
r.ptr = s.ptr + i;
r.len = s.len - i;
return r;
}
}
return s;
}
/* ---- Exact integer width & comparison helpers ---- */
static StigiIntWidth width_from_ast_type(const StigiImage *img, uint32_t uidx,
const StigiType *ty, int depth) {
if (ty == NULL || depth > 16) return STIGI_INT_UNTYPED;
if (str_eq_lit(ty->name, "U8")) return STIGI_INT_U8;
if (str_eq_lit(ty->name, "U32")) return STIGI_INT_U32;
if (str_eq_lit(ty->name, "U64")) return STIGI_INT_U64;
if (str_eq_lit(ty->name, "I32")) return STIGI_INT_I32;
if (str_eq_lit(ty->name, "I64")) return STIGI_INT_I64;
if (img != NULL && uidx < img->unit_count) {
int32_t tgt = stigi_image_resolve_name(img, uidx, ty->name.ptr, ty->name.len);
if (tgt >= 0 && img->units[tgt].ast->decl->kind == STIGI_DECL_TYPE) {
return width_from_ast_type(img, (uint32_t)tgt,
img->units[tgt].ast->decl->u.type_decl.rhs, depth + 1);
}
}
return STIGI_INT_UNTYPED;
}
static bool coerce_int_to_width(EvalCtx *ctx, StigiVal *v, StigiIntWidth w) {
if (v->kind != STIGI_VAL_INT || w == STIGI_INT_UNTYPED) return true;
if (w == STIGI_INT_U8 || w == STIGI_INT_U32 || w == STIGI_INT_U64) {
uint64_t uv = 0;
if (v->is_unsigned) {
uv = v->u.u;
} else {
if (v->u.i < 0) {
eval_fail(ctx, "eval-error", "negative value out of unsigned range");
return false;
}
uv = (uint64_t)v->u.i;
}
if ((w == STIGI_INT_U8 && uv > 255ULL) ||
(w == STIGI_INT_U32 && uv > 4294967295ULL)) {
eval_fail(ctx, "eval-error", "unsigned integer overflow for target width");
return false;
}
v->is_unsigned = true;
v->int_width = w;
v->u.u = uv;
return true;
}
/* Signed I32 / I64 */
int64_t iv = 0;
if (v->is_unsigned) {
if (v->u.u > (uint64_t)INT64_MAX) {
eval_fail(ctx, "eval-error", "integer exceeds signed I64 range");
return false;
}
iv = (int64_t)v->u.u;
} else {
iv = v->u.i;
}
if (w == STIGI_INT_I32 && (iv < -2147483648LL || iv > 2147483647LL)) {
eval_fail(ctx, "eval-error", "signed integer overflow for I32");
return false;
}
v->is_unsigned = false;
v->int_width = w;
v->u.i = iv;
return true;
}
static StigiIntWidth combine_widths(const StigiVal *a, const StigiVal *b) {
if (a->int_width != STIGI_INT_UNTYPED) return a->int_width;
if (b->int_width != STIGI_INT_UNTYPED) return b->int_width;
return (a->is_unsigned && b->is_unsigned) ? STIGI_INT_U64 : STIGI_INT_I64;
}
/* Exact mathematical comparison across [INT64_MIN, UINT64_MAX] */
static int cmp_int_vals(const StigiVal *a, const StigiVal *b) {
if (a->is_unsigned && b->is_unsigned) {
return a->u.u < b->u.u ? -1 : (a->u.u > b->u.u ? 1 : 0);
}
if (!a->is_unsigned && !b->is_unsigned) {
return a->u.i < b->u.i ? -1 : (a->u.i > b->u.i ? 1 : 0);
}
if (!a->is_unsigned) {
if (a->u.i < 0) return -1;
uint64_t au = (uint64_t)a->u.i;
return au < b->u.u ? -1 : (au > b->u.u ? 1 : 0);
}
if (b->u.i < 0) return 1;
uint64_t bu = (uint64_t)b->u.i;
return a->u.u < bu ? -1 : (a->u.u > bu ? 1 : 0);
}
static bool val_equal(const StigiVal *a, const StigiVal *b) {
if (a->kind == STIGI_VAL_STR && b->kind == STIGI_VAL_ARRAY) {
if (a->u.s.len != b->u.arr.len) return false;
for (uint32_t i = 0; i < b->u.arr.len; i++) {
if (b->u.arr.elems[i].kind != STIGI_VAL_INT) return false;
StigiVal ch = { STIGI_VAL_INT, true, STIGI_INT_U8, { .u = (uint8_t)a->u.s.ptr[i] } };
if (cmp_int_vals(&ch, &b->u.arr.elems[i]) != 0) return false;
}
return true;
}
if (a->kind == STIGI_VAL_ARRAY && b->kind == STIGI_VAL_STR) {
return val_equal(b, a);
}
if (a->kind != b->kind) return false;
switch (a->kind) {
case STIGI_VAL_UNIT:
case STIGI_VAL_TEST_OK:
return true;
case STIGI_VAL_BOOL:
return a->u.b == b->u.b;
case STIGI_VAL_INT:
return cmp_int_vals(a, b) == 0;
case STIGI_VAL_STR:
return str_eq_s(a->u.s, b->u.s);
case STIGI_VAL_ENUM:
if (a->u.en.enum_unit_idx >= 0 && b->u.en.enum_unit_idx >= 0 &&
a->u.en.enum_unit_idx != b->u.en.enum_unit_idx) {
return false;
}
if (!str_eq_s(case_short_name(a->u.en.case_name), case_short_name(b->u.en.case_name)) ||
a->u.en.field_count != b->u.en.field_count) {
return false;
}
for (uint32_t i = 0; i < a->u.en.field_count; i++) {
if (!val_equal(&a->u.en.fields[i], &b->u.en.fields[i])) return false;
}
return true;
case STIGI_VAL_ARRAY:
if (a->u.arr.len != b->u.arr.len) return false;
for (uint32_t i = 0; i < a->u.arr.len; i++) {
if (!val_equal(&a->u.arr.elems[i], &b->u.arr.elems[i])) return false;
}
return true;
}
return false;
}
/* ---- Dynamic environment helpers ---- */
static void env_init(EvalEnv *env) {
env->items = NULL;
env->count = 0;
env->cap = 0;
}
static void env_free(EvalEnv *env) {
free(env->items);
env->items = NULL;
env->count = env->cap = 0;
}
static bool env_push(EvalCtx *ctx, EvalEnv *env, StigiStr name, StigiVal val,
StigiVal *handler_var_ptr) {
if (name.len == 0 || (name.len == 1 && name.ptr[0] == '_')) return true;
if (env->count == env->cap) {
uint32_t ncap = env->cap == 0 ? 32U : env->cap * 2U;
if (ncap <= env->cap) { eval_fail(ctx, "eval-error", "env overflow"); return false; }
EvalBinding *ni = realloc(env->items, (size_t)ncap * sizeof *ni);
if (ni == NULL) { eval_fail(ctx, "eval-error", "out of memory"); return false; }
env->items = ni;
env->cap = ncap;
}
EvalBinding *b = &env->items[env->count++];
b->name = name;
b->val = val;
b->is_handler_var = (handler_var_ptr != NULL);
b->handler_var_ptr = handler_var_ptr;
return true;
}
static EvalBinding *find_env(EvalEnv *env, StigiStr name) {
for (uint32_t i = env->count; i > 0; i--) {
if (str_eq_s(env->items[i - 1].name, name)) return &env->items[i - 1];
}
return NULL;
}
/* ---- String literal escape decoder ---- */
static uint8_t eval_hex_nibble(char c) {
if (c >= '0' && c <= '9') return (uint8_t)(c - '0');
if (c >= 'a' && c <= 'f') return (uint8_t)(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return (uint8_t)(c - 'A' + 10);
return 0;
}
static StigiStr decode_str_lit(EvalCtx *ctx, StigiStr raw) {
StigiStr empty = {"", 0};
if (raw.ptr == NULL || raw.len < 2 || raw.ptr[0] != '"' || raw.ptr[raw.len - 1] != '"') {
return raw;
}
size_t max_len = raw.len - 2U;
char *buf = arena_alloc(ctx->arena, max_len + 1U);
if (buf == NULL) { eval_fail(ctx, "eval-error", "out of memory"); return empty; }
size_t out = 0;
size_t i = 1;
size_t end = raw.len - 1U;
while (i < end) {
if (raw.ptr[i] == '\\' && i + 1 < end) {
char c = raw.ptr[i + 1];
i += 2;
switch (c) {
case 'n': buf[out++] = '\n'; break;
case 't': buf[out++] = '\t'; break;
case '\\': buf[out++] = '\\'; break;
case '"': buf[out++] = '"'; break;
case '\'': buf[out++] = '\''; break;
case '0': buf[out++] = '\0'; break;
case 'x':
if (i + 2 <= end) {
uint8_t hi = eval_hex_nibble(raw.ptr[i]);
uint8_t lo = eval_hex_nibble(raw.ptr[i + 1]);
buf[out++] = (char)((hi << 4) | lo);
i += 2;
}
break;
default: buf[out++] = c; break;
}
} else {
buf[out++] = raw.ptr[i++];
}
}
buf[out] = '\0';
StigiStr res = { buf, out };
return res;
}
/* ---- Arithmetic helpers ---- */
static bool checked_add_i64(int64_t a, int64_t b, int64_t *out) {
if ((b > 0 && a > INT64_MAX - b) || (b < 0 && a < INT64_MIN - b)) return false;
*out = a + b;
return true;
}
static bool checked_sub_i64(int64_t a, int64_t b, int64_t *out) {
if ((b < 0 && a > INT64_MAX + b) || (b > 0 && a < INT64_MIN + b)) return false;
*out = a - b;
return true;
}
static bool checked_mul_i64(int64_t a, int64_t b, int64_t *out) {
if (a == 0 || b == 0) { *out = 0; return true; }
if ((a == -1 && b == INT64_MIN) || (b == -1 && a == INT64_MIN)) return false;
if (a > 0) {
if (b > 0) { if (a > INT64_MAX / b) return false; }
else { if (b < INT64_MIN / a) return false; }
} else {
if (b > 0) { if (a < INT64_MIN / b) return false; }
else { if (a < INT64_MAX / b) return false; }
}
*out = a * b;
return true;
}
static StigiVal eval_expr(EvalCtx *ctx, uint32_t uidx, const StigiExpr *e, EvalEnv *env);
static bool is_eval_marker_or_region_cap(const StigiImage *img, uint32_t uidx, const StigiType *ty) {
if (ty == NULL) return true;
if (str_eq_lit(ty->name, "Stigi.Mut") || str_eq_lit(ty->name, "Stigi.Region") ||
str_eq_lit(ty->name, "Stigi.Test") || str_eq_lit(ty->name, "Stigi.NegTest")) {
return true;
}
int32_t tgt = stigi_image_resolve_name(img, uidx, ty->name.ptr, ty->name.len);
if (tgt >= 0 && img->units[tgt].ast->decl->kind == STIGI_DECL_CAPABILITY) {
const StigiDecl *cd = img->units[tgt].ast->decl;
bool has_op = false;
for (uint32_t i = 0; i < cd->u.cap_decl.member_count; i++) {
if (cd->u.cap_decl.members[i]->kind == STIGI_DECL_DEF) { has_op = true; break; }
}
return !has_op;
}
return false;
}
static bool eval_has_handler_for_cap(const EvalCtx *ctx, int32_t cap_unit_idx) {
for (uint32_t i = ctx->handler_count; i > 0; i--) {
if (ctx->handlers[i - 1].cap_unit_idx == cap_unit_idx) return true;
}
return false;
}
#define STIGI_EVAL_MAX_DEPTH 256U
static StigiVal eval_call_handler_op(EvalCtx *ctx, EvalHandlerFrame *hf,
StigiStr op_name, const StigiVal *args, uint32_t argc) {
StigiVal z;
memset(&z, 0, sizeof z);
if (ctx->failed || !burn_fuel(ctx)) return z;
if (ctx->call_depth >= STIGI_EVAL_MAX_DEPTH) {
eval_fail(ctx, "evaluation-fuel", "maximum call depth exceeded");
return z;
}
const StigiDecl *hd = ctx->img->units[hf->handler_unit_idx].ast->decl;
const StigiDecl *op_def = NULL;
for (uint32_t i = 0; i < hd->u.handler_decl.def_count; i++) {
if (str_eq_s(hd->u.handler_decl.defs[i]->name, op_name)) {
op_def = hd->u.handler_decl.defs[i];
break;
}
}
if (op_def == NULL) {
eval_fail(ctx, "eval-error", "handler '%s' does not implement '%.*s'",
ctx->img->units[hf->handler_unit_idx].name, (int)op_name.len, op_name.ptr);
return z;
}
const StigiDefHead *h = &op_def->u.def_decl.head;
if (argc != h->param_count) {
eval_fail(ctx, "eval-error", "handler op '%.*s' arity mismatch",
(int)op_name.len, op_name.ptr);
return z;
}
EvalEnv frame;
env_init(&frame);
for (uint32_t i = 0; i < hf->param_count; i++) {
if (!env_push(ctx, &frame, hf->param_names[i], hf->param_vals[i], NULL)) {
env_free(&frame);
return z;
}
}
for (uint32_t i = 0; i < hf->var_count; i++) {
if (!env_push(ctx, &frame, hf->var_names[i], hf->var_vals[i], &hf->var_vals[i])) {
env_free(&frame);
return z;
}
}
for (uint32_t i = 0; i < h->param_count; i++) {
StigiVal av = args[i];
StigiIntWidth pw = width_from_ast_type(ctx->img, (uint32_t)hf->handler_unit_idx,
h->params[i].type, 0);
if (!coerce_int_to_width(ctx, &av, pw) ||
!env_push(ctx, &frame, h->params[i].name, av, NULL)) {
env_free(&frame);
return z;
}
}
ctx->call_depth++;
StigiVal out = eval_expr(ctx, (uint32_t)hf->handler_unit_idx, stigi_def_body(op_def), &frame);
ctx->call_depth--;
env_free(&frame);
if (!ctx->failed) {
StigiIntWidth rw = width_from_ast_type(ctx->img, (uint32_t)hf->handler_unit_idx,
h->ret_type, 0);
(void)coerce_int_to_width(ctx, &out, rw);
}
return out;
}
static StigiVal eval_call_unit(EvalCtx *ctx, uint32_t tgt_idx,
const StigiVal *args, uint32_t arg_count) {
StigiVal z;
memset(&z, 0, sizeof z);
if (ctx->failed || !burn_fuel(ctx)) return z;
if (ctx->call_depth >= STIGI_EVAL_MAX_DEPTH) {
eval_fail(ctx, "evaluation-fuel", "maximum call depth exceeded");
return z;
}
const StigiDecl *d = ctx->img->units[tgt_idx].ast->decl;
if (d->kind == STIGI_DECL_EXTERN && d->u.extern_decl.body == NULL) {
eval_fail(ctx, "not-compile-time", "cannot evaluate body-less extern '%s' at compile time",
ctx->img->units[tgt_idx].name);
return z;
}
if (d->kind != STIGI_DECL_DEF && d->kind != STIGI_DECL_LEMMA_DEF &&
d->kind != STIGI_DECL_EXTERN) {
eval_fail(ctx, "eval-error", "unit '%s' is not callable", ctx->img->units[tgt_idx].name);
return z;
}
const StigiDefHead *h = (d->kind == STIGI_DECL_EXTERN) ? &d->u.extern_decl.head
: &d->u.def_decl.head;
const StigiExpr *body = (d->kind == STIGI_DECL_EXTERN) ? d->u.extern_decl.body
: stigi_def_body(d);
/* Verify every runtime capability required by callee is either pure/Region/Mut or handled */
for (uint32_t g = 0; g < h->pre_group_count; g++) {
if (h->pre_groups[g].is_fact) continue;
for (uint32_t c = 0; c < h->pre_groups[g].cap_count; c++) {
const StigiType *ct = h->pre_groups[g].caps[c].cap_type;
if (is_eval_marker_or_region_cap(ctx->img, tgt_idx, ct)) continue;
int32_t cidx = stigi_image_resolve_name(ctx->img, tgt_idx, ct->name.ptr, ct->name.len);
if (cidx >= 0 && ctx->img->units[cidx].ast->decl->kind == STIGI_DECL_TRAIT) continue;
if (cidx < 0 || !eval_has_handler_for_cap(ctx, cidx)) {
eval_fail(ctx, "not-compile-time",
"cannot evaluate '%s' requiring unhandled capability '%.*s'",
ctx->img->units[tgt_idx].name, (int)ct->name.len, ct->name.ptr);
return z;
}
}
}
if (arg_count != h->param_count) {
eval_fail(ctx, "eval-error", "arity mismatch calling '%s'", ctx->img->units[tgt_idx].name);
return z;
}
EvalEnv frame;
env_init(&frame);
for (uint32_t i = 0; i < h->param_count; i++) {
StigiVal av = args[i];
StigiIntWidth pw = width_from_ast_type(ctx->img, tgt_idx, h->params[i].type, 0);
if (!coerce_int_to_width(ctx, &av, pw) ||
!env_push(ctx, &frame, h->params[i].name, av, NULL)) {
env_free(&frame);
return z;
}
}
ctx->call_depth++;
StigiVal out = eval_expr(ctx, tgt_idx, body, &frame);
ctx->call_depth--;
env_free(&frame);
if (!ctx->failed && d->kind != STIGI_DECL_LEMMA_DEF) {
StigiIntWidth rw = width_from_ast_type(ctx->img, tgt_idx, h->ret_type, 0);
(void)coerce_int_to_width(ctx, &out, rw);
}
return out;
}
static StigiType *eval_val_to_ast_type(const StigiImage *img, const StigiVal *v, Arena *a) {
StigiType *t = arena_alloc(a, sizeof *t);
if (t == NULL) return NULL;
memset(t, 0, sizeof *t);
t->kind = STIGI_TYPE_NAMED;
if (v->kind == STIGI_VAL_BOOL) {
t->name = (StigiStr){ "Bool", 4 };
return t;
}
if (v->kind == STIGI_VAL_UNIT) {
t->name = (StigiStr){ "Unit", 4 };
return t;
}
if (v->kind == STIGI_VAL_INT) {
switch (v->int_width) {
case STIGI_INT_U8: t->name = (StigiStr){ "U8", 2 }; break;
case STIGI_INT_U32: t->name = (StigiStr){ "U32", 3 }; break;
case STIGI_INT_I32: t->name = (StigiStr){ "I32", 3 }; break;
case STIGI_INT_I64: t->name = (StigiStr){ "I64", 3 }; break;
default: t->name = (StigiStr){ "U64", 3 }; break;
}
return t;
}
if (v->kind == STIGI_VAL_ENUM && v->u.en.enum_unit_idx >= 0 &&
(uint32_t)v->u.en.enum_unit_idx < img->unit_count) {
uint32_t ei = (uint32_t)v->u.en.enum_unit_idx;
t->name = (StigiStr){ img->units[ei].name, (uint32_t)img->units[ei].name_len };
const StigiDecl *ed = img->units[ei].ast->decl;
if (ed->kind == STIGI_DECL_ENUM && ed->u.enum_decl.type_param_count > 0) {
/* Infer enum type args from runtime field values if present */
uint32_t tpc = ed->u.enum_decl.type_param_count;
t->type_args = arena_alloc(a, (size_t)tpc * sizeof *t->type_args);
t->type_arg_count = tpc;
const StigiEnumCase *ec = NULL;
for (uint32_t c = 0; c < ed->u.enum_decl.case_count; c++) {
if (str_eq_s(ed->u.enum_decl.cases[c].name, v->u.en.case_name)) {
ec = &ed->u.enum_decl.cases[c];
break;
}
}
for (uint32_t tp = 0; tp < tpc && t->type_args != NULL; tp++) {
t->type_args[tp] = NULL;
StigiStr tpn = ed->u.enum_decl.type_params[tp].name;
if (ec != NULL) {
for (uint32_t f = 0; f < ec->field_count && f < v->u.en.field_count; f++) {
if (ec->fields[f].type != NULL && ec->fields[f].type->kind == STIGI_TYPE_NAMED &&
str_eq_s(ec->fields[f].type->name, tpn)) {
t->type_args[tp] = eval_val_to_ast_type(img, &v->u.en.fields[f], a);
break;
}
}
}
if (t->type_args[tp] == NULL) {
StigiType *fb = arena_alloc(a, sizeof *fb);
if (fb != NULL) {
memset(fb, 0, sizeof *fb);
fb->kind = STIGI_TYPE_NAMED;
fb->name = (StigiStr){ "U64", 3 };
}
t->type_args[tp] = fb;
}
}
}
return t;
}
t->name = (StigiStr){ "U64", 3 };
return t;
}
static StigiVal eval_call_given_op(EvalCtx *ctx, uint32_t given_uidx, StigiStr op_name,
const StigiVal *args, uint32_t argc) {
StigiVal z;
memset(&z, 0, sizeof z);
if (!burn_fuel(ctx)) return z;
if (ctx->call_depth >= STIGI_EVAL_MAX_DEPTH) {
eval_fail(ctx, "evaluation-fuel", "maximum call depth exceeded");
return z;
}
const StigiDecl *gd = ctx->img->units[given_uidx].ast->decl;
if (gd->kind != STIGI_DECL_GIVEN) {
eval_fail(ctx, "eval-error", "target is not a given");
return z;
}
const StigiDecl *opd = NULL;
for (uint32_t i = 0; i < gd->u.given_decl.def_count; i++) {
if (gd->u.given_decl.defs[i]->kind == STIGI_DECL_DEF &&
str_eq_s(gd->u.given_decl.defs[i]->name, op_name)) {
opd = gd->u.given_decl.defs[i];
break;
}
}
if (opd == NULL) {
eval_fail(ctx, "eval-error", "given '%s' has no method '%.*s'",
ctx->img->units[given_uidx].name, (int)op_name.len, op_name.ptr);
return z;
}
const StigiDefHead *h = &opd->u.def_decl.head;
if (argc != h->param_count) {
eval_fail(ctx, "eval-error", "given method arity mismatch");
return z;
}
EvalEnv frame;
env_init(&frame);
for (uint32_t i = 0; i < h->param_count; i++) {
StigiVal av = args[i];
StigiIntWidth pw = width_from_ast_type(ctx->img, given_uidx, h->params[i].type, 0);
if (!coerce_int_to_width(ctx, &av, pw) ||
!env_push(ctx, &frame, h->params[i].name, av, NULL)) {
env_free(&frame);
return z;
}
}
ctx->call_depth++;
StigiVal out = eval_expr(ctx, given_uidx, stigi_def_body(opd), &frame);
ctx->call_depth--;
env_free(&frame);
if (!ctx->failed) {
StigiIntWidth rw = width_from_ast_type(ctx->img, given_uidx, h->ret_type, 0);
(void)coerce_int_to_width(ctx, &out, rw);
}
return out;
}
static StigiVal eval_index_read_val(EvalCtx *ctx, const StigiVal *target, const StigiVal *idx) {
StigiVal z;
memset(&z, 0, sizeof z);
if (idx->kind != STIGI_VAL_INT) {
eval_fail(ctx, "eval-error", "array index is not an integer");
return z;
}
uint64_t u_idx = idx->is_unsigned ? idx->u.u : (idx->u.i >= 0 ? (uint64_t)idx->u.i : UINT64_MAX);
if (target->kind == STIGI_VAL_ARRAY) {
if (u_idx >= target->u.arr.len) {
eval_fail(ctx, "eval-error", "array index read out of bounds");
return z;
}
return target->u.arr.elems[u_idx];
}
if (target->kind == STIGI_VAL_STR) {
if (u_idx >= target->u.s.len) {
eval_fail(ctx, "eval-error", "string index read out of bounds");
return z;
}
z.kind = STIGI_VAL_INT;
z.is_unsigned = true;
z.int_width = STIGI_INT_U8;
z.u.u = (uint8_t)target->u.s.ptr[u_idx];
return z;
}
eval_fail(ctx, "eval-error", "cannot index non-array value");
return z;
}
static StigiVal eval_expr(EvalCtx *ctx, uint32_t uidx, const StigiExpr *e, EvalEnv *env) {
StigiVal z;
memset(&z, 0, sizeof z);
if (ctx->failed || e == NULL) return z;
switch (e->kind) {
case STIGI_EXPR_LIT_UNIT:
z.kind = STIGI_VAL_UNIT;
return z;
case STIGI_EXPR_LIT_BOOL:
z.kind = STIGI_VAL_BOOL;
z.u.b = e->u.lit_bool.value;
return z;
case STIGI_EXPR_LIT_INT:
if (e->u.lit_int.overflow) {
eval_fail(ctx, "eval-error", "integer literal exceeds U64 range");
return z;
}
z.kind = STIGI_VAL_INT;
z.is_unsigned = true;
z.int_width = STIGI_INT_UNTYPED;
z.u.u = e->u.lit_int.value;
return z;
case STIGI_EXPR_LIT_CHAR:
z.kind = STIGI_VAL_INT;
z.is_unsigned = true;
z.int_width = STIGI_INT_U8;
z.u.u = (uint64_t)e->u.lit_char.value;
return z;
case STIGI_EXPR_LIT_STR:
z.kind = STIGI_VAL_STR;
z.u.s = decode_str_lit(ctx, e->u.lit_str.raw);
return z;
case STIGI_EXPR_LOCAL:
case STIGI_EXPR_GLOBAL: {
EvalBinding *b = find_env(env, e->u.ident.name);
if (b != NULL) return b->is_handler_var ? *b->handler_var_ptr : b->val;
int32_t tgt = stigi_image_resolve_name(ctx->img, uidx,
e->u.ident.name.ptr, e->u.ident.name.len);
if (tgt >= 0) {
const StigiDecl *d = ctx->img->units[tgt].ast->decl;
if (d->kind == STIGI_DECL_VAL) {
if (!burn_fuel(ctx)) return z;
if (ctx->call_depth >= STIGI_EVAL_MAX_DEPTH) {
eval_fail(ctx, "evaluation-fuel", "maximum val evaluation depth exceeded");
return z;
}
EvalEnv sub;
env_init(&sub);
ctx->call_depth++;
StigiVal rv = eval_expr(ctx, (uint32_t)tgt, stigi_val_body(d), &sub);
ctx->call_depth--;
env_free(&sub);
if (!ctx->failed) {
StigiIntWidth vw = width_from_ast_type(ctx->img, (uint32_t)tgt, d->u.val_decl.type, 0);
(void)coerce_int_to_width(ctx, &rv, vw);
}
return rv;
}
if (d->kind == STIGI_DECL_EXTERN && d->u.extern_decl.is_val) {
eval_fail(ctx, "not-compile-time", "cannot read extern val '%s' at compile time",
ctx->img->units[tgt].name);
return z;
}
}
/* Nullary enum constructor (qualified or unqualified) */
uint32_t cidx = 0;
bool amb = false;
int32_t eidx = stigi_image_resolve_enum_case(ctx->img, uidx, e->u.ident.name.ptr,
e->u.ident.name.len, &cidx, &amb);
if (eidx >= 0) {
z.kind = STIGI_VAL_ENUM;
z.u.en.enum_unit_idx = eidx;
z.u.en.case_name = ctx->img->units[eidx].ast->decl->u.enum_decl.cases[cidx].name;
return z;
}
if (e->u.ident.name.len > 0 && e->u.ident.name.ptr[0] >= 'A' &&
e->u.ident.name.ptr[0] <= 'Z') {
z.kind = STIGI_VAL_ENUM;
z.u.en.enum_unit_idx = -1;
z.u.en.case_name = case_short_name(e->u.ident.name);
return z;
}
eval_fail(ctx, "eval-error", "unbound identifier '%.*s'",
(int)e->u.ident.name.len, e->u.ident.name.ptr);
return z;
}
case STIGI_EXPR_UNOP: {
StigiVal v = eval_expr(ctx, uidx, e->u.unop.operand, env);
if (ctx->failed) return z;
if (e->u.unop.op == STIGI_OP_NOT && v.kind == STIGI_VAL_BOOL) {
v.u.b = !v.u.b;
return v;
}
if (e->u.unop.op == STIGI_OP_NEG && v.kind == STIGI_VAL_INT) {
if (v.int_width == STIGI_INT_U8 || v.int_width == STIGI_INT_U32 ||
v.int_width == STIGI_INT_U64) {
eval_fail(ctx, "eval-error", "cannot negate unsigned integer");
return z;
}
if (v.is_unsigned) {
if (v.u.u > 9223372036854775808ULL) {
eval_fail(ctx, "eval-error", "integer negation overflow");
return z;
}
v.is_unsigned = false;
v.int_width = STIGI_INT_UNTYPED;
v.u.i = (v.u.u == 9223372036854775808ULL) ? INT64_MIN : -(int64_t)v.u.u;
return v;
}
if (v.u.i == INT64_MIN || (v.int_width == STIGI_INT_I32 && v.u.i == -2147483648LL)) {
eval_fail(ctx, "eval-error", "integer negation overflow");
return z;
}
v.u.i = -v.u.i;
return v;
}
eval_fail(ctx, "eval-error", "invalid unary operand");
return z;
}
case STIGI_EXPR_BINOP: {
StigiOp op = e->u.binop.op;
if (op == STIGI_OP_AND) {
StigiVal lv = eval_expr(ctx, uidx, e->u.binop.lhs, env);
if (ctx->failed) return z;
if (lv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'&&' left operand is not Bool");
return z;
}
if (!lv.u.b) return lv;
StigiVal rv = eval_expr(ctx, uidx, e->u.binop.rhs, env);
if (!ctx->failed && rv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'&&' right operand is not Bool");
return z;
}
return rv;
}
if (op == STIGI_OP_OR) {
StigiVal lv = eval_expr(ctx, uidx, e->u.binop.lhs, env);
if (ctx->failed) return z;
if (lv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'||' left operand is not Bool");
return z;
}
if (lv.u.b) return lv;
StigiVal rv = eval_expr(ctx, uidx, e->u.binop.rhs, env);
if (!ctx->failed && rv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'||' right operand is not Bool");
return z;
}
return rv;
}
StigiVal lv = eval_expr(ctx, uidx, e->u.binop.lhs, env);
if (ctx->failed) return z;
StigiVal rv = eval_expr(ctx, uidx, e->u.binop.rhs, env);
if (ctx->failed) return z;
if (op == STIGI_OP_EQ || op == STIGI_OP_NE) {
z.kind = STIGI_VAL_BOOL;
z.u.b = (op == STIGI_OP_EQ) ? val_equal(&lv, &rv) : !val_equal(&lv, &rv);
return z;
}
if (lv.kind != STIGI_VAL_INT || rv.kind != STIGI_VAL_INT) {
eval_fail(ctx, "eval-error", "non-integer arithmetic operand");
return z;
}
if (op == STIGI_OP_LT || op == STIGI_OP_LE || op == STIGI_OP_GT || op == STIGI_OP_GE) {
int c = cmp_int_vals(&lv, &rv);
z.kind = STIGI_VAL_BOOL;
if (op == STIGI_OP_LT) z.u.b = (c < 0);
else if (op == STIGI_OP_LE) z.u.b = (c <= 0);
else if (op == STIGI_OP_GT) z.u.b = (c > 0);
else z.u.b = (c >= 0);
return z;
}
StigiIntWidth rw = combine_widths(&lv, &rv);
if (!coerce_int_to_width(ctx, &lv, rw) || !coerce_int_to_width(ctx, &rv, rw)) return z;
if (lv.is_unsigned) {
uint64_t a = lv.u.u, b = rv.u.u;
uint64_t res_u = 0;
switch (op) {
case STIGI_OP_ADD:
if (a > UINT64_MAX - b) { eval_fail(ctx, "eval-error", "unsigned add overflow"); return z; }
res_u = a + b;
break;
case STIGI_OP_SUB:
if (a < b) { eval_fail(ctx, "eval-error", "unsigned sub underflow"); return z; }
res_u = a - b;
break;
case STIGI_OP_MUL:
if (b != 0 && a > UINT64_MAX / b) {
eval_fail(ctx, "eval-error", "unsigned mul overflow");
return z;
}
res_u = a * b;
break;
case STIGI_OP_DIV:
if (b == 0) { eval_fail(ctx, "eval-error", "division by zero"); return z; }
res_u = a / b;
break;
case STIGI_OP_MOD:
if (b == 0) { eval_fail(ctx, "eval-error", "remainder by zero"); return z; }
res_u = a % b;
break;
default:
eval_fail(ctx, "eval-error", "unsupported operator");
return z;
}
z.kind = STIGI_VAL_INT;
z.is_unsigned = true;
z.int_width = rw;
z.u.u = res_u;
(void)coerce_int_to_width(ctx, &z, rw);
return z;
}
int64_t a = lv.u.i, b = rv.u.i, r = 0;
switch (op) {
case STIGI_OP_ADD:
if (!checked_add_i64(a, b, &r)) { eval_fail(ctx, "eval-error", "signed add overflow"); return z; }
break;
case STIGI_OP_SUB:
if (!checked_sub_i64(a, b, &r)) { eval_fail(ctx, "eval-error", "signed sub overflow"); return z; }
break;
case STIGI_OP_MUL:
if (!checked_mul_i64(a, b, &r)) { eval_fail(ctx, "eval-error", "signed mul overflow"); return z; }
break;
case STIGI_OP_DIV:
if (b == 0 || (a == INT64_MIN && b == -1)) {
eval_fail(ctx, "eval-error", "division error");
return z;
}
r = a / b;
break;
case STIGI_OP_MOD:
if (b == 0 || (a == INT64_MIN && b == -1)) {
eval_fail(ctx, "eval-error", "remainder error");
return z;
}
r = a % b;
break;
default:
eval_fail(ctx, "eval-error", "unsupported operator");
return z;
}
z.kind = STIGI_VAL_INT;
z.is_unsigned = false;
z.int_width = rw;
z.u.i = r;
(void)coerce_int_to_width(ctx, &z, rw);
return z;
}
case STIGI_EXPR_IF: {
StigiVal cv = eval_expr(ctx, uidx, e->u.if_expr.cond, env);
if (ctx->failed) return z;
if (cv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'if' condition is not Bool");
return z;
}
return eval_expr(ctx, uidx, cv.u.b ? e->u.if_expr.then_br : e->u.if_expr.else_br, env);
}
case STIGI_EXPR_WHILE: {
for (;;) {
StigiVal cv = eval_expr(ctx, uidx, e->u.while_expr.cond, env);
if (ctx->failed) return z;
if (cv.kind != STIGI_VAL_BOOL) {
eval_fail(ctx, "eval-error", "'while' condition is not Bool");
return z;
}
if (!cv.u.b) break;
if (!burn_fuel(ctx)) return z;
(void)eval_expr(ctx, uidx, e->u.while_expr.body, env);
if (ctx->failed) return z;
}
z.kind = STIGI_VAL_UNIT;
return z;
}
case STIGI_EXPR_VAL: {
StigiVal iv = eval_expr(ctx, uidx, e->u.val_stmt.init, env);
if (ctx->failed) return z;
StigiIntWidth w = width_from_ast_type(ctx->img, uidx, e->u.val_stmt.type, 0);
if (!coerce_int_to_width(ctx, &iv, w)) return z;
if (e->u.val_stmt.pat.kind == STIGI_PAT_VAR) {
(void)env_push(ctx, env, e->u.val_stmt.pat.name, iv, NULL);
} else if (e->u.val_stmt.pat.kind == STIGI_PAT_CTOR && iv.kind == STIGI_VAL_ENUM) {
for (uint32_t i = 0; i < e->u.val_stmt.pat.field_count && i < iv.u.en.field_count; i++) {
(void)env_push(ctx, env, e->u.val_stmt.pat.fields[i], iv.u.en.fields[i], NULL);
}
}
z.kind = STIGI_VAL_UNIT;
return z;
}
case STIGI_EXPR_VAR: {
StigiVal iv = eval_expr(ctx, uidx, e->u.var_stmt.init, env);
if (ctx->failed) return z;
StigiIntWidth w = width_from_ast_type(ctx->img, uidx, e->u.var_stmt.type, 0);
if (!coerce_int_to_width(ctx, &iv, w)) return z;
(void)env_push(ctx, env, e->u.var_stmt.name, iv, NULL);
z.kind = STIGI_VAL_UNIT;
return z;
}
case STIGI_EXPR_ASSIGN: {
StigiVal vv = eval_expr(ctx, uidx, e->u.assign_stmt.value, env);
if (ctx->failed) return z;
EvalBinding *b = find_env(env, e->u.assign_stmt.name);
if (b == NULL) {
eval_fail(ctx, "eval-error", "assignment to unknown var");
return z;
}
StigiVal *dst = b->is_handler_var ? b->handler_var_ptr : &b->val;
if (dst->kind == STIGI_VAL_INT && dst->int_width != STIGI_INT_UNTYPED) {
if (!coerce_int_to_width(ctx, &vv, dst->int_width)) return z;
}
*dst = vv;
z.kind = STIGI_VAL_UNIT;
return z;
}
case STIGI_EXPR_INDEX_READ: {
StigiVal tv = eval_expr(ctx, uidx, e->u.index_expr.target, env);
if (ctx->failed) return z;
StigiVal iv = eval_expr(ctx, uidx, e->u.index_expr.index, env);
if (ctx->failed) return z;
return eval_index_read_val(ctx, &tv, &iv);
}
case STIGI_EXPR_INDEX_WRITE: {
if (e->u.index_expr.target->kind != STIGI_EXPR_LOCAL) {
eval_fail(ctx, "eval-error", "index write target must be a local array");
return z;
}
EvalBinding *b = find_env(env, e->u.index_expr.target->u.ident.name);
StigiVal idx = eval_expr(ctx, uidx, e->u.index_expr.index, env);
StigiVal val = eval_expr(ctx, uidx, e->u.index_expr.value, env);
if (ctx->failed) return z;
StigiVal *arrv = b != NULL ? (b->is_handler_var ? b->handler_var_ptr : &b->val) : NULL;
uint64_t u_idx = idx.is_unsigned ? idx.u.u : (idx.u.i >= 0 ? (uint64_t)idx.u.i : UINT64_MAX);
if (arrv == NULL || arrv->kind != STIGI_VAL_ARRAY || idx.kind != STIGI_VAL_INT ||
u_idx >= arrv->u.arr.len) {
eval_fail(ctx, "eval-error", "array index write out of bounds");
return z;
}
arrv->u.arr.elems[u_idx] = val;
z.kind = STIGI_VAL_UNIT;