-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.cpp
More file actions
1591 lines (1401 loc) · 48.3 KB
/
parser.cpp
File metadata and controls
1591 lines (1401 loc) · 48.3 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
/*
** $Id: lparser.c $
** Lua Parser - Parser Class Methods
** See Copyright Notice in lua.h
*/
#define lparser_c
#define LUA_CORE
#include "lprefix.h"
#include <climits>
#include <cstring>
#include "lua.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"
/* maximum number of variable declarations per function (must be
smaller than 250, due to the bytecode format) */
#define MAXVARS 200
inline bool hasmultret(expkind k) noexcept {
return (k) == VCALL || (k) == VVARARG;
}
/* because all strings are unified by the scanner, the parser
can use pointer equality for string equality */
inline bool eqstr(const TString* a, const TString* b) noexcept {
return (a) == (b);
}
#define check_condition(parser,c,msg) { if (!(c)) parser->getLexState()->syntaxError( msg); }
#define new_localvarliteral(parser,v) \
new_localvar( \
parser->getLexState()->newString( "" v, (sizeof(v)/sizeof(char)) - 1));
inline void enterlevel(LexState* ls) {
luaE_incCstack(ls->getLuaState());
}
inline void leavelevel(LexState* ls) noexcept {
ls->getLuaState()->getNCcallsRef()--;
}
/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
int firstlabel; /* index of first label in this block */
int firstgoto; /* index of first pending goto in this block */
short nactvar; /* number of active declarations at block entry */
lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isloop; /* 1 if 'block' is a loop; 2 if it has pending breaks */
lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */
} BlockCnt;
typedef struct ConsControl {
expdesc v; /* last list item read */
expdesc *t; /* table descriptor */
int nh; /* total number of 'record' elements */
int na; /* number of array elements already stored */
int tostore; /* number of array elements pending to be stored */
int maxtostore; /* maximum number of pending elements */
} ConsControl;
/*
** Maximum number of elements in a constructor, to control the following:
** * counter overflows;
** * overflows in 'extra' for OP_NEWTABLE and OP_SETLIST;
** * overflows when adding multiple returns in OP_SETLIST.
*/
#define MAX_CNST (INT_MAX/2)
#if MAX_CNST/(MAXARG_vC + 1) > MAXARG_Ax
#undef MAX_CNST
#define MAX_CNST (MAXARG_Ax * (MAXARG_vC + 1))
#endif
inline UnOpr getunopr (int op) noexcept {
switch (op) {
case static_cast<int>(RESERVED::TK_NOT): return UnOpr::OPR_NOT;
case '-': return UnOpr::OPR_MINUS;
case '~': return UnOpr::OPR_BNOT;
case '#': return UnOpr::OPR_LEN;
default: return UnOpr::OPR_NOUNOPR;
}
}
inline BinOpr getbinopr (int op) noexcept {
switch (op) {
case '+': return BinOpr::OPR_ADD;
case '-': return BinOpr::OPR_SUB;
case '*': return BinOpr::OPR_MUL;
case '%': return BinOpr::OPR_MOD;
case '^': return BinOpr::OPR_POW;
case '/': return BinOpr::OPR_DIV;
case static_cast<int>(RESERVED::TK_IDIV): return BinOpr::OPR_IDIV;
case '&': return BinOpr::OPR_BAND;
case '|': return BinOpr::OPR_BOR;
case '~': return BinOpr::OPR_BXOR;
case static_cast<int>(RESERVED::TK_SHL): return BinOpr::OPR_SHL;
case static_cast<int>(RESERVED::TK_SHR): return BinOpr::OPR_SHR;
case static_cast<int>(RESERVED::TK_CONCAT): return BinOpr::OPR_CONCAT;
case static_cast<int>(RESERVED::TK_NE): return BinOpr::OPR_NE;
case static_cast<int>(RESERVED::TK_EQ): return BinOpr::OPR_EQ;
case '<': return BinOpr::OPR_LT;
case static_cast<int>(RESERVED::TK_LE): return BinOpr::OPR_LE;
case '>': return BinOpr::OPR_GT;
case static_cast<int>(RESERVED::TK_GE): return BinOpr::OPR_GE;
case static_cast<int>(RESERVED::TK_AND): return BinOpr::OPR_AND;
case static_cast<int>(RESERVED::TK_OR): return BinOpr::OPR_OR;
default: return BinOpr::OPR_NOBINOPR;
}
}
/*
** Priority table for binary operators.
*/
static const struct {
lu_byte left; /* left priority for each binary operator */
lu_byte right; /* right priority */
} priority[] = { /* ORDER OPR */
{10, 10}, {10, 10}, /* '+' '-' */
{11, 11}, {11, 11}, /* '*' '%' */
{14, 13}, /* '^' (right associative) */
{11, 11}, {11, 11}, /* '/' '//' */
{6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
{7, 7}, {7, 7}, /* '<<' '>>' */
{9, 8}, /* '..' (right associative) */
{3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
{3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
{2, 2}, {1, 1} /* and, or */
};
#define UNARY_PRIORITY 12 /* priority for unary operators */
/*
** structure to chain all variables in the left-hand side of an
** assignment
*/
struct LHS_assign {
struct LHS_assign *prev;
expdesc v; /* variable (global, local, upvalue, or indexed) */
};
l_noret Parser::error_expected(int token) {
ls->syntaxError(
luaO_pushfstring(ls->getLuaState(), "%s expected", ls->tokenToStr(token)));
}
int Parser::testnext(int c) {
if (ls->getToken() == c) {
ls->nextToken();
return 1;
}
else return 0;
}
/*
** Check that next token is 'c'.
*/
void Parser::check(int c) {
if (ls->getToken() != c)
error_expected(c);
}
/*
** Check that next token is 'c' and skip it.
*/
void Parser::checknext(int c) {
check(c);
ls->nextToken();
}
#define check_condition(parser,c,msg) { if (!(c)) parser->getLexState()->syntaxError( msg); }
/*
** Check that next token is 'what' and skip it. In case of error,
** raise an error that the expected 'what' should match a 'who'
** in line 'where' (if that is not the current line).
*/
void Parser::check_match(int what, int who, int where) {
if (l_unlikely(!testnext(what))) {
if (where == ls->getLineNumber()) /* all in the same line? */
error_expected(what); /* do not need a complex message */
else {
ls->syntaxError(luaO_pushfstring(ls->getLuaState(),
"%s expected (to close %s at line %d)",
ls->tokenToStr(what), ls->tokenToStr(who), where));
}
}
}
TString *Parser::str_checkname() {
TString *ts;
check(static_cast<int>(RESERVED::TK_NAME));
ts = ls->getSemInfo().ts;
ls->nextToken();
return ts;
}
void Parser::codename(expdesc *e) {
e->initString(str_checkname());
}
/*
** Register a new local variable in the active 'Proto' (for debug
** information).
*/
int Parser::new_varkind(TString *name, lu_byte kind) {
Dyndata *dynData = ls->getDyndata();
Vardesc *var;
var = dynData->actvar().allocateNew(); /* LuaVector automatically grows */
var->vd.kind = kind; /* default */
var->vd.name = name;
return dynData->actvar().getN() - 1 - fs->getFirstLocal();
}
/*
** Create a new local variable with the given 'name' and regular kind.
*/
int Parser::new_localvar(TString *name) {
return new_varkind(name, VDKREG);
}
#define new_localvarliteral(parser,v) \
new_localvar( \
parser->getLexState()->newString( "" v, (sizeof(v)/sizeof(char)) - 1));
/*
** Return the "variable description" (Vardesc) of a given variable.
** (Unless noted otherwise, all variables are referred to by their
** compiler indices.)
*/
void Parser::check_readonly(expdesc *e) {
// FuncState passed as parameter
TString *varname = nullptr; /* to be set if variable is const */
switch (e->getKind()) {
case VCONST: {
varname = ls->getDyndata()->actvar()[e->getInfo()].vd.name;
break;
}
case VLOCAL: {
Vardesc *vardesc = fs->getlocalvardesc(e->getLocalVarIndex());
if (vardesc->vd.kind != VDKREG) /* not a regular variable? */
varname = vardesc->vd.name;
break;
}
case VUPVAL: {
Upvaldesc *up = &fs->getProto()->getUpvalues()[e->getInfo()];
if (up->getKind() != VDKREG)
varname = up->getName();
break;
}
case VINDEXUP: case VINDEXSTR: case VINDEXED: { /* global variable */
if (e->isIndexedReadOnly()) /* read-only? */
varname = tsvalue(&fs->getProto()->getConstants()[e->getIndexedStringKeyIndex()]);
break;
}
default:
lua_assert(e->getKind() == VINDEXI); /* this one doesn't need any check */
return; /* integer index cannot be read-only */
}
if (varname)
ls->semerror("attempt to assign to const variable '%s'", getstr(varname));
}
/*
** Start the scope for the last 'nvars' created variables.
*/
void Parser::adjustlocalvars(int nvars) {
// FuncState passed as parameter
int regLevel = fs->nvarstack();
int i;
for (i = 0; i < nvars; i++) {
int vidx = fs->getNumActiveVarsRef()++;
Vardesc *var = fs->getlocalvardesc(vidx);
var->vd.ridx = cast_byte(regLevel++);
var->vd.pidx = fs->registerlocalvar(var->vd.name);
fs->checklimit(regLevel, MAXVARS, "local variables");
}
}
/*
** Close the scope for all variables up to level 'tolevel'.
** (debug info.)
*/
void Parser::buildglobal(TString *varname, expdesc *var) {
// FuncState passed as parameter
expdesc key;
var->init(VGLOBAL, -1); /* global by default */
fs->singlevaraux(ls->getEnvName(), var, 1); /* get environment variable */
if (var->getKind() == VGLOBAL)
ls->semerror("_ENV is global when accessing variable '%s'", getstr(varname));
fs->exp2anyregup(var); /* _ENV could be a constant */
key.initString(varname); /* key is variable name */
fs->indexed(var, &key); /* 'var' represents _ENV[varname] */
}
/*
** Find a variable with the given name, handling global variables too.
*/
void Parser::buildvar(TString *varname, expdesc *var) {
// FuncState passed as parameter
var->init(VGLOBAL, -1); /* global by default */
fs->singlevaraux(varname, var, 1);
if (var->getKind() == VGLOBAL) { /* global name? */
int info = var->getInfo();
/* global by default in the scope of a global declaration? */
if (info == -2)
ls->semerror("variable '%s' not declared", getstr(varname));
buildglobal(varname, var);
if (info != -1 && ls->getDyndata()->actvar()[info].vd.kind == GDKCONST)
var->setIndexedReadOnly(1); /* mark variable as read-only */
else /* anyway must be a global */
lua_assert(info == -1 || ls->getDyndata()->actvar()[info].vd.kind == GDKREG);
}
}
void Parser::singlevar(expdesc *var) {
buildvar(str_checkname(), var);
}
/*
** Adjust the number of results from an expression list 'e' with 'nexps'
** expressions to 'nvars' values.
*/
void Parser::adjust_assign(int nvars, int nexps, expdesc *e) {
// FuncState passed as parameter
int needed = nvars - nexps; /* extra values needed */
if (hasmultret(e->getKind())) { /* last expression has multiple returns? */
int extra = needed + 1; /* discount last expression itself */
if (extra < 0)
extra = 0;
fs->setreturns(e, extra); /* last exp. provides the difference */
}
else {
if (e->getKind() != VVOID) /* at least one expression? */
fs->exp2nextreg(e); /* close last expression */
if (needed > 0) /* missing values? */
fs->nil(fs->getFreeReg(), needed); /* complete with nils */
}
if (needed > 0)
fs->reserveregs(needed); /* registers for extra values */
else /* adding 'needed' is actually a subtraction */
fs->setFreeReg(cast_byte(fs->getFreeReg() + needed)); /* remove extra values */
}
int Parser::newgotoentry(TString *name, int line) {
// FuncState passed as parameter
int pc = fs->jump(); /* create jump */
fs->codeABC(OP_CLOSE, 0, 1, 0); /* spaceholder, marked as dead */
return ls->newlabelentry(fs, &ls->getDyndata()->gt, name, line, pc);
}
/*
** Create a new label with the given 'name' at the given 'line'.
** 'last' tells whether label is the last non-op statement in its
** block. Solves all pending gotos to this new label and adds
** a close instruction if necessary.
** Returns true iff it added a close instruction.
*/
Proto *Parser::addprototype() {
Proto *clp;
lua_State *state = ls->getLuaState();
FuncState *funcstate = fs;
Proto *proto = funcstate->getProto(); /* prototype of current function */
if (funcstate->getNP() >= proto->getProtosSize()) {
int oldsize = proto->getProtosSize();
luaM_growvector(state, proto->getProtosRef(), funcstate->getNP(), proto->getProtosSizeRef(), Proto *, MAXARG_Bx, "functions");
auto protosSpan = proto->getProtosSpan();
while (oldsize < static_cast<int>(protosSpan.size()))
protosSpan[oldsize++] = nullptr;
}
proto->getProtosSpan()[funcstate->getNPRef()++] = clp = luaF_newproto(state);
luaC_objbarrier(state, proto, clp);
return clp;
}
/*
** codes instruction to create new closure in parent function.
** The OP_CLOSURE instruction uses the last available register,
** so that, if it invokes the GC, the GC knows which registers
** are in use at that time.
*/
void Parser::codeclosure( expdesc *v) {
FuncState *funcstate = fs->getPrev();
v->init(VRELOC, funcstate->codeABx(OP_CLOSURE, 0, funcstate->getNP() - 1));
funcstate->exp2nextreg(v); /* fix it at the last register */
}
void Parser::open_func(FuncState *funcstate, BlockCnt *bl) {
lua_State *state = ls->getLuaState();
Proto *f = funcstate->getProto();
funcstate->setPrev(fs); /* linked list of funcstates */
funcstate->setLexState(ls);
setFuncState(funcstate);
funcstate->setPC(0);
funcstate->setPreviousLine(f->getLineDefined());
funcstate->setInstructionsWithAbs(0);
funcstate->setLastTarget(0);
funcstate->setFreeReg(0);
funcstate->setNK(0);
funcstate->setNAbsLineInfo(0);
funcstate->setNP(0);
funcstate->setNumUpvalues(0);
funcstate->setNumDebugVars(0);
funcstate->setNumActiveVars(0);
funcstate->setNeedClose(0);
funcstate->setFirstLocal(ls->getDyndata()->actvar().getN());
funcstate->setFirstLabel(ls->getDyndata()->label.getN());
funcstate->setBlock(nullptr);
f->setSource(ls->getSource());
luaC_objbarrier(state, f, f->getSource());
f->setMaxStackSize(2); /* registers 0/1 are always valid */
funcstate->setKCache(luaH_new(state)); /* create table for function */
sethvalue2s(state, state->getTop().p, funcstate->getKCache()); /* anchor it */
state->inctop(); /* Phase 25e */
funcstate->enterblock(bl, 0);
}
void Parser::close_func() {
lua_State *state = ls->getLuaState();
FuncState *funcstate = fs;
Proto *f = funcstate->getProto();
funcstate->ret(luaY_nvarstack(funcstate), 0); /* final return */
funcstate->leaveblock();
lua_assert(funcstate->getBlock() == nullptr);
funcstate->finish();
luaM_shrinkvector(state, f->getCodeRef(), f->getCodeSizeRef(), funcstate->getPC(), Instruction);
luaM_shrinkvector(state, f->getLineInfoRef(), f->getLineInfoSizeRef(), funcstate->getPC(), ls_byte);
luaM_shrinkvector(state, f->getAbsLineInfoRef(), f->getAbsLineInfoSizeRef(),
funcstate->getNAbsLineInfo(), AbsLineInfo);
luaM_shrinkvector(state, f->getConstantsRef(), f->getConstantsSizeRef(), funcstate->getNK(), TValue);
luaM_shrinkvector(state, f->getProtosRef(), f->getProtosSizeRef(), funcstate->getNP(), Proto *);
luaM_shrinkvector(state, f->getLocVarsRef(), f->getLocVarsSizeRef(), funcstate->getNumDebugVars(), LocVar);
luaM_shrinkvector(state, f->getUpvaluesRef(), f->getUpvaluesSizeRef(), funcstate->getNumUpvalues(), Upvaldesc);
setFuncState(funcstate->getPrev());
state->getStackSubsystem().pop(); /* pop kcache table */
luaC_checkGC(state);
}
/*
** {======================================================================
** 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 is handled in separate.
*/
int Parser::block_follow( int withuntil) {
switch (ls->getToken()) {
case static_cast<int>(RESERVED::TK_ELSE): case static_cast<int>(RESERVED::TK_ELSEIF):
case static_cast<int>(RESERVED::TK_END): case static_cast<int>(RESERVED::TK_EOS):
return 1;
case static_cast<int>(RESERVED::TK_UNTIL): return withuntil;
default: return 0;
}
}
void Parser::statlist() {
/* statlist -> { stat [';'] } */
while (!block_follow(1)) {
if (ls->getToken() == static_cast<int>(RESERVED::TK_RETURN)) {
statement();
return; /* 'return' must be last statement */
}
statement();
}
}
void Parser::fieldsel( expdesc *v) {
/* fieldsel -> ['.' | ':'] NAME */
FuncState *funcstate = fs;
expdesc key;
funcstate->exp2anyregup(v);
ls->nextToken(); /* skip the dot or colon */
codename( &key);
funcstate->indexed(v, &key);
}
void Parser::yindex( expdesc *v) {
/* index -> '[' expr ']' */
ls->nextToken(); /* skip the '[' */
expr(v);
fs->exp2val(v);
checknext( ']');
}
/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/
void Parser::recfield( ConsControl *cc) {
/* recfield -> (NAME | '['exp']') = exp */
FuncState *funcstate = fs;
lu_byte reg = fs->getFreeReg();
expdesc tab, key, val;
if (ls->getToken() == static_cast<int>(RESERVED::TK_NAME))
codename( &key);
else /* ls->getToken() == '[' */
yindex(&key);
cc->nh++;
checknext( '=');
tab = *cc->t;
funcstate->indexed(&tab, &key);
expr(&val);
funcstate->storevar(&tab, &val);
funcstate->setFreeReg(reg); /* free registers */
}
void Parser::listfield( ConsControl *cc) {
/* listfield -> exp */
expr(&cc->v);
cc->tostore++;
}
void Parser::field( ConsControl *cc) {
/* field -> listfield | recfield */
switch(ls->getToken()) {
case static_cast<int>(RESERVED::TK_NAME): { /* may be 'listfield' or 'recfield' */
if (ls->lookaheadToken() != '=') /* expression? */
listfield(cc);
else
recfield(cc);
break;
}
case '[': {
recfield(cc);
break;
}
default: {
listfield(cc);
break;
}
}
}
/*
** Compute a limit for how many registers a constructor can use before
** emitting a 'SETLIST' instruction, based on how many registers are
** available.
*/
void Parser::constructor( expdesc *table_exp) {
/* constructor -> '{' [ field { sep field } [sep] ] '}'
sep -> ',' | ';' */
FuncState *funcstate = fs;
int line = ls->getLineNumber();
int pc = funcstate->codevABCk(OP_NEWTABLE, 0, 0, 0, 0);
ConsControl cc;
funcstate->code(0); /* space for extra arg. */
cc.na = cc.nh = cc.tostore = 0;
cc.t = table_exp;
table_exp->init(VNONRELOC, funcstate->getFreeReg()); /* table will be at stack top */
funcstate->reserveregs(1);
cc.v.init(VVOID, 0); /* no value (yet) */
checknext( '{' /*}*/);
cc.maxtostore = funcstate->maxtostore();
do {
if (ls->getToken() == /*{*/ '}') break;
if (cc.v.getKind() != VVOID) /* is there a previous list item? */
funcstate->closelistfield(&cc); /* close it */
field(&cc);
luaY_checklimit(funcstate, cc.tostore + cc.na + cc.nh, MAX_CNST,
"items in a constructor");
} while (testnext( ',') || testnext( ';'));
check_match( /*{*/ '}', '{' /*}*/, line);
funcstate->lastlistfield(&cc);
funcstate->settablesize(pc, static_cast<unsigned>(table_exp->getInfo()), static_cast<unsigned>(cc.na), static_cast<unsigned>(cc.nh));
}
/* }====================================================================== */
void Parser::parlist() {
/* parlist -> [ {NAME ','} (NAME | '...') ] */
FuncState *funcstate = fs;
Proto *f = funcstate->getProto();
int nparams = 0;
int isvararg = 0;
if (ls->getToken() != ')') { /* is 'parlist' not empty? */
do {
switch (ls->getToken()) {
case static_cast<int>(RESERVED::TK_NAME): {
new_localvar( str_checkname());
nparams++;
break;
}
case static_cast<int>(RESERVED::TK_DOTS): {
ls->nextToken();
isvararg = 1;
break;
}
default: ls->syntaxError( "<name> or '...' expected");
}
} while (!isvararg && testnext( ','));
}
adjustlocalvars(nparams);
f->setNumParams(cast_byte(funcstate->getNumActiveVars()));
if (isvararg)
funcstate->setvararg(f->getNumParams()); /* declared vararg */
funcstate->reserveregs(funcstate->getNumActiveVars()); /* reserve registers for parameters */
}
void Parser::body( expdesc *e, int ismethod, int line) {
/* body -> '(' parlist ')' block END */
FuncState new_fs;
BlockCnt bl;
new_fs.setProto(addprototype());
new_fs.getProto()->setLineDefined(line);
open_func(&new_fs, &bl);
checknext( '(');
if (ismethod) {
new_localvarliteral(this, "self"); /* create 'self' parameter */
adjustlocalvars(1);
}
parlist();
checknext( ')');
statlist();
new_fs.getProto()->setLastLineDefined(ls->getLineNumber());
check_match(static_cast<int>(RESERVED::TK_END), static_cast<int>(RESERVED::TK_FUNCTION), line);
codeclosure(e);
close_func();
}
int Parser::explist( expdesc *v) {
/* explist -> expr { ',' expr } */
int n = 1; /* at least one expression */
expr(v);
while (testnext( ',')) {
fs->exp2nextreg(v);
expr(v);
n++;
}
return n;
}
void Parser::funcargs( expdesc *f) {
FuncState *funcstate = fs;
expdesc args;
int base, nparams;
int line = ls->getLineNumber();
switch (ls->getToken()) {
case '(': { /* funcargs -> '(' [ explist ] ')' */
ls->nextToken();
if (ls->getToken() == ')') /* arg list is empty? */
args.setKind(VVOID);
else {
explist(&args);
if (hasmultret(args.getKind()))
funcstate->setreturns(&args, LUA_MULTRET);
}
check_match( ')', '(', line);
break;
}
case '{' /*}*/: { /* funcargs -> constructor */
constructor(&args);
break;
}
case static_cast<int>(RESERVED::TK_STRING): { /* funcargs -> STRING */
args.initString(ls->getSemInfo().ts);
ls->nextToken(); /* must use 'seminfo' before 'next' */
break;
}
default: {
ls->syntaxError( "function arguments expected");
}
}
lua_assert(f->getKind() == VNONRELOC);
base = f->getInfo(); /* base register for call */
if (hasmultret(args.getKind()))
nparams = LUA_MULTRET; /* open call */
else {
if (args.getKind() != VVOID)
funcstate->exp2nextreg(&args); /* close last argument */
nparams = funcstate->getFreeReg() - (base+1);
}
f->init(VCALL, funcstate->codeABC(OP_CALL, base, nparams+1, 2));
funcstate->fixline(line);
/* call removes function and arguments and leaves one result (unless
changed later) */
funcstate->setFreeReg(cast_byte(base + 1));
}
/*
** {======================================================================
** Expression parsing
** =======================================================================
*/
void Parser::primaryexp( expdesc *v) {
/* primaryexp -> NAME | '(' expr ')' */
switch (ls->getToken()) {
case '(': {
int line = ls->getLineNumber();
ls->nextToken();
expr(v);
check_match( ')', '(', line);
fs->dischargevars(v);
return;
}
case static_cast<int>(RESERVED::TK_NAME): {
singlevar(v);
return;
}
default: {
ls->syntaxError( "unexpected symbol");
}
}
}
void Parser::suffixedexp( expdesc *v) {
/* suffixedexp ->
primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
FuncState *funcstate = fs;
primaryexp(v);
for (;;) {
switch (ls->getToken()) {
case '.': { /* fieldsel */
fieldsel(v);
break;
}
case '[': { /* '[' exp ']' */
expdesc key;
funcstate->exp2anyregup(v);
yindex(&key);
funcstate->indexed(v, &key);
break;
}
case ':': { /* ':' NAME funcargs */
expdesc key;
ls->nextToken();
codename( &key);
funcstate->self(v, &key);
funcargs(v);
break;
}
case '(': case static_cast<int>(RESERVED::TK_STRING): case '{' /*}*/: { /* funcargs */
funcstate->exp2nextreg(v);
funcargs(v);
break;
}
default: return;
}
}
}
void Parser::simpleexp( expdesc *v) {
/* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
constructor | FUNCTION body | suffixedexp */
switch (ls->getToken()) {
case static_cast<int>(RESERVED::TK_FLT): {
v->init(VKFLT, 0);
v->setFloatValue(ls->getSemInfo().r);
break;
}
case static_cast<int>(RESERVED::TK_INT): {
v->init(VKINT, 0);
v->setIntValue(ls->getSemInfo().i);
break;
}
case static_cast<int>(RESERVED::TK_STRING): {
v->initString(ls->getSemInfo().ts);
break;
}
case static_cast<int>(RESERVED::TK_NIL): {
v->init(VNIL, 0);
break;
}
case static_cast<int>(RESERVED::TK_TRUE): {
v->init(VTRUE, 0);
break;
}
case static_cast<int>(RESERVED::TK_FALSE): {
v->init(VFALSE, 0);
break;
}
case static_cast<int>(RESERVED::TK_DOTS): { /* vararg */
FuncState *funcstate = fs;
check_condition(this, funcstate->getProto()->getFlag() & PF_ISVARARG,
"cannot use '...' outside a vararg function");
v->init(VVARARG, funcstate->codeABC(OP_VARARG, 0, 0, 1));
break;
}
case '{' /*}*/: { /* constructor */
constructor(v);
return;
}
case static_cast<int>(RESERVED::TK_FUNCTION): {
ls->nextToken();
body(v, 0, ls->getLineNumber());
return;
}
default: {
suffixedexp(v);
return;
}
}
ls->nextToken();
}
BinOpr Parser::subexpr( expdesc *v, int limit) {
BinOpr op;
UnOpr uop;
enterlevel(ls);
uop = getunopr(ls->getToken());
if (uop != UnOpr::OPR_NOUNOPR) { /* prefix (unary) operator? */
int line = ls->getLineNumber();
ls->nextToken(); /* skip operator */
subexpr(v, UNARY_PRIORITY);
fs->prefix(uop, v, line);
}
else simpleexp(v);
/* expand while operators have priorities higher than 'limit' */
op = getbinopr(ls->getToken());
while (op != BinOpr::OPR_NOBINOPR && priority[static_cast<int>(op)].left > limit) {
expdesc v2;
BinOpr nextop;
int line = ls->getLineNumber();
ls->nextToken(); /* skip operator */
fs->infix(op, v);
/* read sub-expression with higher priority */
nextop = subexpr(&v2, priority[static_cast<int>(op)].right);
fs->posfix(op, v, &v2, line);
op = nextop;
}
leavelevel(ls);
return op; /* return first untreated operator */
}
void Parser::expr( expdesc *v) {
subexpr(v, 0);
}
/* }==================================================================== */
/*
** {======================================================================
** Rules for Statements
** =======================================================================
*/
void Parser::block() {
/* block -> statlist */
FuncState *funcstate = fs;
BlockCnt bl;
funcstate->enterblock(&bl, 0);
statlist();
funcstate->leaveblock();
}
/*
** check whether, in an assignment to an upvalue/local variable, the
** upvalue/local variable is begin used in a previous assignment to a
** table. If so, save original upvalue/local value in a safe place and
** use this safe copy in the previous assignment.
*/
void Parser::check_conflict( struct LHS_assign *lh, expdesc *v) {
FuncState *funcstate = fs;
lu_byte extra = funcstate->getFreeReg(); /* eventual position to save local variable */
int conflict = 0;
for (; lh; lh = lh->prev) { /* check all previous assignments */
if (expdesc::isIndexed(lh->v.getKind())) { /* assignment to table field? */
if (lh->v.getKind() == VINDEXUP) { /* is table an upvalue? */
if (v->getKind() == VUPVAL && lh->v.getIndexedTableReg() == v->getInfo()) {
conflict = 1; /* table is the upvalue being assigned now */
lh->v.setKind(VINDEXSTR);
lh->v.setIndexedTableReg(extra); /* assignment will use safe copy */
}
}
else { /* table is a register */
if (v->getKind() == VLOCAL && lh->v.getIndexedTableReg() == v->getLocalRegister()) {
conflict = 1; /* table is the local being assigned now */
lh->v.setIndexedTableReg(extra); /* assignment will use safe copy */
}
/* is index the local being assigned? */
if (lh->v.getKind() == VINDEXED && v->getKind() == VLOCAL &&
lh->v.getIndexedKeyIndex() == v->getLocalRegister()) {
conflict = 1;
lh->v.setIndexedKeyIndex(extra); /* previous assignment will use safe copy */
}
}
}
}
if (conflict) {
/* copy upvalue/local value to a temporary (in position 'extra') */
if (v->getKind() == VLOCAL)
funcstate->codeABC(OP_MOVE, extra, v->getLocalRegister(), 0);
else
funcstate->codeABC(OP_GETUPVAL, extra, v->getInfo(), 0);
funcstate->reserveregs(1);
}
}
/* Create code to store the "top" register in 'var' */
void Parser::restassign( struct LHS_assign *lh, int nvars) {
expdesc e;
check_condition(this, expdesc::isVar(lh->v.getKind()), "syntax error");
check_readonly(&lh->v);
if (testnext( ',')) { /* restassign -> ',' suffixedexp restassign */
struct LHS_assign nv;
nv.prev = lh;
suffixedexp(&nv.v);
if (!expdesc::isIndexed(nv.v.getKind()))
check_conflict(lh, &nv.v);
enterlevel(ls); /* control recursion depth */
restassign(&nv, nvars+1);
leavelevel(ls);
}
else { /* restassign -> '=' explist */
int nexps;
checknext( '=');
nexps = explist(&e);
if (nexps != nvars)
adjust_assign(nvars, nexps, &e);
else {
fs->setoneret(&e); /* close last expression */
fs->storevar(&lh->v, &e);
return; /* avoid default */
}
}
fs->storevartop(&lh->v); /* default assignment */