forked from terralang/terra
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lparser.cpp
2339 lines (2115 loc) · 70.6 KB
/
lparser.cpp
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
/*
** $Id: lparser.c,v 2.124 2011/12/02 13:23:56 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
*/
#include <string.h>
#include <assert.h>
#include <inttypes.h>
#define lparser_c
#define LUA_CORE
//#include "lua.h"
//#include "lcode.h"
//#include "ldebug.h"
//#include "ldo.h"
//#include "lfunc.h"
#include "llex.h"
//#include "lmem.h"
#include "lobject.h"
//#include "lopcodes.h"
#include "lparser.h"
//#include "lstate.h"
#include "lstring.h"
//#include "ltable.h"
#include <vector>
#include <set>
#include <sstream>
#include "llvm/ADT/SmallSet.h"
#include "treadnumber.h"
static void dump_stack(lua_State *L, int elem);
// helpers to ensure that the lua stack contains the right number of arguments after a
// call
#define RETURNS_N(x, n) \
do { \
if (ls->in_terra) { \
int begin = lua_gettop(ls->L); \
(x); \
int end = lua_gettop(ls->L); \
if (begin + n != end) { \
fprintf(stderr, "%s:%d: unmatched return\n", __FILE__, __LINE__); \
luaX_syntaxerror(ls, "error"); \
} \
} else { \
(x); \
} \
} while (0)
#define RETURNS_1(x) RETURNS_N(x, 1)
#define RETURNS_0(x) RETURNS_N(x, 0)
/* maximum number of local variables per function (must be smaller
than 250, due to the bytecode format) */
#define MAXVARS 200
#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
typedef llvm::SmallSet<TString *, 16> StringSet;
/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
StringSet defined;
int isterra; /* does this scope describe a terra scope or a lua scope?*/
int languageextensionsdefined;
int starttoken;
} BlockCnt;
struct TerraCnt {
StringSet capturedlocals; /*list of all local variables that this terra block captures
from the immediately enclosing lua block */
BlockCnt block;
TerraCnt *previous;
};
static int new_table(LexState *ls) {
if (ls->in_terra) {
// printf("(new table)\n");
lua_newtable(ls->L);
return lua_gettop(ls->L);
} else
return 0;
}
static int new_list(LexState *ls) {
if (ls->in_terra) {
luaX_globalpush(ls, TA_NEWLIST);
lua_call(ls->L, 0, 1);
return lua_gettop(ls->L);
} else
return 0;
}
static int new_list_before(LexState *ls) {
if (ls->in_terra) {
int t = new_list(ls);
lua_insert(ls->L, -2);
return t - 1;
} else
return 0;
}
static void push_string_before(LexState *ls, const char *str) {
if (ls->in_terra) {
lua_pushstring(ls->L, str);
lua_insert(ls->L, -2);
}
}
// this should eventually be optimized to use 'add_field' with tokens already on the stack
static void add_field(LexState *ls, int table, const char *field) {
if (ls->in_terra) {
table = (table < 0) ? (table + lua_gettop(ls->L) + 1)
: table; // otherwise table is wrong once we modify the stack
// printf("consume field\n");
lua_setfield(ls->L, table, field);
}
}
static void push_string(LexState *ls, const char *str) {
if (ls->in_terra) {
// printf("push string: %s\n",str);
lua_pushstring(ls->L, str);
}
}
struct Position {
int linenumber;
int offset;
};
static Position getposition(LexState *ls) {
Position p = {ls->linenumber, ls->currentoffset - 1};
return p;
}
static void table_setposition(LexState *ls, int t, Position p) {
lua_pushinteger(ls->L, p.linenumber);
lua_setfield(ls->L, t, "linenumber");
lua_pushinteger(ls->L, p.offset);
lua_setfield(ls->L, t, "offset");
lua_pushstring(ls->L, getstr(ls->source));
lua_setfield(ls->L, t, "filename");
}
static int newobjecterror(lua_State *L) {
printf("newobjecterror: %s\n", lua_tostring(L, -1));
exit(1);
}
static int new_object(LexState *ls, const char *k, int N, Position *p) {
if (ls->in_terra) {
luaX_globalgetfield(ls, TA_TYPE_TABLE, k);
lua_insert(ls->L, -(N + 1));
lua_pushcfunction(ls->L, newobjecterror);
lua_insert(ls->L, -(N + 2));
lua_pcall(ls->L, N, 1, -(N + 2));
table_setposition(ls, lua_gettop(ls->L), *p);
lua_remove(ls->L, -2);
return lua_gettop(ls->L);
} else
return 0;
}
static void add_index(LexState *ls, int table, int n) {
if (ls->in_terra) {
// printf("consume index\n");
lua_pushinteger(ls->L, n);
lua_pushvalue(ls->L, -2);
lua_settable(ls->L, table);
lua_pop(ls->L, 1);
}
}
static int add_entry(LexState *ls, int table) {
if (ls->in_terra) {
int n = lua_objlen(ls->L, table);
add_index(ls, table, n + 1);
return n + 1;
} else
return 0;
}
static void push_string(LexState *ls, TString *str) { push_string(ls, getstr(str)); }
static void push_boolean(LexState *ls, int b) {
if (ls->in_terra) {
// printf("push boolean\n");
lua_pushboolean(ls->L, b);
}
}
static void check_no_terra(LexState *ls, const char *thing) {
if (ls->in_terra) {
luaX_syntaxerror(
ls,
luaS_cstringf(ls->LP, "%s cannot be nested in terra functions.", thing));
}
}
static void check_terra(LexState *ls, const char *thing) {
if (!ls->in_terra) {
luaX_syntaxerror(
ls, luaS_cstringf(ls->LP, "%s cannot be used outside terra functions.",
thing));
}
}
/*
** prototypes for recursive non-terminal functions
*/
static void statement(LexState *ls);
static void expr(LexState *ls);
static void terratype(LexState *ls);
static void luaexpr(LexState *ls);
static void embeddedcode(LexState *ls, int isterra, int isexp);
static void doquote(LexState *ls, int isexp);
static void languageextension(LexState *ls, int isstatement, int islocal);
static void definevariable(LexState *ls, TString *varname) {
ls->fs->bl->defined.insert(varname);
}
static void refvariable(LexState *ls, TString *varname) {
if (ls->terracnt == NULL)
return; /* no need to search for variables if we are not in a terra scope at all
*/
// printf("searching %s\n",getstr(varname));
TerraCnt *cur = NULL;
for (BlockCnt *bl = ls->fs->bl; bl != NULL; bl = bl->previous) {
// printf("ctx %d\n",bl->isterra);
if (bl->defined.count(varname)) {
if (cur && !bl->isterra) cur->capturedlocals.insert(varname);
break;
}
if (bl->isterra && bl->previous && !bl->previous->isterra) {
cur = (cur) ? cur->previous : ls->terracnt;
assert(cur != NULL);
}
}
}
static l_noret error_expected(LexState *ls, int token) {
luaX_syntaxerror(ls, luaS_cstringf(ls->LP, "%s expected", luaX_token2str(ls, token)));
}
static l_noret errorlimit(FuncState *fs, int limit, const char *what) {
terra_State *L = fs->ls->LP;
const char *msg;
int line = fs->f.linedefined;
const char *where =
(line == 0) ? "main function" : luaS_cstringf(L, "function at line %d", line);
msg = luaS_cstringf(L, "too many %s (limit is %d) in %s", what, limit, where);
luaX_syntaxerror(fs->ls, msg);
}
static void checklimit(FuncState *fs, int v, int l, const char *what) {
if (v > l) errorlimit(fs, l, what);
}
static int testnext(LexState *ls, int c) {
if (ls->t.token == c) {
luaX_next(ls);
return 1;
} else
return 0;
}
static void check(LexState *ls, int c) {
if (ls->t.token != c) error_expected(ls, c);
}
static void checknext(LexState *ls, int c) {
check(ls, c);
luaX_next(ls);
}
#define check_condition(ls, c, msg) \
{ \
if (!(c)) luaX_syntaxerror(ls, msg); \
}
static void check_match(LexState *ls, int what, int who, int where) {
if (!testnext(ls, what)) {
if (where == ls->linenumber)
error_expected(ls, what);
else {
luaX_syntaxerror(
ls, luaS_cstringf(ls->LP, "%s expected (to close %s at line %d)",
luaX_token2str(ls, what), luaX_token2str(ls, who),
where));
}
}
}
static TString *str_checkname(LexState *ls) {
TString *ts;
check(ls, TK_NAME);
ts = ls->t.seminfo.ts;
luaX_next(ls);
return ts;
}
static void singlevar(LexState *ls) {
Position p = getposition(ls);
TString *varname = str_checkname(ls);
push_string(ls, varname);
new_object(ls, "var", 1, &p);
refvariable(ls, varname);
}
// tries to parse a symbol "NAME | '['' lua expression '']'"
// returns true if a name was parsed and sets str to that name
// otherwise, str is not modified
static bool checksymbol(LexState *ls, TString **str) {
Position p = getposition(ls);
int line = ls->linenumber;
if (ls->in_terra && testnext(ls, '[')) {
RETURNS_1(luaexpr(ls));
new_object(ls, "escapedident", 1, &p);
check_match(ls, ']', '[', line);
return false;
}
TString *nm = str_checkname(ls);
if (str) *str = nm;
push_string(ls, nm);
new_object(ls, "namedident", 1, &p);
return true;
}
static void enterlevel(LexState *ls) {
terra_State *L = ls->LP;
++L->nCcalls;
checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
}
#define leavelevel(ls) ((ls)->LP->nCcalls--)
static void enterblock(FuncState *fs, BlockCnt *bl, int starttoken) {
bl->previous = fs->bl;
bl->isterra = fs->ls->in_terra;
bl->languageextensionsdefined = 0;
bl->starttoken = starttoken;
fs->bl = bl;
// printf("entering block %lld\n", (long long int)bl);
// printf("previous is %lld\n", (long long int)bl->previous);
}
static void leaveblock(FuncState *fs) {
BlockCnt *bl = fs->bl;
LexState *ls = fs->ls;
if (bl->languageextensionsdefined > 0) {
luaX_globalgetfield(ls, TA_TERRA_OBJECT, "unimportlanguages");
luaX_globalpush(ls, TA_LANGUAGES_TABLE);
lua_pushnumber(ls->L, bl->languageextensionsdefined);
luaX_globalpush(ls, TA_ENTRY_POINT_TABLE);
lua_call(ls->L, 3, 0);
ls->languageextensionsenabled -= bl->languageextensionsdefined;
}
fs->bl = bl->previous;
// printf("leaving block %lld\n", (long long int)bl);
// printf("now is %lld\n", (long long int)fs->bl);
// for(int i = 0; i < bl->local_variables.size(); i++) {
// printf("v[%d] = %s\n",i,getstr(bl->local_variables[i]));
//}
}
static void enterterra(LexState *ls, TerraCnt *current) {
current->previous = ls->terracnt;
ls->terracnt = current;
ls->in_terra++;
enterblock(ls->fs, ¤t->block, 0);
}
static void leaveterra(LexState *ls) {
assert(ls->in_terra);
assert(ls->terracnt);
leaveblock(ls->fs);
ls->terracnt = ls->terracnt->previous;
ls->in_terra--;
}
static void open_func(LexState *ls, FuncState *fs, BlockCnt *bl) {
fs->prev = ls->fs; /* linked list of funcstates */
fs->bl = (fs->prev) ? ls->fs->bl : NULL;
fs->ls = ls;
ls->fs = fs;
fs->f.linedefined = 0;
fs->f.is_vararg = 0;
fs->f.source = ls->source;
enterblock(fs, bl, 0);
}
static void close_func(LexState *ls) {
FuncState *fs = ls->fs;
leaveblock(fs);
ls->fs = fs->prev;
}
/*
** opens the main function, which is a regular vararg function with an
** upvalue named LUA_ENV
*/
static void open_mainfunc(LexState *ls, FuncState *fs, BlockCnt *bl) {
open_func(ls, fs, bl);
fs->f.is_vararg = 1; /* main function is always vararg */
}
static void dump_stack(lua_State *L, int elem) {
lua_pushvalue(L, elem);
lua_getfield(L, LUA_GLOBALSINDEX, "terra");
lua_getfield(L, -1, "tree");
lua_getfield(L, -1, "printraw");
lua_pushvalue(L, -4);
lua_call(L, 1, 0);
lua_pop(L, 3);
}
/*============================================================*/
/* GRAMMAR RULES */
/*============================================================*/
/*
** check whether current token is in the follow set of a block.
** 'until' closes syntactical blocks, but do not close scope,
** so it handled in separate.
*/
static int block_follow(LexState *ls, int withuntil) {
switch (ls->t.token) {
case TK_CASE:
return ls->fs->bl->starttoken == TK_CASE;
case TK_ELSE:
case TK_ELSEIF:
case TK_END:
case TK_EOS:
case TK_IN:
return 1;
case TK_UNTIL:
return withuntil;
default:
return 0;
}
}
static void statlist(LexState *ls) {
/* statlist -> { stat [`;'] } */
int tbl = new_list(ls);
while (!block_follow(ls, 1)) {
if (ls->t.token == TK_RETURN) {
statement(ls);
add_entry(ls, tbl);
return; /* 'return' must be last statement */
}
if (ls->t.token == ';') {
luaX_next(ls);
} else {
statement(ls);
add_entry(ls, tbl);
}
}
}
static void push_type(LexState *ls, const char *typ) {
if (ls->in_terra) {
luaX_globalgetfield(ls, TA_TERRA_OBJECT, "types");
lua_getfield(ls->L, -1, typ);
lua_remove(ls->L, -2); // types object
}
}
static void push_literal(LexState *ls, const char *typ) {
if (ls->in_terra) {
push_type(ls, typ);
Position p = getposition(ls);
new_object(ls, "literal", 2, &p);
}
}
static void push_double(LexState *ls, double d) {
if (ls->in_terra) {
lua_pushnumber(ls->L, d);
}
}
static void push_integer(LexState *ls, int64_t i) {
if (ls->in_terra) {
void *data = lua_newuserdata(ls->L, sizeof(int64_t));
*(int64_t *)data = i;
}
}
static void push_nil(LexState *ls) {
if (ls->in_terra) lua_pushnil(ls->L);
}
static void yindex(LexState *ls) {
/* index -> '[' expr ']' */
luaX_next(ls); /* skip the '[' */
RETURNS_1(expr(ls));
// luaK_exp2val(ls->fs, v);
checknext(ls, ']');
}
/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/
struct ConsControl {
int nh; /* total number of `record' elements */
int na; /* total number of array elements */
};
static void recfield(LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
FuncState *fs = ls->fs;
Position pos = getposition(ls);
if (ls->t.token == TK_NAME) {
checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
RETURNS_1(checksymbol(ls, NULL));
} else { /* ls->t.token == '[' */
if (!ls->in_terra) {
yindex(ls);
} else {
RETURNS_1(expr(ls));
if (ls->t.token == '=') {
lua_getfield(ls->L, -1, "kind");
lua_pushstring(ls->L, "luaexpression");
if (!lua_equal(ls->L, -1, -2)) luaX_syntaxerror(ls, "unexpected symbol");
lua_pop(ls->L, 2); // kind and luaexpression
new_object(ls, "escapedident", 1, &pos);
} else {
/* oops! this wasn't a recfield, but a listfield with an escape */
new_object(ls, "listfield", 1, &pos);
return;
}
}
}
cc->nh++;
checknext(ls, '=');
RETURNS_1(expr(ls));
new_object(ls, "recfield", 2, &pos);
}
static void listfield(LexState *ls, struct ConsControl *cc) {
/* listfield -> exp */
Position pos = getposition(ls);
RETURNS_1(expr(ls));
new_object(ls, "listfield", 1, &pos);
checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
cc->na++;
}
static void field(LexState *ls, struct ConsControl *cc) {
/* field -> listfield | recfield */
switch (ls->t.token) {
case TK_NAME: { /* may be 'listfield' or 'recfield' */
if (luaX_lookahead(ls) != '=') /* expression? */
listfield(ls, cc);
else
recfield(ls, cc);
break;
}
case '[': {
recfield(ls, cc);
break;
}
default: {
listfield(ls, cc);
break;
}
}
}
static void constructor(LexState *ls) {
/* constructor -> '{' [ field { sep field } [sep] ] '}'
sep -> ',' | ';' */
int line = ls->linenumber;
struct ConsControl cc;
cc.na = cc.nh = 0;
Position pos = getposition(ls);
int records = new_list(ls);
checknext(ls, '{');
do {
if (ls->t.token == '}') break;
RETURNS_1(field(ls, &cc));
add_entry(ls, records);
} while (testnext(ls, ',') || testnext(ls, ';'));
check_match(ls, '}', '{', line);
new_object(ls, "constructoru", 1, &pos);
}
static void structfield(LexState *ls) {
Position p = getposition(ls);
push_string(ls, str_checkname(ls));
checknext(ls, ':');
RETURNS_1(terratype(ls));
new_object(ls, "structentry", 2, &p);
}
static void structbody(LexState *ls) {
Position p = getposition(ls);
int records = new_list(ls);
checknext(ls, '{');
while (ls->t.token != '}') {
if (testnext(ls, TK_UNION))
RETURNS_1(structbody(ls));
else
RETURNS_1(structfield(ls));
add_entry(ls, records);
if (ls->t.token == ',' || ls->t.token == ';') luaX_next(ls);
}
check_match(ls, '}', '{', p.linenumber);
new_object(ls, "structlist", 1, &p);
}
static void structconstructor(LexState *ls) {
// already parsed 'struct' or 'struct' name.
// starting at '{' or '('
Position p = getposition(ls);
if (testnext(ls, '(')) {
RETURNS_1(luaexpr(ls));
check_match(ls, ')', '(', p.linenumber);
} else
push_nil(ls);
structbody(ls);
new_object(ls, "structdef", 2, &p);
}
struct Name {
std::vector<TString *> data; // for patching the [local] terra a.b.c.d, and [local]
// var a.b.c.d sugar
};
static void Name_add(Name *name, TString *string) { name->data.push_back(string); }
static void Name_print(Name *name, LexState *ls) {
size_t N = name->data.size();
for (size_t i = 0; i < N; i++) {
OutputBuffer_printf(&ls->output_buffer, "%s", getstr(name->data[i]));
if (i + 1 < N) OutputBuffer_putc(&ls->output_buffer, '.');
}
}
static void print_captured_locals(LexState *ls, TerraCnt *tc);
/* print_stack not used anywhere right now - comment out to eliminate
compiler warning */
#if 0
static void print_stack(lua_State * L, int idx) {
lua_pushvalue(L,idx);
lua_getfield(L,LUA_GLOBALSINDEX,"print");
lua_insert(L,-2);
lua_call(L,1,0);
}
#endif
// store the lua object on the top of the stack to to the _G.terra._trees table, returning
// its index in the table
static int store_value(LexState *ls) {
int i = 0;
if (ls->in_terra) {
luaX_globalpush(ls, TA_FUNCTION_TABLE);
lua_insert(ls->L, -2);
i = add_entry(ls, lua_gettop(ls->L) - 1);
lua_pop(ls->L, 1); /*remove function table*/
}
return i;
}
static void printtreesandnames(LexState *ls, std::vector<int> *trees,
std::vector<TString *> *names) {
OutputBuffer_printf(&ls->output_buffer, "{");
for (size_t i = 0; i < trees->size(); i++) {
OutputBuffer_printf(&ls->output_buffer, "_G.terra._trees[%d]", (*trees)[i]);
if (i + 1 < trees->size()) OutputBuffer_putc(&ls->output_buffer, ',');
}
OutputBuffer_printf(&ls->output_buffer, "},{");
for (size_t i = 0; i < names->size(); i++) {
OutputBuffer_printf(&ls->output_buffer, "\"%s\"", getstr((*names)[i]));
if (i + 1 < names->size()) OutputBuffer_putc(&ls->output_buffer, ',');
}
OutputBuffer_printf(&ls->output_buffer, "}");
}
/* }====================================================================== */
static int vardecl(LexState *ls, int requiretype, TString **vname) {
Position p = getposition(ls);
int wasstring = checksymbol(ls, vname);
if (ls->in_terra && wasstring && (requiretype || ls->t.token == ':')) {
checknext(ls, ':');
RETURNS_1(terratype(ls));
} else
push_nil(ls);
new_object(ls, "unevaluatedparam", 2, &p);
return wasstring;
}
static void parlist(LexState *ls) {
/* parlist -> [ param { `,' param } ] */
FuncState *fs = ls->fs;
Proto *f = &fs->f;
int tbl = new_list(ls);
f->is_vararg = 0;
std::vector<TString *> vnames;
if (ls->t.token != ')') { /* is `parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME:
case '[': { /* param -> NAME */
TString *vname;
if (vardecl(ls, 1, &vname)) vnames.push_back(vname);
add_entry(ls, tbl);
break;
}
case TK_DOTS: { /* param -> `...' */
luaX_next(ls);
f->is_vararg = 1;
break;
}
default:
luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
}
} while (!f->is_vararg && testnext(ls, ','));
}
for (size_t i = 0; i < vnames.size(); i++) definevariable(ls, vnames[i]);
}
static void block(LexState *ls);
static void body(LexState *ls, int ismethod, int line) {
/* body -> `(' parlist `)' block END */
FuncState new_fs;
BlockCnt bl;
open_func(ls, &new_fs, &bl);
new_fs.f.linedefined = line;
Position p = getposition(ls);
checknext(ls, '(');
RETURNS_1(parlist(ls));
if (ismethod) {
definevariable(ls, luaS_new(ls->LP, "self"));
}
push_boolean(ls, new_fs.f.is_vararg);
checknext(ls, ')');
if (ls->in_terra && testnext(ls, ':')) {
RETURNS_1(terratype(ls));
} else
push_nil(ls);
RETURNS_1(block(ls));
new_fs.f.lastlinedefined = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line);
close_func(ls);
new_object(ls, "functiondefu", 4, &p);
}
static int explist(LexState *ls) {
/* explist -> expr { `,' expr } */
int n = 1; /* at least one expression */
int lst = new_list(ls);
expr(ls);
add_entry(ls, lst);
while (testnext(ls, ',')) {
// luaK_exp2nextreg(ls->fs, v);
expr(ls);
add_entry(ls, lst);
n++;
}
return n;
}
static void funcargs(LexState *ls, int line) {
switch (ls->t.token) {
case '(': { /* funcargs -> `(' [ explist ] `)' */
luaX_next(ls);
if (ls->t.token == ')') { /* arg list is empty? */
new_list(ls); // empty return list
} else {
RETURNS_1(explist(ls));
}
check_match(ls, ')', '(', line);
break;
}
case '{': { /* funcargs -> constructor */
int exps = new_list(ls);
RETURNS_1(constructor(ls));
add_entry(ls, exps);
break;
}
case TK_STRING: { /* funcargs -> STRING */
// codestring(ls, &args, ls->t.seminfo.ts);
int exps = new_list(ls);
push_string(ls, ls->t.seminfo.ts);
push_literal(ls, "rawstring");
add_entry(ls, exps);
luaX_next(ls); /* must use `seminfo' before `next' */
break;
}
case '`':
case TK_QUOTE: {
int exps = new_list(ls);
doquote(ls, ls->t.token == '`');
add_entry(ls, exps);
break;
}
default: {
luaX_syntaxerror(ls, "function arguments expected");
}
}
}
/*
** {======================================================================
** Expression parsing
** =======================================================================
*/
static void prefixexp(LexState *ls) {
/* prefixexp -> NAME | '(' expr ')' */
switch (ls->t.token) {
case '(': {
int line = ls->linenumber;
luaX_next(ls);
RETURNS_1(expr(ls));
check_match(ls, ')', '(', line);
return;
}
case '[': {
check_terra(ls, "escape");
int line = ls->linenumber;
luaX_next(ls);
RETURNS_1(luaexpr(ls));
check_match(ls, ']', '[', line);
return;
}
case TK_NAME: {
RETURNS_1(singlevar(ls));
return;
}
default: {
luaX_syntaxerror(ls, "unexpected symbol");
}
}
}
static int issplitprimary(LexState *ls) {
if (ls->lastline != ls->linenumber) {
luaX_insertbeforecurrenttoken(ls, ';');
return 1;
} else {
return 0;
}
}
static void primaryexp(LexState *ls) {
/* primaryexp ->
prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
int line = ls->linenumber;
RETURNS_1(prefixexp(ls));
Position p = getposition(ls);
for (;;) {
switch (ls->t.token) {
case '.': { /* fieldsel */
luaX_next(ls);
checksymbol(ls, NULL);
new_object(ls, "selectu", 2, &p);
break;
}
case '[': { /* `[' exp1 `]' */
if (issplitprimary(ls)) return;
RETURNS_1(yindex(ls));
new_object(ls, "index", 2, &p);
break;
}
case ':': { /* `:' NAME funcargs */
luaX_next(ls);
RETURNS_1(checksymbol(ls, NULL));
RETURNS_1(funcargs(ls, line));
new_object(ls, "method", 3, &p);
break;
}
case '(':
case '`':
case TK_QUOTE: /* funcargs */
if (issplitprimary(ls)) return;
/* fallthrough */
case TK_STRING:
case '{': {
RETURNS_1(funcargs(ls, line));
new_object(ls, "apply", 2, &p);
break;
}
default:
return;
}
}
}
// TODO: eventually we should record the set of possibly used symbols, and only quote the
// ones appearing in it
static void print_captured_locals(LexState *ls, TerraCnt *tc) {
OutputBuffer_printf(&ls->output_buffer, "function() return terra.makeenv({ ");
int in_terra = ls->in_terra;
ls->in_terra = 1; // force new_table, etc to do something, not the cleanest way to
// express this...
int tbl = new_table(ls);
for (StringSet::iterator i = tc->capturedlocals.begin(),
end = tc->capturedlocals.end();
i != end; ++i) {
TString *iv = *i;
const char *str = getstr(iv);
lua_pushboolean(ls->L, true);
add_field(ls, tbl, str);
OutputBuffer_printf(&ls->output_buffer, "%s = %s;", str, str);
}
int defined = store_value(ls);
ls->in_terra = in_terra;
OutputBuffer_printf(&ls->output_buffer, " },_G.terra._trees[%d],getfenv()) end",
defined);
}
static void doquote(LexState *ls, int isexp) {
int isfullquote = ls->t.token == '`' || ls->t.token == TK_QUOTE;
check_no_terra(ls, isexp ? "`" : "quote");
TerraCnt tc;
enterterra(ls, &tc);
Token begin = ls->t;
int line = ls->linenumber;
if (isfullquote) luaX_next(ls); // skip ` or quote
if (isexp) {
RETURNS_1(expr(ls));
} else {
FuncState *fs = ls->fs;
BlockCnt bc;
enterblock(fs, &bc, begin.token);
Position p = getposition(ls);
RETURNS_1(statlist(ls));
if (isfullquote && testnext(ls, TK_IN)) {
RETURNS_1(explist(ls));
} else {
new_list(ls);
}
push_boolean(ls, true);
if (isfullquote) check_match(ls, TK_END, TK_QUOTE, line);
leaveblock(fs);
new_object(ls, "letin", 3, &p);
}
luaX_patchbegin(ls, &begin);
int id = store_value(ls);
OutputBuffer_printf(&ls->output_buffer, "(terra.definequote(_G.terra._trees[%d],",
id);
print_captured_locals(ls, &tc);
OutputBuffer_printf(&ls->output_buffer, "))");
luaX_patchend(ls, &begin);
leaveterra(ls);
}
// buf should be at least 128 chars
static void number_type(LexState *ls, int flags, char *buf, size_t bufsiz) {
if (ls->in_terra) {
if (flags & F_ISINTEGER) {
const char *sign = (flags & F_ISUNSIGNED) ? "u" : "";
const char *sz = (flags & F_IS8BYTES) ? "64" : "";
snprintf(buf, bufsiz, "%sint%s", sign, sz);
} else {
snprintf(buf, bufsiz, "%s", (flags & F_IS8BYTES) ? "double" : "float");
}
}
}
static void blockescape(LexState *ls) {
check_terra(ls, "escape");
int line = ls->linenumber;
luaX_next(ls);
embeddedcode(ls, 0, 0);
check_match(ls, TK_END, TK_ESCAPE, line);
}
static void bodyortype(LexState *ls, int ismethod) {
if (ls->t.token == '(') {
body(ls, ismethod, ls->linenumber);
} else {
checknext(ls, TK_DBCOLON);
terratype(ls);
}
}
static void simpleexp(LexState *ls) {
/* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
constructor | FUNCTION body | primaryexp */
switch (ls->t.token) {
case TK_NUMBER: {
char buf[128];
int flags = ls->t.seminfo.flags;
number_type(ls, flags, &buf[0], sizeof(buf));