-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.c
1422 lines (1324 loc) · 37.5 KB
/
parser.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 <stdio.h>
#include <string.h>
#include "closure.h"
#include "codegen.h"
#include "debug.h"
#include "intern.h"
#include "lexer.h"
#include "memory.h"
#include "object.h"
#include "opcodes.h"
#include "parser.h"
#include "stack.h"
#include "state.h"
#include "table.h"
#define HAS_MULTI_RETURN(k) ((k) == EXPR_CALL || (k) == EXPR_VARARG_CALL)
#define GET_LOCAL_VAR(fs, i) ((fs)->f->locVars[(fs)->actvar[i]])
#define CHECK_LIMIT(fs, v, l, m) \
do { \
if ((v) > (l)) { \
errorlimit(fs, l, m); \
} \
} while (false)
/*
** nodes for block list (list of active blocks)
*/
typedef struct Block {
struct Block *prev;
// List of jumps out of this loop.
int breaklist;
// Number of active locals outside the breakable structure.
uint8_t nactvar;
// True if some variables in the block are upvalues.
bool hasUpvalues;
// True if this block is a loop.
bool isBreakable;
} Block;
static void chunk(LexState *ls);
static void expr(LexState *ls, ExprInfo *v);
static void anchor_token(LexState *ls) {
if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
String *ts = ls->t.literal.str;
luaX_newstring(ls, STRING_CONTENT(ts), ts->len);
}
}
static void throwToken(LexState *ls, int token) {
Lex_throw(ls,
Object_sprintf(ls->L, "'%s' expected", Lex_tokenText(ls, token)));
}
static void errorlimit(FuncState *fs, int limit, const char *what) {
const char *msg =
fs->f->lineDefined == 0
? Object_sprintf(fs->L, "main function has more than %d %s", limit,
what)
: Object_sprintf(fs->L, "function at line %d has more than %d %s",
fs->f->lineDefined, limit, what);
Lex_throwWith(fs->ls, msg, 0);
}
static bool testNext(LexState *ls, int c) {
if (ls->t.token == c) {
Lexer_next(ls);
return true;
}
return false;
}
static void check(LexState *ls, int c) {
if (ls->t.token != c) {
throwToken(ls, c);
}
}
static void checkNext(LexState *ls, int c) {
check(ls, c);
Lexer_next(ls);
}
static void check_match(LexState *ls, int what, int who, int where) {
if (!testNext(ls, what)) {
if (where == ls->linenumber) {
throwToken(ls, what);
} else {
Lex_throw(ls, Object_sprintf(ls->L,
"'%s' expected (to close '%s' at line %d)",
Lex_tokenText(ls, what),
Lex_tokenText(ls, who), where));
}
}
}
static String *checkName(LexState *ls) {
check(ls, TK_NAME);
String *ts = ls->t.literal.str;
Lexer_next(ls);
return ts;
}
static void exprSetKind(ExprInfo *e, ExprKind k) {
e->f = NO_JUMP;
e->t = NO_JUMP;
e->k = k;
}
static void numberLiteral(ExprInfo *e, double value) {
exprSetKind(e, EXPR_CONST_NUM);
e->u.numValue = value;
}
static void stringLiteral(LexState *ls, ExprInfo *e, String *s) {
exprSetKind(e, EXPR_CONST_STR);
e->u.constID = Codegen_addString(ls->fs, s);
}
static void checkname(LexState *ls, ExprInfo *e) {
stringLiteral(ls, e, checkName(ls));
}
static size_t registerLocalVar(LexState *ls, String *varname) {
FuncState *fs = ls->fs;
Prototype *f = fs->f;
size_t oldSize = f->locVarsSize;
Mem_growVec(ls->L, f->locVars, fs->nlocvars, f->locVarsSize, LocVar, SHRT_MAX,
"too many local variables");
while (oldSize < f->locVarsSize) {
f->locVars[oldSize++].name = nullptr;
}
f->locVars[fs->nlocvars].name = varname;
luaC_objbarrier(ls->L, f, varname);
return fs->nlocvars++;
}
#define new_localvarliteral(ls, v, n) \
new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v) / sizeof(char)) - 1), n)
static void new_localvar(LexState *ls, String *name, int n) {
FuncState *fs = ls->fs;
CHECK_LIMIT(fs, fs->nactvar + n + 1, LUAI_MAX_VARS, "local variables");
// FIXME(anqur): Conversion? Really?
fs->actvar[fs->nactvar + n] = (int)registerLocalVar(ls, name);
}
static void adjustlocalvars(LexState *ls, int nvars) {
FuncState *fs = ls->fs;
fs->nactvar = (uint8_t)(fs->nactvar + nvars);
for (; nvars; nvars--) {
GET_LOCAL_VAR(fs, fs->nactvar - nvars).startPC = fs->pc;
}
}
static void removevars(LexState *ls, int tolevel) {
FuncState *fs = ls->fs;
while (fs->nactvar > tolevel) {
GET_LOCAL_VAR(fs, --fs->nactvar).endPC = fs->pc;
}
}
static UpvalueInfo exprToUpvalueInfo(const ExprInfo *e) {
switch (e->k) {
case EXPR_LOCAL:
return (UpvalueInfo){
.k = e->k,
.v = (UpvalueVariant){.localReg = e->u.localReg},
};
case EXPR_UPVALUE:
return (UpvalueInfo){
.k = e->k,
.v = (UpvalueVariant){.upvalueID = e->u.upvalueID},
};
default:
assert(false);
}
}
static bool upvalueEqual(const UpvalueInfo *lhs, const UpvalueInfo *rhs) {
if (lhs->k == EXPR_LOCAL && rhs->k == EXPR_LOCAL &&
lhs->v.localReg == rhs->v.localReg) {
return true;
}
if (lhs->k == EXPR_UPVALUE && rhs->k == EXPR_UPVALUE &&
lhs->v.upvalueID == rhs->v.upvalueID) {
return true;
}
return false;
}
static size_t createUpvalue(FuncState *fs, String *name, const ExprInfo *v) {
assert(v->k == EXPR_LOCAL || v->k == EXPR_UPVALUE);
UpvalueInfo rhs = exprToUpvalueInfo(v);
Prototype *f = fs->f;
for (size_t i = 0; i < f->upvaluesNum; i++) {
if (upvalueEqual(&fs->upvalues[i], &rhs)) {
assert(f->upvalues[i] == name);
return i;
}
}
// Create a new upvalue.
size_t oldSize = f->upvaluesSize;
CHECK_LIMIT(fs, f->upvaluesNum + 1, LUAI_MAX_UPVALUES, "upvalues");
Mem_growVec(fs->L, f->upvalues, f->upvaluesNum, f->upvaluesSize, String *,
SAFE_INT_MAX, "");
while (oldSize < f->upvaluesSize) {
f->upvalues[oldSize++] = nullptr;
}
f->upvalues[f->upvaluesNum] = name;
luaC_objbarrier(fs->L, f, name);
fs->upvalues[f->upvaluesNum] = rhs;
return f->upvaluesNum++;
}
static int lookupLocalVar(FuncState *fs, String *name) {
for (int i = fs->nactvar - 1; i >= 0; i--) {
if (name == GET_LOCAL_VAR(fs, i).name) {
return i;
}
}
return -1;
}
static void markUpvalue(FuncState *fs, int level) {
Block *bl = fs->bl;
while (bl && bl->nactvar > level) {
bl = bl->prev;
}
if (bl) {
bl->hasUpvalues = true;
}
}
static int lookupVar(FuncState *fs, String *n, ExprInfo *var, bool isBaseLvl) {
if (fs == nullptr) {
// No more levels found, it's a new global variable.
exprSetKind(var, EXPR_GLOBAL);
return EXPR_GLOBAL;
}
int v = lookupLocalVar(fs, n);
if (v >= 0) {
exprSetKind(var, EXPR_LOCAL);
var->u.localReg = v;
if (!isBaseLvl) {
// This local variable will be used as an upvalue since it escapes the
// base level.
markUpvalue(fs, v);
}
return EXPR_LOCAL;
}
// Not found at the current level, try the upper one.
if (lookupVar(fs->prev, n, var, false) == EXPR_GLOBAL) {
return EXPR_GLOBAL;
}
var->u.upvalueID = createUpvalue(fs, n, var);
var->k = EXPR_UPVALUE;
return EXPR_UPVALUE;
}
static void singleVar(LexState *ls, ExprInfo *var) {
String *name = checkName(ls);
if (lookupVar(ls->fs, name, var, true) == EXPR_GLOBAL) {
var->u.globalID = Codegen_addString(ls->fs, name);
}
}
static void adjust_assign(LexState *ls, int nvars, int nexps, ExprInfo *e) {
FuncState *fs = ls->fs;
int extra = nvars - nexps;
if (HAS_MULTI_RETURN(e->k)) {
extra++; /* includes call itself */
if (extra < 0) {
extra = 0;
}
// Last expression provides the difference.
Codegen_setReturnMulti(fs, e, extra);
if (extra > 1) {
luaK_reserveRegs(fs, extra - 1);
}
} else {
if (e->k != EXPR_VOID) {
Codegen_exprToNextReg(fs, e); /* close last expression */
}
if (extra > 0) {
int reg = fs->freereg;
luaK_reserveRegs(fs, extra);
Codegen_emitNil(fs, reg, extra);
}
}
}
static void enterLevel(LexState *ls) {
ls->L->nestedCCallsNum++;
if (ls->L->nestedCCallsNum > LUAI_MAX_C_CALLS) {
Lex_throwWith(ls, "chunk has too many syntax levels", 0);
}
}
#define leaveLevel(ls) ((ls)->L->nestedCCallsNum--)
static void enterBlock(FuncState *fs, Block *bl, bool isBreakable) {
bl->breaklist = NO_JUMP;
bl->isBreakable = isBreakable;
bl->nactvar = fs->nactvar;
bl->hasUpvalues = false;
bl->prev = fs->bl;
fs->bl = bl;
assert(fs->freereg == fs->nactvar);
}
static void leaveBlock(FuncState *fs) {
Block *bl = fs->bl;
fs->bl = bl->prev;
removevars(fs->ls, bl->nactvar);
if (bl->hasUpvalues) {
Codegen_emitABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
}
/* a block either controls scope or breaks (never both) */
assert(!bl->isBreakable || !bl->hasUpvalues);
assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */
Codegen_patchTo(fs, bl->breaklist);
}
static void pushclosure(LexState *ls, FuncState *func, ExprInfo *v) {
FuncState *fs = ls->fs;
Prototype *f = fs->f;
size_t oldSize = f->innersSize;
Mem_growVec(ls->L, f->inners, fs->np, f->innersSize, Prototype *, MAXARG_Bx,
"constant table overflow");
while (oldSize < f->innersSize) {
f->inners[oldSize++] = nullptr;
}
f->inners[fs->np++] = func->f;
luaC_objbarrier(ls->L, f, func->f);
exprSetKind(v, EXPR_RELOC);
v->u.relocatePC = Codegen_emitABx(fs, OP_CLOSURE, 0, fs->np - 1);
for (size_t i = 0; i < func->f->upvaluesNum; i++) {
if (func->upvalues[i].k == EXPR_LOCAL) {
Codegen_emitABC(fs, OP_MOVE, 0, func->upvalues[i].v.localReg, 0);
} else {
// FIXME(anqur): Suspicious conversion.
Codegen_emitABC(fs, OP_GETUPVAL, 0, (int)func->upvalues[i].v.upvalueID,
0);
}
}
}
static void openFunc(LexState *ls, FuncState *fs) {
lua_State *L = ls->L;
Prototype *f = Prototype_new(L);
fs->f = f;
fs->prev = ls->fs; /* linked list of funcstates */
fs->ls = ls;
fs->L = L;
ls->fs = fs;
fs->pc = 0;
fs->lasttarget = -1;
fs->jpc = NO_JUMP;
fs->freereg = 0;
fs->nk = 0;
fs->np = 0;
fs->nlocvars = 0;
fs->nactvar = 0;
fs->bl = nullptr;
f->source = ls->source;
f->maxStackSize = 2; /* registers 0/1 are always valid */
fs->h = Table_new(L, 0, 0);
/* anchor table of constants and prototype (to avoid being collected) */
SET_TABLE_TO_STACK(L, L->top, fs->h);
incr_top(L);
SET_PROTO_TO_STACK(L, L->top, f);
incr_top(L);
}
static void closeFunc(LexState *ls) {
lua_State *L = ls->L;
FuncState *fs = ls->fs;
Prototype *f = fs->f;
removevars(ls, 0);
Codegen_return(fs, 0, 0); /* final return */
Mem_reallocVec(L, f->code, f->codeSize, fs->pc, Instruction);
f->codeSize = fs->pc;
Mem_reallocVec(L, f->lineInfo, f->lineInfoSize, fs->pc, int);
f->lineInfoSize = fs->pc;
Mem_reallocVec(L, f->constants, f->constantsSize, fs->nk, Value);
f->constantsSize = fs->nk;
Mem_reallocVec(L, f->inners, f->innersSize, fs->np, Prototype *);
f->innersSize = fs->np;
Mem_reallocVec(L, f->locVars, f->locVarsSize, fs->nlocvars, LocVar);
f->locVarsSize = fs->nlocvars;
Mem_reallocVec(L, f->upvalues, f->upvaluesSize, f->upvaluesNum, String *);
f->upvaluesSize = f->upvaluesNum;
assert(luaG_checkcode(f));
assert(fs->bl == nullptr);
ls->fs = fs->prev;
/* last token read was anchored in defunct function; must re-anchor it */
anchor_token(ls);
L->top -= 2; /* remove table and prototype from the stack */
}
Prototype *luaY_parser(lua_State *L, ZIO *z, StringBuilder *buff,
const char *name) {
struct LexState lexstate;
struct FuncState funcstate;
lexstate.tokens = buff;
Lexer_setInput(L, &lexstate, z, String_create(L, name));
openFunc(&lexstate, &funcstate);
funcstate.f->varargMode = VARARG_IS_VARARG; /* main func. is always vararg */
Lexer_next(&lexstate); /* read first token */
chunk(&lexstate);
check(&lexstate, TK_EOS);
closeFunc(&lexstate);
assert(funcstate.prev == nullptr);
assert(funcstate.f->upvaluesNum == 0);
assert(lexstate.fs == nullptr);
return funcstate.f;
}
static void field(LexState *ls, ExprInfo *v) {
/* field -> ['.' | ':'] NAME */
FuncState *fs = ls->fs;
ExprInfo key;
Codegen_exprToAnyReg(fs, v);
Lexer_next(ls); /* skip the dot or colon */
checkname(ls, &key);
Codegen_indexed(fs, v, &key);
}
/// \code
/// index
/// : '[' expr ']'
/// ;
/// \endcode
static void indexing(LexState *ls, ExprInfo *v) {
Lexer_next(ls); /* skip the '[' */
expr(ls, v);
Codegen_exprToValue(ls->fs, v);
checkNext(ls, ']');
}
struct ConsControl {
ExprInfo v; /* last list item read */
ExprInfo *t; /* table descriptor */
int nh; /* total number of `record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
static void recfield(LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
FuncState *fs = ls->fs;
int reg = ls->fs->freereg;
ExprInfo key, val;
int rkkey;
if (ls->t.token == TK_NAME) {
CHECK_LIMIT(fs, cc->nh, SAFE_INT_MAX, "items in a constructor");
checkname(ls, &key);
} else { /* ls->t.token == '[' */
indexing(ls, &key);
}
cc->nh++;
checkNext(ls, '=');
rkkey = Codegen_exprToRK(fs, &key);
expr(ls, &val);
assert(cc->t->k == EXPR_NON_RELOC);
Codegen_emitABC(fs, OP_SETTABLE, cc->t->u.nonRelocReg, rkkey,
Codegen_exprToRK(fs, &val));
fs->freereg = reg; /* free registers */
}
static void closelistfield(FuncState *fs, struct ConsControl *cc) {
if (cc->v.k == EXPR_VOID) {
return; /* there is no list item */
}
Codegen_exprToNextReg(fs, &cc->v);
cc->v.k = EXPR_VOID;
if (cc->tostore == LFIELDS_PER_FLUSH) {
assert(cc->t->k == EXPR_NON_RELOC);
luaK_setlist(fs, cc->t->u.nonRelocReg, cc->na, cc->tostore); /* flush */
cc->tostore = 0; /* no more items pending */
}
}
static void lastlistfield(FuncState *fs, struct ConsControl *cc) {
if (cc->tostore == 0) {
return;
}
if (HAS_MULTI_RETURN(cc->v.k)) {
Codegen_setReturnMulti(fs, &cc->v, LUA_MULTRET);
// FIXME(anqur): Suspicious conversion.
luaK_setlist(fs,
cc->v.k == EXPR_CALL ? (int)cc->t->u.callPC
: (int)cc->t->u.varargCallPC,
cc->na, LUA_MULTRET);
cc->na--; /* do not count last expression (unknown number of elements) */
} else {
if (cc->v.k != EXPR_VOID) {
Codegen_exprToNextReg(fs, &cc->v);
}
assert(cc->t->k == EXPR_NON_RELOC);
luaK_setlist(fs, cc->t->u.nonRelocReg, cc->na, cc->tostore);
}
}
static void listfield(LexState *ls, struct ConsControl *cc) {
expr(ls, &cc->v);
CHECK_LIMIT(ls->fs, cc->na, SAFE_INT_MAX, "items in a constructor");
cc->na++;
cc->tostore++;
}
static void constructor(LexState *ls, ExprInfo *t) {
/* constructor -> ?? */
FuncState *fs = ls->fs;
int line = ls->linenumber;
size_t pc = Codegen_emitABC(fs, OP_NEWTABLE, 0, 0, 0);
struct ConsControl cc;
cc.na = cc.nh = cc.tostore = 0;
cc.t = t;
exprSetKind(t, EXPR_RELOC);
t->u.relocatePC = pc;
exprSetKind(&cc.v, EXPR_VOID); /* no value (yet) */
Codegen_exprToNextReg(ls->fs, t); /* fix it at stack top (for gc) */
checkNext(ls, '{');
do {
assert(cc.v.k == EXPR_VOID || cc.tostore > 0);
if (ls->t.token == '}') {
break;
}
closelistfield(fs, &cc);
switch (ls->t.token) {
case TK_NAME: { /* may be listfields or recfields */
Lexer_lookahead(ls);
if (ls->lookahead.token != '=') { /* expression? */
listfield(ls, &cc);
} else {
recfield(ls, &cc);
}
break;
}
case '[': { /* constructor_item -> recfield */
recfield(ls, &cc);
break;
}
default: { /* constructor_part -> listfield */
listfield(ls, &cc);
break;
}
}
} while (testNext(ls, ',') || testNext(ls, ';'));
check_match(ls, '}', '{', line);
lastlistfield(fs, &cc);
SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
}
static void parlist(LexState *ls) {
/* parlist -> [ param { `,' param } ] */
FuncState *fs = ls->fs;
Prototype *f = fs->f;
int nparams = 0;
f->varargMode = 0;
if (ls->t.token != ')') { /* is `parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME: { /* param -> NAME */
new_localvar(ls, checkName(ls), nparams++);
break;
}
case TK_DOTS: { /* param -> `...' */
Lexer_next(ls);
// Compatible with the old-style variadic arguments: Use `arg` as the
// default name.
new_localvarliteral(ls, "arg", nparams++);
f->varargMode = VARARG_HAS_ARG | VARARG_NEEDS_ARG;
f->varargMode |= VARARG_IS_VARARG;
break;
}
default:
Lex_throw(ls, "<name> or '...' expected");
}
} while (!f->varargMode && testNext(ls, ','));
}
adjustlocalvars(ls, nparams);
f->paramsNum = (uint8_t)(fs->nactvar - (f->varargMode & VARARG_HAS_ARG));
luaK_reserveRegs(fs, fs->nactvar); /* reserve register for parameters */
}
/// \code
/// body
/// : '(' parlist ')' chunk END
/// ;
/// \endcode
static void body(LexState *ls, ExprInfo *e, bool hasSelf, int line) {
FuncState fs;
openFunc(ls, &fs);
fs.f->lineDefined = line;
checkNext(ls, '(');
if (hasSelf) {
new_localvarliteral(ls, "self", 0);
adjustlocalvars(ls, 1);
}
parlist(ls);
checkNext(ls, ')');
chunk(ls);
fs.f->lineDefinedLast = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line);
closeFunc(ls);
pushclosure(ls, &fs, e);
}
/// \code
/// exprList1
/// : expr (',' expr)*
/// ;
/// \endcode
static int exprList1(LexState *ls, ExprInfo *v) {
int exprNum = 1;
expr(ls, v);
while (testNext(ls, ',')) {
Codegen_exprToNextReg(ls->fs, v);
expr(ls, v);
exprNum++;
}
return exprNum;
}
/// \code
/// arguments
/// : '(' exprList1? ')'
/// | constructor
/// | STRING
/// ;
/// \endcode
static void arguments(LexState *ls, ExprInfo *f) {
FuncState *fs = ls->fs;
ExprInfo args;
int line = ls->linenumber;
switch (ls->t.token) {
case '(':
if (line != ls->lastline) {
Lex_throw(ls, "ambiguous syntax (function call x new stmt)");
}
Lexer_next(ls);
if (ls->t.token == ')') { /* arg list is empty? */
args.k = EXPR_VOID;
} else {
exprList1(ls, &args);
Codegen_setReturnMulti(fs, &args, LUA_MULTRET);
}
check_match(ls, ')', '(', line);
break;
case '{':
constructor(ls, &args);
break;
case TK_STRING:
stringLiteral(ls, &args, ls->t.literal.str);
Lexer_next(ls); /* must use `literal' before `next' */
break;
default:
Lex_throw(ls, "function arguments expected");
return;
}
assert(f->k == EXPR_NON_RELOC);
int base = f->u.nonRelocReg; /* base register for call */
int nparams = LUA_MULTRET; /* open call */
if (!HAS_MULTI_RETURN(args.k)) {
if (args.k != EXPR_VOID) {
Codegen_exprToNextReg(fs, &args); /* close last argument */
}
nparams = fs->freereg - (base + 1);
}
exprSetKind(f, EXPR_CALL);
f->u.callPC = Codegen_emitABC(fs, OP_CALL, base, nparams + 1, 2);
Codegen_fixLine(fs, line);
fs->freereg = base + 1; /* call remove function and arguments and leaves
(unless changed) one result */
}
/// \code
/// prefixExpr
/// : NAME
/// | '(' expr ')'
/// ;
/// \endcode
static void prefixExpr(LexState *ls, ExprInfo *v) {
switch (ls->t.token) {
case '(':
int line = ls->linenumber;
Lexer_next(ls);
expr(ls, v);
check_match(ls, ')', '(', line);
Codegen_releaseVars(ls->fs, v);
return;
case TK_NAME:
singleVar(ls, v);
return;
default:
Lex_throw(ls, "unexpected symbol");
return;
}
}
/// \code
/// primaryExpr
/// : prefixExpr ('.' NAME | indexing | ':' NAME arguments | arguments)*
/// ;
/// \endcode
static void primaryExpr(LexState *ls, ExprInfo *v) {
FuncState *fs = ls->fs;
prefixExpr(ls, v);
while (true) {
switch (ls->t.token) {
case '.':
field(ls, v);
break;
case '[': {
Codegen_exprToAnyReg(fs, v);
ExprInfo key;
indexing(ls, &key);
Codegen_indexed(fs, v, &key);
break;
}
case ':': {
Lexer_next(ls);
ExprInfo key;
checkname(ls, &key);
Codegen_self(fs, v, &key);
arguments(ls, v);
break;
}
case '(':
case TK_STRING:
case '{':
Codegen_exprToNextReg(fs, v);
arguments(ls, v);
break;
default:
return;
}
}
}
/// \code
/// simpleExpr
/// : NUMBER
/// | STRING
/// | NIL
/// | true
/// | false
/// | ... # vararg
/// | constructor
/// | FUNCTION body
/// | primaryExpr
/// ;
/// \endcode
static void simpleExpr(LexState *ls, ExprInfo *v) {
switch (ls->t.token) {
case TK_NUMBER:
numberLiteral(v, ls->t.literal.num);
break;
case TK_STRING:
stringLiteral(ls, v, ls->t.literal.str);
break;
case TK_NIL:
exprSetKind(v, EXPR_NIL);
break;
case TK_TRUE:
exprSetKind(v, EXPR_TRUE);
break;
case TK_FALSE:
exprSetKind(v, EXPR_FALSE);
break;
case TK_DOTS:
// Vararg.
FuncState *fs = ls->fs;
if (!fs->f->varargMode) {
Lex_throw(ls, "cannot use '...' outside a vararg function");
}
fs->f->varargMode &= ~VARARG_NEEDS_ARG; /* don't need 'arg' */
exprSetKind(v, EXPR_VARARG_CALL);
v->u.varargCallPC = Codegen_emitABC(fs, OP_VARARG, 0, 1, 0);
break;
case '{':
// Constructor.
constructor(ls, v);
return;
case TK_FUNCTION:
Lexer_next(ls);
body(ls, v, false, ls->linenumber);
return;
default:
primaryExpr(ls, v);
return;
}
Lexer_next(ls);
}
static OpKind unaryOp(int token) {
switch (token) {
case TK_NOT:
return OPR_NOT;
case '-':
return OPR_MINUS;
case '#':
return OPR_LEN;
default:
return OPR_NONE;
}
}
static OpKind binaryOp(int token) {
switch (token) {
case '+':
return OPR_ADD;
case '-':
return OPR_SUB;
case '*':
return OPR_MUL;
case '/':
return OPR_DIV;
case '%':
return OPR_MOD;
case '^':
return OPR_POW;
case TK_CONCAT:
return OPR_CONCAT;
case TK_NE:
return OPR_NE;
case TK_EQ:
return OPR_EQ;
case '<':
return OPR_LT;
case TK_LE:
return OPR_LE;
case '>':
return OPR_GT;
case TK_GE:
return OPR_GE;
case TK_AND:
return OPR_AND;
case TK_OR:
return OPR_OR;
default:
return OPR_NONE;
}
}
static const struct {
uint8_t left; /* left priority for each binary operator */
uint8_t right; /* right priority */
} priority[] = {
// Arithmetic.
[OPR_ADD] = {6, 6},
[OPR_SUB] = {6, 6},
[OPR_MUL] = {7, 7},
[OPR_DIV] = {7, 7},
[OPR_MOD] = {7, 7},
// Power and concat.
[OPR_POW] = {10, 9},
[OPR_CONCAT] = {5, 4},
// Equality and inequality.
[OPR_NE] = {3, 3},
[OPR_EQ] = {3, 3},
// Ordering.
[OPR_LT] = {3, 3},
[OPR_LE] = {3, 3},
[OPR_GT] = {3, 3},
[OPR_GE] = {3, 3},
// Logical and/or.
[OPR_AND] = {2, 2},
[OPR_OR] = {1, 1},
};
#define UNARY_PRIORITY 8 /* priority for unary operators */
/// \code
/// subExpr
/// : (unaryOp subExpr | simpleExpr) (binaryOp subExpr)*
/// ;
/// \endcode
///
/// Accept binary operators with their priority greater than `minPriority`.
static OpKind subExpr(LexState *ls, ExprInfo *v, uint32_t minPriority) {
enterLevel(ls);
OpKind op = unaryOp(ls->t.token);
if (op != OPR_NONE) {
Lexer_next(ls);
subExpr(ls, v, UNARY_PRIORITY);
Codegen_prefix(ls->fs, op, v);
} else {
simpleExpr(ls, v);
}
/* expand while operators have priorities higher than `minPriority' */
op = binaryOp(ls->t.token);
while (op != OPR_NONE && priority[op].left > minPriority) {
ExprInfo v2;
OpKind nextop;
Lexer_next(ls);
Codegen_infix(ls->fs, op, v);
/* read sub-expression with higher priority */
nextop = subExpr(ls, &v2, priority[op].right);
Codegen_suffix(ls->fs, op, v, &v2);
op = nextop;
}
leaveLevel(ls);
return op; /* return first untreated operator */
}
static void expr(LexState *ls, ExprInfo *v) { subExpr(ls, v, 0); }
static bool isBlockEnded(int token) {
switch (token) {
case TK_ELSE:
case TK_ELSEIF:
case TK_END:
case TK_UNTIL:
case TK_EOS:
return true;
default:
return false;
}
}
/// \code
/// block
/// : chunk
/// ;
/// \endcode
static void block(LexState *ls) {
FuncState *fs = ls->fs;
Block bl;
enterBlock(fs, &bl, false);
chunk(ls);
assert(bl.breaklist == NO_JUMP);
leaveBlock(fs);
}
/// Expressions that appear in the left-hand side of an assignment.
typedef struct LExpr {
struct LExpr *prev;
// Global, local, upvalue, or indexed variable.
ExprInfo v;
} LExpr;
/*
** check whether, in an assignment to a local variable, the local variable
** is needed in a previous assignment (to a table). If so, save the original
** local value in a safe place and use this safe copy in the previous
** assignment.
*/
static void checkConflict(LexState *ls, LExpr *lhs, ExprInfo *v) {
FuncState *fs = ls->fs;
int extra = fs->freereg; /* eventual position to save local variable */
bool conflict = false;
assert(v->k == EXPR_LOCAL);
for (; lhs; lhs = lhs->prev) {
if (lhs->v.k == EXPR_INDEXED) {
if (lhs->v.u.indexer.tableReg == v->u.localReg) { /* conflict? */
conflict = true;
/* previous assignment will use safe copy */
lhs->v.u.indexer.tableReg = extra;
}
if (lhs->v.u.indexer.idxReg == v->u.localReg) { /* conflict? */
conflict = true;
/* previous assignment will use safe copy */
lhs->v.u.indexer.idxReg = extra;
}
}
}
if (conflict) {
// Make a copy.
Codegen_emitABC(fs, OP_MOVE, fs->freereg, v->u.localReg, 0);
luaK_reserveRegs(fs, 1);
}
}
static void assignment(LexState *ls, LExpr *lh, int nvars) {
ExprInfo e;
if (!(EXPR_LOCAL <= lh->v.k && lh->v.k <= EXPR_INDEXED)) {
Lex_throw(ls, "syntax error");
}
if (testNext(ls, ',')) { /* assignment -> `,' primaryExpr assignment */
LExpr nv;
nv.prev = lh;