-
Notifications
You must be signed in to change notification settings - Fork 19
/
little.c
2279 lines (1892 loc) · 63.2 KB
/
little.c
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 "little.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <setjmp.h>
static lt_Value LT_NULL = LT_VALUE_NULL;
typedef struct {
uint64_t hash;
char* string;
lt_Value value;
uint32_t refcount;
uint32_t len;
} lt_StringDedupEntry;
typedef enum {
LT_OP_NOP,
LT_OP_PUSH, LT_OP_POP, LT_OP_DUP,
LT_OP_PUSHS, LT_OP_PUSHC, LT_OP_PUSHN, LT_OP_PUSHT, LT_OP_PUSHF,
LT_OP_ADD, LT_OP_SUB, LT_OP_MUL, LT_OP_DIV, LT_OP_NEG,
LT_OP_EQ, LT_OP_NEQ, LT_OP_GT, LT_OP_GTE,
LT_OP_AND, LT_OP_OR, LT_OP_NOT,
LT_OP_LOAD, LT_OP_STORE,
LT_OP_LOADUP, LT_OP_STOREUP,
LT_OP_LOADB,
LT_OP_CLOSE, LT_OP_CALL,
LT_OP_MAKET, LT_OP_MAKEA, LT_OP_SETT, LT_OP_GETT, LT_OP_GETG,
LT_OP_JMP, LT_OP_JMPC, LT_OP_JMPN,
LT_OP_RET,
} lt_OpCode;
typedef struct {
uint16_t op;
int16_t arg;
} lt_Op;
uint64_t static MurmurOAAT64(const char* key)
{
uint64_t h = 525201411107845655ull;
for (; *key; ++key) {
h ^= *key;
h *= 0x5bd1e9955bd1e995;
h ^= h >> 47;
}
return h;
}
typedef union {
double flt;
uint64_t bits;
} _lt_conversion_union;
lt_Buffer lt_buffer_new(uint32_t element_size)
{
lt_Buffer buf;
buf.element_size = element_size;
buf.capacity = 0;
buf.length = 0;
buf.data = 0;
return buf;
}
void lt_buffer_destroy(lt_VM* vm, lt_Buffer* buf)
{
if (buf->data != 0) vm->free(buf->data);
buf->data = 0;
buf->length = 0;
buf->capacity = 0;
}
static uint8_t lt_buffer_push(lt_VM* vm, lt_Buffer* buf, void* element)
{
uint8_t has_allocated = 0;
if (buf->length + 1 > buf->capacity)
{
has_allocated = 1;
void* new_buffer = vm->alloc(buf->element_size * (buf->capacity + 16));
if (buf->data != 0)
{
memcpy(new_buffer, buf->data, buf->element_size * buf->capacity);
free(buf->data);
}
buf->data = new_buffer;
buf->capacity += 16;
}
memcpy((uint8_t*)buf->data + buf->element_size * buf->length, element, buf->element_size);
buf->length++;
return has_allocated;
}
static void* lt_buffer_at(lt_Buffer* buf, uint32_t idx)
{
return (uint8_t*)buf->data + buf->element_size * idx;
}
static void* lt_buffer_last(lt_Buffer* buf)
{
return lt_buffer_at(buf, buf->length - 1);
}
static void lt_buffer_cycle(lt_Buffer* buf, uint32_t idx)
{
memcpy(lt_buffer_at(buf, idx), lt_buffer_last(buf), buf->element_size);
buf->length--;
}
static void lt_buffer_pop(lt_Buffer* buf)
{
buf->length--;
}
lt_Value lt_make_number(double n)
{
_lt_conversion_union u;
u.flt = n;
return (lt_Value)u.bits;
}
double lt_get_number(lt_Value v)
{
_lt_conversion_union u;
u.bits = v;
return (double)u.flt;
}
static void _lt_tokenize_error(lt_VM* vm, const char* module, uint16_t line, uint16_t col, const char* message)
{
char sprint_buf[128];
sprintf_s(sprint_buf, 128, "%s|%d:%d: %s", module, line, col, message);
lt_error(vm, sprint_buf);
}
static void _lt_parse_error(lt_VM* vm, const char* module, lt_Token* t, const char* message)
{
char sprint_buf[128];
sprintf_s(sprint_buf, 128, "%s|%d:%d: %s", module, t->line, t->col, message);
lt_error(vm, sprint_buf);
}
static lt_DebugInfo* _lt_get_debuginfo(lt_Object* obj)
{
switch (obj->type)
{
case LT_OBJECT_CHUNK: return obj->chunk.debug;
case LT_OBJECT_FN: return obj->fn.debug;
case LT_OBJECT_CLOSURE: return LT_GET_OBJECT(obj->closure.function)->fn.debug;
}
return 0;
}
static lt_DebugLoc _lt_get_location(lt_DebugInfo* info, uint32_t pc)
{
if (info)
{
return *(lt_DebugLoc*)lt_buffer_at(&info->locations, pc);
}
return (lt_DebugLoc){ 0, 0 };
}
void lt_runtime_error(lt_VM* vm, const char* message)
{
char sprint_buf[1024];
lt_Frame* topmost = &vm->callstack[vm->depth - 1];
lt_DebugInfo* info = _lt_get_debuginfo(topmost->callee);
lt_DebugLoc loc = _lt_get_location(info, topmost->pc);
const char* name = "<unknown>";
if (info) name = info->module_name;
uint32_t len = sprintf_s(sprint_buf, 1024, "%s|%d:%d: %s\ntraceback:", name, loc.line, loc.col, message);
for (uint32_t i = vm->depth - 1; i >= 0; --i)
{
lt_Frame* frame = &vm->callstack[i];
lt_DebugInfo* info = _lt_get_debuginfo(frame->callee);
lt_DebugLoc loc = _lt_get_location(info, 0);
const char* name = "<unknown>";
if (info) name = info->module_name;
len = sprintf_s(sprint_buf + len, 1024 - len, "\n(%s|%d:%d)", name, loc.line, loc.col);
}
lt_error(vm, sprint_buf);
}
lt_Value lt_make_string(lt_VM* vm, const char* string)
{
uint32_t len = (uint32_t)strlen(string);
uint64_t hash = MurmurOAAT64(string);
uint16_t bucket = hash % LT_DEDUP_TABLE_SIZE;
lt_Buffer* buf = vm->strings + bucket;
if (buf->element_size == 0) *buf = lt_buffer_new(sizeof(lt_StringDedupEntry));
int32_t first_empty = -1;
for (uint32_t i = 0; i < buf->length; i++)
{
lt_StringDedupEntry* entry = lt_buffer_at(buf, i);
if (entry->hash == hash)
{
return entry->value;
}
else if (entry->hash == 0 && first_empty == -1) first_empty = i;
}
lt_StringDedupEntry new_entry;
new_entry.hash = hash;
new_entry.len = len;
new_entry.refcount = 0;
new_entry.string = vm->alloc(len + 1);
memcpy(new_entry.string, string, len);
new_entry.string[len] = 0;
uint32_t index = 0;
if (first_empty != -1)
{
index = first_empty;
lt_StringDedupEntry* e = lt_buffer_at(buf, first_empty);
new_entry.value = (LT_NAN_MASK | LT_TYPE_STRING) | (bucket << 24) | (index & 0xFFFFFF);
memcpy(e, &new_entry, sizeof(lt_StringDedupEntry));
return new_entry.value;
}
else
{
lt_buffer_push(vm, buf, &new_entry);
lt_StringDedupEntry* e = lt_buffer_at(buf, buf->length - 1);
index = buf->length - 1;
e->value = (LT_NAN_MASK | LT_TYPE_STRING) | (bucket << 24) | (index & 0xFFFFFF);
return e->value;
}
}
const char* lt_get_string(lt_VM* vm, lt_Value value)
{
uint16_t bucket = (uint16_t)((value & 0xFFFFFF000000) >> 24);
uint32_t index = value & 0xFFFFFF;
return ((lt_StringDedupEntry*)lt_buffer_at(vm->strings + bucket, index))->string;
}
static void _lt_reference_string(lt_VM* vm, lt_Value value)
{
uint16_t bucket = (uint16_t)((value & 0xFFFFFF000000) >> 24);
uint32_t index = value & 0xFFFFFF;
((lt_StringDedupEntry*)lt_buffer_at(vm->strings + bucket, index))->refcount++;
}
static uint8_t faststrcmp(const char* a, uint64_t a_len, const char* b, uint64_t b_len)
{
if (a_len != b_len) return 0;
for (int i = 0; i < a_len; ++i)
{
if (*(a + i) != *(b + i)) return 0;
}
return 1;
}
uint8_t lt_equals(lt_Value a, lt_Value b)
{
if (LT_IS_NUMBER(a) != LT_IS_NUMBER(b) || (a & LT_TYPE_MASK) != (b & LT_TYPE_MASK)) return 0;
switch (a & LT_TYPE_MASK)
{
case LT_TYPE_NULL:
case LT_TYPE_BOOL:
case LT_TYPE_STRING:
return a == b;
case LT_TYPE_OBJECT: {
lt_Object* obja = LT_GET_OBJECT(a);
lt_Object* objb = LT_GET_OBJECT(b);
if (obja->type != objb->type) return 0;
switch (obja->type)
{
case LT_OBJECT_CHUNK:
case LT_OBJECT_CLOSURE:
case LT_OBJECT_FN:
case LT_OBJECT_TABLE:
case LT_OBJECT_NATIVEFN:
return obja == objb;
}
} break;
}
return 0;
}
lt_Tokenizer lt_tokenize(lt_VM* vm, const char* source, const char* mod_name)
{
lt_Tokenizer t;
t.module = mod_name;
t.is_valid = 0;
t.source = source;
t.token_buffer = lt_buffer_new(sizeof(lt_Token));
t.identifier_buffer = lt_buffer_new(sizeof(lt_Identifier));
t.literal_buffer = lt_buffer_new(sizeof(lt_Literal));
if (!setjmp(*(jmp_buf*)vm->error_buf))
{
const char* current = source;
uint16_t line = 1, col = 0;
#define PUSH_TOKEN(new_type) { \
lt_Token _t; _t.type = new_type; _t.line = line; _t.col = col++; _t.idx = 0; \
lt_buffer_push(vm, &t.token_buffer, &_t); current++; found = 1;\
};
while (*current)
{
uint8_t found = 0;
switch (*current)
{
case ' ': case '\t': { col++; current++; } found = 1; break;
case '\n': { col = 0; line++; current++; } found = 1; break;
case '\r': { current++; } found = 1; break;
case ';': { while (*current++ != '\n'); col = 1; line++; found = 1; } break;
case '.': PUSH_TOKEN(LT_TOKEN_PERIOD) break;
case ',': PUSH_TOKEN(LT_TOKEN_COMMA) break;
case ':': PUSH_TOKEN(LT_TOKEN_COLON) break;
case '(': PUSH_TOKEN(LT_TOKEN_OPENPAREN) break;
case ')': PUSH_TOKEN(LT_TOKEN_CLOSEPAREN) break;
case '[': PUSH_TOKEN(LT_TOKEN_OPENBRACKET) break;
case ']': PUSH_TOKEN(LT_TOKEN_CLOSEBRACKET) break;
case '{': PUSH_TOKEN(LT_TOKEN_OPENBRACE) break;
case '}': PUSH_TOKEN(LT_TOKEN_CLOSEBRACE) break;
case '+': PUSH_TOKEN(LT_TOKEN_PLUS) break;
case '-': PUSH_TOKEN(LT_TOKEN_MINUS) break;
case '*': PUSH_TOKEN(LT_TOKEN_MULTIPLY) break;
case '/': PUSH_TOKEN(LT_TOKEN_DIVIDE) break;
case '=': PUSH_TOKEN(LT_TOKEN_ASSIGN) break;
}
if (!found)
{
if (*current == '>')
{
if (*(current + 1) == '=')
{
current++;
PUSH_TOKEN(LT_TOKEN_GTE);
}
else PUSH_TOKEN(LT_TOKEN_GT);
}
else if (*current == '<')
{
if (*(current + 1) == '=')
{
current++;
PUSH_TOKEN(LT_TOKEN_LTE);
}
else PUSH_TOKEN(LT_TOKEN_LT);
}
else if (*current == '"')
{
const char* start = ++current;
while (*current++ != '"') if (*current == '\n') { col = 0; line++; }
uint32_t length = (uint32_t)(current - start - 1);
lt_Literal newlit;
newlit.type = LT_TOKEN_STRING_LITERAL;
newlit.string = vm->alloc(length + 1);
strncpy_s(newlit.string, length + 1, start, length);
newlit.string[length] = 0;
lt_buffer_push(vm, &t.literal_buffer, &newlit);
lt_Token tok;
tok.type = LT_TOKEN_STRING_LITERAL;
tok.line = line;
tok.col = col; col += length;
tok.idx = t.literal_buffer.length - 1;
lt_buffer_push(vm, &t.token_buffer, &tok);
}
else if (isalnum(*current) && !isalpha(*current))
{
const char* start = current;
uint8_t has_decimal = 0;
while ((isalnum(*current) && !isalpha(*current)) || *current == '.')
{
if (*current == '.')
{
if (has_decimal) _lt_tokenize_error(vm, t.module, line, col, "Can't have multiple decimals in number literal!");
has_decimal = 1;
}
current++;
}
uint32_t length = (uint32_t)(current - start);
char* end = 0;
double number = strtod(start, &end);
if (end != current) _lt_tokenize_error(vm, t.module, line, col, "Failed to parse number!");
lt_Literal newlit;
newlit.type = LT_TOKEN_NUMBER_LITERAL;
newlit.number = number;
lt_buffer_push(vm, &t.literal_buffer, &newlit);
lt_Token tok;
tok.type = LT_TOKEN_NUMBER_LITERAL;
tok.line = line;
tok.col = col; col += length;
tok.idx = t.literal_buffer.length - 1;
lt_buffer_push(vm, &t.token_buffer, &tok);
}
else if (isalpha(*current) || *current == '_')
{
const char* start = current;
uint8_t search = 1;
while (search)
{
current++;
if (!isalnum(*current) && *current != '_')
{
search = 0;
}
}
uint16_t length = (uint16_t)(current - start);
#define PUSH_STR_TOKEN(name, new_type) \
if(faststrcmp(name, sizeof(name) - 1, start, length)) { \
lt_Token _t; _t.type = new_type; _t.line = line; _t.col = col; col += length; _t.idx = 0; \
lt_buffer_push(vm, &t.token_buffer, &_t); found = 1; }
PUSH_STR_TOKEN("fn", LT_TOKEN_FN)
else PUSH_STR_TOKEN("var", LT_TOKEN_VAR)
else PUSH_STR_TOKEN("if", LT_TOKEN_IF)
else PUSH_STR_TOKEN("else", LT_TOKEN_ELSE)
else PUSH_STR_TOKEN("elseif", LT_TOKEN_ELSEIF)
else PUSH_STR_TOKEN("for", LT_TOKEN_FOR)
else PUSH_STR_TOKEN("in", LT_TOKEN_IN)
else PUSH_STR_TOKEN("while", LT_TOKEN_WHILE)
else PUSH_STR_TOKEN("break", LT_TOKEN_BREAK)
else PUSH_STR_TOKEN("return", LT_TOKEN_RETURN)
else PUSH_STR_TOKEN("is", LT_TOKEN_EQUALS)
else PUSH_STR_TOKEN("isnt", LT_TOKEN_NOTEQUALS)
else PUSH_STR_TOKEN("and", LT_TOKEN_AND)
else PUSH_STR_TOKEN("or", LT_TOKEN_OR)
else PUSH_STR_TOKEN("not", LT_TOKEN_NOT)
else PUSH_STR_TOKEN("true", LT_TOKEN_TRUE_LITERAL)
else PUSH_STR_TOKEN("false", LT_TOKEN_FALSE_LITERAL)
else PUSH_STR_TOKEN("null", LT_TOKEN_NULL_LITERAL)
if (!found)
{
for (uint32_t i = 0; i < t.identifier_buffer.length; i++)
{
lt_Identifier* id = lt_buffer_at(&t.identifier_buffer, i);
if (faststrcmp(start, length, id->name, strlen(id->name)))
{
found = 1;
id->num_references++;
lt_Token tok;
tok.type = LT_TOKEN_IDENTIFIER;
tok.line = line;
tok.col = col; col += length;
tok.idx = i;
lt_buffer_push(vm, &t.token_buffer, &tok);
break;
}
}
if (!found)
{
lt_Identifier newid;
newid.num_references = 1;
newid.name = vm->alloc(length + 1);
strncpy_s(newid.name, length + 1, start, length);
newid.name[length] = 0;
lt_buffer_push(vm, &t.identifier_buffer, &newid);
lt_Token tok;
tok.type = LT_TOKEN_IDENTIFIER;
tok.line = line;
tok.col = col; col += length;
tok.idx = t.identifier_buffer.length - 1;
lt_buffer_push(vm, &t.token_buffer, &tok);
}
}
}
else _lt_tokenize_error(vm, t.module, line, col, "Unrecognized token!");
}
}
lt_Token tok;
tok.type = LT_TOKEN_END;
tok.line = line;
tok.col = col;
lt_buffer_push(vm, &t.token_buffer, &tok);
t.is_valid = 1;
}
return t;
}
lt_AstNode* _lt_get_node_of_type(lt_VM* vm, lt_Token* current, lt_Parser* p, lt_AstNodeType type)
{
lt_AstNode* new_node = vm->alloc(sizeof(lt_AstNode));
memset(new_node, 0, sizeof(lt_AstNode));
new_node->type = type;
new_node->loc.line = current->line;
new_node->loc.col = current->col;
lt_buffer_push(vm, &p->ast_nodes, &new_node);
return *(void**)lt_buffer_last(&p->ast_nodes);
}
uint32_t _lt_tokens_equal(lt_Token* a, lt_Token* b)
{
return (a->type == LT_TOKEN_IDENTIFIER && b->type == LT_TOKEN_IDENTIFIER && a->idx == b->idx);
}
uint16_t _lt_make_local(lt_VM* vm, lt_Scope* scope, lt_Token* t)
{
lt_Scope* current = scope;
for (uint32_t i = 0; i < current->locals.length; ++i)
{
if (_lt_tokens_equal((lt_Token*)lt_buffer_at(¤t->locals, i), t)) return i;
}
lt_buffer_push(vm, ¤t->locals, t);
return current->locals.length - 1;
}
#define UPVAL_BIT 0x07000000
#define NOT_FOUND ((uint32_t)-1)
uint32_t _lt_find_local(lt_VM* vm, lt_Scope* scope, lt_Token* t)
{
lt_Scope* current = scope;
for (uint32_t i = 0; i < current->locals.length; ++i)
if (_lt_tokens_equal((lt_Token*)lt_buffer_at(¤t->locals, i), t)) return i;
for (uint32_t i = 0; i < current->upvals.length; ++i)
if (_lt_tokens_equal((lt_Token*)lt_buffer_at(¤t->upvals, i), t)) return i | UPVAL_BIT;
lt_Scope* test = current->last;
while (test)
{
uint8_t found = 0;
for (uint32_t i = 0; i < test->locals.length; ++i)
{
if (_lt_tokens_equal((lt_Token*)lt_buffer_at(&test->locals, i), t)) { found = 1; break; }
}
if(!found)
for (uint32_t i = 0; i < test->upvals.length; ++i)
{
if (_lt_tokens_equal((lt_Token*)lt_buffer_at(&test->upvals, i), t)) { found = 1; break; }
}
if (found)
{
lt_buffer_push(vm, ¤t->upvals, t);
return (current->upvals.length - 1) | UPVAL_BIT;
}
test = test->last;
}
return NOT_FOUND;
}
lt_Token* _lt_parse_expression(lt_VM* vm, lt_Parser* p, lt_Token* start, lt_AstNode* dst);
lt_Scope* _lt_parse_block(lt_VM* vm, lt_Parser* p, lt_Token* start, lt_Buffer* dst, uint8_t expects_terminator, uint8_t makes_scope, lt_Token** argnames)
{
if (makes_scope)
{
lt_Scope* new_scope = vm->alloc(sizeof(lt_Scope));
new_scope->last = p->current;
p->current = new_scope;
new_scope->start = start;
new_scope->end = start;
new_scope->locals = lt_buffer_new(sizeof(lt_Token));
new_scope->upvals = lt_buffer_new(sizeof(lt_Token));
if (argnames) while (*argnames) _lt_make_local(vm, p->current, *argnames++);
}
lt_Token* current = start;
#define PEEK() (current + 1)
#define NEXT() (last = current, current++)
while (current->type != LT_TOKEN_END)
{
switch (current->type)
{
case LT_TOKEN_CLOSEBRACE:
if (expects_terminator) { current++; goto end_block; }
_lt_parse_error(vm, p->tkn->module, current, "Unexpected closing brace!");
case LT_TOKEN_END:
_lt_parse_error(vm, p->tkn->module, current, "Unexpected end of file!");
case LT_TOKEN_IF: {
lt_AstNode* if_statement = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_IF);
current++;
lt_AstNode* expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, expr);
if (current->type != LT_TOKEN_OPENBRACE) _lt_parse_error(vm, p->tkn->module, current, "Expeceted open brace to follow if expression!");
current++;
lt_Buffer body = lt_buffer_new(sizeof(lt_AstNode*));
_lt_parse_block(vm, p, current, &body, 1, 0, 0);
current = p->current->end;
if_statement->branch.expr = expr;
if_statement->branch.body = body;
if_statement->branch.next = 0;
lt_AstNode* last = 0;
while (current->type == LT_TOKEN_ELSEIF || current->type == LT_TOKEN_ELSE)
{
lt_AstNode* node = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
if (if_statement->branch.next == 0) if_statement->branch.next = node;
if (last) last->branch.next = node;
if (current->type == LT_TOKEN_ELSEIF)
{
current++;
node->type = LT_AST_NODE_ELSEIF;
lt_AstNode* expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, expr);
node->branch.expr = expr;
}
else
{
current++;
node->type = LT_AST_NODE_ELSE;
}
if (current->type != LT_TOKEN_OPENBRACE) _lt_parse_error(vm, p->tkn->module, current, "Expected open brace to follow else expression!");
current++;
lt_Buffer body = lt_buffer_new(sizeof(lt_AstNode*));
_lt_parse_block(vm, p, current, &body, 1, 0, 0);
current = p->current->end;
node->branch.body = body;
last = node;
}
lt_buffer_push(vm, dst, &if_statement);
} break;
case LT_TOKEN_FOR: {
lt_AstNode* for_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_FOR);
current++; // eat for
lt_Token* ident = current++;
uint16_t iteridx = _lt_make_local(vm, p->current, ident);
if (current->type != LT_TOKEN_IN) _lt_parse_error(vm, p->tkn->module, current, "Expected 'in' to follow 'for' iterator!");
current++;
lt_AstNode* iter_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, iter_expr);
for_expr->loop.identifier = iteridx;
const char* FOR_ITER_NAME = "__iter";
uint16_t len = (uint16_t)strlen(FOR_ITER_NAME);
lt_Identifier newid;
newid.num_references = 1;
newid.name = vm->alloc(len + 1);
strncpy_s(newid.name, len + 1, FOR_ITER_NAME, len);
newid.name[len] = 0;
lt_buffer_push(vm, &p->tkn->identifier_buffer, &newid);
lt_Token tok;
tok.type = LT_TOKEN_IDENTIFIER;
tok.line = ident->line;
tok.col = ident->col;
tok.idx = p->tkn->identifier_buffer.length - 1;
for_expr->loop.closureidx = _lt_make_local(vm, p->current, &tok);
for_expr->loop.iterator = iter_expr;
if (current->type != LT_TOKEN_OPENBRACE) _lt_parse_error(vm, p->tkn->module, current, "Expected open brace to follow 'for' header!");
current++;
lt_Buffer body = lt_buffer_new(sizeof(lt_AstNode*));
_lt_parse_block(vm, p, current, &body, 1, 0, 0);
current = p->current->end;
for_expr->loop.body = body;
lt_buffer_push(vm, dst, &for_expr);
} break;
case LT_TOKEN_WHILE: {
lt_AstNode* while_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_WHILE);
current++; // eat while
lt_AstNode* iter_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, iter_expr);
while_expr->loop.iterator = iter_expr;
if (current->type != LT_TOKEN_OPENBRACE) _lt_parse_error(vm, p->tkn->module, current, "Expected open brace to follow 'while' header!");
current++;
lt_Buffer body = lt_buffer_new(sizeof(lt_AstNode*));
_lt_parse_block(vm, p, current, &body, 1, 0, 0);
current = p->current->end;
while_expr->loop.body = body;
lt_buffer_push(vm, dst, &while_expr);
} break;
case LT_TOKEN_RETURN: {
lt_AstNode* ret = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_RETURN);
ret->ret.expr = 0;
current++; // eat 'return'
lt_AstNode* expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
lt_Token* new_current = _lt_parse_expression(vm, p, current, expr);
if (current != new_current)
{
ret->ret.expr = expr;
current = new_current;
}
lt_buffer_push(vm, dst, &ret);
} break;
case LT_TOKEN_BREAK: {
lt_AstNode* brk = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_BREAK);
current++; // eat 'break'
lt_buffer_push(vm, dst, &brk);
}
case LT_TOKEN_VAR: {
lt_AstNode* declare = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_DECLARE);
current++;
if (current->type == LT_TOKEN_IDENTIFIER)
{
declare->declare.identifier = current++;
_lt_make_local(vm, p->current, declare->declare.identifier);
}
else _lt_parse_error(vm, p->tkn->module, current, "Expected identifier to follow 'var'!");
lt_AstNode* rhs = 0;
if (current->type == LT_TOKEN_ASSIGN)
{
current++;
rhs = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, rhs);
}
declare->declare.expr = rhs;
lt_buffer_push(vm, dst, &declare);
} break;
default: {
lt_AstNode* result = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, result);
if (current->type == LT_TOKEN_ASSIGN)
{
current++;
lt_AstNode* expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, expr);
lt_AstNode* lhs = result;
result = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_ASSIGN);
result->assign.left = lhs;
result->assign.right = expr;
}
lt_buffer_push(vm, dst, &result);
} break;
}
}
end_block:
p->current->end = current;
lt_Scope* new_scope = p->current;
if(makes_scope) p->current = p->current->last;
return new_scope;
}
uint8_t _lt_get_prec(lt_TokenType op)
{
switch (op)
{
case LT_TOKEN_NOT: case LT_TOKEN_NEGATE: return 5;
case LT_TOKEN_MULTIPLY: case LT_TOKEN_DIVIDE: return 4;
case LT_TOKEN_PLUS: case LT_TOKEN_MINUS: return 3;
case LT_TOKEN_GT: case LT_TOKEN_GTE: case LT_TOKEN_LT: case LT_TOKEN_LTE: case LT_TOKEN_EQUALS: case LT_TOKEN_NOTEQUALS: return 2;
case LT_TOKEN_AND: case LT_TOKEN_OR: return 1;
}
return 0;
}
#define LT_TOKEN_ANY_LITERAL \
LT_TOKEN_NULL_LITERAL: \
case LT_TOKEN_FALSE_LITERAL: \
case LT_TOKEN_TRUE_LITERAL: \
case LT_TOKEN_NUMBER_LITERAL: \
case LT_TOKEN_STRING_LITERAL: \
case LT_TOKEN_FN
lt_Token* _lt_parse_expression(lt_VM* vm, lt_Parser* p, lt_Token* start, lt_AstNode* dst)
{
uint8_t n_open = 0;
lt_Token* last = 0;
lt_Token* current = start;
lt_Buffer result = lt_buffer_new(sizeof(lt_AstNode*));
lt_Buffer operator_stack = lt_buffer_new(sizeof(lt_TokenType));
#define PUSH_EXPR_FROM_OP(op) \
if (op == LT_TOKEN_NOT || op == LT_TOKEN_NEGATE) \
{ \
lt_AstNode* unaryop = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_UNARYOP); \
unaryop->unary_op.type = op; \
lt_buffer_push(vm, &result, &unaryop); \
} \
else \
{ \
lt_AstNode* binaryop = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_BINARYOP); \
binaryop->binary_op.type = op; \
lt_buffer_push(vm, &result, &binaryop); \
}
#define BREAK_ON_EXPR_BOUNDRY \
if (last) switch (last->type) \
{ \
case LT_TOKEN_IDENTIFIER: \
case LT_TOKEN_CLOSEBRACE: \
case LT_TOKEN_CLOSEBRACKET: \
case LT_TOKEN_CLOSEPAREN: \
case LT_TOKEN_ANY_LITERAL: \
goto expr_end; \
}
while (current->type != LT_TOKEN_END)
{
switch (current->type)
{
case LT_TOKEN_IDENTIFIER: {
BREAK_ON_EXPR_BOUNDRY
lt_AstNode* ident = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_IDENTIFIER);
ident->identifier.token = NEXT();
if (_lt_find_local(vm, p->current, ident->identifier.token) == NOT_FOUND) {} // ERROR!
lt_buffer_push(vm, &result, &ident);
} break;
case LT_TOKEN_OPENBRACKET: {
uint8_t is_index = last != 0;
if (last) switch(last->type)
{
case LT_TOKEN_CLOSEBRACE:
case LT_TOKEN_CLOSEBRACKET:
case LT_TOKEN_CLOSEPAREN:
case LT_TOKEN_IDENTIFIER:
is_index = 1;
}
if (is_index)
{
NEXT(); // eat bracket
lt_AstNode* idx_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, idx_expr);
if (!PEEK()->type == LT_TOKEN_CLOSEBRACKET) _lt_parse_error(vm, p->tkn->module, current, "Expected closing bracket to follow index expression!");
NEXT();
lt_AstNode* source = *(void**)lt_buffer_last(&result); lt_buffer_pop(&result);
lt_AstNode* index = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_INDEX);
index->index.source = source;
index->index.idx = idx_expr;
lt_buffer_push(vm, &result, &index);
}
else
{
// array literal
NEXT(); // eat bracket
lt_AstNode* arr_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_ARRAY);
arr_expr->array.values = lt_buffer_new(sizeof(lt_AstNode*));
while (current->type != LT_TOKEN_CLOSEBRACKET)
{
lt_AstNode* value = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_EMPTY);
current = _lt_parse_expression(vm, p, current, value);
lt_buffer_push(vm, &arr_expr->array.values, &value);
if (current->type == LT_TOKEN_COMMA) current++;
}
NEXT();
lt_buffer_push(vm, &result, &arr_expr);
}
} break;
case LT_TOKEN_PERIOD: {
uint8_t allowed = 0;
if (last) switch (last->type)
{
case LT_TOKEN_CLOSEBRACE:
case LT_TOKEN_CLOSEBRACKET:
case LT_TOKEN_CLOSEPAREN:
case LT_TOKEN_IDENTIFIER:
allowed = 1;
}
if (!allowed) goto expr_end;
NEXT(); // eat period
lt_AstNode* idx_expr = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_LITERAL);
if (current->type != LT_TOKEN_IDENTIFIER) _lt_parse_error(vm, p->tkn->module, current, "Expected identifier to follow '.' operator!");
idx_expr->literal.token = NEXT();
lt_AstNode* source = *(void**)lt_buffer_last(&result); lt_buffer_pop(&result);
lt_AstNode* index = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_INDEX);
index->index.source = source;
index->index.idx = idx_expr;
lt_buffer_push(vm, &result, &index);
} break;
case LT_TOKEN_NUMBER_LITERAL: case LT_TOKEN_NULL_LITERAL: case LT_TOKEN_TRUE_LITERAL: case LT_TOKEN_FALSE_LITERAL: case LT_TOKEN_STRING_LITERAL: {
BREAK_ON_EXPR_BOUNDRY
lt_AstNode* lit = _lt_get_node_of_type(vm, current, p, LT_AST_NODE_LITERAL);
lit->literal.token = NEXT();
lt_buffer_push(vm, &result, &lit);
} break;
case LT_TOKEN_PLUS: case LT_TOKEN_MINUS:
case LT_TOKEN_MULTIPLY: case LT_TOKEN_DIVIDE:
case LT_TOKEN_EQUALS: case LT_TOKEN_NOTEQUALS:
case LT_TOKEN_GT: case LT_TOKEN_GTE: case LT_TOKEN_LT: case LT_TOKEN_LTE:
case LT_TOKEN_AND: case LT_TOKEN_OR: case LT_TOKEN_NOT: {
lt_TokenType optype = current->type;
if (optype == LT_TOKEN_MINUS)
{
optype = LT_TOKEN_NEGATE;
if (last) switch (last->type)
{
case LT_TOKEN_ANY_LITERAL:
case LT_TOKEN_IDENTIFIER:
case LT_TOKEN_CLOSEPAREN:
case LT_TOKEN_CLOSEBRACKET:
optype = LT_TOKEN_MINUS;
}
}
while (operator_stack.length > 0)
{
if (_lt_get_prec(*(lt_TokenType*)lt_buffer_last(&operator_stack)) > _lt_get_prec(optype))
{
lt_TokenType shunted = *(lt_TokenType*)lt_buffer_last(&operator_stack);
lt_buffer_pop(&operator_stack);
PUSH_EXPR_FROM_OP(shunted);
}
else break;