-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
1916 lines (1589 loc) · 58.4 KB
/
Copy pathparser.c
File metadata and controls
1916 lines (1589 loc) · 58.4 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
//---------------------------------------------------------
// parser.c - implementation of the parser for SK
//
// Copyright (c) 2025 Mark Seminatore
//----------------------------------------------------------
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include "parser.h"
#include "modules.h"
#include "term_colors.h"
#define LOOKAHEAD (pSK->lookahead)
// forward declarations
static int expr(SKState* pSK);
static void quote_datum(SKState* pSK);
#define PARSE_LOG(...) (void)(pSK && pSK->parse_log_enabled && indent(pSK) && fprintf(stderr, __VA_ARGS__))
//------------------------
// pretty print parse tree
//------------------------
static int indent(SKState* pSK)
{
for (int i = 0; i < pSK->indent_level; i++)
{
fprintf(stderr, " ");
}
fprintf(stderr, "|_ ");
pSK->indent_level++;
return 1;
}
//------------------------
// parse tree indent
//------------------------
static void unindent(SKState* pSK)
{
if (!pSK || !pSK->parse_log_enabled) return;
pSK->indent_level--;
if (pSK->indent_level < 0)
pSK->indent_level = 0;
}
//------------------------
// error routine
//------------------------
//------------------------
// Helper function to log with optional stdin context clearing
//------------------------
static void log_with_stdin_check(SKState* pSK, SKLogLevel level, const char *s,
const char* fallback_color, const char* level_str)
{
if (pSK) {
// Check if stdin to avoid file context
if (pSK->yyin == stdin) {
// Clear file context for stdin
char* saved_file = pSK->file_stack_ptr >= 0 ?
pSK->file_stack[pSK->file_stack_ptr].filename : NULL;
int saved_line = pSK->file_stack_ptr >= 0 ?
pSK->file_stack[pSK->file_stack_ptr].yylineno : 0;
// Temporarily clear for stdin
if (pSK->file_stack_ptr >= 0) {
pSK->file_stack[pSK->file_stack_ptr].filename = NULL;
pSK->file_stack[pSK->file_stack_ptr].yylineno = 0;
}
sk_log(pSK, level, "%s", s);
// Restore
if (pSK->file_stack_ptr >= 0) {
pSK->file_stack[pSK->file_stack_ptr].filename = saved_file;
pSK->file_stack[pSK->file_stack_ptr].yylineno = saved_line;
}
} else {
sk_log(pSK, level, "%s", s);
}
} else {
fprintf(stderr, "%s%s: '%s'\n"TERM_RESET, fallback_color, level_str, s);
}
}
//------------------------
// error routine
//------------------------
void yyerror(SKState* pSK, const char *s)
{
log_with_stdin_check(pSK, SK_LOG_ERROR, s, TERM_RED, "ERROR");
}
//------------------------
// warning routine
//------------------------
void yywarning(SKState* pSK, const char *s)
{
log_with_stdin_check(pSK, SK_LOG_WARNING, s, TERM_YELLOW, "WARNING");
}
//------------------------
// info routine
//------------------------
void yyinfo(SKState* pSK, const char *s)
{
log_with_stdin_check(pSK, SK_LOG_INFO, s, TERM_GREEN, "INFO");
}
//---------------------------------------------------
// error message for unexpected tokens
//---------------------------------------------------
static void expected(SKState* pSK, int token)
{
if (token < 256)
yyerror(pSK, "unexpected character"); //'%c'", token);
else
yyerror(pSK, "expected token"); //'%s'", getLexemeFromToken(token));
}
//---------------------------------------------------
// if token is matched continue, otherwise error
//---------------------------------------------------
static int match(SKState* pSK, int token)
{
if (LOOKAHEAD == token)
{
LOOKAHEAD = yylex(pSK);
}
else
{
expected(pSK, token);
}
return LOOKAHEAD;
}
//-----------------------------------------------
// Register an upvalue for the current lambda being parsed.
// Returns the upvalue index (deduplicating by name).
//-----------------------------------------------
static int register_upvalue(SKState* pSK, const char* name, int scope_depth, int local_index)
{
// Check if already registered
for (int i = 0; i < pSK->upvalue_count; i++) {
if (strcmp(pSK->upvalues[i].name, name) == 0)
return i;
}
if (pSK->upvalue_count >= MAX_UPVALUES) {
yyerror(pSK, "too many upvalues in closure");
return -1;
}
int idx = pSK->upvalue_count++;
strncpy(pSK->upvalues[idx].name, name, sizeof(pSK->upvalues[idx].name) - 1);
pSK->upvalues[idx].name[sizeof(pSK->upvalues[idx].name) - 1] = '\0';
pSK->upvalues[idx].scope_depth = scope_depth;
pSK->upvalues[idx].local_index = local_index;
pSK->upvalues[idx].is_upvalue = 0; // default: capture from parent's locals
return idx;
}
//-----------------------------------------------
// <atom> ==> <number> | <string> | <boolean> |
// <nil> | <identifier> | '(' <expr> ')'
//-----------------------------------------------
static int atom(SKState* pSK)
{
PARSE_LOG("atom(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
switch (LOOKAHEAD)
{
case '(':
expr(pSK);
break;
case TOKEN_TRUE:
PARSE_LOG("TOKEN_TRUE\n");
vm_emit(&pSK->vm, OP_TRUE);
match(pSK, TOKEN_TRUE);
unindent(pSK);
break;
case TOKEN_FALSE:
PARSE_LOG("TOKEN_FALSE\n");
vm_emit(&pSK->vm, OP_FALSE);
match(pSK, TOKEN_FALSE);
unindent(pSK);
break;
case NUMBER:
// handle number
PARSE_LOG("NUMBER: %d\n", pSK->yylval.ival);
if (pSK->yylval.ival == 0)
vm_emit(&pSK->vm, OP_NUM_0);
else if (pSK->yylval.ival == 1)
vm_emit(&pSK->vm, OP_NUM_1);
else if (pSK->yylval.ival == 2)
vm_emit(&pSK->vm, OP_NUM_2);
else
vm_emit_number(&pSK->vm, pSK->yylval.ival);
match(pSK, NUMBER);
unindent(pSK);
break;
case FLOAT:
// handle float literal
PARSE_LOG("FLOAT: %g\n", pSK->yylval.fval);
{
Object* flt = vm_new_float(&pSK->vm, pSK->yylval.fval);
vm_emit_push_object(&pSK->vm, flt);
}
match(pSK, FLOAT);
unindent(pSK);
break;
case CHAR:
// handle character literal
PARSE_LOG("CHAR: '%c'\n", pSK->yylval.ival);
vm_emit_push_object(&pSK->vm, MAKE_CHAR(pSK->yylval.ival));
match(pSK, CHAR);
unindent(pSK);
break;
case STRING:
PARSE_LOG("STRING: '%s'\n", pSK->yylval.word);
vm_emit_string(&pSK->vm, pSK->yylval.word);
match(pSK, STRING);
unindent(pSK);
break;
case NIL:
PARSE_LOG("NIL\n");
vm_emit_push_object(&pSK->vm, NULL);
match(pSK, NIL);
unindent(pSK);
break;
case QUOTE:
// 'datum shorthand — QUOTE token comes from lexer when ' is seen
match(pSK, QUOTE);
quote_datum(pSK);
unindent(pSK);
break;
case ID:
{
PARSE_LOG("ID: '%s'\n", pSK->yylval.word);
// check if var is local (with scope depth), if so emit stack read or upvalue
int scope_depth = -1;
Object* obj = vm_get_local_var_ex(&pSK->vm, pSK->yylval.word, &scope_depth);
// handle variable and check for undefined symbol
Object* key = vm_get_string(&pSK->vm, pSK->yylval.word);
char var_name[64];
strncpy(var_name, pSK->yylval.word, sizeof(var_name) - 1);
var_name[sizeof(var_name) - 1] = '\0';
match(pSK, ID);
if (!key)
{
yyerror(pSK, "entity undefined");
}
else if (scope_depth == 0 && IS_NUM(obj))
{
// Local variable in current scope
vm_emit(&pSK->vm, OP_GET_LOCAL);
vm_emit(&pSK->vm, (VMCode_t)AS_NUM(obj));
}
else if (scope_depth > 0 && IS_NUM(obj))
{
// Variable from enclosing scope — capture as upvalue
int uv_idx = register_upvalue(pSK, var_name, scope_depth, AS_NUM(obj));
if (uv_idx >= 0) {
vm_emit(&pSK->vm, OP_GET_UPVALUE);
vm_emit(&pSK->vm, (VMCode_t)uv_idx);
}
}
else
{
vm_emit_push_object(&pSK->vm, key);
vm_emit(&pSK->vm, OP_LOAD);
}
unindent(pSK);
}
break;
default:
yyerror(pSK, "syntax error");
match(pSK, LOOKAHEAD);
unindent(pSK);
return 0;
}
unindent(pSK);
return 1;
}
//-----------------------------------------------
// <formals> ==> (<variable>*) | <variable>
//-----------------------------------------------
static int formals(SKState* pSK, Procedure* proc)
{
PARSE_LOG("formals(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
int arity = 0;
while (LOOKAHEAD == ID)
{
arity++;
vm_set_var(&pSK->vm, pSK->yylval.word, MAKE_NUM(arity)); // add parameter to function scope
match(pSK, ID);
}
if (pSK->vm.current_scope)
{
Environment* env = pSK->vm.current_scope;
// update all bindings in the current environment
// Stack layout: [args..., ret_addr, saved_fp, arity] with fp pointing past arity
// So args are at fp-4, fp-5, etc. (arity at fp-1, saved_fp at fp-2, ret_addr at fp-3)
size_t env_index = 0;
ht_key_t env_key;
ht_value_t env_value;
while (ht_next(env->bindings, &env_index, &env_key, &env_value))
{
ht_add(env->bindings, env_key, MAKE_NUM(arity - AS_NUM(env_value) + 3)); // +3 for ret_addr, saved_fp, arity
}
}
if (proc)
proc->arity = arity;
unindent(pSK);
return 0;
}
//-----------------------------------------------
// <body> ==> <definition>* <sequence>
// <sequence> ==> <command>* <expression>
// <command> ==> <expression>
//-----------------------------------------------
static int local_body(SKState* pSK)
{
PARSE_LOG("local_body(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
// Parse the body expressions - last expression's value becomes return value
//
// TCO Strategy: We record the offset of each CALL/ICALL as we emit it.
// After parsing all expressions, we patch the LAST call to TAILCALL.
// This correctly handles both single and multi-expression bodies.
// Save state for nested functions
int saved_last_call_offset = pSK->last_call_offset;
CodeChunk* saved_last_call_chunk = pSK->last_call_chunk;
// Reset for this function body
pSK->last_call_offset = -1;
pSK->last_call_chunk = NULL;
// Parse all body expressions
while (LOOKAHEAD != ')')
{
expr(pSK);
}
// TCO: Patch the last CALL to TAILCALL if there was one
if (pSK->last_call_offset >= 0 && pSK->last_call_chunk != NULL)
{
VMCode_t opcode = pSK->last_call_chunk->code[pSK->last_call_offset];
if (opcode == OP_CALL)
{
PARSE_LOG("TCO: patching CALL at offset %d to TAILCALL\n", pSK->last_call_offset);
pSK->last_call_chunk->code[pSK->last_call_offset] = OP_TAILCALL;
}
else if (opcode == OP_ICALL)
{
PARSE_LOG("TCO: patching ICALL at offset %d to TAILCALL_I\n", pSK->last_call_offset);
pSK->last_call_chunk->code[pSK->last_call_offset] = OP_TAILCALL_I;
}
}
// Restore state for outer function
pSK->last_call_offset = saved_last_call_offset;
pSK->last_call_chunk = saved_last_call_chunk;
unindent(pSK);
return 0;
}
//-----------------------------------------------
// defintion := '(' 'define' ( function-definition | variable-definition ) ')'
// function-definition := '(' ID parameter* ')' s-expr
// variable-definition := ID s-expr
//-----------------------------------------------
static int definition(SKState* pSK)
{
PARSE_LOG("definition(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, DEFINE);
// look for a function definition or variable definition
if (LOOKAHEAD == '(')
{
// function definition
match(pSK, '(');
// Check if we're inside a local scope (nested define)
int is_local = (pSK->vm.current_scope != NULL);
// Save upvalue state for nested lambdas (like lambda() does)
ParseUpvalue saved_upvalues[MAX_UPVALUES];
int saved_upvalue_count = pSK->upvalue_count;
if (is_local)
{
if (saved_upvalue_count > 0)
memcpy(saved_upvalues, pSK->upvalues, sizeof(ParseUpvalue) * saved_upvalue_count);
pSK->upvalue_count = 0;
}
vm_new_environment(&pSK->vm); // create new environment for function scope
// function name
Object* proc_name = vm_new_string(&pSK->vm, pSK->yylval.word);
vm_push(&pSK->vm, proc_name); // stash function name on stack in case of GC
Object* proc_obj = vm_new_proc(&pSK->vm);
vm_pop(&pSK->vm); // remove function name from stack
Procedure* proc = AS_OBJ(Procedure, proc_obj);
proc->name = (String*)proc_name; // set function name
CodeChunk* prev_chunk = vm_set_current_chunk(&pSK->vm, &proc->chunk);
// Store as GC root in globals
if (!is_local)
{
// Top-level: the proc IS the final value, store under its real name
vm_define_global(&pSK->vm, proc_name, proc_obj);
}
else
{
// Nested: store under a unique internal name for GC safety only
// The real name will be bound via OP_STORE at runtime
static int inner_def_id = 0;
char gc_name[48];
snprintf(gc_name, sizeof(gc_name), "<define-%d>", inner_def_id++);
Object* gc_key = vm_new_string(&pSK->vm, gc_name);
vm_define_global(&pSK->vm, gc_key, proc_obj);
}
match(pSK, ID);
// parameters
formals(pSK, proc);
match(pSK, ')');
// function body
local_body(pSK);
// return from function (arity is now stored in frame by CALL)
vm_emit(&pSK->vm, OP_RET);
vm_set_current_chunk(&pSK->vm, prev_chunk);
vm_free_environment(&pSK->vm); // pop function environment off chain
if (is_local)
{
// Capture upvalue info before restoring outer state
int num_upvalues = pSK->upvalue_count;
ParseUpvalue captured[MAX_UPVALUES];
if (num_upvalues > 0)
memcpy(captured, pSK->upvalues, sizeof(ParseUpvalue) * num_upvalues);
// Restore outer lambda's upvalue state
pSK->upvalue_count = saved_upvalue_count;
if (saved_upvalue_count > 0)
memcpy(pSK->upvalues, saved_upvalues, sizeof(ParseUpvalue) * saved_upvalue_count);
// Propagate deep captures upward (same as lambda)
for (int i = 0; i < num_upvalues; i++)
{
if (captured[i].scope_depth > 1)
{
int parent_uv_idx = register_upvalue(pSK, captured[i].name,
captured[i].scope_depth - 1, captured[i].local_index);
captured[i].local_index = parent_uv_idx;
captured[i].is_upvalue = 1;
}
}
if (num_upvalues > 0)
{
// Emit closure creation and store to global under its real name
vm_emit_push_object(&pSK->vm, proc_name);
for (int i = 0; i < num_upvalues; i++)
{
if (captured[i].is_upvalue)
{
vm_emit(&pSK->vm, OP_GET_UPVALUE);
vm_emit(&pSK->vm, (VMCode_t)captured[i].local_index);
}
else
{
vm_emit(&pSK->vm, OP_GET_LOCAL);
vm_emit(&pSK->vm, (VMCode_t)captured[i].local_index);
}
}
vm_emit_push_object(&pSK->vm, proc_obj);
vm_emit(&pSK->vm, OP_MAKE_CLOSURE);
vm_emit(&pSK->vm, (VMCode_t)num_upvalues);
// Store the closure to global under its real name
vm_emit(&pSK->vm, OP_STORE);
}
else
{
// No upvalues — store plain procedure to global under its real name
vm_emit_push_object(&pSK->vm, proc_name);
vm_emit_push_object(&pSK->vm, proc_obj);
vm_emit(&pSK->vm, OP_STORE);
}
}
}
else
{
// variable definition
Object* key = vm_new_string(&pSK->vm, pSK->yylval.word);
vm_define_global(&pSK->vm, key, NULL); // needs to be in global table before expr() in case of GC
vm_emit_push_object(&pSK->vm, key);
match(pSK, ID);
expr(pSK);
vm_emit(&pSK->vm, OP_STORE);
}
unindent(pSK);
return 0;
}
//-----------------------------------------------
// lambda := '(' 'lambda' ( lambda-definition ) ')'
// lambda-definition := '(' parameter* ')' s-expr
// test: (define a (lambda (x) (* 2 2)))
//-----------------------------------------------
static int lambda(SKState* pSK)
{
PARSE_LOG("lambda(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, LAMBDA);
// Save outer lambda's upvalue state (for nested lambdas)
ParseUpvalue saved_upvalues[MAX_UPVALUES];
int saved_upvalue_count = pSK->upvalue_count;
if (saved_upvalue_count > 0)
memcpy(saved_upvalues, pSK->upvalues, sizeof(ParseUpvalue) * saved_upvalue_count);
pSK->upvalue_count = 0;
vm_new_environment(&pSK->vm); // create new environment for lambda scope
Object* proc_obj = vm_new_proc(&pSK->vm);
// put the procedure object on the stack for GC safety
vm_push(&pSK->vm, proc_obj);
Procedure* proc = AS_OBJ(Procedure, proc_obj);
// Give each lambda a unique internal name for GC root storage
static int lambda_id = 0;
char lambda_name[32];
snprintf(lambda_name, sizeof(lambda_name), "<lambda-%d>", lambda_id++);
proc->name = (String*)vm_new_string(&pSK->vm, lambda_name);
vm_define_global(&pSK->vm, (Object*)proc->name, proc_obj); // store in globals as GC root
CodeChunk* prev_chunk = vm_set_current_chunk(&pSK->vm, &proc->chunk);
if (LOOKAHEAD == '(')
{
match(pSK, '(');
// parameters
formals(pSK, proc);
match(pSK, ')');
}
else
{
if (LOOKAHEAD == ID)
{
// single parameter
proc->arity = 1;
match(pSK, ID);
}
else
proc->arity = 0;
}
// function body
local_body(pSK);
// return from function (arity is now stored in frame by CALL)
vm_emit(&pSK->vm, OP_RET);
vm_set_current_chunk(&pSK->vm, prev_chunk);
vm_free_environment(&pSK->vm); // pop lambda environment off chain
// Capture upvalue info before restoring outer state
int num_upvalues = pSK->upvalue_count;
ParseUpvalue captured[MAX_UPVALUES];
if (num_upvalues > 0)
memcpy(captured, pSK->upvalues, sizeof(ParseUpvalue) * num_upvalues);
// Restore outer lambda's upvalue state
pSK->upvalue_count = saved_upvalue_count;
if (saved_upvalue_count > 0)
memcpy(pSK->upvalues, saved_upvalues, sizeof(ParseUpvalue) * saved_upvalue_count);
// Propagate deep captures: if an inner lambda captured a variable at depth > 1,
// the parent (us) must also capture it as an upvalue so we can pass it along.
for (int i = 0; i < num_upvalues; i++)
{
if (captured[i].scope_depth > 1)
{
// Register this variable as an upvalue in the OUTER (parent) lambda
int parent_uv_idx = register_upvalue(pSK, captured[i].name,
captured[i].scope_depth - 1, captured[i].local_index);
// Update captured entry: at closure creation time, get from parent's upvalue
captured[i].local_index = parent_uv_idx;
captured[i].is_upvalue = 1;
}
}
if (num_upvalues > 0)
{
// Emit closure creation in the OUTER context.
// OP_MAKE_CLOSURE expects stack (bottom→top): [upval0, ..., upvalN-1, proc, count]
// Push captured values from enclosing scope
for (int i = 0; i < num_upvalues; i++)
{
if (captured[i].is_upvalue)
{
// Variable was captured from grandparent+ — read from parent's upvalues
vm_emit(&pSK->vm, OP_GET_UPVALUE);
vm_emit(&pSK->vm, (VMCode_t)captured[i].local_index);
}
else
{
// Variable is in immediate parent's locals
vm_emit(&pSK->vm, OP_GET_LOCAL);
vm_emit(&pSK->vm, (VMCode_t)captured[i].local_index);
}
}
// Then push the procedure object
vm_emit_push_object(&pSK->vm, proc_obj);
// Then emit the closure with upvalue count as immediate
vm_emit(&pSK->vm, OP_MAKE_CLOSURE);
vm_emit(&pSK->vm, (VMCode_t)num_upvalues);
}
else
{
// No upvalues — emit plain procedure push (original behavior)
vm_emit_push_object(&pSK->vm, proc_obj);
}
// NOTE: We intentionally DO NOT pop proc_obj from the stack here!
// It must stay on the stack as a GC root until parsing completes.
// The bytecode contains a pointer to proc_obj, but GC doesn't scan bytecode.
// Leaving it on stack keeps it alive during subsequent allocs that might trigger GC.
// The stack will be cleared before execution starts.
unindent(pSK);
return 0;
}
//-----------------------------------------------
// list := '(' expr* ')'
//-----------------------------------------------
static int parse_list(SKState* pSK)
{
PARSE_LOG("parse_list(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
int nargs = 0;
match(pSK, LIST);
while (LOOKAHEAD != ')')
{
expr(pSK);
nargs++;
}
vm_emit(&pSK->vm, OP_LIST);
vm_emit(&pSK->vm, (VMCode_t)nargs);
unindent(pSK);
return 0;
}
//-----------------------------------------------
// load_expr := '(' 'load' STRING ')'
//-----------------------------------------------
static int load_expr(SKState* pSK)
{
PARSE_LOG("load_expr(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, LOAD);
if (LOOKAHEAD != STRING)
{
yyerror(pSK, "expected string filename in 'load' expression");
unindent(pSK);
return 0;
}
// get filename - must copy before match() overwrites yylval
char filename[BUF_SIZE];
strncpy(filename, pSK->yylval.word, BUF_SIZE - 1);
filename[BUF_SIZE - 1] = '\0';
match(pSK, STRING);
// load (parse) the file
push_filename_stack(pSK, filename);
unindent(pSK);
return 0;
}
//-----------------------------------------------
// quote_datum - recursively emit code to construct a quoted value
// Numbers, strings, bools, chars are self-evaluating.
// Identifiers become symbols. Lists become OP_LIST constructions.
//-----------------------------------------------
static void quote_datum(SKState* pSK)
{
PARSE_LOG("quote_datum(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
if (LOOKAHEAD == '(')
{
match(pSK, '(');
// empty list?
if (LOOKAHEAD == ')')
{
match(pSK, ')');
vm_emit_push_object(&pSK->vm, NULL); // nil = empty list
return;
}
// non-empty list: recursively quote each element
int count = 0;
while (LOOKAHEAD != ')' && LOOKAHEAD != DONE)
{
quote_datum(pSK);
count++;
}
match(pSK, ')');
vm_emit(&pSK->vm, OP_LIST);
vm_emit(&pSK->vm, (VMCode_t)count);
}
else if (LOOKAHEAD == NUMBER)
{
vm_emit_number(&pSK->vm, pSK->yylval.ival);
match(pSK, NUMBER);
}
else if (LOOKAHEAD == STRING)
{
vm_emit_string(&pSK->vm, pSK->yylval.word);
match(pSK, STRING);
}
else if (LOOKAHEAD == TOKEN_TRUE)
{
vm_emit(&pSK->vm, OP_TRUE);
match(pSK, TOKEN_TRUE);
}
else if (LOOKAHEAD == TOKEN_FALSE)
{
vm_emit(&pSK->vm, OP_FALSE);
match(pSK, TOKEN_FALSE);
}
else if (LOOKAHEAD == CHAR)
{
vm_emit(&pSK->vm, OP_PUSH);
vm_emit(&pSK->vm, (VMCode_t)MAKE_CHAR(pSK->yylval.ival));
match(pSK, CHAR);
}
else if (LOOKAHEAD == NIL)
{
vm_emit_push_object(&pSK->vm, NULL);
match(pSK, NIL);
}
else if (LOOKAHEAD == QUOTE)
{
// nested quote: '('a) inside a quoted list
match(pSK, QUOTE);
quote_datum(pSK);
// wrap in (quote x) → build a 2-element list: (symbol:quote, datum)
vm_emit_symbol(&pSK->vm, "quote");
vm_emit(&pSK->vm, OP_LIST);
vm_emit(&pSK->vm, 2);
}
else if (LOOKAHEAD == ID || LOOKAHEAD == '+' || LOOKAHEAD == '-' ||
LOOKAHEAD == '*' || LOOKAHEAD == '/' || LOOKAHEAD == '<' ||
LOOKAHEAD == '>' || LOOKAHEAD == '=')
{
// identifiers and operators become symbols
vm_emit_symbol(&pSK->vm, pSK->yylval.word);
match(pSK, LOOKAHEAD);
}
else
{
yyerror(pSK, "unexpected token in quoted expression");
match(pSK, LOOKAHEAD); // consume to avoid infinite loop
}
}
//-----------------------------------------------
// quote_expr := '(' 'quote' datum ')'
// Also handles 'datum (shorthand) when called directly
//-----------------------------------------------
static int quote_expr(SKState* pSK)
{
PARSE_LOG("quote_expr(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, QUOTE);
quote_datum(pSK);
unindent(pSK);
return 0;
}
//-----------------------------------------------
// import_expr := '(' 'import' ID ')'
//-----------------------------------------------
static int import_expr(SKState* pSK)
{
PARSE_LOG("import_expr(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, IMPORT);
if (LOOKAHEAD != ID)
{
yyerror(pSK, "expected module name in 'import' expression");
unindent(pSK);
return 0;
}
const char* module_name = pSK->yylval.word;
if (sk_import_module(pSK, module_name) != 0)
yyerror(pSK, "failed to import module");
match(pSK, ID);
unindent(pSK);
return 0;
}
//-----------------------------------------------
// do_expr := '(' 'do' ((var init step) ...) (test result ...) body ... ')'
// Implemented as: emit inits, create lambda frame, loop with BRA/BNT
//-----------------------------------------------
#define MAX_DO_BINDINGS 16
static int do_expr(SKState* pSK)
{
PARSE_LOG("do_expr(): lookahead = %d '%c'\n", LOOKAHEAD, (char)LOOKAHEAD);
match(pSK, DO);
// Parse bindings: ((var init step) ...)
char bind_names[MAX_DO_BINDINGS][64];
char step_strs[MAX_DO_BINDINGS][BUF_SIZE];
int nbindings = 0;
match(pSK, '(');
while (LOOKAHEAD != ')' && LOOKAHEAD != DONE)
{
match(pSK, '(');
// var name
strncpy(bind_names[nbindings], pSK->yylval.word, 63);
bind_names[nbindings][63] = '\0';
match(pSK, ID);
// init expression — emit into outer chunk (init values)
expr(pSK);
// step expression — save as text for later re-parse
step_strs[nbindings][0] = '\0';
if (LOOKAHEAD != ')')
{
int depth = 0;
int pos = 0;
if (LOOKAHEAD == '(')
{
depth = 1;
step_strs[nbindings][pos++] = '(';
match(pSK, '(');
while (depth > 0 && LOOKAHEAD != DONE && pos < BUF_SIZE - 2)
{
if (LOOKAHEAD == '(') {
step_strs[nbindings][pos++] = '(';
depth++;
match(pSK, '(');
} else if (LOOKAHEAD == ')') {
step_strs[nbindings][pos++] = ')';
depth--;
if (depth > 0) match(pSK, ')');
} else {
if (LOOKAHEAD == NUMBER)
pos += snprintf(step_strs[nbindings] + pos, BUF_SIZE - pos, "%d", pSK->yylval.ival);
else {
int len = (int)strlen(pSK->yylval.word);
if (pos + len + 1 < BUF_SIZE) {
memcpy(step_strs[nbindings] + pos, pSK->yylval.word, len);
pos += len;
}
}
step_strs[nbindings][pos++] = ' ';
match(pSK, LOOKAHEAD);
}
}
match(pSK, ')');
}
else
{
if (LOOKAHEAD == NUMBER)
pos += snprintf(step_strs[nbindings] + pos, BUF_SIZE - pos, "%d", pSK->yylval.ival);
else {
int len = (int)strlen(pSK->yylval.word);
memcpy(step_strs[nbindings] + pos, pSK->yylval.word, len);
pos += len;
}
match(pSK, LOOKAHEAD);
}
step_strs[nbindings][pos] = '\0';
}
nbindings++;
match(pSK, ')');
}
match(pSK, ')');
// Create lambda for loop body (inlined, not using let_create_lambda)
ParseUpvalue saved_upvalues[MAX_UPVALUES];
int saved_upvalue_count = pSK->upvalue_count;
if (saved_upvalue_count > 0)
memcpy(saved_upvalues, pSK->upvalues, sizeof(ParseUpvalue) * saved_upvalue_count);
pSK->upvalue_count = 0;
vm_new_environment(&pSK->vm);
Object* proc_obj = vm_new_proc(&pSK->vm);
vm_push(&pSK->vm, proc_obj);
Procedure* proc = AS_OBJ(Procedure, proc_obj);
static int do_id = 0;
char do_name[32];
snprintf(do_name, sizeof(do_name), "<do-%d>", do_id++);
proc->name = (String*)vm_new_string(&pSK->vm, do_name);
vm_define_global(&pSK->vm, (Object*)proc->name, proc_obj);
CodeChunk* prev_chunk = vm_set_current_chunk(&pSK->vm, &proc->chunk);
proc->arity = nbindings;
for (int i = 0; i < nbindings; i++)
vm_set_var(&pSK->vm, bind_names[i], MAKE_NUM(i + 1));
if (pSK->vm.current_scope)
{
Environment* env = pSK->vm.current_scope;
size_t env_index = 0;
ht_key_t env_key;
ht_value_t env_value;
while (ht_next(env->bindings, &env_index, &env_key, &env_value))
ht_add(env->bindings, env_key, MAKE_NUM(nbindings - AS_NUM(env_value) + 3));
}