1/* This is a heavily customized and minimized copy of Lua 5.1.5. */
2/* It's only used to build LuaJIT. It does NOT have all standard functions! */
3/******************************************************************************
4* Copyright (C) 1994-2012 Lua.org, PUC-Rio. All rights reserved.
5*
6* Permission is hereby granted, free of charge, to any person obtaining
7* a copy of this software and associated documentation files (the
8* "Software"), to deal in the Software without restriction, including
9* without limitation the rights to use, copy, modify, merge, publish,
10* distribute, sublicense, and/or sell copies of the Software, and to
11* permit persons to whom the Software is furnished to do so, subject to
12* the following conditions:
13*
14* The above copyright notice and this permission notice shall be
15* included in all copies or substantial portions of the Software.
16*
17* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24******************************************************************************/
25#ifdef _MSC_VER
26typedef unsigned __int64 U64;
27#else
28typedef unsigned long long U64;
29#endif
30int _CRT_glob = 0;
31#include <stddef.h>
32#include <stdarg.h>
33#include <limits.h>
34#include <math.h>
35#include <ctype.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <setjmp.h>
40#include <errno.h>
41#include <time.h>
42typedef enum{
43TM_INDEX,
44TM_NEWINDEX,
45TM_GC,
46TM_MODE,
47TM_EQ,
48TM_ADD,
49TM_SUB,
50TM_MUL,
51TM_DIV,
52TM_MOD,
53TM_POW,
54TM_UNM,
55TM_LEN,
56TM_LT,
57TM_LE,
58TM_CONCAT,
59TM_CALL,
60TM_N
61}TMS;
62enum OpMode{iABC,iABx,iAsBx};
63typedef enum{
64OP_MOVE,
65OP_LOADK,
66OP_LOADBOOL,
67OP_LOADNIL,
68OP_GETUPVAL,
69OP_GETGLOBAL,
70OP_GETTABLE,
71OP_SETGLOBAL,
72OP_SETUPVAL,
73OP_SETTABLE,
74OP_NEWTABLE,
75OP_SELF,
76OP_ADD,
77OP_SUB,
78OP_MUL,
79OP_DIV,
80OP_MOD,
81OP_POW,
82OP_UNM,
83OP_NOT,
84OP_LEN,
85OP_CONCAT,
86OP_JMP,
87OP_EQ,
88OP_LT,
89OP_LE,
90OP_TEST,
91OP_TESTSET,
92OP_CALL,
93OP_TAILCALL,
94OP_RETURN,
95OP_FORLOOP,
96OP_FORPREP,
97OP_TFORLOOP,
98OP_SETLIST,
99OP_CLOSE,
100OP_CLOSURE,
101OP_VARARG
102}OpCode;
103enum OpArgMask{
104OpArgN,
105OpArgU,
106OpArgR,
107OpArgK
108};
109typedef enum{
110VVOID,
111VNIL,
112VTRUE,
113VFALSE,
114VK,
115VKNUM,
116VLOCAL,
117VUPVAL,
118VGLOBAL,
119VINDEXED,
120VJMP,
121VRELOCABLE,
122VNONRELOC,
123VCALL,
124VVARARG
125}expkind;
126enum RESERVED{
127TK_AND=257,TK_BREAK,
128TK_DO,TK_ELSE,TK_ELSEIF,TK_END,TK_FALSE,TK_FOR,TK_FUNCTION,
129TK_IF,TK_IN,TK_LOCAL,TK_NIL,TK_NOT,TK_OR,TK_REPEAT,
130TK_RETURN,TK_THEN,TK_TRUE,TK_UNTIL,TK_WHILE,
131TK_CONCAT,TK_DOTS,TK_EQ,TK_GE,TK_LE,TK_NE,TK_NUMBER,
132TK_NAME,TK_STRING,TK_EOS
133};
134typedef enum BinOpr{
135OPR_ADD,OPR_SUB,OPR_MUL,OPR_DIV,OPR_MOD,OPR_POW,
136OPR_CONCAT,
137OPR_NE,OPR_EQ,
138OPR_LT,OPR_LE,OPR_GT,OPR_GE,
139OPR_AND,OPR_OR,
140OPR_NOBINOPR
141}BinOpr;
142typedef enum UnOpr{OPR_MINUS,OPR_NOT,OPR_LEN,OPR_NOUNOPR}UnOpr;
143#define LUA_QL(x)"'"x"'"
144#define luai_apicheck(L,o){(void)L;}
145#define lua_number2str(s,n)sprintf((s),"%.14g",(n))
146#define lua_str2number(s,p)strtod((s),(p))
147#define luai_numadd(a,b)((a)+(b))
148#define luai_numsub(a,b)((a)-(b))
149#define luai_nummul(a,b)((a)*(b))
150#define luai_numdiv(a,b)((a)/(b))
151#define luai_nummod(a,b)((a)-floor((a)/(b))*(b))
152#define luai_numpow(a,b)(pow(a,b))
153#define luai_numunm(a)(-(a))
154#define luai_numeq(a,b)((a)==(b))
155#define luai_numlt(a,b)((a)<(b))
156#define luai_numle(a,b)((a)<=(b))
157#define luai_numisnan(a)(!luai_numeq((a),(a)))
158#define lua_number2int(i,d)((i)=(int)(d))
159#define lua_number2integer(i,d)((i)=(lua_Integer)(d))
160#define LUAI_THROW(L,c)longjmp((c)->b,1)
161#define LUAI_TRY(L,c,a)if(setjmp((c)->b)==0){a}
162#define lua_pclose(L,file)((void)((void)L,file),0)
163#define lua_upvalueindex(i)((-10002)-(i))
164typedef struct lua_State lua_State;
165typedef int(*lua_CFunction)(lua_State*L);
166typedef const char*(*lua_Reader)(lua_State*L,void*ud,size_t*sz);
167typedef void*(*lua_Alloc)(void*ud,void*ptr,size_t osize,size_t nsize);
168typedef double lua_Number;
169typedef ptrdiff_t lua_Integer;
170static void lua_settop(lua_State*L,int idx);
171static int lua_type(lua_State*L,int idx);
172static const char* lua_tolstring(lua_State*L,int idx,size_t*len);
173static size_t lua_objlen(lua_State*L,int idx);
174static void lua_pushlstring(lua_State*L,const char*s,size_t l);
175static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n);
176static void lua_createtable(lua_State*L,int narr,int nrec);
177static void lua_setfield(lua_State*L,int idx,const char*k);
178#define lua_pop(L,n)lua_settop(L,-(n)-1)
179#define lua_newtable(L)lua_createtable(L,0,0)
180#define lua_pushcfunction(L,f)lua_pushcclosure(L,(f),0)
181#define lua_strlen(L,i)lua_objlen(L,(i))
182#define lua_isfunction(L,n)(lua_type(L,(n))==6)
183#define lua_istable(L,n)(lua_type(L,(n))==5)
184#define lua_isnil(L,n)(lua_type(L,(n))==0)
185#define lua_isboolean(L,n)(lua_type(L,(n))==1)
186#define lua_isnone(L,n)(lua_type(L,(n))==(-1))
187#define lua_isnoneornil(L,n)(lua_type(L,(n))<=0)
188#define lua_pushliteral(L,s)lua_pushlstring(L,""s,(sizeof(s)/sizeof(char))-1)
189#define lua_setglobal(L,s)lua_setfield(L,(-10002),(s))
190#define lua_tostring(L,i)lua_tolstring(L,(i),NULL)
191typedef struct lua_Debug lua_Debug;
192typedef void(*lua_Hook)(lua_State*L,lua_Debug*ar);
193struct lua_Debug{
194int event;
195const char*name;
196const char*namewhat;
197const char*what;
198const char*source;
199int currentline;
200int nups;
201int linedefined;
202int lastlinedefined;
203char short_src[60];
204int i_ci;
205};
206typedef unsigned int lu_int32;
207typedef size_t lu_mem;
208typedef ptrdiff_t l_mem;
209typedef unsigned char lu_byte;
210#define IntPoint(p)((unsigned int)(lu_mem)(p))
211typedef union{double u;void*s;long l;}L_Umaxalign;
212typedef double l_uacNumber;
213#define check_exp(c,e)(e)
214#define UNUSED(x)((void)(x))
215#define cast(t,exp)((t)(exp))
216#define cast_byte(i)cast(lu_byte,(i))
217#define cast_num(i)cast(lua_Number,(i))
218#define cast_int(i)cast(int,(i))
219typedef lu_int32 Instruction;
220#define condhardstacktests(x)((void)0)
221typedef union GCObject GCObject;
222typedef struct GCheader{
223GCObject*next;lu_byte tt;lu_byte marked;
224}GCheader;
225typedef union{
226GCObject*gc;
227void*p;
228lua_Number n;
229int b;
230}Value;
231typedef struct lua_TValue{
232Value value;int tt;
233}TValue;
234#define ttisnil(o)(ttype(o)==0)
235#define ttisnumber(o)(ttype(o)==3)
236#define ttisstring(o)(ttype(o)==4)
237#define ttistable(o)(ttype(o)==5)
238#define ttisfunction(o)(ttype(o)==6)
239#define ttisboolean(o)(ttype(o)==1)
240#define ttisuserdata(o)(ttype(o)==7)
241#define ttisthread(o)(ttype(o)==8)
242#define ttislightuserdata(o)(ttype(o)==2)
243#define ttype(o)((o)->tt)
244#define gcvalue(o)check_exp(iscollectable(o),(o)->value.gc)
245#define pvalue(o)check_exp(ttislightuserdata(o),(o)->value.p)
246#define nvalue(o)check_exp(ttisnumber(o),(o)->value.n)
247#define rawtsvalue(o)check_exp(ttisstring(o),&(o)->value.gc->ts)
248#define tsvalue(o)(&rawtsvalue(o)->tsv)
249#define rawuvalue(o)check_exp(ttisuserdata(o),&(o)->value.gc->u)
250#define uvalue(o)(&rawuvalue(o)->uv)
251#define clvalue(o)check_exp(ttisfunction(o),&(o)->value.gc->cl)
252#define hvalue(o)check_exp(ttistable(o),&(o)->value.gc->h)
253#define bvalue(o)check_exp(ttisboolean(o),(o)->value.b)
254#define thvalue(o)check_exp(ttisthread(o),&(o)->value.gc->th)
255#define l_isfalse(o)(ttisnil(o)||(ttisboolean(o)&&bvalue(o)==0))
256#define checkconsistency(obj)
257#define checkliveness(g,obj)
258#define setnilvalue(obj)((obj)->tt=0)
259#define setnvalue(obj,x){TValue*i_o=(obj);i_o->value.n=(x);i_o->tt=3;}
260#define setbvalue(obj,x){TValue*i_o=(obj);i_o->value.b=(x);i_o->tt=1;}
261#define setsvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=4;checkliveness(G(L),i_o);}
262#define setuvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=7;checkliveness(G(L),i_o);}
263#define setthvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=8;checkliveness(G(L),i_o);}
264#define setclvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=6;checkliveness(G(L),i_o);}
265#define sethvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=5;checkliveness(G(L),i_o);}
266#define setptvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=(8+1);checkliveness(G(L),i_o);}
267#define setobj(L,obj1,obj2){const TValue*o2=(obj2);TValue*o1=(obj1);o1->value=o2->value;o1->tt=o2->tt;checkliveness(G(L),o1);}
268#define setttype(obj,tt)(ttype(obj)=(tt))
269#define iscollectable(o)(ttype(o)>=4)
270typedef TValue*StkId;
271typedef union TString{
272L_Umaxalign dummy;
273struct{
274GCObject*next;lu_byte tt;lu_byte marked;
275lu_byte reserved;
276unsigned int hash;
277size_t len;
278}tsv;
279}TString;
280#define getstr(ts)cast(const char*,(ts)+1)
281#define svalue(o)getstr(rawtsvalue(o))
282typedef union Udata{
283L_Umaxalign dummy;
284struct{
285GCObject*next;lu_byte tt;lu_byte marked;
286struct Table*metatable;
287struct Table*env;
288size_t len;
289}uv;
290}Udata;
291typedef struct Proto{
292GCObject*next;lu_byte tt;lu_byte marked;
293TValue*k;
294Instruction*code;
295struct Proto**p;
296int*lineinfo;
297struct LocVar*locvars;
298TString**upvalues;
299TString*source;
300int sizeupvalues;
301int sizek;
302int sizecode;
303int sizelineinfo;
304int sizep;
305int sizelocvars;
306int linedefined;
307int lastlinedefined;
308GCObject*gclist;
309lu_byte nups;
310lu_byte numparams;
311lu_byte is_vararg;
312lu_byte maxstacksize;
313}Proto;
314typedef struct LocVar{
315TString*varname;
316int startpc;
317int endpc;
318}LocVar;
319typedef struct UpVal{
320GCObject*next;lu_byte tt;lu_byte marked;
321TValue*v;
322union{
323TValue value;
324struct{
325struct UpVal*prev;
326struct UpVal*next;
327}l;
328}u;
329}UpVal;
330typedef struct CClosure{
331GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env;
332lua_CFunction f;
333TValue upvalue[1];
334}CClosure;
335typedef struct LClosure{
336GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env;
337struct Proto*p;
338UpVal*upvals[1];
339}LClosure;
340typedef union Closure{
341CClosure c;
342LClosure l;
343}Closure;
344#define iscfunction(o)(ttype(o)==6&&clvalue(o)->c.isC)
345typedef union TKey{
346struct{
347Value value;int tt;
348struct Node*next;
349}nk;
350TValue tvk;
351}TKey;
352typedef struct Node{
353TValue i_val;
354TKey i_key;
355}Node;
356typedef struct Table{
357GCObject*next;lu_byte tt;lu_byte marked;
358lu_byte flags;
359lu_byte lsizenode;
360struct Table*metatable;
361TValue*array;
362Node*node;
363Node*lastfree;
364GCObject*gclist;
365int sizearray;
366}Table;
367#define lmod(s,size)(check_exp((size&(size-1))==0,(cast(int,(s)&((size)-1)))))
368#define twoto(x)((size_t)1<<(x))
369#define sizenode(t)(twoto((t)->lsizenode))
370static const TValue luaO_nilobject_;
371#define ceillog2(x)(luaO_log2((x)-1)+1)
372static int luaO_log2(unsigned int x);
373#define gfasttm(g,et,e)((et)==NULL?NULL:((et)->flags&(1u<<(e)))?NULL:luaT_gettm(et,e,(g)->tmname[e]))
374#define fasttm(l,et,e)gfasttm(G(l),et,e)
375static const TValue*luaT_gettm(Table*events,TMS event,TString*ename);
376#define luaM_reallocv(L,b,on,n,e)((cast(size_t,(n)+1)<=((size_t)(~(size_t)0)-2)/(e))?luaM_realloc_(L,(b),(on)*(e),(n)*(e)):luaM_toobig(L))
377#define luaM_freemem(L,b,s)luaM_realloc_(L,(b),(s),0)
378#define luaM_free(L,b)luaM_realloc_(L,(b),sizeof(*(b)),0)
379#define luaM_freearray(L,b,n,t)luaM_reallocv(L,(b),n,0,sizeof(t))
380#define luaM_malloc(L,t)luaM_realloc_(L,NULL,0,(t))
381#define luaM_new(L,t)cast(t*,luaM_malloc(L,sizeof(t)))
382#define luaM_newvector(L,n,t)cast(t*,luaM_reallocv(L,NULL,0,n,sizeof(t)))
383#define luaM_growvector(L,v,nelems,size,t,limit,e)if((nelems)+1>(size))((v)=cast(t*,luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
384#define luaM_reallocvector(L,v,oldn,n,t)((v)=cast(t*,luaM_reallocv(L,v,oldn,n,sizeof(t))))
385static void*luaM_realloc_(lua_State*L,void*block,size_t oldsize,
386size_t size);
387static void*luaM_toobig(lua_State*L);
388static void*luaM_growaux_(lua_State*L,void*block,int*size,
389size_t size_elem,int limit,
390const char*errormsg);
391typedef struct Zio ZIO;
392#define char2int(c)cast(int,cast(unsigned char,(c)))
393#define zgetc(z)(((z)->n--)>0?char2int(*(z)->p++):luaZ_fill(z))
394typedef struct Mbuffer{
395char*buffer;
396size_t n;
397size_t buffsize;
398}Mbuffer;
399#define luaZ_initbuffer(L,buff)((buff)->buffer=NULL,(buff)->buffsize=0)
400#define luaZ_buffer(buff)((buff)->buffer)
401#define luaZ_sizebuffer(buff)((buff)->buffsize)
402#define luaZ_bufflen(buff)((buff)->n)
403#define luaZ_resetbuffer(buff)((buff)->n=0)
404#define luaZ_resizebuffer(L,buff,size)(luaM_reallocvector(L,(buff)->buffer,(buff)->buffsize,size,char),(buff)->buffsize=size)
405#define luaZ_freebuffer(L,buff)luaZ_resizebuffer(L,buff,0)
406struct Zio{
407size_t n;
408const char*p;
409lua_Reader reader;
410void*data;
411lua_State*L;
412};
413static int luaZ_fill(ZIO*z);
414struct lua_longjmp;
415#define gt(L)(&L->l_gt)
416#define registry(L)(&G(L)->l_registry)
417typedef struct stringtable{
418GCObject**hash;
419lu_int32 nuse;
420int size;
421}stringtable;
422typedef struct CallInfo{
423StkId base;
424StkId func;
425StkId top;
426const Instruction*savedpc;
427int nresults;
428int tailcalls;
429}CallInfo;
430#define curr_func(L)(clvalue(L->ci->func))
431#define ci_func(ci)(clvalue((ci)->func))
432#define f_isLua(ci)(!ci_func(ci)->c.isC)
433#define isLua(ci)(ttisfunction((ci)->func)&&f_isLua(ci))
434typedef struct global_State{
435stringtable strt;
436lua_Alloc frealloc;
437void*ud;
438lu_byte currentwhite;
439lu_byte gcstate;
440int sweepstrgc;
441GCObject*rootgc;
442GCObject**sweepgc;
443GCObject*gray;
444GCObject*grayagain;
445GCObject*weak;
446GCObject*tmudata;
447Mbuffer buff;
448lu_mem GCthreshold;
449lu_mem totalbytes;
450lu_mem estimate;
451lu_mem gcdept;
452int gcpause;
453int gcstepmul;
454lua_CFunction panic;
455TValue l_registry;
456struct lua_State*mainthread;
457UpVal uvhead;
458struct Table*mt[(8+1)];
459TString*tmname[TM_N];
460}global_State;
461struct lua_State{
462GCObject*next;lu_byte tt;lu_byte marked;
463lu_byte status;
464StkId top;
465StkId base;
466global_State*l_G;
467CallInfo*ci;
468const Instruction*savedpc;
469StkId stack_last;
470StkId stack;
471CallInfo*end_ci;
472CallInfo*base_ci;
473int stacksize;
474int size_ci;
475unsigned short nCcalls;
476unsigned short baseCcalls;
477lu_byte hookmask;
478lu_byte allowhook;
479int basehookcount;
480int hookcount;
481lua_Hook hook;
482TValue l_gt;
483TValue env;
484GCObject*openupval;
485GCObject*gclist;
486struct lua_longjmp*errorJmp;
487ptrdiff_t errfunc;
488};
489#define G(L)(L->l_G)
490union GCObject{
491GCheader gch;
492union TString ts;
493union Udata u;
494union Closure cl;
495struct Table h;
496struct Proto p;
497struct UpVal uv;
498struct lua_State th;
499};
500#define rawgco2ts(o)check_exp((o)->gch.tt==4,&((o)->ts))
501#define gco2ts(o)(&rawgco2ts(o)->tsv)
502#define rawgco2u(o)check_exp((o)->gch.tt==7,&((o)->u))
503#define gco2u(o)(&rawgco2u(o)->uv)
504#define gco2cl(o)check_exp((o)->gch.tt==6,&((o)->cl))
505#define gco2h(o)check_exp((o)->gch.tt==5,&((o)->h))
506#define gco2p(o)check_exp((o)->gch.tt==(8+1),&((o)->p))
507#define gco2uv(o)check_exp((o)->gch.tt==(8+2),&((o)->uv))
508#define ngcotouv(o)check_exp((o)==NULL||(o)->gch.tt==(8+2),&((o)->uv))
509#define gco2th(o)check_exp((o)->gch.tt==8,&((o)->th))
510#define obj2gco(v)(cast(GCObject*,(v)))
511static void luaE_freethread(lua_State*L,lua_State*L1);
512#define pcRel(pc,p)(cast(int,(pc)-(p)->code)-1)
513#define getline_(f,pc)(((f)->lineinfo)?(f)->lineinfo[pc]:0)
514#define resethookcount(L)(L->hookcount=L->basehookcount)
515static void luaG_typeerror(lua_State*L,const TValue*o,
516const char*opname);
517static void luaG_runerror(lua_State*L,const char*fmt,...);
518#define luaD_checkstack(L,n)if((char*)L->stack_last-(char*)L->top<=(n)*(int)sizeof(TValue))luaD_growstack(L,n);else condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1));
519#define incr_top(L){luaD_checkstack(L,1);L->top++;}
520#define savestack(L,p)((char*)(p)-(char*)L->stack)
521#define restorestack(L,n)((TValue*)((char*)L->stack+(n)))
522#define saveci(L,p)((char*)(p)-(char*)L->base_ci)
523#define restoreci(L,n)((CallInfo*)((char*)L->base_ci+(n)))
524typedef void(*Pfunc)(lua_State*L,void*ud);
525static int luaD_poscall(lua_State*L,StkId firstResult);
526static void luaD_reallocCI(lua_State*L,int newsize);
527static void luaD_reallocstack(lua_State*L,int newsize);
528static void luaD_growstack(lua_State*L,int n);
529static void luaD_throw(lua_State*L,int errcode);
530static void*luaM_growaux_(lua_State*L,void*block,int*size,size_t size_elems,
531int limit,const char*errormsg){
532void*newblock;
533int newsize;
534if(*size>=limit/2){
535if(*size>=limit)
536luaG_runerror(L,errormsg);
537newsize=limit;
538}
539else{
540newsize=(*size)*2;
541if(newsize<4)
542newsize=4;
543}
544newblock=luaM_reallocv(L,block,*size,newsize,size_elems);
545*size=newsize;
546return newblock;
547}
548static void*luaM_toobig(lua_State*L){
549luaG_runerror(L,"memory allocation error: block too big");
550return NULL;
551}
552static void*luaM_realloc_(lua_State*L,void*block,size_t osize,size_t nsize){
553global_State*g=G(L);
554block=(*g->frealloc)(g->ud,block,osize,nsize);
555if(block==NULL&&nsize>0)
556luaD_throw(L,4);
557g->totalbytes=(g->totalbytes-osize)+nsize;
558return block;
559}
560#define resetbits(x,m)((x)&=cast(lu_byte,~(m)))
561#define setbits(x,m)((x)|=(m))
562#define testbits(x,m)((x)&(m))
563#define bitmask(b)(1<<(b))
564#define bit2mask(b1,b2)(bitmask(b1)|bitmask(b2))
565#define l_setbit(x,b)setbits(x,bitmask(b))
566#define resetbit(x,b)resetbits(x,bitmask(b))
567#define testbit(x,b)testbits(x,bitmask(b))
568#define set2bits(x,b1,b2)setbits(x,(bit2mask(b1,b2)))
569#define reset2bits(x,b1,b2)resetbits(x,(bit2mask(b1,b2)))
570#define test2bits(x,b1,b2)testbits(x,(bit2mask(b1,b2)))
571#define iswhite(x)test2bits((x)->gch.marked,0,1)
572#define isblack(x)testbit((x)->gch.marked,2)
573#define isgray(x)(!isblack(x)&&!iswhite(x))
574#define otherwhite(g)(g->currentwhite^bit2mask(0,1))
575#define isdead(g,v)((v)->gch.marked&otherwhite(g)&bit2mask(0,1))
576#define changewhite(x)((x)->gch.marked^=bit2mask(0,1))
577#define gray2black(x)l_setbit((x)->gch.marked,2)
578#define valiswhite(x)(iscollectable(x)&&iswhite(gcvalue(x)))
579#define luaC_white(g)cast(lu_byte,(g)->currentwhite&bit2mask(0,1))
580#define luaC_checkGC(L){condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1));if(G(L)->totalbytes>=G(L)->GCthreshold)luaC_step(L);}
581#define luaC_barrier(L,p,v){if(valiswhite(v)&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),gcvalue(v));}
582#define luaC_barriert(L,t,v){if(valiswhite(v)&&isblack(obj2gco(t)))luaC_barrierback(L,t);}
583#define luaC_objbarrier(L,p,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),obj2gco(o));}
584#define luaC_objbarriert(L,t,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(t)))luaC_barrierback(L,t);}
585static void luaC_step(lua_State*L);
586static void luaC_link(lua_State*L,GCObject*o,lu_byte tt);
587static void luaC_linkupval(lua_State*L,UpVal*uv);
588static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v);
589static void luaC_barrierback(lua_State*L,Table*t);
590#define sizestring(s)(sizeof(union TString)+((s)->len+1)*sizeof(char))
591#define sizeudata(u)(sizeof(union Udata)+(u)->len)
592#define luaS_new(L,s)(luaS_newlstr(L,s,strlen(s)))
593#define luaS_newliteral(L,s)(luaS_newlstr(L,""s,(sizeof(s)/sizeof(char))-1))
594#define luaS_fix(s)l_setbit((s)->tsv.marked,5)
595static TString*luaS_newlstr(lua_State*L,const char*str,size_t l);
596#define tostring(L,o)((ttype(o)==4)||(luaV_tostring(L,o)))
597#define tonumber(o,n)(ttype(o)==3||(((o)=luaV_tonumber(o,n))!=NULL))
598#define equalobj(L,o1,o2)(ttype(o1)==ttype(o2)&&luaV_equalval(L,o1,o2))
599static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2);
600static const TValue*luaV_tonumber(const TValue*obj,TValue*n);
601static int luaV_tostring(lua_State*L,StkId obj);
602static void luaV_execute(lua_State*L,int nexeccalls);
603static void luaV_concat(lua_State*L,int total,int last);
604static const TValue luaO_nilobject_={{NULL},0};
605static int luaO_int2fb(unsigned int x){
606int e=0;
607while(x>=16){
608x=(x+1)>>1;
609e++;
610}
611if(x<8)return x;
612else return((e+1)<<3)|(cast_int(x)-8);
613}
614static int luaO_fb2int(int x){
615int e=(x>>3)&31;
616if(e==0)return x;
617else return((x&7)+8)<<(e-1);
618}
619static int luaO_log2(unsigned int x){
620static const lu_byte log_2[256]={
6210,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6226,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6237,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
6247,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
6258,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6268,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6278,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6288,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
629};
630int l=-1;
631while(x>=256){l+=8;x>>=8;}
632return l+log_2[x];
633}
634static int luaO_rawequalObj(const TValue*t1,const TValue*t2){
635if(ttype(t1)!=ttype(t2))return 0;
636else switch(ttype(t1)){
637case 0:
638return 1;
639case 3:
640return luai_numeq(nvalue(t1),nvalue(t2));
641case 1:
642return bvalue(t1)==bvalue(t2);
643case 2:
644return pvalue(t1)==pvalue(t2);
645default:
646return gcvalue(t1)==gcvalue(t2);
647}
648}
649static int luaO_str2d(const char*s,lua_Number*result){
650char*endptr;
651*result=lua_str2number(s,&endptr);
652if(endptr==s)return 0;
653if(*endptr=='x'||*endptr=='X')
654*result=cast_num(strtoul(s,&endptr,16));
655if(*endptr=='\0')return 1;
656while(isspace(cast(unsigned char,*endptr)))endptr++;
657if(*endptr!='\0')return 0;
658return 1;
659}
660static void pushstr(lua_State*L,const char*str){
661setsvalue(L,L->top,luaS_new(L,str));
662incr_top(L);
663}
664static const char*luaO_pushvfstring(lua_State*L,const char*fmt,va_list argp){
665int n=1;
666pushstr(L,"");
667for(;;){
668const char*e=strchr(fmt,'%');
669if(e==NULL)break;
670setsvalue(L,L->top,luaS_newlstr(L,fmt,e-fmt));
671incr_top(L);
672switch(*(e+1)){
673case's':{
674const char*s=va_arg(argp,char*);
675if(s==NULL)s="(null)";
676pushstr(L,s);
677break;
678}
679case'c':{
680char buff[2];
681buff[0]=cast(char,va_arg(argp,int));
682buff[1]='\0';
683pushstr(L,buff);
684break;
685}
686case'd':{
687setnvalue(L->top,cast_num(va_arg(argp,int)));
688incr_top(L);
689break;
690}
691case'f':{
692setnvalue(L->top,cast_num(va_arg(argp,l_uacNumber)));
693incr_top(L);
694break;
695}
696case'p':{
697char buff[4*sizeof(void*)+8];
698sprintf(buff,"%p",va_arg(argp,void*));
699pushstr(L,buff);
700break;
701}
702case'%':{
703pushstr(L,"%");
704break;
705}
706default:{
707char buff[3];
708buff[0]='%';
709buff[1]=*(e+1);
710buff[2]='\0';
711pushstr(L,buff);
712break;
713}
714}
715n+=2;
716fmt=e+2;
717}
718pushstr(L,fmt);
719luaV_concat(L,n+1,cast_int(L->top-L->base)-1);
720L->top-=n;
721return svalue(L->top-1);
722}
723static const char*luaO_pushfstring(lua_State*L,const char*fmt,...){
724const char*msg;
725va_list argp;
726va_start(argp,fmt);
727msg=luaO_pushvfstring(L,fmt,argp);
728va_end(argp);
729return msg;
730}
731static void luaO_chunkid(char*out,const char*source,size_t bufflen){
732if(*source=='='){
733strncpy(out,source+1,bufflen);
734out[bufflen-1]='\0';
735}
736else{
737if(*source=='@'){
738size_t l;
739source++;
740bufflen-=sizeof(" '...' ");
741l=strlen(source);
742strcpy(out,"");
743if(l>bufflen){
744source+=(l-bufflen);
745strcat(out,"...");
746}
747strcat(out,source);
748}
749else{
750size_t len=strcspn(source,"\n\r");
751bufflen-=sizeof(" [string \"...\"] ");
752if(len>bufflen)len=bufflen;
753strcpy(out,"[string \"");
754if(source[len]!='\0'){
755strncat(out,source,len);
756strcat(out,"...");
757}
758else
759strcat(out,source);
760strcat(out,"\"]");
761}
762}
763}
764#define gnode(t,i)(&(t)->node[i])
765#define gkey(n)(&(n)->i_key.nk)
766#define gval(n)(&(n)->i_val)
767#define gnext(n)((n)->i_key.nk.next)
768#define key2tval(n)(&(n)->i_key.tvk)
769static TValue*luaH_setnum(lua_State*L,Table*t,int key);
770static const TValue*luaH_getstr(Table*t,TString*key);
771static TValue*luaH_set(lua_State*L,Table*t,const TValue*key);
772static const char*const luaT_typenames[]={
773"nil","boolean","userdata","number",
774"string","table","function","userdata","thread",
775"proto","upval"
776};
777static void luaT_init(lua_State*L){
778static const char*const luaT_eventname[]={
779"__index","__newindex",
780"__gc","__mode","__eq",
781"__add","__sub","__mul","__div","__mod",
782"__pow","__unm","__len","__lt","__le",
783"__concat","__call"
784};
785int i;
786for(i=0;i<TM_N;i++){
787G(L)->tmname[i]=luaS_new(L,luaT_eventname[i]);
788luaS_fix(G(L)->tmname[i]);
789}
790}
791static const TValue*luaT_gettm(Table*events,TMS event,TString*ename){
792const TValue*tm=luaH_getstr(events,ename);
793if(ttisnil(tm)){
794events->flags|=cast_byte(1u<<event);
795return NULL;
796}
797else return tm;
798}
799static const TValue*luaT_gettmbyobj(lua_State*L,const TValue*o,TMS event){
800Table*mt;
801switch(ttype(o)){
802case 5:
803mt=hvalue(o)->metatable;
804break;
805case 7:
806mt=uvalue(o)->metatable;
807break;
808default:
809mt=G(L)->mt[ttype(o)];
810}
811return(mt?luaH_getstr(mt,G(L)->tmname[event]):(&luaO_nilobject_));
812}
813#define sizeCclosure(n)(cast(int,sizeof(CClosure))+cast(int,sizeof(TValue)*((n)-1)))
814#define sizeLclosure(n)(cast(int,sizeof(LClosure))+cast(int,sizeof(TValue*)*((n)-1)))
815static Closure*luaF_newCclosure(lua_State*L,int nelems,Table*e){
816Closure*c=cast(Closure*,luaM_malloc(L,sizeCclosure(nelems)));
817luaC_link(L,obj2gco(c),6);
818c->c.isC=1;
819c->c.env=e;
820c->c.nupvalues=cast_byte(nelems);
821return c;
822}
823static Closure*luaF_newLclosure(lua_State*L,int nelems,Table*e){
824Closure*c=cast(Closure*,luaM_malloc(L,sizeLclosure(nelems)));
825luaC_link(L,obj2gco(c),6);
826c->l.isC=0;
827c->l.env=e;
828c->l.nupvalues=cast_byte(nelems);
829while(nelems--)c->l.upvals[nelems]=NULL;
830return c;
831}
832static UpVal*luaF_newupval(lua_State*L){
833UpVal*uv=luaM_new(L,UpVal);
834luaC_link(L,obj2gco(uv),(8+2));
835uv->v=&uv->u.value;
836setnilvalue(uv->v);
837return uv;
838}
839static UpVal*luaF_findupval(lua_State*L,StkId level){
840global_State*g=G(L);
841GCObject**pp=&L->openupval;
842UpVal*p;
843UpVal*uv;
844while(*pp!=NULL&&(p=ngcotouv(*pp))->v>=level){
845if(p->v==level){
846if(isdead(g,obj2gco(p)))
847changewhite(obj2gco(p));
848return p;
849}
850pp=&p->next;
851}
852uv=luaM_new(L,UpVal);
853uv->tt=(8+2);
854uv->marked=luaC_white(g);
855uv->v=level;
856uv->next=*pp;
857*pp=obj2gco(uv);
858uv->u.l.prev=&g->uvhead;
859uv->u.l.next=g->uvhead.u.l.next;
860uv->u.l.next->u.l.prev=uv;
861g->uvhead.u.l.next=uv;
862return uv;
863}
864static void unlinkupval(UpVal*uv){
865uv->u.l.next->u.l.prev=uv->u.l.prev;
866uv->u.l.prev->u.l.next=uv->u.l.next;
867}
868static void luaF_freeupval(lua_State*L,UpVal*uv){
869if(uv->v!=&uv->u.value)
870unlinkupval(uv);
871luaM_free(L,uv);
872}
873static void luaF_close(lua_State*L,StkId level){
874UpVal*uv;
875global_State*g=G(L);
876while(L->openupval!=NULL&&(uv=ngcotouv(L->openupval))->v>=level){
877GCObject*o=obj2gco(uv);
878L->openupval=uv->next;
879if(isdead(g,o))
880luaF_freeupval(L,uv);
881else{
882unlinkupval(uv);
883setobj(L,&uv->u.value,uv->v);
884uv->v=&uv->u.value;
885luaC_linkupval(L,uv);
886}
887}
888}
889static Proto*luaF_newproto(lua_State*L){
890Proto*f=luaM_new(L,Proto);
891luaC_link(L,obj2gco(f),(8+1));
892f->k=NULL;
893f->sizek=0;
894f->p=NULL;
895f->sizep=0;
896f->code=NULL;
897f->sizecode=0;
898f->sizelineinfo=0;
899f->sizeupvalues=0;
900f->nups=0;
901f->upvalues=NULL;
902f->numparams=0;
903f->is_vararg=0;
904f->maxstacksize=0;
905f->lineinfo=NULL;
906f->sizelocvars=0;
907f->locvars=NULL;
908f->linedefined=0;
909f->lastlinedefined=0;
910f->source=NULL;
911return f;
912}
913static void luaF_freeproto(lua_State*L,Proto*f){
914luaM_freearray(L,f->code,f->sizecode,Instruction);
915luaM_freearray(L,f->p,f->sizep,Proto*);
916luaM_freearray(L,f->k,f->sizek,TValue);
917luaM_freearray(L,f->lineinfo,f->sizelineinfo,int);
918luaM_freearray(L,f->locvars,f->sizelocvars,struct LocVar);
919luaM_freearray(L,f->upvalues,f->sizeupvalues,TString*);
920luaM_free(L,f);
921}
922static void luaF_freeclosure(lua_State*L,Closure*c){
923int size=(c->c.isC)?sizeCclosure(c->c.nupvalues):
924sizeLclosure(c->l.nupvalues);
925luaM_freemem(L,c,size);
926}
927#define MASK1(n,p)((~((~(Instruction)0)<<n))<<p)
928#define MASK0(n,p)(~MASK1(n,p))
929#define GET_OPCODE(i)(cast(OpCode,((i)>>0)&MASK1(6,0)))
930#define SET_OPCODE(i,o)((i)=(((i)&MASK0(6,0))|((cast(Instruction,o)<<0)&MASK1(6,0))))
931#define GETARG_A(i)(cast(int,((i)>>(0+6))&MASK1(8,0)))
932#define SETARG_A(i,u)((i)=(((i)&MASK0(8,(0+6)))|((cast(Instruction,u)<<(0+6))&MASK1(8,(0+6)))))
933#define GETARG_B(i)(cast(int,((i)>>(((0+6)+8)+9))&MASK1(9,0)))
934#define SETARG_B(i,b)((i)=(((i)&MASK0(9,(((0+6)+8)+9)))|((cast(Instruction,b)<<(((0+6)+8)+9))&MASK1(9,(((0+6)+8)+9)))))
935#define GETARG_C(i)(cast(int,((i)>>((0+6)+8))&MASK1(9,0)))
936#define SETARG_C(i,b)((i)=(((i)&MASK0(9,((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1(9,((0+6)+8)))))
937#define GETARG_Bx(i)(cast(int,((i)>>((0+6)+8))&MASK1((9+9),0)))
938#define SETARG_Bx(i,b)((i)=(((i)&MASK0((9+9),((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1((9+9),((0+6)+8)))))
939#define GETARG_sBx(i)(GETARG_Bx(i)-(((1<<(9+9))-1)>>1))
940#define SETARG_sBx(i,b)SETARG_Bx((i),cast(unsigned int,(b)+(((1<<(9+9))-1)>>1)))
941#define CREATE_ABC(o,a,b,c)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,b)<<(((0+6)+8)+9))|(cast(Instruction,c)<<((0+6)+8)))
942#define CREATE_ABx(o,a,bc)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,bc)<<((0+6)+8)))
943#define ISK(x)((x)&(1<<(9-1)))
944#define INDEXK(r)((int)(r)&~(1<<(9-1)))
945#define RKASK(x)((x)|(1<<(9-1)))
946static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)];
947#define getBMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>4)&3))
948#define getCMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>2)&3))
949#define testTMode(m)(luaP_opmodes[m]&(1<<7))
950typedef struct expdesc{
951expkind k;
952union{
953struct{int info,aux;}s;
954lua_Number nval;
955}u;
956int t;
957int f;
958}expdesc;
959typedef struct upvaldesc{
960lu_byte k;
961lu_byte info;
962}upvaldesc;
963struct BlockCnt;
964typedef struct FuncState{
965Proto*f;
966Table*h;
967struct FuncState*prev;
968struct LexState*ls;
969struct lua_State*L;
970struct BlockCnt*bl;
971int pc;
972int lasttarget;
973int jpc;
974int freereg;
975int nk;
976int np;
977short nlocvars;
978lu_byte nactvar;
979upvaldesc upvalues[60];
980unsigned short actvar[200];
981}FuncState;
982static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff,
983const char*name);
984struct lua_longjmp{
985struct lua_longjmp*previous;
986jmp_buf b;
987volatile int status;
988};
989static void luaD_seterrorobj(lua_State*L,int errcode,StkId oldtop){
990switch(errcode){
991case 4:{
992setsvalue(L,oldtop,luaS_newliteral(L,"not enough memory"));
993break;
994}
995case 5:{
996setsvalue(L,oldtop,luaS_newliteral(L,"error in error handling"));
997break;
998}
999case 3:
1000case 2:{
1001setobj(L,oldtop,L->top-1);
1002break;
1003}
1004}
1005L->top=oldtop+1;
1006}
1007static void restore_stack_limit(lua_State*L){
1008if(L->size_ci>20000){
1009int inuse=cast_int(L->ci-L->base_ci);
1010if(inuse+1<20000)
1011luaD_reallocCI(L,20000);
1012}
1013}
1014static void resetstack(lua_State*L,int status){
1015L->ci=L->base_ci;
1016L->base=L->ci->base;
1017luaF_close(L,L->base);
1018luaD_seterrorobj(L,status,L->base);
1019L->nCcalls=L->baseCcalls;
1020L->allowhook=1;
1021restore_stack_limit(L);
1022L->errfunc=0;
1023L->errorJmp=NULL;
1024}
1025static void luaD_throw(lua_State*L,int errcode){
1026if(L->errorJmp){
1027L->errorJmp->status=errcode;
1028LUAI_THROW(L,L->errorJmp);
1029}
1030else{
1031L->status=cast_byte(errcode);
1032if(G(L)->panic){
1033resetstack(L,errcode);
1034G(L)->panic(L);
1035}
1036exit(EXIT_FAILURE);
1037}
1038}
1039static int luaD_rawrunprotected(lua_State*L,Pfunc f,void*ud){
1040struct lua_longjmp lj;
1041lj.status=0;
1042lj.previous=L->errorJmp;
1043L->errorJmp=&lj;
1044LUAI_TRY(L,&lj,
1045(*f)(L,ud);
1046);
1047L->errorJmp=lj.previous;
1048return lj.status;
1049}
1050static void correctstack(lua_State*L,TValue*oldstack){
1051CallInfo*ci;
1052GCObject*up;
1053L->top=(L->top-oldstack)+L->stack;
1054for(up=L->openupval;up!=NULL;up=up->gch.next)
1055gco2uv(up)->v=(gco2uv(up)->v-oldstack)+L->stack;
1056for(ci=L->base_ci;ci<=L->ci;ci++){
1057ci->top=(ci->top-oldstack)+L->stack;
1058ci->base=(ci->base-oldstack)+L->stack;
1059ci->func=(ci->func-oldstack)+L->stack;
1060}
1061L->base=(L->base-oldstack)+L->stack;
1062}
1063static void luaD_reallocstack(lua_State*L,int newsize){
1064TValue*oldstack=L->stack;
1065int realsize=newsize+1+5;
1066luaM_reallocvector(L,L->stack,L->stacksize,realsize,TValue);
1067L->stacksize=realsize;
1068L->stack_last=L->stack+newsize;
1069correctstack(L,oldstack);
1070}
1071static void luaD_reallocCI(lua_State*L,int newsize){
1072CallInfo*oldci=L->base_ci;
1073luaM_reallocvector(L,L->base_ci,L->size_ci,newsize,CallInfo);
1074L->size_ci=newsize;
1075L->ci=(L->ci-oldci)+L->base_ci;
1076L->end_ci=L->base_ci+L->size_ci-1;
1077}
1078static void luaD_growstack(lua_State*L,int n){
1079if(n<=L->stacksize)
1080luaD_reallocstack(L,2*L->stacksize);
1081else
1082luaD_reallocstack(L,L->stacksize+n);
1083}
1084static CallInfo*growCI(lua_State*L){
1085if(L->size_ci>20000)
1086luaD_throw(L,5);
1087else{
1088luaD_reallocCI(L,2*L->size_ci);
1089if(L->size_ci>20000)
1090luaG_runerror(L,"stack overflow");
1091}
1092return++L->ci;
1093}
1094static StkId adjust_varargs(lua_State*L,Proto*p,int actual){
1095int i;
1096int nfixargs=p->numparams;
1097Table*htab=NULL;
1098StkId base,fixed;
1099for(;actual<nfixargs;++actual)
1100setnilvalue(L->top++);
1101fixed=L->top-actual;
1102base=L->top;
1103for(i=0;i<nfixargs;i++){
1104setobj(L,L->top++,fixed+i);
1105setnilvalue(fixed+i);
1106}
1107if(htab){
1108sethvalue(L,L->top++,htab);
1109}
1110return base;
1111}
1112static StkId tryfuncTM(lua_State*L,StkId func){
1113const TValue*tm=luaT_gettmbyobj(L,func,TM_CALL);
1114StkId p;
1115ptrdiff_t funcr=savestack(L,func);
1116if(!ttisfunction(tm))
1117luaG_typeerror(L,func,"call");
1118for(p=L->top;p>func;p--)setobj(L,p,p-1);
1119incr_top(L);
1120func=restorestack(L,funcr);
1121setobj(L,func,tm);
1122return func;
1123}
1124#define inc_ci(L)((L->ci==L->end_ci)?growCI(L):(condhardstacktests(luaD_reallocCI(L,L->size_ci)),++L->ci))
1125static int luaD_precall(lua_State*L,StkId func,int nresults){
1126LClosure*cl;
1127ptrdiff_t funcr;
1128if(!ttisfunction(func))
1129func=tryfuncTM(L,func);
1130funcr=savestack(L,func);
1131cl=&clvalue(func)->l;
1132L->ci->savedpc=L->savedpc;
1133if(!cl->isC){
1134CallInfo*ci;
1135StkId st,base;
1136Proto*p=cl->p;
1137luaD_checkstack(L,p->maxstacksize);
1138func=restorestack(L,funcr);
1139if(!p->is_vararg){
1140base=func+1;
1141if(L->top>base+p->numparams)
1142L->top=base+p->numparams;
1143}
1144else{
1145int nargs=cast_int(L->top-func)-1;
1146base=adjust_varargs(L,p,nargs);
1147func=restorestack(L,funcr);
1148}
1149ci=inc_ci(L);
1150ci->func=func;
1151L->base=ci->base=base;
1152ci->top=L->base+p->maxstacksize;
1153L->savedpc=p->code;
1154ci->tailcalls=0;
1155ci->nresults=nresults;
1156for(st=L->top;st<ci->top;st++)
1157setnilvalue(st);
1158L->top=ci->top;
1159return 0;
1160}
1161else{
1162CallInfo*ci;
1163int n;
1164luaD_checkstack(L,20);
1165ci=inc_ci(L);
1166ci->func=restorestack(L,funcr);
1167L->base=ci->base=ci->func+1;
1168ci->top=L->top+20;
1169ci->nresults=nresults;
1170n=(*curr_func(L)->c.f)(L);
1171if(n<0)
1172return 2;
1173else{
1174luaD_poscall(L,L->top-n);
1175return 1;
1176}
1177}
1178}
1179static int luaD_poscall(lua_State*L,StkId firstResult){
1180StkId res;
1181int wanted,i;
1182CallInfo*ci;
1183ci=L->ci--;
1184res=ci->func;
1185wanted=ci->nresults;
1186L->base=(ci-1)->base;
1187L->savedpc=(ci-1)->savedpc;
1188for(i=wanted;i!=0&&firstResult<L->top;i--)
1189setobj(L,res++,firstResult++);
1190while(i-->0)
1191setnilvalue(res++);
1192L->top=res;
1193return(wanted-(-1));
1194}
1195static void luaD_call(lua_State*L,StkId func,int nResults){
1196if(++L->nCcalls>=200){
1197if(L->nCcalls==200)
1198luaG_runerror(L,"C stack overflow");
1199else if(L->nCcalls>=(200+(200>>3)))
1200luaD_throw(L,5);
1201}
1202if(luaD_precall(L,func,nResults)==0)
1203luaV_execute(L,1);
1204L->nCcalls--;
1205luaC_checkGC(L);
1206}
1207static int luaD_pcall(lua_State*L,Pfunc func,void*u,
1208ptrdiff_t old_top,ptrdiff_t ef){
1209int status;
1210unsigned short oldnCcalls=L->nCcalls;
1211ptrdiff_t old_ci=saveci(L,L->ci);
1212lu_byte old_allowhooks=L->allowhook;
1213ptrdiff_t old_errfunc=L->errfunc;
1214L->errfunc=ef;
1215status=luaD_rawrunprotected(L,func,u);
1216if(status!=0){
1217StkId oldtop=restorestack(L,old_top);
1218luaF_close(L,oldtop);
1219luaD_seterrorobj(L,status,oldtop);
1220L->nCcalls=oldnCcalls;
1221L->ci=restoreci(L,old_ci);
1222L->base=L->ci->base;
1223L->savedpc=L->ci->savedpc;
1224L->allowhook=old_allowhooks;
1225restore_stack_limit(L);
1226}
1227L->errfunc=old_errfunc;
1228return status;
1229}
1230struct SParser{
1231ZIO*z;
1232Mbuffer buff;
1233const char*name;
1234};
1235static void f_parser(lua_State*L,void*ud){
1236int i;
1237Proto*tf;
1238Closure*cl;
1239struct SParser*p=cast(struct SParser*,ud);
1240luaC_checkGC(L);
1241tf=luaY_parser(L,p->z,
1242&p->buff,p->name);
1243cl=luaF_newLclosure(L,tf->nups,hvalue(gt(L)));
1244cl->l.p=tf;
1245for(i=0;i<tf->nups;i++)
1246cl->l.upvals[i]=luaF_newupval(L);
1247setclvalue(L,L->top,cl);
1248incr_top(L);
1249}
1250static int luaD_protectedparser(lua_State*L,ZIO*z,const char*name){
1251struct SParser p;
1252int status;
1253p.z=z;p.name=name;
1254luaZ_initbuffer(L,&p.buff);
1255status=luaD_pcall(L,f_parser,&p,savestack(L,L->top),L->errfunc);
1256luaZ_freebuffer(L,&p.buff);
1257return status;
1258}
1259static void luaS_resize(lua_State*L,int newsize){
1260GCObject**newhash;
1261stringtable*tb;
1262int i;
1263if(G(L)->gcstate==2)
1264return;
1265newhash=luaM_newvector(L,newsize,GCObject*);
1266tb=&G(L)->strt;
1267for(i=0;i<newsize;i++)newhash[i]=NULL;
1268for(i=0;i<tb->size;i++){
1269GCObject*p=tb->hash[i];
1270while(p){
1271GCObject*next=p->gch.next;
1272unsigned int h=gco2ts(p)->hash;
1273int h1=lmod(h,newsize);
1274p->gch.next=newhash[h1];
1275newhash[h1]=p;
1276p=next;
1277}
1278}
1279luaM_freearray(L,tb->hash,tb->size,TString*);
1280tb->size=newsize;
1281tb->hash=newhash;
1282}
1283static TString*newlstr(lua_State*L,const char*str,size_t l,
1284unsigned int h){
1285TString*ts;
1286stringtable*tb;
1287if(l+1>(((size_t)(~(size_t)0)-2)-sizeof(TString))/sizeof(char))
1288luaM_toobig(L);
1289ts=cast(TString*,luaM_malloc(L,(l+1)*sizeof(char)+sizeof(TString)));
1290ts->tsv.len=l;
1291ts->tsv.hash=h;
1292ts->tsv.marked=luaC_white(G(L));
1293ts->tsv.tt=4;
1294ts->tsv.reserved=0;
1295memcpy(ts+1,str,l*sizeof(char));
1296((char*)(ts+1))[l]='\0';
1297tb=&G(L)->strt;
1298h=lmod(h,tb->size);
1299ts->tsv.next=tb->hash[h];
1300tb->hash[h]=obj2gco(ts);
1301tb->nuse++;
1302if(tb->nuse>cast(lu_int32,tb->size)&&tb->size<=(INT_MAX-2)/2)
1303luaS_resize(L,tb->size*2);
1304return ts;
1305}
1306static TString*luaS_newlstr(lua_State*L,const char*str,size_t l){
1307GCObject*o;
1308unsigned int h=cast(unsigned int,l);
1309size_t step=(l>>5)+1;
1310size_t l1;
1311for(l1=l;l1>=step;l1-=step)
1312h=h^((h<<5)+(h>>2)+cast(unsigned char,str[l1-1]));
1313for(o=G(L)->strt.hash[lmod(h,G(L)->strt.size)];
1314o!=NULL;
1315o=o->gch.next){
1316TString*ts=rawgco2ts(o);
1317if(ts->tsv.len==l&&(memcmp(str,getstr(ts),l)==0)){
1318if(isdead(G(L),o))changewhite(o);
1319return ts;
1320}
1321}
1322return newlstr(L,str,l,h);
1323}
1324static Udata*luaS_newudata(lua_State*L,size_t s,Table*e){
1325Udata*u;
1326if(s>((size_t)(~(size_t)0)-2)-sizeof(Udata))
1327luaM_toobig(L);
1328u=cast(Udata*,luaM_malloc(L,s+sizeof(Udata)));
1329u->uv.marked=luaC_white(G(L));
1330u->uv.tt=7;
1331u->uv.len=s;
1332u->uv.metatable=NULL;
1333u->uv.env=e;
1334u->uv.next=G(L)->mainthread->next;
1335G(L)->mainthread->next=obj2gco(u);
1336return u;
1337}
1338#define hashpow2(t,n)(gnode(t,lmod((n),sizenode(t))))
1339#define hashstr(t,str)hashpow2(t,(str)->tsv.hash)
1340#define hashboolean(t,p)hashpow2(t,p)
1341#define hashmod(t,n)(gnode(t,((n)%((sizenode(t)-1)|1))))
1342#define hashpointer(t,p)hashmod(t,IntPoint(p))
1343static const Node dummynode_={
1344{{NULL},0},
1345{{{NULL},0,NULL}}
1346};
1347static Node*hashnum(const Table*t,lua_Number n){
1348unsigned int a[cast_int(sizeof(lua_Number)/sizeof(int))];
1349int i;
1350if(luai_numeq(n,0))
1351return gnode(t,0);
1352memcpy(a,&n,sizeof(a));
1353for(i=1;i<cast_int(sizeof(lua_Number)/sizeof(int));i++)a[0]+=a[i];
1354return hashmod(t,a[0]);
1355}
1356static Node*mainposition(const Table*t,const TValue*key){
1357switch(ttype(key)){
1358case 3:
1359return hashnum(t,nvalue(key));
1360case 4:
1361return hashstr(t,rawtsvalue(key));
1362case 1:
1363return hashboolean(t,bvalue(key));
1364case 2:
1365return hashpointer(t,pvalue(key));
1366default:
1367return hashpointer(t,gcvalue(key));
1368}
1369}
1370static int arrayindex(const TValue*key){
1371if(ttisnumber(key)){
1372lua_Number n=nvalue(key);
1373int k;
1374lua_number2int(k,n);
1375if(luai_numeq(cast_num(k),n))
1376return k;
1377}
1378return-1;
1379}
1380static int findindex(lua_State*L,Table*t,StkId key){
1381int i;
1382if(ttisnil(key))return-1;
1383i=arrayindex(key);
1384if(0<i&&i<=t->sizearray)
1385return i-1;
1386else{
1387Node*n=mainposition(t,key);
1388do{
1389if(luaO_rawequalObj(key2tval(n),key)||
1390(ttype(gkey(n))==(8+3)&&iscollectable(key)&&
1391gcvalue(gkey(n))==gcvalue(key))){
1392i=cast_int(n-gnode(t,0));
1393return i+t->sizearray;
1394}
1395else n=gnext(n);
1396}while(n);
1397luaG_runerror(L,"invalid key to "LUA_QL("next"));
1398return 0;
1399}
1400}
1401static int luaH_next(lua_State*L,Table*t,StkId key){
1402int i=findindex(L,t,key);
1403for(i++;i<t->sizearray;i++){
1404if(!ttisnil(&t->array[i])){
1405setnvalue(key,cast_num(i+1));
1406setobj(L,key+1,&t->array[i]);
1407return 1;
1408}
1409}
1410for(i-=t->sizearray;i<(int)sizenode(t);i++){
1411if(!ttisnil(gval(gnode(t,i)))){
1412setobj(L,key,key2tval(gnode(t,i)));
1413setobj(L,key+1,gval(gnode(t,i)));
1414return 1;
1415}
1416}
1417return 0;
1418}
1419static int computesizes(int nums[],int*narray){
1420int i;
1421int twotoi;
1422int a=0;
1423int na=0;
1424int n=0;
1425for(i=0,twotoi=1;twotoi/2<*narray;i++,twotoi*=2){
1426if(nums[i]>0){
1427a+=nums[i];
1428if(a>twotoi/2){
1429n=twotoi;
1430na=a;
1431}
1432}
1433if(a==*narray)break;
1434}
1435*narray=n;
1436return na;
1437}
1438static int countint(const TValue*key,int*nums){
1439int k=arrayindex(key);
1440if(0<k&&k<=(1<<(32-2))){
1441nums[ceillog2(k)]++;
1442return 1;
1443}
1444else
1445return 0;
1446}
1447static int numusearray(const Table*t,int*nums){
1448int lg;
1449int ttlg;
1450int ause=0;
1451int i=1;
1452for(lg=0,ttlg=1;lg<=(32-2);lg++,ttlg*=2){
1453int lc=0;
1454int lim=ttlg;
1455if(lim>t->sizearray){
1456lim=t->sizearray;
1457if(i>lim)
1458break;
1459}
1460for(;i<=lim;i++){
1461if(!ttisnil(&t->array[i-1]))
1462lc++;
1463}
1464nums[lg]+=lc;
1465ause+=lc;
1466}
1467return ause;
1468}
1469static int numusehash(const Table*t,int*nums,int*pnasize){
1470int totaluse=0;
1471int ause=0;
1472int i=sizenode(t);
1473while(i--){
1474Node*n=&t->node[i];
1475if(!ttisnil(gval(n))){
1476ause+=countint(key2tval(n),nums);
1477totaluse++;
1478}
1479}
1480*pnasize+=ause;
1481return totaluse;
1482}
1483static void setarrayvector(lua_State*L,Table*t,int size){
1484int i;
1485luaM_reallocvector(L,t->array,t->sizearray,size,TValue);
1486for(i=t->sizearray;i<size;i++)
1487setnilvalue(&t->array[i]);
1488t->sizearray=size;
1489}
1490static void setnodevector(lua_State*L,Table*t,int size){
1491int lsize;
1492if(size==0){
1493t->node=cast(Node*,(&dummynode_));
1494lsize=0;
1495}
1496else{
1497int i;
1498lsize=ceillog2(size);
1499if(lsize>(32-2))
1500luaG_runerror(L,"table overflow");
1501size=twoto(lsize);
1502t->node=luaM_newvector(L,size,Node);
1503for(i=0;i<size;i++){
1504Node*n=gnode(t,i);
1505gnext(n)=NULL;
1506setnilvalue(gkey(n));
1507setnilvalue(gval(n));
1508}
1509}
1510t->lsizenode=cast_byte(lsize);
1511t->lastfree=gnode(t,size);
1512}
1513static void resize(lua_State*L,Table*t,int nasize,int nhsize){
1514int i;
1515int oldasize=t->sizearray;
1516int oldhsize=t->lsizenode;
1517Node*nold=t->node;
1518if(nasize>oldasize)
1519setarrayvector(L,t,nasize);
1520setnodevector(L,t,nhsize);
1521if(nasize<oldasize){
1522t->sizearray=nasize;
1523for(i=nasize;i<oldasize;i++){
1524if(!ttisnil(&t->array[i]))
1525setobj(L,luaH_setnum(L,t,i+1),&t->array[i]);
1526}
1527luaM_reallocvector(L,t->array,oldasize,nasize,TValue);
1528}
1529for(i=twoto(oldhsize)-1;i>=0;i--){
1530Node*old=nold+i;
1531if(!ttisnil(gval(old)))
1532setobj(L,luaH_set(L,t,key2tval(old)),gval(old));
1533}
1534if(nold!=(&dummynode_))
1535luaM_freearray(L,nold,twoto(oldhsize),Node);
1536}
1537static void luaH_resizearray(lua_State*L,Table*t,int nasize){
1538int nsize=(t->node==(&dummynode_))?0:sizenode(t);
1539resize(L,t,nasize,nsize);
1540}
1541static void rehash(lua_State*L,Table*t,const TValue*ek){
1542int nasize,na;
1543int nums[(32-2)+1];
1544int i;
1545int totaluse;
1546for(i=0;i<=(32-2);i++)nums[i]=0;
1547nasize=numusearray(t,nums);
1548totaluse=nasize;
1549totaluse+=numusehash(t,nums,&nasize);
1550nasize+=countint(ek,nums);
1551totaluse++;
1552na=computesizes(nums,&nasize);
1553resize(L,t,nasize,totaluse-na);
1554}
1555static Table*luaH_new(lua_State*L,int narray,int nhash){
1556Table*t=luaM_new(L,Table);
1557luaC_link(L,obj2gco(t),5);
1558t->metatable=NULL;
1559t->flags=cast_byte(~0);
1560t->array=NULL;
1561t->sizearray=0;
1562t->lsizenode=0;
1563t->node=cast(Node*,(&dummynode_));
1564setarrayvector(L,t,narray);
1565setnodevector(L,t,nhash);
1566return t;
1567}
1568static void luaH_free(lua_State*L,Table*t){
1569if(t->node!=(&dummynode_))
1570luaM_freearray(L,t->node,sizenode(t),Node);
1571luaM_freearray(L,t->array,t->sizearray,TValue);
1572luaM_free(L,t);
1573}
1574static Node*getfreepos(Table*t){
1575while(t->lastfree-->t->node){
1576if(ttisnil(gkey(t->lastfree)))
1577return t->lastfree;
1578}
1579return NULL;
1580}
1581static TValue*newkey(lua_State*L,Table*t,const TValue*key){
1582Node*mp=mainposition(t,key);
1583if(!ttisnil(gval(mp))||mp==(&dummynode_)){
1584Node*othern;
1585Node*n=getfreepos(t);
1586if(n==NULL){
1587rehash(L,t,key);
1588return luaH_set(L,t,key);
1589}
1590othern=mainposition(t,key2tval(mp));
1591if(othern!=mp){
1592while(gnext(othern)!=mp)othern=gnext(othern);
1593gnext(othern)=n;
1594*n=*mp;
1595gnext(mp)=NULL;
1596setnilvalue(gval(mp));
1597}
1598else{
1599gnext(n)=gnext(mp);
1600gnext(mp)=n;
1601mp=n;
1602}
1603}
1604gkey(mp)->value=key->value;gkey(mp)->tt=key->tt;
1605luaC_barriert(L,t,key);
1606return gval(mp);
1607}
1608static const TValue*luaH_getnum(Table*t,int key){
1609if(cast(unsigned int,key)-1<cast(unsigned int,t->sizearray))
1610return&t->array[key-1];
1611else{
1612lua_Number nk=cast_num(key);
1613Node*n=hashnum(t,nk);
1614do{
1615if(ttisnumber(gkey(n))&&luai_numeq(nvalue(gkey(n)),nk))
1616return gval(n);
1617else n=gnext(n);
1618}while(n);
1619return(&luaO_nilobject_);
1620}
1621}
1622static const TValue*luaH_getstr(Table*t,TString*key){
1623Node*n=hashstr(t,key);
1624do{
1625if(ttisstring(gkey(n))&&rawtsvalue(gkey(n))==key)
1626return gval(n);
1627else n=gnext(n);
1628}while(n);
1629return(&luaO_nilobject_);
1630}
1631static const TValue*luaH_get(Table*t,const TValue*key){
1632switch(ttype(key)){
1633case 0:return(&luaO_nilobject_);
1634case 4:return luaH_getstr(t,rawtsvalue(key));
1635case 3:{
1636int k;
1637lua_Number n=nvalue(key);
1638lua_number2int(k,n);
1639if(luai_numeq(cast_num(k),nvalue(key)))
1640return luaH_getnum(t,k);
1641}
1642default:{
1643Node*n=mainposition(t,key);
1644do{
1645if(luaO_rawequalObj(key2tval(n),key))
1646return gval(n);
1647else n=gnext(n);
1648}while(n);
1649return(&luaO_nilobject_);
1650}
1651}
1652}
1653static TValue*luaH_set(lua_State*L,Table*t,const TValue*key){
1654const TValue*p=luaH_get(t,key);
1655t->flags=0;
1656if(p!=(&luaO_nilobject_))
1657return cast(TValue*,p);
1658else{
1659if(ttisnil(key))luaG_runerror(L,"table index is nil");
1660else if(ttisnumber(key)&&luai_numisnan(nvalue(key)))
1661luaG_runerror(L,"table index is NaN");
1662return newkey(L,t,key);
1663}
1664}
1665static TValue*luaH_setnum(lua_State*L,Table*t,int key){
1666const TValue*p=luaH_getnum(t,key);
1667if(p!=(&luaO_nilobject_))
1668return cast(TValue*,p);
1669else{
1670TValue k;
1671setnvalue(&k,cast_num(key));
1672return newkey(L,t,&k);
1673}
1674}
1675static TValue*luaH_setstr(lua_State*L,Table*t,TString*key){
1676const TValue*p=luaH_getstr(t,key);
1677if(p!=(&luaO_nilobject_))
1678return cast(TValue*,p);
1679else{
1680TValue k;
1681setsvalue(L,&k,key);
1682return newkey(L,t,&k);
1683}
1684}
1685static int unbound_search(Table*t,unsigned int j){
1686unsigned int i=j;
1687j++;
1688while(!ttisnil(luaH_getnum(t,j))){
1689i=j;
1690j*=2;
1691if(j>cast(unsigned int,(INT_MAX-2))){
1692i=1;
1693while(!ttisnil(luaH_getnum(t,i)))i++;
1694return i-1;
1695}
1696}
1697while(j-i>1){
1698unsigned int m=(i+j)/2;
1699if(ttisnil(luaH_getnum(t,m)))j=m;
1700else i=m;
1701}
1702return i;
1703}
1704static int luaH_getn(Table*t){
1705unsigned int j=t->sizearray;
1706if(j>0&&ttisnil(&t->array[j-1])){
1707unsigned int i=0;
1708while(j-i>1){
1709unsigned int m=(i+j)/2;
1710if(ttisnil(&t->array[m-1]))j=m;
1711else i=m;
1712}
1713return i;
1714}
1715else if(t->node==(&dummynode_))
1716return j;
1717else return unbound_search(t,j);
1718}
1719#define makewhite(g,x)((x)->gch.marked=cast_byte(((x)->gch.marked&cast_byte(~(bitmask(2)|bit2mask(0,1))))|luaC_white(g)))
1720#define white2gray(x)reset2bits((x)->gch.marked,0,1)
1721#define black2gray(x)resetbit((x)->gch.marked,2)
1722#define stringmark(s)reset2bits((s)->tsv.marked,0,1)
1723#define isfinalized(u)testbit((u)->marked,3)
1724#define markfinalized(u)l_setbit((u)->marked,3)
1725#define markvalue(g,o){checkconsistency(o);if(iscollectable(o)&&iswhite(gcvalue(o)))reallymarkobject(g,gcvalue(o));}
1726#define markobject(g,t){if(iswhite(obj2gco(t)))reallymarkobject(g,obj2gco(t));}
1727#define setthreshold(g)(g->GCthreshold=(g->estimate/100)*g->gcpause)
1728static void removeentry(Node*n){
1729if(iscollectable(gkey(n)))
1730setttype(gkey(n),(8+3));
1731}
1732static void reallymarkobject(global_State*g,GCObject*o){
1733white2gray(o);
1734switch(o->gch.tt){
1735case 4:{
1736return;
1737}
1738case 7:{
1739Table*mt=gco2u(o)->metatable;
1740gray2black(o);
1741if(mt)markobject(g,mt);
1742markobject(g,gco2u(o)->env);
1743return;
1744}
1745case(8+2):{
1746UpVal*uv=gco2uv(o);
1747markvalue(g,uv->v);
1748if(uv->v==&uv->u.value)
1749gray2black(o);
1750return;
1751}
1752case 6:{
1753gco2cl(o)->c.gclist=g->gray;
1754g->gray=o;
1755break;
1756}
1757case 5:{
1758gco2h(o)->gclist=g->gray;
1759g->gray=o;
1760break;
1761}
1762case 8:{
1763gco2th(o)->gclist=g->gray;
1764g->gray=o;
1765break;
1766}
1767case(8+1):{
1768gco2p(o)->gclist=g->gray;
1769g->gray=o;
1770break;
1771}
1772default:;
1773}
1774}
1775static void marktmu(global_State*g){
1776GCObject*u=g->tmudata;
1777if(u){
1778do{
1779u=u->gch.next;
1780makewhite(g,u);
1781reallymarkobject(g,u);
1782}while(u!=g->tmudata);
1783}
1784}
1785static size_t luaC_separateudata(lua_State*L,int all){
1786global_State*g=G(L);
1787size_t deadmem=0;
1788GCObject**p=&g->mainthread->next;
1789GCObject*curr;
1790while((curr=*p)!=NULL){
1791if(!(iswhite(curr)||all)||isfinalized(gco2u(curr)))
1792p=&curr->gch.next;
1793else if(fasttm(L,gco2u(curr)->metatable,TM_GC)==NULL){
1794markfinalized(gco2u(curr));
1795p=&curr->gch.next;
1796}
1797else{
1798deadmem+=sizeudata(gco2u(curr));
1799markfinalized(gco2u(curr));
1800*p=curr->gch.next;
1801if(g->tmudata==NULL)
1802g->tmudata=curr->gch.next=curr;
1803else{
1804curr->gch.next=g->tmudata->gch.next;
1805g->tmudata->gch.next=curr;
1806g->tmudata=curr;
1807}
1808}
1809}
1810return deadmem;
1811}
1812static int traversetable(global_State*g,Table*h){
1813int i;
1814int weakkey=0;
1815int weakvalue=0;
1816const TValue*mode;
1817if(h->metatable)
1818markobject(g,h->metatable);
1819mode=gfasttm(g,h->metatable,TM_MODE);
1820if(mode&&ttisstring(mode)){
1821weakkey=(strchr(svalue(mode),'k')!=NULL);
1822weakvalue=(strchr(svalue(mode),'v')!=NULL);
1823if(weakkey||weakvalue){
1824h->marked&=~(bitmask(3)|bitmask(4));
1825h->marked|=cast_byte((weakkey<<3)|
1826(weakvalue<<4));
1827h->gclist=g->weak;
1828g->weak=obj2gco(h);
1829}
1830}
1831if(weakkey&&weakvalue)return 1;
1832if(!weakvalue){
1833i=h->sizearray;
1834while(i--)
1835markvalue(g,&h->array[i]);
1836}
1837i=sizenode(h);
1838while(i--){
1839Node*n=gnode(h,i);
1840if(ttisnil(gval(n)))
1841removeentry(n);
1842else{
1843if(!weakkey)markvalue(g,gkey(n));
1844if(!weakvalue)markvalue(g,gval(n));
1845}
1846}
1847return weakkey||weakvalue;
1848}
1849static void traverseproto(global_State*g,Proto*f){
1850int i;
1851if(f->source)stringmark(f->source);
1852for(i=0;i<f->sizek;i++)
1853markvalue(g,&f->k[i]);
1854for(i=0;i<f->sizeupvalues;i++){
1855if(f->upvalues[i])
1856stringmark(f->upvalues[i]);
1857}
1858for(i=0;i<f->sizep;i++){
1859if(f->p[i])
1860markobject(g,f->p[i]);
1861}
1862for(i=0;i<f->sizelocvars;i++){
1863if(f->locvars[i].varname)
1864stringmark(f->locvars[i].varname);
1865}
1866}
1867static void traverseclosure(global_State*g,Closure*cl){
1868markobject(g,cl->c.env);
1869if(cl->c.isC){
1870int i;
1871for(i=0;i<cl->c.nupvalues;i++)
1872markvalue(g,&cl->c.upvalue[i]);
1873}
1874else{
1875int i;
1876markobject(g,cl->l.p);
1877for(i=0;i<cl->l.nupvalues;i++)
1878markobject(g,cl->l.upvals[i]);
1879}
1880}
1881static void checkstacksizes(lua_State*L,StkId max){
1882int ci_used=cast_int(L->ci-L->base_ci);
1883int s_used=cast_int(max-L->stack);
1884if(L->size_ci>20000)
1885return;
1886if(4*ci_used<L->size_ci&&2*8<L->size_ci)
1887luaD_reallocCI(L,L->size_ci/2);
1888condhardstacktests(luaD_reallocCI(L,ci_used+1));
1889if(4*s_used<L->stacksize&&
18902*((2*20)+5)<L->stacksize)
1891luaD_reallocstack(L,L->stacksize/2);
1892condhardstacktests(luaD_reallocstack(L,s_used));
1893}
1894static void traversestack(global_State*g,lua_State*l){
1895StkId o,lim;
1896CallInfo*ci;
1897markvalue(g,gt(l));
1898lim=l->top;
1899for(ci=l->base_ci;ci<=l->ci;ci++){
1900if(lim<ci->top)lim=ci->top;
1901}
1902for(o=l->stack;o<l->top;o++)
1903markvalue(g,o);
1904for(;o<=lim;o++)
1905setnilvalue(o);
1906checkstacksizes(l,lim);
1907}
1908static l_mem propagatemark(global_State*g){
1909GCObject*o=g->gray;
1910gray2black(o);
1911switch(o->gch.tt){
1912case 5:{
1913Table*h=gco2h(o);
1914g->gray=h->gclist;
1915if(traversetable(g,h))
1916black2gray(o);
1917return sizeof(Table)+sizeof(TValue)*h->sizearray+
1918sizeof(Node)*sizenode(h);
1919}
1920case 6:{
1921Closure*cl=gco2cl(o);
1922g->gray=cl->c.gclist;
1923traverseclosure(g,cl);
1924return(cl->c.isC)?sizeCclosure(cl->c.nupvalues):
1925sizeLclosure(cl->l.nupvalues);
1926}
1927case 8:{
1928lua_State*th=gco2th(o);
1929g->gray=th->gclist;
1930th->gclist=g->grayagain;
1931g->grayagain=o;
1932black2gray(o);
1933traversestack(g,th);
1934return sizeof(lua_State)+sizeof(TValue)*th->stacksize+
1935sizeof(CallInfo)*th->size_ci;
1936}
1937case(8+1):{
1938Proto*p=gco2p(o);
1939g->gray=p->gclist;
1940traverseproto(g,p);
1941return sizeof(Proto)+sizeof(Instruction)*p->sizecode+
1942sizeof(Proto*)*p->sizep+
1943sizeof(TValue)*p->sizek+
1944sizeof(int)*p->sizelineinfo+
1945sizeof(LocVar)*p->sizelocvars+
1946sizeof(TString*)*p->sizeupvalues;
1947}
1948default:return 0;
1949}
1950}
1951static size_t propagateall(global_State*g){
1952size_t m=0;
1953while(g->gray)m+=propagatemark(g);
1954return m;
1955}
1956static int iscleared(const TValue*o,int iskey){
1957if(!iscollectable(o))return 0;
1958if(ttisstring(o)){
1959stringmark(rawtsvalue(o));
1960return 0;
1961}
1962return iswhite(gcvalue(o))||
1963(ttisuserdata(o)&&(!iskey&&isfinalized(uvalue(o))));
1964}
1965static void cleartable(GCObject*l){
1966while(l){
1967Table*h=gco2h(l);
1968int i=h->sizearray;
1969if(testbit(h->marked,4)){
1970while(i--){
1971TValue*o=&h->array[i];
1972if(iscleared(o,0))
1973setnilvalue(o);
1974}
1975}
1976i=sizenode(h);
1977while(i--){
1978Node*n=gnode(h,i);
1979if(!ttisnil(gval(n))&&
1980(iscleared(key2tval(n),1)||iscleared(gval(n),0))){
1981setnilvalue(gval(n));
1982removeentry(n);
1983}
1984}
1985l=h->gclist;
1986}
1987}
1988static void freeobj(lua_State*L,GCObject*o){
1989switch(o->gch.tt){
1990case(8+1):luaF_freeproto(L,gco2p(o));break;
1991case 6:luaF_freeclosure(L,gco2cl(o));break;
1992case(8+2):luaF_freeupval(L,gco2uv(o));break;
1993case 5:luaH_free(L,gco2h(o));break;
1994case 8:{
1995luaE_freethread(L,gco2th(o));
1996break;
1997}
1998case 4:{
1999G(L)->strt.nuse--;
2000luaM_freemem(L,o,sizestring(gco2ts(o)));
2001break;
2002}
2003case 7:{
2004luaM_freemem(L,o,sizeudata(gco2u(o)));
2005break;
2006}
2007default:;
2008}
2009}
2010#define sweepwholelist(L,p)sweeplist(L,p,((lu_mem)(~(lu_mem)0)-2))
2011static GCObject**sweeplist(lua_State*L,GCObject**p,lu_mem count){
2012GCObject*curr;
2013global_State*g=G(L);
2014int deadmask=otherwhite(g);
2015while((curr=*p)!=NULL&&count-->0){
2016if(curr->gch.tt==8)
2017sweepwholelist(L,&gco2th(curr)->openupval);
2018if((curr->gch.marked^bit2mask(0,1))&deadmask){
2019makewhite(g,curr);
2020p=&curr->gch.next;
2021}
2022else{
2023*p=curr->gch.next;
2024if(curr==g->rootgc)
2025g->rootgc=curr->gch.next;
2026freeobj(L,curr);
2027}
2028}
2029return p;
2030}
2031static void checkSizes(lua_State*L){
2032global_State*g=G(L);
2033if(g->strt.nuse<cast(lu_int32,g->strt.size/4)&&
2034g->strt.size>32*2)
2035luaS_resize(L,g->strt.size/2);
2036if(luaZ_sizebuffer(&g->buff)>32*2){
2037size_t newsize=luaZ_sizebuffer(&g->buff)/2;
2038luaZ_resizebuffer(L,&g->buff,newsize);
2039}
2040}
2041static void GCTM(lua_State*L){
2042global_State*g=G(L);
2043GCObject*o=g->tmudata->gch.next;
2044Udata*udata=rawgco2u(o);
2045const TValue*tm;
2046if(o==g->tmudata)
2047g->tmudata=NULL;
2048else
2049g->tmudata->gch.next=udata->uv.next;
2050udata->uv.next=g->mainthread->next;
2051g->mainthread->next=o;
2052makewhite(g,o);
2053tm=fasttm(L,udata->uv.metatable,TM_GC);
2054if(tm!=NULL){
2055lu_byte oldah=L->allowhook;
2056lu_mem oldt=g->GCthreshold;
2057L->allowhook=0;
2058g->GCthreshold=2*g->totalbytes;
2059setobj(L,L->top,tm);
2060setuvalue(L,L->top+1,udata);
2061L->top+=2;
2062luaD_call(L,L->top-2,0);
2063L->allowhook=oldah;
2064g->GCthreshold=oldt;
2065}
2066}
2067static void luaC_callGCTM(lua_State*L){
2068while(G(L)->tmudata)
2069GCTM(L);
2070}
2071static void luaC_freeall(lua_State*L){
2072global_State*g=G(L);
2073int i;
2074g->currentwhite=bit2mask(0,1)|bitmask(6);
2075sweepwholelist(L,&g->rootgc);
2076for(i=0;i<g->strt.size;i++)
2077sweepwholelist(L,&g->strt.hash[i]);
2078}
2079static void markmt(global_State*g){
2080int i;
2081for(i=0;i<(8+1);i++)
2082if(g->mt[i])markobject(g,g->mt[i]);
2083}
2084static void markroot(lua_State*L){
2085global_State*g=G(L);
2086g->gray=NULL;
2087g->grayagain=NULL;
2088g->weak=NULL;
2089markobject(g,g->mainthread);
2090markvalue(g,gt(g->mainthread));
2091markvalue(g,registry(L));
2092markmt(g);
2093g->gcstate=1;
2094}
2095static void remarkupvals(global_State*g){
2096UpVal*uv;
2097for(uv=g->uvhead.u.l.next;uv!=&g->uvhead;uv=uv->u.l.next){
2098if(isgray(obj2gco(uv)))
2099markvalue(g,uv->v);
2100}
2101}
2102static void atomic(lua_State*L){
2103global_State*g=G(L);
2104size_t udsize;
2105remarkupvals(g);
2106propagateall(g);
2107g->gray=g->weak;
2108g->weak=NULL;
2109markobject(g,L);
2110markmt(g);
2111propagateall(g);
2112g->gray=g->grayagain;
2113g->grayagain=NULL;
2114propagateall(g);
2115udsize=luaC_separateudata(L,0);
2116marktmu(g);
2117udsize+=propagateall(g);
2118cleartable(g->weak);
2119g->currentwhite=cast_byte(otherwhite(g));
2120g->sweepstrgc=0;
2121g->sweepgc=&g->rootgc;
2122g->gcstate=2;
2123g->estimate=g->totalbytes-udsize;
2124}
2125static l_mem singlestep(lua_State*L){
2126global_State*g=G(L);
2127switch(g->gcstate){
2128case 0:{
2129markroot(L);
2130return 0;
2131}
2132case 1:{
2133if(g->gray)
2134return propagatemark(g);
2135else{
2136atomic(L);
2137return 0;
2138}
2139}
2140case 2:{
2141lu_mem old=g->totalbytes;
2142sweepwholelist(L,&g->strt.hash[g->sweepstrgc++]);
2143if(g->sweepstrgc>=g->strt.size)
2144g->gcstate=3;
2145g->estimate-=old-g->totalbytes;
2146return 10;
2147}
2148case 3:{
2149lu_mem old=g->totalbytes;
2150g->sweepgc=sweeplist(L,g->sweepgc,40);
2151if(*g->sweepgc==NULL){
2152checkSizes(L);
2153g->gcstate=4;
2154}
2155g->estimate-=old-g->totalbytes;
2156return 40*10;
2157}
2158case 4:{
2159if(g->tmudata){
2160GCTM(L);
2161if(g->estimate>100)
2162g->estimate-=100;
2163return 100;
2164}
2165else{
2166g->gcstate=0;
2167g->gcdept=0;
2168return 0;
2169}
2170}
2171default:return 0;
2172}
2173}
2174static void luaC_step(lua_State*L){
2175global_State*g=G(L);
2176l_mem lim=(1024u/100)*g->gcstepmul;
2177if(lim==0)
2178lim=(((lu_mem)(~(lu_mem)0)-2)-1)/2;
2179g->gcdept+=g->totalbytes-g->GCthreshold;
2180do{
2181lim-=singlestep(L);
2182if(g->gcstate==0)
2183break;
2184}while(lim>0);
2185if(g->gcstate!=0){
2186if(g->gcdept<1024u)
2187g->GCthreshold=g->totalbytes+1024u;
2188else{
2189g->gcdept-=1024u;
2190g->GCthreshold=g->totalbytes;
2191}
2192}
2193else{
2194setthreshold(g);
2195}
2196}
2197static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v){
2198global_State*g=G(L);
2199if(g->gcstate==1)
2200reallymarkobject(g,v);
2201else
2202makewhite(g,o);
2203}
2204static void luaC_barrierback(lua_State*L,Table*t){
2205global_State*g=G(L);
2206GCObject*o=obj2gco(t);
2207black2gray(o);
2208t->gclist=g->grayagain;
2209g->grayagain=o;
2210}
2211static void luaC_link(lua_State*L,GCObject*o,lu_byte tt){
2212global_State*g=G(L);
2213o->gch.next=g->rootgc;
2214g->rootgc=o;
2215o->gch.marked=luaC_white(g);
2216o->gch.tt=tt;
2217}
2218static void luaC_linkupval(lua_State*L,UpVal*uv){
2219global_State*g=G(L);
2220GCObject*o=obj2gco(uv);
2221o->gch.next=g->rootgc;
2222g->rootgc=o;
2223if(isgray(o)){
2224if(g->gcstate==1){
2225gray2black(o);
2226luaC_barrier(L,uv,uv->v);
2227}
2228else{
2229makewhite(g,o);
2230}
2231}
2232}
2233typedef union{
2234lua_Number r;
2235TString*ts;
2236}SemInfo;
2237typedef struct Token{
2238int token;
2239SemInfo seminfo;
2240}Token;
2241typedef struct LexState{
2242int current;
2243int linenumber;
2244int lastline;
2245Token t;
2246Token lookahead;
2247struct FuncState*fs;
2248struct lua_State*L;
2249ZIO*z;
2250Mbuffer*buff;
2251TString*source;
2252char decpoint;
2253}LexState;
2254static void luaX_init(lua_State*L);
2255static void luaX_lexerror(LexState*ls,const char*msg,int token);
2256#define state_size(x)(sizeof(x)+0)
2257#define fromstate(l)(cast(lu_byte*,(l))-0)
2258#define tostate(l)(cast(lua_State*,cast(lu_byte*,l)+0))
2259typedef struct LG{
2260lua_State l;
2261global_State g;
2262}LG;
2263static void stack_init(lua_State*L1,lua_State*L){
2264L1->base_ci=luaM_newvector(L,8,CallInfo);
2265L1->ci=L1->base_ci;
2266L1->size_ci=8;
2267L1->end_ci=L1->base_ci+L1->size_ci-1;
2268L1->stack=luaM_newvector(L,(2*20)+5,TValue);
2269L1->stacksize=(2*20)+5;
2270L1->top=L1->stack;
2271L1->stack_last=L1->stack+(L1->stacksize-5)-1;
2272L1->ci->func=L1->top;
2273setnilvalue(L1->top++);
2274L1->base=L1->ci->base=L1->top;
2275L1->ci->top=L1->top+20;
2276}
2277static void freestack(lua_State*L,lua_State*L1){
2278luaM_freearray(L,L1->base_ci,L1->size_ci,CallInfo);
2279luaM_freearray(L,L1->stack,L1->stacksize,TValue);
2280}
2281static void f_luaopen(lua_State*L,void*ud){
2282global_State*g=G(L);
2283UNUSED(ud);
2284stack_init(L,L);
2285sethvalue(L,gt(L),luaH_new(L,0,2));
2286sethvalue(L,registry(L),luaH_new(L,0,2));
2287luaS_resize(L,32);
2288luaT_init(L);
2289luaX_init(L);
2290luaS_fix(luaS_newliteral(L,"not enough memory"));
2291g->GCthreshold=4*g->totalbytes;
2292}
2293static void preinit_state(lua_State*L,global_State*g){
2294G(L)=g;
2295L->stack=NULL;
2296L->stacksize=0;
2297L->errorJmp=NULL;
2298L->hook=NULL;
2299L->hookmask=0;
2300L->basehookcount=0;
2301L->allowhook=1;
2302resethookcount(L);
2303L->openupval=NULL;
2304L->size_ci=0;
2305L->nCcalls=L->baseCcalls=0;
2306L->status=0;
2307L->base_ci=L->ci=NULL;
2308L->savedpc=NULL;
2309L->errfunc=0;
2310setnilvalue(gt(L));
2311}
2312static void close_state(lua_State*L){
2313global_State*g=G(L);
2314luaF_close(L,L->stack);
2315luaC_freeall(L);
2316luaM_freearray(L,G(L)->strt.hash,G(L)->strt.size,TString*);
2317luaZ_freebuffer(L,&g->buff);
2318freestack(L,L);
2319(*g->frealloc)(g->ud,fromstate(L),state_size(LG),0);
2320}
2321static void luaE_freethread(lua_State*L,lua_State*L1){
2322luaF_close(L1,L1->stack);
2323freestack(L,L1);
2324luaM_freemem(L,fromstate(L1),state_size(lua_State));
2325}
2326static lua_State*lua_newstate(lua_Alloc f,void*ud){
2327int i;
2328lua_State*L;
2329global_State*g;
2330void*l=(*f)(ud,NULL,0,state_size(LG));
2331if(l==NULL)return NULL;
2332L=tostate(l);
2333g=&((LG*)L)->g;
2334L->next=NULL;
2335L->tt=8;
2336g->currentwhite=bit2mask(0,5);
2337L->marked=luaC_white(g);
2338set2bits(L->marked,5,6);
2339preinit_state(L,g);
2340g->frealloc=f;
2341g->ud=ud;
2342g->mainthread=L;
2343g->uvhead.u.l.prev=&g->uvhead;
2344g->uvhead.u.l.next=&g->uvhead;
2345g->GCthreshold=0;
2346g->strt.size=0;
2347g->strt.nuse=0;
2348g->strt.hash=NULL;
2349setnilvalue(registry(L));
2350luaZ_initbuffer(L,&g->buff);
2351g->panic=NULL;
2352g->gcstate=0;
2353g->rootgc=obj2gco(L);
2354g->sweepstrgc=0;
2355g->sweepgc=&g->rootgc;
2356g->gray=NULL;
2357g->grayagain=NULL;
2358g->weak=NULL;
2359g->tmudata=NULL;
2360g->totalbytes=sizeof(LG);
2361g->gcpause=200;
2362g->gcstepmul=200;
2363g->gcdept=0;
2364for(i=0;i<(8+1);i++)g->mt[i]=NULL;
2365if(luaD_rawrunprotected(L,f_luaopen,NULL)!=0){
2366close_state(L);
2367L=NULL;
2368}
2369else
2370{}
2371return L;
2372}
2373static void callallgcTM(lua_State*L,void*ud){
2374UNUSED(ud);
2375luaC_callGCTM(L);
2376}
2377static void lua_close(lua_State*L){
2378L=G(L)->mainthread;
2379luaF_close(L,L->stack);
2380luaC_separateudata(L,1);
2381L->errfunc=0;
2382do{
2383L->ci=L->base_ci;
2384L->base=L->top=L->ci->base;
2385L->nCcalls=L->baseCcalls=0;
2386}while(luaD_rawrunprotected(L,callallgcTM,NULL)!=0);
2387close_state(L);
2388}
2389#define getcode(fs,e)((fs)->f->code[(e)->u.s.info])
2390#define luaK_codeAsBx(fs,o,A,sBx)luaK_codeABx(fs,o,A,(sBx)+(((1<<(9+9))-1)>>1))
2391#define luaK_setmultret(fs,e)luaK_setreturns(fs,e,(-1))
2392static int luaK_codeABx(FuncState*fs,OpCode o,int A,unsigned int Bx);
2393static int luaK_codeABC(FuncState*fs,OpCode o,int A,int B,int C);
2394static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults);
2395static void luaK_patchtohere(FuncState*fs,int list);
2396static void luaK_concat(FuncState*fs,int*l1,int l2);
2397static int currentpc(lua_State*L,CallInfo*ci){
2398if(!isLua(ci))return-1;
2399if(ci==L->ci)
2400ci->savedpc=L->savedpc;
2401return pcRel(ci->savedpc,ci_func(ci)->l.p);
2402}
2403static int currentline(lua_State*L,CallInfo*ci){
2404int pc=currentpc(L,ci);
2405if(pc<0)
2406return-1;
2407else
2408return getline_(ci_func(ci)->l.p,pc);
2409}
2410static int lua_getstack(lua_State*L,int level,lua_Debug*ar){
2411int status;
2412CallInfo*ci;
2413for(ci=L->ci;level>0&&ci>L->base_ci;ci--){
2414level--;
2415if(f_isLua(ci))
2416level-=ci->tailcalls;
2417}
2418if(level==0&&ci>L->base_ci){
2419status=1;
2420ar->i_ci=cast_int(ci-L->base_ci);
2421}
2422else if(level<0){
2423status=1;
2424ar->i_ci=0;
2425}
2426else status=0;
2427return status;
2428}
2429static Proto*getluaproto(CallInfo*ci){
2430return(isLua(ci)?ci_func(ci)->l.p:NULL);
2431}
2432static void funcinfo(lua_Debug*ar,Closure*cl){
2433if(cl->c.isC){
2434ar->source="=[C]";
2435ar->linedefined=-1;
2436ar->lastlinedefined=-1;
2437ar->what="C";
2438}
2439else{
2440ar->source=getstr(cl->l.p->source);
2441ar->linedefined=cl->l.p->linedefined;
2442ar->lastlinedefined=cl->l.p->lastlinedefined;
2443ar->what=(ar->linedefined==0)?"main":"Lua";
2444}
2445luaO_chunkid(ar->short_src,ar->source,60);
2446}
2447static void info_tailcall(lua_Debug*ar){
2448ar->name=ar->namewhat="";
2449ar->what="tail";
2450ar->lastlinedefined=ar->linedefined=ar->currentline=-1;
2451ar->source="=(tail call)";
2452luaO_chunkid(ar->short_src,ar->source,60);
2453ar->nups=0;
2454}
2455static void collectvalidlines(lua_State*L,Closure*f){
2456if(f==NULL||f->c.isC){
2457setnilvalue(L->top);
2458}
2459else{
2460Table*t=luaH_new(L,0,0);
2461int*lineinfo=f->l.p->lineinfo;
2462int i;
2463for(i=0;i<f->l.p->sizelineinfo;i++)
2464setbvalue(luaH_setnum(L,t,lineinfo[i]),1);
2465sethvalue(L,L->top,t);
2466}
2467incr_top(L);
2468}
2469static int auxgetinfo(lua_State*L,const char*what,lua_Debug*ar,
2470Closure*f,CallInfo*ci){
2471int status=1;
2472if(f==NULL){
2473info_tailcall(ar);
2474return status;
2475}
2476for(;*what;what++){
2477switch(*what){
2478case'S':{
2479funcinfo(ar,f);
2480break;
2481}
2482case'l':{
2483ar->currentline=(ci)?currentline(L,ci):-1;
2484break;
2485}
2486case'u':{
2487ar->nups=f->c.nupvalues;
2488break;
2489}
2490case'n':{
2491ar->namewhat=(ci)?NULL:NULL;
2492if(ar->namewhat==NULL){
2493ar->namewhat="";
2494ar->name=NULL;
2495}
2496break;
2497}
2498case'L':
2499case'f':
2500break;
2501default:status=0;
2502}
2503}
2504return status;
2505}
2506static int lua_getinfo(lua_State*L,const char*what,lua_Debug*ar){
2507int status;
2508Closure*f=NULL;
2509CallInfo*ci=NULL;
2510if(*what=='>'){
2511StkId func=L->top-1;
2512luai_apicheck(L,ttisfunction(func));
2513what++;
2514f=clvalue(func);
2515L->top--;
2516}
2517else if(ar->i_ci!=0){
2518ci=L->base_ci+ar->i_ci;
2519f=clvalue(ci->func);
2520}
2521status=auxgetinfo(L,what,ar,f,ci);
2522if(strchr(what,'f')){
2523if(f==NULL)setnilvalue(L->top);
2524else setclvalue(L,L->top,f);
2525incr_top(L);
2526}
2527if(strchr(what,'L'))
2528collectvalidlines(L,f);
2529return status;
2530}
2531static int isinstack(CallInfo*ci,const TValue*o){
2532StkId p;
2533for(p=ci->base;p<ci->top;p++)
2534if(o==p)return 1;
2535return 0;
2536}
2537static void luaG_typeerror(lua_State*L,const TValue*o,const char*op){
2538const char*name=NULL;
2539const char*t=luaT_typenames[ttype(o)];
2540const char*kind=(isinstack(L->ci,o))?
2541NULL:
2542NULL;
2543if(kind)
2544luaG_runerror(L,"attempt to %s %s "LUA_QL("%s")" (a %s value)",
2545op,kind,name,t);
2546else
2547luaG_runerror(L,"attempt to %s a %s value",op,t);
2548}
2549static void luaG_concaterror(lua_State*L,StkId p1,StkId p2){
2550if(ttisstring(p1)||ttisnumber(p1))p1=p2;
2551luaG_typeerror(L,p1,"concatenate");
2552}
2553static void luaG_aritherror(lua_State*L,const TValue*p1,const TValue*p2){
2554TValue temp;
2555if(luaV_tonumber(p1,&temp)==NULL)
2556p2=p1;
2557luaG_typeerror(L,p2,"perform arithmetic on");
2558}
2559static int luaG_ordererror(lua_State*L,const TValue*p1,const TValue*p2){
2560const char*t1=luaT_typenames[ttype(p1)];
2561const char*t2=luaT_typenames[ttype(p2)];
2562if(t1[2]==t2[2])
2563luaG_runerror(L,"attempt to compare two %s values",t1);
2564else
2565luaG_runerror(L,"attempt to compare %s with %s",t1,t2);
2566return 0;
2567}
2568static void addinfo(lua_State*L,const char*msg){
2569CallInfo*ci=L->ci;
2570if(isLua(ci)){
2571char buff[60];
2572int line=currentline(L,ci);
2573luaO_chunkid(buff,getstr(getluaproto(ci)->source),60);
2574luaO_pushfstring(L,"%s:%d: %s",buff,line,msg);
2575}
2576}
2577static void luaG_errormsg(lua_State*L){
2578if(L->errfunc!=0){
2579StkId errfunc=restorestack(L,L->errfunc);
2580if(!ttisfunction(errfunc))luaD_throw(L,5);
2581setobj(L,L->top,L->top-1);
2582setobj(L,L->top-1,errfunc);
2583incr_top(L);
2584luaD_call(L,L->top-2,1);
2585}
2586luaD_throw(L,2);
2587}
2588static void luaG_runerror(lua_State*L,const char*fmt,...){
2589va_list argp;
2590va_start(argp,fmt);
2591addinfo(L,luaO_pushvfstring(L,fmt,argp));
2592va_end(argp);
2593luaG_errormsg(L);
2594}
2595static int luaZ_fill(ZIO*z){
2596size_t size;
2597lua_State*L=z->L;
2598const char*buff;
2599buff=z->reader(L,z->data,&size);
2600if(buff==NULL||size==0)return(-1);
2601z->n=size-1;
2602z->p=buff;
2603return char2int(*(z->p++));
2604}
2605static void luaZ_init(lua_State*L,ZIO*z,lua_Reader reader,void*data){
2606z->L=L;
2607z->reader=reader;
2608z->data=data;
2609z->n=0;
2610z->p=NULL;
2611}
2612static char*luaZ_openspace(lua_State*L,Mbuffer*buff,size_t n){
2613if(n>buff->buffsize){
2614if(n<32)n=32;
2615luaZ_resizebuffer(L,buff,n);
2616}
2617return buff->buffer;
2618}
2619#define opmode(t,a,b,c,m)(((t)<<7)|((a)<<6)|((b)<<4)|((c)<<2)|(m))
2620static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)]={
2621opmode(0,1,OpArgR,OpArgN,iABC)
2622,opmode(0,1,OpArgK,OpArgN,iABx)
2623,opmode(0,1,OpArgU,OpArgU,iABC)
2624,opmode(0,1,OpArgR,OpArgN,iABC)
2625,opmode(0,1,OpArgU,OpArgN,iABC)
2626,opmode(0,1,OpArgK,OpArgN,iABx)
2627,opmode(0,1,OpArgR,OpArgK,iABC)
2628,opmode(0,0,OpArgK,OpArgN,iABx)
2629,opmode(0,0,OpArgU,OpArgN,iABC)
2630,opmode(0,0,OpArgK,OpArgK,iABC)
2631,opmode(0,1,OpArgU,OpArgU,iABC)
2632,opmode(0,1,OpArgR,OpArgK,iABC)
2633,opmode(0,1,OpArgK,OpArgK,iABC)
2634,opmode(0,1,OpArgK,OpArgK,iABC)
2635,opmode(0,1,OpArgK,OpArgK,iABC)
2636,opmode(0,1,OpArgK,OpArgK,iABC)
2637,opmode(0,1,OpArgK,OpArgK,iABC)
2638,opmode(0,1,OpArgK,OpArgK,iABC)
2639,opmode(0,1,OpArgR,OpArgN,iABC)
2640,opmode(0,1,OpArgR,OpArgN,iABC)
2641,opmode(0,1,OpArgR,OpArgN,iABC)
2642,opmode(0,1,OpArgR,OpArgR,iABC)
2643,opmode(0,0,OpArgR,OpArgN,iAsBx)
2644,opmode(1,0,OpArgK,OpArgK,iABC)
2645,opmode(1,0,OpArgK,OpArgK,iABC)
2646,opmode(1,0,OpArgK,OpArgK,iABC)
2647,opmode(1,1,OpArgR,OpArgU,iABC)
2648,opmode(1,1,OpArgR,OpArgU,iABC)
2649,opmode(0,1,OpArgU,OpArgU,iABC)
2650,opmode(0,1,OpArgU,OpArgU,iABC)
2651,opmode(0,0,OpArgU,OpArgN,iABC)
2652,opmode(0,1,OpArgR,OpArgN,iAsBx)
2653,opmode(0,1,OpArgR,OpArgN,iAsBx)
2654,opmode(1,0,OpArgN,OpArgU,iABC)
2655,opmode(0,0,OpArgU,OpArgU,iABC)
2656,opmode(0,0,OpArgN,OpArgN,iABC)
2657,opmode(0,1,OpArgU,OpArgN,iABx)
2658,opmode(0,1,OpArgU,OpArgN,iABC)
2659};
2660#define next(ls)(ls->current=zgetc(ls->z))
2661#define currIsNewline(ls)(ls->current=='\n'||ls->current=='\r')
2662static const char*const luaX_tokens[]={
2663"and","break","do","else","elseif",
2664"end","false","for","function","if",
2665"in","local","nil","not","or","repeat",
2666"return","then","true","until","while",
2667"..","...","==",">=","<=","~=",
2668"<number>","<name>","<string>","<eof>",
2669NULL
2670};
2671#define save_and_next(ls)(save(ls,ls->current),next(ls))
2672static void save(LexState*ls,int c){
2673Mbuffer*b=ls->buff;
2674if(b->n+1>b->buffsize){
2675size_t newsize;
2676if(b->buffsize>=((size_t)(~(size_t)0)-2)/2)
2677luaX_lexerror(ls,"lexical element too long",0);
2678newsize=b->buffsize*2;
2679luaZ_resizebuffer(ls->L,b,newsize);
2680}
2681b->buffer[b->n++]=cast(char,c);
2682}
2683static void luaX_init(lua_State*L){
2684int i;
2685for(i=0;i<(cast(int,TK_WHILE-257+1));i++){
2686TString*ts=luaS_new(L,luaX_tokens[i]);
2687luaS_fix(ts);
2688ts->tsv.reserved=cast_byte(i+1);
2689}
2690}
2691static const char*luaX_token2str(LexState*ls,int token){
2692if(token<257){
2693return(iscntrl(token))?luaO_pushfstring(ls->L,"char(%d)",token):
2694luaO_pushfstring(ls->L,"%c",token);
2695}
2696else
2697return luaX_tokens[token-257];
2698}
2699static const char*txtToken(LexState*ls,int token){
2700switch(token){
2701case TK_NAME:
2702case TK_STRING:
2703case TK_NUMBER:
2704save(ls,'\0');
2705return luaZ_buffer(ls->buff);
2706default:
2707return luaX_token2str(ls,token);
2708}
2709}
2710static void luaX_lexerror(LexState*ls,const char*msg,int token){
2711char buff[80];
2712luaO_chunkid(buff,getstr(ls->source),80);
2713msg=luaO_pushfstring(ls->L,"%s:%d: %s",buff,ls->linenumber,msg);
2714if(token)
2715luaO_pushfstring(ls->L,"%s near "LUA_QL("%s"),msg,txtToken(ls,token));
2716luaD_throw(ls->L,3);
2717}
2718static void luaX_syntaxerror(LexState*ls,const char*msg){
2719luaX_lexerror(ls,msg,ls->t.token);
2720}
2721static TString*luaX_newstring(LexState*ls,const char*str,size_t l){
2722lua_State*L=ls->L;
2723TString*ts=luaS_newlstr(L,str,l);
2724TValue*o=luaH_setstr(L,ls->fs->h,ts);
2725if(ttisnil(o)){
2726setbvalue(o,1);
2727luaC_checkGC(L);
2728}
2729return ts;
2730}
2731static void inclinenumber(LexState*ls){
2732int old=ls->current;
2733next(ls);
2734if(currIsNewline(ls)&&ls->current!=old)
2735next(ls);
2736if(++ls->linenumber>=(INT_MAX-2))
2737luaX_syntaxerror(ls,"chunk has too many lines");
2738}
2739static void luaX_setinput(lua_State*L,LexState*ls,ZIO*z,TString*source){
2740ls->decpoint='.';
2741ls->L=L;
2742ls->lookahead.token=TK_EOS;
2743ls->z=z;
2744ls->fs=NULL;
2745ls->linenumber=1;
2746ls->lastline=1;
2747ls->source=source;
2748luaZ_resizebuffer(ls->L,ls->buff,32);
2749next(ls);
2750}
2751static int check_next(LexState*ls,const char*set){
2752if(!strchr(set,ls->current))
2753return 0;
2754save_and_next(ls);
2755return 1;
2756}
2757static void buffreplace(LexState*ls,char from,char to){
2758size_t n=luaZ_bufflen(ls->buff);
2759char*p=luaZ_buffer(ls->buff);
2760while(n--)
2761if(p[n]==from)p[n]=to;
2762}
2763static void read_numeral(LexState*ls,SemInfo*seminfo){
2764do{
2765save_and_next(ls);
2766}while(isdigit(ls->current)||ls->current=='.');
2767if(check_next(ls,"Ee"))
2768check_next(ls,"+-");
2769while(isalnum(ls->current)||ls->current=='_')
2770save_and_next(ls);
2771save(ls,'\0');
2772buffreplace(ls,'.',ls->decpoint);
2773if(!luaO_str2d(luaZ_buffer(ls->buff),&seminfo->r))
2774luaX_lexerror(ls,"malformed number",TK_NUMBER);
2775}
2776static int skip_sep(LexState*ls){
2777int count=0;
2778int s=ls->current;
2779save_and_next(ls);
2780while(ls->current=='='){
2781save_and_next(ls);
2782count++;
2783}
2784return(ls->current==s)?count:(-count)-1;
2785}
2786static void read_long_string(LexState*ls,SemInfo*seminfo,int sep){
2787int cont=0;
2788(void)(cont);
2789save_and_next(ls);
2790if(currIsNewline(ls))
2791inclinenumber(ls);
2792for(;;){
2793switch(ls->current){
2794case(-1):
2795luaX_lexerror(ls,(seminfo)?"unfinished long string":
2796"unfinished long comment",TK_EOS);
2797break;
2798case']':{
2799if(skip_sep(ls)==sep){
2800save_and_next(ls);
2801goto endloop;
2802}
2803break;
2804}
2805case'\n':
2806case'\r':{
2807save(ls,'\n');
2808inclinenumber(ls);
2809if(!seminfo)luaZ_resetbuffer(ls->buff);
2810break;
2811}
2812default:{
2813if(seminfo)save_and_next(ls);
2814else next(ls);
2815}
2816}
2817}endloop:
2818if(seminfo)
2819seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+(2+sep),
2820luaZ_bufflen(ls->buff)-2*(2+sep));
2821}
2822static void read_string(LexState*ls,int del,SemInfo*seminfo){
2823save_and_next(ls);
2824while(ls->current!=del){
2825switch(ls->current){
2826case(-1):
2827luaX_lexerror(ls,"unfinished string",TK_EOS);
2828continue;
2829case'\n':
2830case'\r':
2831luaX_lexerror(ls,"unfinished string",TK_STRING);
2832continue;
2833case'\\':{
2834int c;
2835next(ls);
2836switch(ls->current){
2837case'a':c='\a';break;
2838case'b':c='\b';break;
2839case'f':c='\f';break;
2840case'n':c='\n';break;
2841case'r':c='\r';break;
2842case't':c='\t';break;
2843case'v':c='\v';break;
2844case'\n':
2845case'\r':save(ls,'\n');inclinenumber(ls);continue;
2846case(-1):continue;
2847default:{
2848if(!isdigit(ls->current))
2849save_and_next(ls);
2850else{
2851int i=0;
2852c=0;
2853do{
2854c=10*c+(ls->current-'0');
2855next(ls);
2856}while(++i<3&&isdigit(ls->current));
2857if(c>UCHAR_MAX)
2858luaX_lexerror(ls,"escape sequence too large",TK_STRING);
2859save(ls,c);
2860}
2861continue;
2862}
2863}
2864save(ls,c);
2865next(ls);
2866continue;
2867}
2868default:
2869save_and_next(ls);
2870}
2871}
2872save_and_next(ls);
2873seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+1,
2874luaZ_bufflen(ls->buff)-2);
2875}
2876static int llex(LexState*ls,SemInfo*seminfo){
2877luaZ_resetbuffer(ls->buff);
2878for(;;){
2879switch(ls->current){
2880case'\n':
2881case'\r':{
2882inclinenumber(ls);
2883continue;
2884}
2885case'-':{
2886next(ls);
2887if(ls->current!='-')return'-';
2888next(ls);
2889if(ls->current=='['){
2890int sep=skip_sep(ls);
2891luaZ_resetbuffer(ls->buff);
2892if(sep>=0){
2893read_long_string(ls,NULL,sep);
2894luaZ_resetbuffer(ls->buff);
2895continue;
2896}
2897}
2898while(!currIsNewline(ls)&&ls->current!=(-1))
2899next(ls);
2900continue;
2901}
2902case'[':{
2903int sep=skip_sep(ls);
2904if(sep>=0){
2905read_long_string(ls,seminfo,sep);
2906return TK_STRING;
2907}
2908else if(sep==-1)return'[';
2909else luaX_lexerror(ls,"invalid long string delimiter",TK_STRING);
2910}
2911case'=':{
2912next(ls);
2913if(ls->current!='=')return'=';
2914else{next(ls);return TK_EQ;}
2915}
2916case'<':{
2917next(ls);
2918if(ls->current!='=')return'<';
2919else{next(ls);return TK_LE;}
2920}
2921case'>':{
2922next(ls);
2923if(ls->current!='=')return'>';
2924else{next(ls);return TK_GE;}
2925}
2926case'~':{
2927next(ls);
2928if(ls->current!='=')return'~';
2929else{next(ls);return TK_NE;}
2930}
2931case'"':
2932case'\'':{
2933read_string(ls,ls->current,seminfo);
2934return TK_STRING;
2935}
2936case'.':{
2937save_and_next(ls);
2938if(check_next(ls,".")){
2939if(check_next(ls,"."))
2940return TK_DOTS;
2941else return TK_CONCAT;
2942}
2943else if(!isdigit(ls->current))return'.';
2944else{
2945read_numeral(ls,seminfo);
2946return TK_NUMBER;
2947}
2948}
2949case(-1):{
2950return TK_EOS;
2951}
2952default:{
2953if(isspace(ls->current)){
2954next(ls);
2955continue;
2956}
2957else if(isdigit(ls->current)){
2958read_numeral(ls,seminfo);
2959return TK_NUMBER;
2960}
2961else if(isalpha(ls->current)||ls->current=='_'){
2962TString*ts;
2963do{
2964save_and_next(ls);
2965}while(isalnum(ls->current)||ls->current=='_');
2966ts=luaX_newstring(ls,luaZ_buffer(ls->buff),
2967luaZ_bufflen(ls->buff));
2968if(ts->tsv.reserved>0)
2969return ts->tsv.reserved-1+257;
2970else{
2971seminfo->ts=ts;
2972return TK_NAME;
2973}
2974}
2975else{
2976int c=ls->current;
2977next(ls);
2978return c;
2979}
2980}
2981}
2982}
2983}
2984static void luaX_next(LexState*ls){
2985ls->lastline=ls->linenumber;
2986if(ls->lookahead.token!=TK_EOS){
2987ls->t=ls->lookahead;
2988ls->lookahead.token=TK_EOS;
2989}
2990else
2991ls->t.token=llex(ls,&ls->t.seminfo);
2992}
2993static void luaX_lookahead(LexState*ls){
2994ls->lookahead.token=llex(ls,&ls->lookahead.seminfo);
2995}
2996#define hasjumps(e)((e)->t!=(e)->f)
2997static int isnumeral(expdesc*e){
2998return(e->k==VKNUM&&e->t==(-1)&&e->f==(-1));
2999}
3000static void luaK_nil(FuncState*fs,int from,int n){
3001Instruction*previous;
3002if(fs->pc>fs->lasttarget){
3003if(fs->pc==0){
3004if(from>=fs->nactvar)
3005return;
3006}
3007else{
3008previous=&fs->f->code[fs->pc-1];
3009if(GET_OPCODE(*previous)==OP_LOADNIL){
3010int pfrom=GETARG_A(*previous);
3011int pto=GETARG_B(*previous);
3012if(pfrom<=from&&from<=pto+1){
3013if(from+n-1>pto)
3014SETARG_B(*previous,from+n-1);
3015return;
3016}
3017}
3018}
3019}
3020luaK_codeABC(fs,OP_LOADNIL,from,from+n-1,0);
3021}
3022static int luaK_jump(FuncState*fs){
3023int jpc=fs->jpc;
3024int j;
3025fs->jpc=(-1);
3026j=luaK_codeAsBx(fs,OP_JMP,0,(-1));
3027luaK_concat(fs,&j,jpc);
3028return j;
3029}
3030static void luaK_ret(FuncState*fs,int first,int nret){
3031luaK_codeABC(fs,OP_RETURN,first,nret+1,0);
3032}
3033static int condjump(FuncState*fs,OpCode op,int A,int B,int C){
3034luaK_codeABC(fs,op,A,B,C);
3035return luaK_jump(fs);
3036}
3037static void fixjump(FuncState*fs,int pc,int dest){
3038Instruction*jmp=&fs->f->code[pc];
3039int offset=dest-(pc+1);
3040if(abs(offset)>(((1<<(9+9))-1)>>1))
3041luaX_syntaxerror(fs->ls,"control structure too long");
3042SETARG_sBx(*jmp,offset);
3043}
3044static int luaK_getlabel(FuncState*fs){
3045fs->lasttarget=fs->pc;
3046return fs->pc;
3047}
3048static int getjump(FuncState*fs,int pc){
3049int offset=GETARG_sBx(fs->f->code[pc]);
3050if(offset==(-1))
3051return(-1);
3052else
3053return(pc+1)+offset;
3054}
3055static Instruction*getjumpcontrol(FuncState*fs,int pc){
3056Instruction*pi=&fs->f->code[pc];
3057if(pc>=1&&testTMode(GET_OPCODE(*(pi-1))))
3058return pi-1;
3059else
3060return pi;
3061}
3062static int need_value(FuncState*fs,int list){
3063for(;list!=(-1);list=getjump(fs,list)){
3064Instruction i=*getjumpcontrol(fs,list);
3065if(GET_OPCODE(i)!=OP_TESTSET)return 1;
3066}
3067return 0;
3068}
3069static int patchtestreg(FuncState*fs,int node,int reg){
3070Instruction*i=getjumpcontrol(fs,node);
3071if(GET_OPCODE(*i)!=OP_TESTSET)
3072return 0;
3073if(reg!=((1<<8)-1)&&reg!=GETARG_B(*i))
3074SETARG_A(*i,reg);
3075else
3076*i=CREATE_ABC(OP_TEST,GETARG_B(*i),0,GETARG_C(*i));
3077return 1;
3078}
3079static void removevalues(FuncState*fs,int list){
3080for(;list!=(-1);list=getjump(fs,list))
3081patchtestreg(fs,list,((1<<8)-1));
3082}
3083static void patchlistaux(FuncState*fs,int list,int vtarget,int reg,
3084int dtarget){
3085while(list!=(-1)){
3086int next=getjump(fs,list);
3087if(patchtestreg(fs,list,reg))
3088fixjump(fs,list,vtarget);
3089else
3090fixjump(fs,list,dtarget);
3091list=next;
3092}
3093}
3094static void dischargejpc(FuncState*fs){
3095patchlistaux(fs,fs->jpc,fs->pc,((1<<8)-1),fs->pc);
3096fs->jpc=(-1);
3097}
3098static void luaK_patchlist(FuncState*fs,int list,int target){
3099if(target==fs->pc)
3100luaK_patchtohere(fs,list);
3101else{
3102patchlistaux(fs,list,target,((1<<8)-1),target);
3103}
3104}
3105static void luaK_patchtohere(FuncState*fs,int list){
3106luaK_getlabel(fs);
3107luaK_concat(fs,&fs->jpc,list);
3108}
3109static void luaK_concat(FuncState*fs,int*l1,int l2){
3110if(l2==(-1))return;
3111else if(*l1==(-1))
3112*l1=l2;
3113else{
3114int list=*l1;
3115int next;
3116while((next=getjump(fs,list))!=(-1))
3117list=next;
3118fixjump(fs,list,l2);
3119}
3120}
3121static void luaK_checkstack(FuncState*fs,int n){
3122int newstack=fs->freereg+n;
3123if(newstack>fs->f->maxstacksize){
3124if(newstack>=250)
3125luaX_syntaxerror(fs->ls,"function or expression too complex");
3126fs->f->maxstacksize=cast_byte(newstack);
3127}
3128}
3129static void luaK_reserveregs(FuncState*fs,int n){
3130luaK_checkstack(fs,n);
3131fs->freereg+=n;
3132}
3133static void freereg(FuncState*fs,int reg){
3134if(!ISK(reg)&&reg>=fs->nactvar){
3135fs->freereg--;
3136}
3137}
3138static void freeexp(FuncState*fs,expdesc*e){
3139if(e->k==VNONRELOC)
3140freereg(fs,e->u.s.info);
3141}
3142static int addk(FuncState*fs,TValue*k,TValue*v){
3143lua_State*L=fs->L;
3144TValue*idx=luaH_set(L,fs->h,k);
3145Proto*f=fs->f;
3146int oldsize=f->sizek;
3147if(ttisnumber(idx)){
3148return cast_int(nvalue(idx));
3149}
3150else{
3151setnvalue(idx,cast_num(fs->nk));
3152luaM_growvector(L,f->k,fs->nk,f->sizek,TValue,
3153((1<<(9+9))-1),"constant table overflow");
3154while(oldsize<f->sizek)setnilvalue(&f->k[oldsize++]);
3155setobj(L,&f->k[fs->nk],v);
3156luaC_barrier(L,f,v);
3157return fs->nk++;
3158}
3159}
3160static int luaK_stringK(FuncState*fs,TString*s){
3161TValue o;
3162setsvalue(fs->L,&o,s);
3163return addk(fs,&o,&o);
3164}
3165static int luaK_numberK(FuncState*fs,lua_Number r){
3166TValue o;
3167setnvalue(&o,r);
3168return addk(fs,&o,&o);
3169}
3170static int boolK(FuncState*fs,int b){
3171TValue o;
3172setbvalue(&o,b);
3173return addk(fs,&o,&o);
3174}
3175static int nilK(FuncState*fs){
3176TValue k,v;
3177setnilvalue(&v);
3178sethvalue(fs->L,&k,fs->h);
3179return addk(fs,&k,&v);
3180}
3181static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults){
3182if(e->k==VCALL){
3183SETARG_C(getcode(fs,e),nresults+1);
3184}
3185else if(e->k==VVARARG){
3186SETARG_B(getcode(fs,e),nresults+1);
3187SETARG_A(getcode(fs,e),fs->freereg);
3188luaK_reserveregs(fs,1);
3189}
3190}
3191static void luaK_setoneret(FuncState*fs,expdesc*e){
3192if(e->k==VCALL){
3193e->k=VNONRELOC;
3194e->u.s.info=GETARG_A(getcode(fs,e));
3195}
3196else if(e->k==VVARARG){
3197SETARG_B(getcode(fs,e),2);
3198e->k=VRELOCABLE;
3199}
3200}
3201static void luaK_dischargevars(FuncState*fs,expdesc*e){
3202switch(e->k){
3203case VLOCAL:{
3204e->k=VNONRELOC;
3205break;
3206}
3207case VUPVAL:{
3208e->u.s.info=luaK_codeABC(fs,OP_GETUPVAL,0,e->u.s.info,0);
3209e->k=VRELOCABLE;
3210break;
3211}
3212case VGLOBAL:{
3213e->u.s.info=luaK_codeABx(fs,OP_GETGLOBAL,0,e->u.s.info);
3214e->k=VRELOCABLE;
3215break;
3216}
3217case VINDEXED:{
3218freereg(fs,e->u.s.aux);
3219freereg(fs,e->u.s.info);
3220e->u.s.info=luaK_codeABC(fs,OP_GETTABLE,0,e->u.s.info,e->u.s.aux);
3221e->k=VRELOCABLE;
3222break;
3223}
3224case VVARARG:
3225case VCALL:{
3226luaK_setoneret(fs,e);
3227break;
3228}
3229default:break;
3230}
3231}
3232static int code_label(FuncState*fs,int A,int b,int jump){
3233luaK_getlabel(fs);
3234return luaK_codeABC(fs,OP_LOADBOOL,A,b,jump);
3235}
3236static void discharge2reg(FuncState*fs,expdesc*e,int reg){
3237luaK_dischargevars(fs,e);
3238switch(e->k){
3239case VNIL:{
3240luaK_nil(fs,reg,1);
3241break;
3242}
3243case VFALSE:case VTRUE:{
3244luaK_codeABC(fs,OP_LOADBOOL,reg,e->k==VTRUE,0);
3245break;
3246}
3247case VK:{
3248luaK_codeABx(fs,OP_LOADK,reg,e->u.s.info);
3249break;
3250}
3251case VKNUM:{
3252luaK_codeABx(fs,OP_LOADK,reg,luaK_numberK(fs,e->u.nval));
3253break;
3254}
3255case VRELOCABLE:{
3256Instruction*pc=&getcode(fs,e);
3257SETARG_A(*pc,reg);
3258break;
3259}
3260case VNONRELOC:{
3261if(reg!=e->u.s.info)
3262luaK_codeABC(fs,OP_MOVE,reg,e->u.s.info,0);
3263break;
3264}
3265default:{
3266return;
3267}
3268}
3269e->u.s.info=reg;
3270e->k=VNONRELOC;
3271}
3272static void discharge2anyreg(FuncState*fs,expdesc*e){
3273if(e->k!=VNONRELOC){
3274luaK_reserveregs(fs,1);
3275discharge2reg(fs,e,fs->freereg-1);
3276}
3277}
3278static void exp2reg(FuncState*fs,expdesc*e,int reg){
3279discharge2reg(fs,e,reg);
3280if(e->k==VJMP)
3281luaK_concat(fs,&e->t,e->u.s.info);
3282if(hasjumps(e)){
3283int final;
3284int p_f=(-1);
3285int p_t=(-1);
3286if(need_value(fs,e->t)||need_value(fs,e->f)){
3287int fj=(e->k==VJMP)?(-1):luaK_jump(fs);
3288p_f=code_label(fs,reg,0,1);
3289p_t=code_label(fs,reg,1,0);
3290luaK_patchtohere(fs,fj);
3291}
3292final=luaK_getlabel(fs);
3293patchlistaux(fs,e->f,final,reg,p_f);
3294patchlistaux(fs,e->t,final,reg,p_t);
3295}
3296e->f=e->t=(-1);
3297e->u.s.info=reg;
3298e->k=VNONRELOC;
3299}
3300static void luaK_exp2nextreg(FuncState*fs,expdesc*e){
3301luaK_dischargevars(fs,e);
3302freeexp(fs,e);
3303luaK_reserveregs(fs,1);
3304exp2reg(fs,e,fs->freereg-1);
3305}
3306static int luaK_exp2anyreg(FuncState*fs,expdesc*e){
3307luaK_dischargevars(fs,e);
3308if(e->k==VNONRELOC){
3309if(!hasjumps(e))return e->u.s.info;
3310if(e->u.s.info>=fs->nactvar){
3311exp2reg(fs,e,e->u.s.info);
3312return e->u.s.info;
3313}
3314}
3315luaK_exp2nextreg(fs,e);
3316return e->u.s.info;
3317}
3318static void luaK_exp2val(FuncState*fs,expdesc*e){
3319if(hasjumps(e))
3320luaK_exp2anyreg(fs,e);
3321else
3322luaK_dischargevars(fs,e);
3323}
3324static int luaK_exp2RK(FuncState*fs,expdesc*e){
3325luaK_exp2val(fs,e);
3326switch(e->k){
3327case VKNUM:
3328case VTRUE:
3329case VFALSE:
3330case VNIL:{
3331if(fs->nk<=((1<<(9-1))-1)){
3332e->u.s.info=(e->k==VNIL)?nilK(fs):
3333(e->k==VKNUM)?luaK_numberK(fs,e->u.nval):
3334boolK(fs,(e->k==VTRUE));
3335e->k=VK;
3336return RKASK(e->u.s.info);
3337}
3338else break;
3339}
3340case VK:{
3341if(e->u.s.info<=((1<<(9-1))-1))
3342return RKASK(e->u.s.info);
3343else break;
3344}
3345default:break;
3346}
3347return luaK_exp2anyreg(fs,e);
3348}
3349static void luaK_storevar(FuncState*fs,expdesc*var,expdesc*ex){
3350switch(var->k){
3351case VLOCAL:{
3352freeexp(fs,ex);
3353exp2reg(fs,ex,var->u.s.info);
3354return;
3355}
3356case VUPVAL:{
3357int e=luaK_exp2anyreg(fs,ex);
3358luaK_codeABC(fs,OP_SETUPVAL,e,var->u.s.info,0);
3359break;
3360}
3361case VGLOBAL:{
3362int e=luaK_exp2anyreg(fs,ex);
3363luaK_codeABx(fs,OP_SETGLOBAL,e,var->u.s.info);
3364break;
3365}
3366case VINDEXED:{
3367int e=luaK_exp2RK(fs,ex);
3368luaK_codeABC(fs,OP_SETTABLE,var->u.s.info,var->u.s.aux,e);
3369break;
3370}
3371default:{
3372break;
3373}
3374}
3375freeexp(fs,ex);
3376}
3377static void luaK_self(FuncState*fs,expdesc*e,expdesc*key){
3378int func;
3379luaK_exp2anyreg(fs,e);
3380freeexp(fs,e);
3381func=fs->freereg;
3382luaK_reserveregs(fs,2);
3383luaK_codeABC(fs,OP_SELF,func,e->u.s.info,luaK_exp2RK(fs,key));
3384freeexp(fs,key);
3385e->u.s.info=func;
3386e->k=VNONRELOC;
3387}
3388static void invertjump(FuncState*fs,expdesc*e){
3389Instruction*pc=getjumpcontrol(fs,e->u.s.info);
3390SETARG_A(*pc,!(GETARG_A(*pc)));
3391}
3392static int jumponcond(FuncState*fs,expdesc*e,int cond){
3393if(e->k==VRELOCABLE){
3394Instruction ie=getcode(fs,e);
3395if(GET_OPCODE(ie)==OP_NOT){
3396fs->pc--;
3397return condjump(fs,OP_TEST,GETARG_B(ie),0,!cond);
3398}
3399}
3400discharge2anyreg(fs,e);
3401freeexp(fs,e);
3402return condjump(fs,OP_TESTSET,((1<<8)-1),e->u.s.info,cond);
3403}
3404static void luaK_goiftrue(FuncState*fs,expdesc*e){
3405int pc;
3406luaK_dischargevars(fs,e);
3407switch(e->k){
3408case VK:case VKNUM:case VTRUE:{
3409pc=(-1);
3410break;
3411}
3412case VJMP:{
3413invertjump(fs,e);
3414pc=e->u.s.info;
3415break;
3416}
3417default:{
3418pc=jumponcond(fs,e,0);
3419break;
3420}
3421}
3422luaK_concat(fs,&e->f,pc);
3423luaK_patchtohere(fs,e->t);
3424e->t=(-1);
3425}
3426static void luaK_goiffalse(FuncState*fs,expdesc*e){
3427int pc;
3428luaK_dischargevars(fs,e);
3429switch(e->k){
3430case VNIL:case VFALSE:{
3431pc=(-1);
3432break;
3433}
3434case VJMP:{
3435pc=e->u.s.info;
3436break;
3437}
3438default:{
3439pc=jumponcond(fs,e,1);
3440break;
3441}
3442}
3443luaK_concat(fs,&e->t,pc);
3444luaK_patchtohere(fs,e->f);
3445e->f=(-1);
3446}
3447static void codenot(FuncState*fs,expdesc*e){
3448luaK_dischargevars(fs,e);
3449switch(e->k){
3450case VNIL:case VFALSE:{
3451e->k=VTRUE;
3452break;
3453}
3454case VK:case VKNUM:case VTRUE:{
3455e->k=VFALSE;
3456break;
3457}
3458case VJMP:{
3459invertjump(fs,e);
3460break;
3461}
3462case VRELOCABLE:
3463case VNONRELOC:{
3464discharge2anyreg(fs,e);
3465freeexp(fs,e);
3466e->u.s.info=luaK_codeABC(fs,OP_NOT,0,e->u.s.info,0);
3467e->k=VRELOCABLE;
3468break;
3469}
3470default:{
3471break;
3472}
3473}
3474{int temp=e->f;e->f=e->t;e->t=temp;}
3475removevalues(fs,e->f);
3476removevalues(fs,e->t);
3477}
3478static void luaK_indexed(FuncState*fs,expdesc*t,expdesc*k){
3479t->u.s.aux=luaK_exp2RK(fs,k);
3480t->k=VINDEXED;
3481}
3482static int constfolding(OpCode op,expdesc*e1,expdesc*e2){
3483lua_Number v1,v2,r;
3484if(!isnumeral(e1)||!isnumeral(e2))return 0;
3485v1=e1->u.nval;
3486v2=e2->u.nval;
3487switch(op){
3488case OP_ADD:r=luai_numadd(v1,v2);break;
3489case OP_SUB:r=luai_numsub(v1,v2);break;
3490case OP_MUL:r=luai_nummul(v1,v2);break;
3491case OP_DIV:
3492if(v2==0)return 0;
3493r=luai_numdiv(v1,v2);break;
3494case OP_MOD:
3495if(v2==0)return 0;
3496r=luai_nummod(v1,v2);break;
3497case OP_POW:r=luai_numpow(v1,v2);break;
3498case OP_UNM:r=luai_numunm(v1);break;
3499case OP_LEN:return 0;
3500default:r=0;break;
3501}
3502if(luai_numisnan(r))return 0;
3503e1->u.nval=r;
3504return 1;
3505}
3506static void codearith(FuncState*fs,OpCode op,expdesc*e1,expdesc*e2){
3507if(constfolding(op,e1,e2))
3508return;
3509else{
3510int o2=(op!=OP_UNM&&op!=OP_LEN)?luaK_exp2RK(fs,e2):0;
3511int o1=luaK_exp2RK(fs,e1);
3512if(o1>o2){
3513freeexp(fs,e1);
3514freeexp(fs,e2);
3515}
3516else{
3517freeexp(fs,e2);
3518freeexp(fs,e1);
3519}
3520e1->u.s.info=luaK_codeABC(fs,op,0,o1,o2);
3521e1->k=VRELOCABLE;
3522}
3523}
3524static void codecomp(FuncState*fs,OpCode op,int cond,expdesc*e1,
3525expdesc*e2){
3526int o1=luaK_exp2RK(fs,e1);
3527int o2=luaK_exp2RK(fs,e2);
3528freeexp(fs,e2);
3529freeexp(fs,e1);
3530if(cond==0&&op!=OP_EQ){
3531int temp;
3532temp=o1;o1=o2;o2=temp;
3533cond=1;
3534}
3535e1->u.s.info=condjump(fs,op,cond,o1,o2);
3536e1->k=VJMP;
3537}
3538static void luaK_prefix(FuncState*fs,UnOpr op,expdesc*e){
3539expdesc e2;
3540e2.t=e2.f=(-1);e2.k=VKNUM;e2.u.nval=0;
3541switch(op){
3542case OPR_MINUS:{
3543if(!isnumeral(e))
3544luaK_exp2anyreg(fs,e);
3545codearith(fs,OP_UNM,e,&e2);
3546break;
3547}
3548case OPR_NOT:codenot(fs,e);break;
3549case OPR_LEN:{
3550luaK_exp2anyreg(fs,e);
3551codearith(fs,OP_LEN,e,&e2);
3552break;
3553}
3554default:;
3555}
3556}
3557static void luaK_infix(FuncState*fs,BinOpr op,expdesc*v){
3558switch(op){
3559case OPR_AND:{
3560luaK_goiftrue(fs,v);
3561break;
3562}
3563case OPR_OR:{
3564luaK_goiffalse(fs,v);
3565break;
3566}
3567case OPR_CONCAT:{
3568luaK_exp2nextreg(fs,v);
3569break;
3570}
3571case OPR_ADD:case OPR_SUB:case OPR_MUL:case OPR_DIV:
3572case OPR_MOD:case OPR_POW:{
3573if(!isnumeral(v))luaK_exp2RK(fs,v);
3574break;
3575}
3576default:{
3577luaK_exp2RK(fs,v);
3578break;
3579}
3580}
3581}
3582static void luaK_posfix(FuncState*fs,BinOpr op,expdesc*e1,expdesc*e2){
3583switch(op){
3584case OPR_AND:{
3585luaK_dischargevars(fs,e2);
3586luaK_concat(fs,&e2->f,e1->f);
3587*e1=*e2;
3588break;
3589}
3590case OPR_OR:{
3591luaK_dischargevars(fs,e2);
3592luaK_concat(fs,&e2->t,e1->t);
3593*e1=*e2;
3594break;
3595}
3596case OPR_CONCAT:{
3597luaK_exp2val(fs,e2);
3598if(e2->k==VRELOCABLE&&GET_OPCODE(getcode(fs,e2))==OP_CONCAT){
3599freeexp(fs,e1);
3600SETARG_B(getcode(fs,e2),e1->u.s.info);
3601e1->k=VRELOCABLE;e1->u.s.info=e2->u.s.info;
3602}
3603else{
3604luaK_exp2nextreg(fs,e2);
3605codearith(fs,OP_CONCAT,e1,e2);
3606}
3607break;
3608}
3609case OPR_ADD:codearith(fs,OP_ADD,e1,e2);break;
3610case OPR_SUB:codearith(fs,OP_SUB,e1,e2);break;
3611case OPR_MUL:codearith(fs,OP_MUL,e1,e2);break;
3612case OPR_DIV:codearith(fs,OP_DIV,e1,e2);break;
3613case OPR_MOD:codearith(fs,OP_MOD,e1,e2);break;
3614case OPR_POW:codearith(fs,OP_POW,e1,e2);break;
3615case OPR_EQ:codecomp(fs,OP_EQ,1,e1,e2);break;
3616case OPR_NE:codecomp(fs,OP_EQ,0,e1,e2);break;
3617case OPR_LT:codecomp(fs,OP_LT,1,e1,e2);break;
3618case OPR_LE:codecomp(fs,OP_LE,1,e1,e2);break;
3619case OPR_GT:codecomp(fs,OP_LT,0,e1,e2);break;
3620case OPR_GE:codecomp(fs,OP_LE,0,e1,e2);break;
3621default:;
3622}
3623}
3624static void luaK_fixline(FuncState*fs,int line){
3625fs->f->lineinfo[fs->pc-1]=line;
3626}
3627static int luaK_code(FuncState*fs,Instruction i,int line){
3628Proto*f=fs->f;
3629dischargejpc(fs);
3630luaM_growvector(fs->L,f->code,fs->pc,f->sizecode,Instruction,
3631(INT_MAX-2),"code size overflow");
3632f->code[fs->pc]=i;
3633luaM_growvector(fs->L,f->lineinfo,fs->pc,f->sizelineinfo,int,
3634(INT_MAX-2),"code size overflow");
3635f->lineinfo[fs->pc]=line;
3636return fs->pc++;
3637}
3638static int luaK_codeABC(FuncState*fs,OpCode o,int a,int b,int c){
3639return luaK_code(fs,CREATE_ABC(o,a,b,c),fs->ls->lastline);
3640}
3641static int luaK_codeABx(FuncState*fs,OpCode o,int a,unsigned int bc){
3642return luaK_code(fs,CREATE_ABx(o,a,bc),fs->ls->lastline);
3643}
3644static void luaK_setlist(FuncState*fs,int base,int nelems,int tostore){
3645int c=(nelems-1)/50+1;
3646int b=(tostore==(-1))?0:tostore;
3647if(c<=((1<<9)-1))
3648luaK_codeABC(fs,OP_SETLIST,base,b,c);
3649else{
3650luaK_codeABC(fs,OP_SETLIST,base,b,0);
3651luaK_code(fs,cast(Instruction,c),fs->ls->lastline);
3652}
3653fs->freereg=base+1;
3654}
3655#define hasmultret(k)((k)==VCALL||(k)==VVARARG)
3656#define getlocvar(fs,i)((fs)->f->locvars[(fs)->actvar[i]])
3657#define luaY_checklimit(fs,v,l,m)if((v)>(l))errorlimit(fs,l,m)
3658typedef struct BlockCnt{
3659struct BlockCnt*previous;
3660int breaklist;
3661lu_byte nactvar;
3662lu_byte upval;
3663lu_byte isbreakable;
3664}BlockCnt;
3665static void chunk(LexState*ls);
3666static void expr(LexState*ls,expdesc*v);
3667static void anchor_token(LexState*ls){
3668if(ls->t.token==TK_NAME||ls->t.token==TK_STRING){
3669TString*ts=ls->t.seminfo.ts;
3670luaX_newstring(ls,getstr(ts),ts->tsv.len);
3671}
3672}
3673static void error_expected(LexState*ls,int token){
3674luaX_syntaxerror(ls,
3675luaO_pushfstring(ls->L,LUA_QL("%s")" expected",luaX_token2str(ls,token)));
3676}
3677static void errorlimit(FuncState*fs,int limit,const char*what){
3678const char*msg=(fs->f->linedefined==0)?
3679luaO_pushfstring(fs->L,"main function has more than %d %s",limit,what):
3680luaO_pushfstring(fs->L,"function at line %d has more than %d %s",
3681fs->f->linedefined,limit,what);
3682luaX_lexerror(fs->ls,msg,0);
3683}
3684static int testnext(LexState*ls,int c){
3685if(ls->t.token==c){
3686luaX_next(ls);
3687return 1;
3688}
3689else return 0;
3690}
3691static void check(LexState*ls,int c){
3692if(ls->t.token!=c)
3693error_expected(ls,c);
3694}
3695static void checknext(LexState*ls,int c){
3696check(ls,c);
3697luaX_next(ls);
3698}
3699#define check_condition(ls,c,msg){if(!(c))luaX_syntaxerror(ls,msg);}
3700static void check_match(LexState*ls,int what,int who,int where){
3701if(!testnext(ls,what)){
3702if(where==ls->linenumber)
3703error_expected(ls,what);
3704else{
3705luaX_syntaxerror(ls,luaO_pushfstring(ls->L,
3706LUA_QL("%s")" expected (to close "LUA_QL("%s")" at line %d)",
3707luaX_token2str(ls,what),luaX_token2str(ls,who),where));
3708}
3709}
3710}
3711static TString*str_checkname(LexState*ls){
3712TString*ts;
3713check(ls,TK_NAME);
3714ts=ls->t.seminfo.ts;
3715luaX_next(ls);
3716return ts;
3717}
3718static void init_exp(expdesc*e,expkind k,int i){
3719e->f=e->t=(-1);
3720e->k=k;
3721e->u.s.info=i;
3722}
3723static void codestring(LexState*ls,expdesc*e,TString*s){
3724init_exp(e,VK,luaK_stringK(ls->fs,s));
3725}
3726static void checkname(LexState*ls,expdesc*e){
3727codestring(ls,e,str_checkname(ls));
3728}
3729static int registerlocalvar(LexState*ls,TString*varname){
3730FuncState*fs=ls->fs;
3731Proto*f=fs->f;
3732int oldsize=f->sizelocvars;
3733luaM_growvector(ls->L,f->locvars,fs->nlocvars,f->sizelocvars,
3734LocVar,SHRT_MAX,"too many local variables");
3735while(oldsize<f->sizelocvars)f->locvars[oldsize++].varname=NULL;
3736f->locvars[fs->nlocvars].varname=varname;
3737luaC_objbarrier(ls->L,f,varname);
3738return fs->nlocvars++;
3739}
3740#define new_localvarliteral(ls,v,n)new_localvar(ls,luaX_newstring(ls,""v,(sizeof(v)/sizeof(char))-1),n)
3741static void new_localvar(LexState*ls,TString*name,int n){
3742FuncState*fs=ls->fs;
3743luaY_checklimit(fs,fs->nactvar+n+1,200,"local variables");
3744fs->actvar[fs->nactvar+n]=cast(unsigned short,registerlocalvar(ls,name));
3745}
3746static void adjustlocalvars(LexState*ls,int nvars){
3747FuncState*fs=ls->fs;
3748fs->nactvar=cast_byte(fs->nactvar+nvars);
3749for(;nvars;nvars--){
3750getlocvar(fs,fs->nactvar-nvars).startpc=fs->pc;
3751}
3752}
3753static void removevars(LexState*ls,int tolevel){
3754FuncState*fs=ls->fs;
3755while(fs->nactvar>tolevel)
3756getlocvar(fs,--fs->nactvar).endpc=fs->pc;
3757}
3758static int indexupvalue(FuncState*fs,TString*name,expdesc*v){
3759int i;
3760Proto*f=fs->f;
3761int oldsize=f->sizeupvalues;
3762for(i=0;i<f->nups;i++){
3763if(fs->upvalues[i].k==v->k&&fs->upvalues[i].info==v->u.s.info){
3764return i;
3765}
3766}
3767luaY_checklimit(fs,f->nups+1,60,"upvalues");
3768luaM_growvector(fs->L,f->upvalues,f->nups,f->sizeupvalues,
3769TString*,(INT_MAX-2),"");
3770while(oldsize<f->sizeupvalues)f->upvalues[oldsize++]=NULL;
3771f->upvalues[f->nups]=name;
3772luaC_objbarrier(fs->L,f,name);
3773fs->upvalues[f->nups].k=cast_byte(v->k);
3774fs->upvalues[f->nups].info=cast_byte(v->u.s.info);
3775return f->nups++;
3776}
3777static int searchvar(FuncState*fs,TString*n){
3778int i;
3779for(i=fs->nactvar-1;i>=0;i--){
3780if(n==getlocvar(fs,i).varname)
3781return i;
3782}
3783return-1;
3784}
3785static void markupval(FuncState*fs,int level){
3786BlockCnt*bl=fs->bl;
3787while(bl&&bl->nactvar>level)bl=bl->previous;
3788if(bl)bl->upval=1;
3789}
3790static int singlevaraux(FuncState*fs,TString*n,expdesc*var,int base){
3791if(fs==NULL){
3792init_exp(var,VGLOBAL,((1<<8)-1));
3793return VGLOBAL;
3794}
3795else{
3796int v=searchvar(fs,n);
3797if(v>=0){
3798init_exp(var,VLOCAL,v);
3799if(!base)
3800markupval(fs,v);
3801return VLOCAL;
3802}
3803else{
3804if(singlevaraux(fs->prev,n,var,0)==VGLOBAL)
3805return VGLOBAL;
3806var->u.s.info=indexupvalue(fs,n,var);
3807var->k=VUPVAL;
3808return VUPVAL;
3809}
3810}
3811}
3812static void singlevar(LexState*ls,expdesc*var){
3813TString*varname=str_checkname(ls);
3814FuncState*fs=ls->fs;
3815if(singlevaraux(fs,varname,var,1)==VGLOBAL)
3816var->u.s.info=luaK_stringK(fs,varname);
3817}
3818static void adjust_assign(LexState*ls,int nvars,int nexps,expdesc*e){
3819FuncState*fs=ls->fs;
3820int extra=nvars-nexps;
3821if(hasmultret(e->k)){
3822extra++;
3823if(extra<0)extra=0;
3824luaK_setreturns(fs,e,extra);
3825if(extra>1)luaK_reserveregs(fs,extra-1);
3826}
3827else{
3828if(e->k!=VVOID)luaK_exp2nextreg(fs,e);
3829if(extra>0){
3830int reg=fs->freereg;
3831luaK_reserveregs(fs,extra);
3832luaK_nil(fs,reg,extra);
3833}
3834}
3835}
3836static void enterlevel(LexState*ls){
3837if(++ls->L->nCcalls>200)
3838luaX_lexerror(ls,"chunk has too many syntax levels",0);
3839}
3840#define leavelevel(ls)((ls)->L->nCcalls--)
3841static void enterblock(FuncState*fs,BlockCnt*bl,lu_byte isbreakable){
3842bl->breaklist=(-1);
3843bl->isbreakable=isbreakable;
3844bl->nactvar=fs->nactvar;
3845bl->upval=0;
3846bl->previous=fs->bl;
3847fs->bl=bl;
3848}
3849static void leaveblock(FuncState*fs){
3850BlockCnt*bl=fs->bl;
3851fs->bl=bl->previous;
3852removevars(fs->ls,bl->nactvar);
3853if(bl->upval)
3854luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0);
3855fs->freereg=fs->nactvar;
3856luaK_patchtohere(fs,bl->breaklist);
3857}
3858static void pushclosure(LexState*ls,FuncState*func,expdesc*v){
3859FuncState*fs=ls->fs;
3860Proto*f=fs->f;
3861int oldsize=f->sizep;
3862int i;
3863luaM_growvector(ls->L,f->p,fs->np,f->sizep,Proto*,
3864((1<<(9+9))-1),"constant table overflow");
3865while(oldsize<f->sizep)f->p[oldsize++]=NULL;
3866f->p[fs->np++]=func->f;
3867luaC_objbarrier(ls->L,f,func->f);
3868init_exp(v,VRELOCABLE,luaK_codeABx(fs,OP_CLOSURE,0,fs->np-1));
3869for(i=0;i<func->f->nups;i++){
3870OpCode o=(func->upvalues[i].k==VLOCAL)?OP_MOVE:OP_GETUPVAL;
3871luaK_codeABC(fs,o,0,func->upvalues[i].info,0);
3872}
3873}
3874static void open_func(LexState*ls,FuncState*fs){
3875lua_State*L=ls->L;
3876Proto*f=luaF_newproto(L);
3877fs->f=f;
3878fs->prev=ls->fs;
3879fs->ls=ls;
3880fs->L=L;
3881ls->fs=fs;
3882fs->pc=0;
3883fs->lasttarget=-1;
3884fs->jpc=(-1);
3885fs->freereg=0;
3886fs->nk=0;
3887fs->np=0;
3888fs->nlocvars=0;
3889fs->nactvar=0;
3890fs->bl=NULL;
3891f->source=ls->source;
3892f->maxstacksize=2;
3893fs->h=luaH_new(L,0,0);
3894sethvalue(L,L->top,fs->h);
3895incr_top(L);
3896setptvalue(L,L->top,f);
3897incr_top(L);
3898}
3899static void close_func(LexState*ls){
3900lua_State*L=ls->L;
3901FuncState*fs=ls->fs;
3902Proto*f=fs->f;
3903removevars(ls,0);
3904luaK_ret(fs,0,0);
3905luaM_reallocvector(L,f->code,f->sizecode,fs->pc,Instruction);
3906f->sizecode=fs->pc;
3907luaM_reallocvector(L,f->lineinfo,f->sizelineinfo,fs->pc,int);
3908f->sizelineinfo=fs->pc;
3909luaM_reallocvector(L,f->k,f->sizek,fs->nk,TValue);
3910f->sizek=fs->nk;
3911luaM_reallocvector(L,f->p,f->sizep,fs->np,Proto*);
3912f->sizep=fs->np;
3913luaM_reallocvector(L,f->locvars,f->sizelocvars,fs->nlocvars,LocVar);
3914f->sizelocvars=fs->nlocvars;
3915luaM_reallocvector(L,f->upvalues,f->sizeupvalues,f->nups,TString*);
3916f->sizeupvalues=f->nups;
3917ls->fs=fs->prev;
3918if(fs)anchor_token(ls);
3919L->top-=2;
3920}
3921static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff,const char*name){
3922struct LexState lexstate;
3923struct FuncState funcstate;
3924lexstate.buff=buff;
3925luaX_setinput(L,&lexstate,z,luaS_new(L,name));
3926open_func(&lexstate,&funcstate);
3927funcstate.f->is_vararg=2;
3928luaX_next(&lexstate);
3929chunk(&lexstate);
3930check(&lexstate,TK_EOS);
3931close_func(&lexstate);
3932return funcstate.f;
3933}
3934static void field(LexState*ls,expdesc*v){
3935FuncState*fs=ls->fs;
3936expdesc key;
3937luaK_exp2anyreg(fs,v);
3938luaX_next(ls);
3939checkname(ls,&key);
3940luaK_indexed(fs,v,&key);
3941}
3942static void yindex(LexState*ls,expdesc*v){
3943luaX_next(ls);
3944expr(ls,v);
3945luaK_exp2val(ls->fs,v);
3946checknext(ls,']');
3947}
3948struct ConsControl{
3949expdesc v;
3950expdesc*t;
3951int nh;
3952int na;
3953int tostore;
3954};
3955static void recfield(LexState*ls,struct ConsControl*cc){
3956FuncState*fs=ls->fs;
3957int reg=ls->fs->freereg;
3958expdesc key,val;
3959int rkkey;
3960if(ls->t.token==TK_NAME){
3961luaY_checklimit(fs,cc->nh,(INT_MAX-2),"items in a constructor");
3962checkname(ls,&key);
3963}
3964else
3965yindex(ls,&key);
3966cc->nh++;
3967checknext(ls,'=');
3968rkkey=luaK_exp2RK(fs,&key);
3969expr(ls,&val);
3970luaK_codeABC(fs,OP_SETTABLE,cc->t->u.s.info,rkkey,luaK_exp2RK(fs,&val));
3971fs->freereg=reg;
3972}
3973static void closelistfield(FuncState*fs,struct ConsControl*cc){
3974if(cc->v.k==VVOID)return;
3975luaK_exp2nextreg(fs,&cc->v);
3976cc->v.k=VVOID;
3977if(cc->tostore==50){
3978luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore);
3979cc->tostore=0;
3980}
3981}
3982static void lastlistfield(FuncState*fs,struct ConsControl*cc){
3983if(cc->tostore==0)return;
3984if(hasmultret(cc->v.k)){
3985luaK_setmultret(fs,&cc->v);
3986luaK_setlist(fs,cc->t->u.s.info,cc->na,(-1));
3987cc->na--;
3988}
3989else{
3990if(cc->v.k!=VVOID)
3991luaK_exp2nextreg(fs,&cc->v);
3992luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore);
3993}
3994}
3995static void listfield(LexState*ls,struct ConsControl*cc){
3996expr(ls,&cc->v);
3997luaY_checklimit(ls->fs,cc->na,(INT_MAX-2),"items in a constructor");
3998cc->na++;
3999cc->tostore++;
4000}
4001static void constructor(LexState*ls,expdesc*t){
4002FuncState*fs=ls->fs;
4003int line=ls->linenumber;
4004int pc=luaK_codeABC(fs,OP_NEWTABLE,0,0,0);
4005struct ConsControl cc;
4006cc.na=cc.nh=cc.tostore=0;
4007cc.t=t;
4008init_exp(t,VRELOCABLE,pc);
4009init_exp(&cc.v,VVOID,0);
4010luaK_exp2nextreg(ls->fs,t);
4011checknext(ls,'{');
4012do{
4013if(ls->t.token=='}')break;
4014closelistfield(fs,&cc);
4015switch(ls->t.token){
4016case TK_NAME:{
4017luaX_lookahead(ls);
4018if(ls->lookahead.token!='=')
4019listfield(ls,&cc);
4020else
4021recfield(ls,&cc);
4022break;
4023}
4024case'[':{
4025recfield(ls,&cc);
4026break;
4027}
4028default:{
4029listfield(ls,&cc);
4030break;
4031}
4032}
4033}while(testnext(ls,',')||testnext(ls,';'));
4034check_match(ls,'}','{',line);
4035lastlistfield(fs,&cc);
4036SETARG_B(fs->f->code[pc],luaO_int2fb(cc.na));
4037SETARG_C(fs->f->code[pc],luaO_int2fb(cc.nh));
4038}
4039static void parlist(LexState*ls){
4040FuncState*fs=ls->fs;
4041Proto*f=fs->f;
4042int nparams=0;
4043f->is_vararg=0;
4044if(ls->t.token!=')'){
4045do{
4046switch(ls->t.token){
4047case TK_NAME:{
4048new_localvar(ls,str_checkname(ls),nparams++);
4049break;
4050}
4051case TK_DOTS:{
4052luaX_next(ls);
4053f->is_vararg|=2;
4054break;
4055}
4056default:luaX_syntaxerror(ls,"<name> or "LUA_QL("...")" expected");
4057}
4058}while(!f->is_vararg&&testnext(ls,','));
4059}
4060adjustlocalvars(ls,nparams);
4061f->numparams=cast_byte(fs->nactvar-(f->is_vararg&1));
4062luaK_reserveregs(fs,fs->nactvar);
4063}
4064static void body(LexState*ls,expdesc*e,int needself,int line){
4065FuncState new_fs;
4066open_func(ls,&new_fs);
4067new_fs.f->linedefined=line;
4068checknext(ls,'(');
4069if(needself){
4070new_localvarliteral(ls,"self",0);
4071adjustlocalvars(ls,1);
4072}
4073parlist(ls);
4074checknext(ls,')');
4075chunk(ls);
4076new_fs.f->lastlinedefined=ls->linenumber;
4077check_match(ls,TK_END,TK_FUNCTION,line);
4078close_func(ls);
4079pushclosure(ls,&new_fs,e);
4080}
4081static int explist1(LexState*ls,expdesc*v){
4082int n=1;
4083expr(ls,v);
4084while(testnext(ls,',')){
4085luaK_exp2nextreg(ls->fs,v);
4086expr(ls,v);
4087n++;
4088}
4089return n;
4090}
4091static void funcargs(LexState*ls,expdesc*f){
4092FuncState*fs=ls->fs;
4093expdesc args;
4094int base,nparams;
4095int line=ls->linenumber;
4096switch(ls->t.token){
4097case'(':{
4098if(line!=ls->lastline)
4099luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
4100luaX_next(ls);
4101if(ls->t.token==')')
4102args.k=VVOID;
4103else{
4104explist1(ls,&args);
4105luaK_setmultret(fs,&args);
4106}
4107check_match(ls,')','(',line);
4108break;
4109}
4110case'{':{
4111constructor(ls,&args);
4112break;
4113}
4114case TK_STRING:{
4115codestring(ls,&args,ls->t.seminfo.ts);
4116luaX_next(ls);
4117break;
4118}
4119default:{
4120luaX_syntaxerror(ls,"function arguments expected");
4121return;
4122}
4123}
4124base=f->u.s.info;
4125if(hasmultret(args.k))
4126nparams=(-1);
4127else{
4128if(args.k!=VVOID)
4129luaK_exp2nextreg(fs,&args);
4130nparams=fs->freereg-(base+1);
4131}
4132init_exp(f,VCALL,luaK_codeABC(fs,OP_CALL,base,nparams+1,2));
4133luaK_fixline(fs,line);
4134fs->freereg=base+1;
4135}
4136static void prefixexp(LexState*ls,expdesc*v){
4137switch(ls->t.token){
4138case'(':{
4139int line=ls->linenumber;
4140luaX_next(ls);
4141expr(ls,v);
4142check_match(ls,')','(',line);
4143luaK_dischargevars(ls->fs,v);
4144return;
4145}
4146case TK_NAME:{
4147singlevar(ls,v);
4148return;
4149}
4150default:{
4151luaX_syntaxerror(ls,"unexpected symbol");
4152return;
4153}
4154}
4155}
4156static void primaryexp(LexState*ls,expdesc*v){
4157FuncState*fs=ls->fs;
4158prefixexp(ls,v);
4159for(;;){
4160switch(ls->t.token){
4161case'.':{
4162field(ls,v);
4163break;
4164}
4165case'[':{
4166expdesc key;
4167luaK_exp2anyreg(fs,v);
4168yindex(ls,&key);
4169luaK_indexed(fs,v,&key);
4170break;
4171}
4172case':':{
4173expdesc key;
4174luaX_next(ls);
4175checkname(ls,&key);
4176luaK_self(fs,v,&key);
4177funcargs(ls,v);
4178break;
4179}
4180case'(':case TK_STRING:case'{':{
4181luaK_exp2nextreg(fs,v);
4182funcargs(ls,v);
4183break;
4184}
4185default:return;
4186}
4187}
4188}
4189static void simpleexp(LexState*ls,expdesc*v){
4190switch(ls->t.token){
4191case TK_NUMBER:{
4192init_exp(v,VKNUM,0);
4193v->u.nval=ls->t.seminfo.r;
4194break;
4195}
4196case TK_STRING:{
4197codestring(ls,v,ls->t.seminfo.ts);
4198break;
4199}
4200case TK_NIL:{
4201init_exp(v,VNIL,0);
4202break;
4203}
4204case TK_TRUE:{
4205init_exp(v,VTRUE,0);
4206break;
4207}
4208case TK_FALSE:{
4209init_exp(v,VFALSE,0);
4210break;
4211}
4212case TK_DOTS:{
4213FuncState*fs=ls->fs;
4214check_condition(ls,fs->f->is_vararg,
4215"cannot use "LUA_QL("...")" outside a vararg function");
4216fs->f->is_vararg&=~4;
4217init_exp(v,VVARARG,luaK_codeABC(fs,OP_VARARG,0,1,0));
4218break;
4219}
4220case'{':{
4221constructor(ls,v);
4222return;
4223}
4224case TK_FUNCTION:{
4225luaX_next(ls);
4226body(ls,v,0,ls->linenumber);
4227return;
4228}
4229default:{
4230primaryexp(ls,v);
4231return;
4232}
4233}
4234luaX_next(ls);
4235}
4236static UnOpr getunopr(int op){
4237switch(op){
4238case TK_NOT:return OPR_NOT;
4239case'-':return OPR_MINUS;
4240case'#':return OPR_LEN;
4241default:return OPR_NOUNOPR;
4242}
4243}
4244static BinOpr getbinopr(int op){
4245switch(op){
4246case'+':return OPR_ADD;
4247case'-':return OPR_SUB;
4248case'*':return OPR_MUL;
4249case'/':return OPR_DIV;
4250case'%':return OPR_MOD;
4251case'^':return OPR_POW;
4252case TK_CONCAT:return OPR_CONCAT;
4253case TK_NE:return OPR_NE;
4254case TK_EQ:return OPR_EQ;
4255case'<':return OPR_LT;
4256case TK_LE:return OPR_LE;
4257case'>':return OPR_GT;
4258case TK_GE:return OPR_GE;
4259case TK_AND:return OPR_AND;
4260case TK_OR:return OPR_OR;
4261default:return OPR_NOBINOPR;
4262}
4263}
4264static const struct{
4265lu_byte left;
4266lu_byte right;
4267}priority[]={
4268{6,6},{6,6},{7,7},{7,7},{7,7},
4269{10,9},{5,4},
4270{3,3},{3,3},
4271{3,3},{3,3},{3,3},{3,3},
4272{2,2},{1,1}
4273};
4274static BinOpr subexpr(LexState*ls,expdesc*v,unsigned int limit){
4275BinOpr op;
4276UnOpr uop;
4277enterlevel(ls);
4278uop=getunopr(ls->t.token);
4279if(uop!=OPR_NOUNOPR){
4280luaX_next(ls);
4281subexpr(ls,v,8);
4282luaK_prefix(ls->fs,uop,v);
4283}
4284else simpleexp(ls,v);
4285op=getbinopr(ls->t.token);
4286while(op!=OPR_NOBINOPR&&priority[op].left>limit){
4287expdesc v2;
4288BinOpr nextop;
4289luaX_next(ls);
4290luaK_infix(ls->fs,op,v);
4291nextop=subexpr(ls,&v2,priority[op].right);
4292luaK_posfix(ls->fs,op,v,&v2);
4293op=nextop;
4294}
4295leavelevel(ls);
4296return op;
4297}
4298static void expr(LexState*ls,expdesc*v){
4299subexpr(ls,v,0);
4300}
4301static int block_follow(int token){
4302switch(token){
4303case TK_ELSE:case TK_ELSEIF:case TK_END:
4304case TK_UNTIL:case TK_EOS:
4305return 1;
4306default:return 0;
4307}
4308}
4309static void block(LexState*ls){
4310FuncState*fs=ls->fs;
4311BlockCnt bl;
4312enterblock(fs,&bl,0);
4313chunk(ls);
4314leaveblock(fs);
4315}
4316struct LHS_assign{
4317struct LHS_assign*prev;
4318expdesc v;
4319};
4320static void check_conflict(LexState*ls,struct LHS_assign*lh,expdesc*v){
4321FuncState*fs=ls->fs;
4322int extra=fs->freereg;
4323int conflict=0;
4324for(;lh;lh=lh->prev){
4325if(lh->v.k==VINDEXED){
4326if(lh->v.u.s.info==v->u.s.info){
4327conflict=1;
4328lh->v.u.s.info=extra;
4329}
4330if(lh->v.u.s.aux==v->u.s.info){
4331conflict=1;
4332lh->v.u.s.aux=extra;
4333}
4334}
4335}
4336if(conflict){
4337luaK_codeABC(fs,OP_MOVE,fs->freereg,v->u.s.info,0);
4338luaK_reserveregs(fs,1);
4339}
4340}
4341static void assignment(LexState*ls,struct LHS_assign*lh,int nvars){
4342expdesc e;
4343check_condition(ls,VLOCAL<=lh->v.k&&lh->v.k<=VINDEXED,
4344"syntax error");
4345if(testnext(ls,',')){
4346struct LHS_assign nv;
4347nv.prev=lh;
4348primaryexp(ls,&nv.v);
4349if(nv.v.k==VLOCAL)
4350check_conflict(ls,lh,&nv.v);
4351luaY_checklimit(ls->fs,nvars,200-ls->L->nCcalls,
4352"variables in assignment");
4353assignment(ls,&nv,nvars+1);
4354}
4355else{
4356int nexps;
4357checknext(ls,'=');
4358nexps=explist1(ls,&e);
4359if(nexps!=nvars){
4360adjust_assign(ls,nvars,nexps,&e);
4361if(nexps>nvars)
4362ls->fs->freereg-=nexps-nvars;
4363}
4364else{
4365luaK_setoneret(ls->fs,&e);
4366luaK_storevar(ls->fs,&lh->v,&e);
4367return;
4368}
4369}
4370init_exp(&e,VNONRELOC,ls->fs->freereg-1);
4371luaK_storevar(ls->fs,&lh->v,&e);
4372}
4373static int cond(LexState*ls){
4374expdesc v;
4375expr(ls,&v);
4376if(v.k==VNIL)v.k=VFALSE;
4377luaK_goiftrue(ls->fs,&v);
4378return v.f;
4379}
4380static void breakstat(LexState*ls){
4381FuncState*fs=ls->fs;
4382BlockCnt*bl=fs->bl;
4383int upval=0;
4384while(bl&&!bl->isbreakable){
4385upval|=bl->upval;
4386bl=bl->previous;
4387}
4388if(!bl)
4389luaX_syntaxerror(ls,"no loop to break");
4390if(upval)
4391luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0);
4392luaK_concat(fs,&bl->breaklist,luaK_jump(fs));
4393}
4394static void whilestat(LexState*ls,int line){
4395FuncState*fs=ls->fs;
4396int whileinit;
4397int condexit;
4398BlockCnt bl;
4399luaX_next(ls);
4400whileinit=luaK_getlabel(fs);
4401condexit=cond(ls);
4402enterblock(fs,&bl,1);
4403checknext(ls,TK_DO);
4404block(ls);
4405luaK_patchlist(fs,luaK_jump(fs),whileinit);
4406check_match(ls,TK_END,TK_WHILE,line);
4407leaveblock(fs);
4408luaK_patchtohere(fs,condexit);
4409}
4410static void repeatstat(LexState*ls,int line){
4411int condexit;
4412FuncState*fs=ls->fs;
4413int repeat_init=luaK_getlabel(fs);
4414BlockCnt bl1,bl2;
4415enterblock(fs,&bl1,1);
4416enterblock(fs,&bl2,0);
4417luaX_next(ls);
4418chunk(ls);
4419check_match(ls,TK_UNTIL,TK_REPEAT,line);
4420condexit=cond(ls);
4421if(!bl2.upval){
4422leaveblock(fs);
4423luaK_patchlist(ls->fs,condexit,repeat_init);
4424}
4425else{
4426breakstat(ls);
4427luaK_patchtohere(ls->fs,condexit);
4428leaveblock(fs);
4429luaK_patchlist(ls->fs,luaK_jump(fs),repeat_init);
4430}
4431leaveblock(fs);
4432}
4433static int exp1(LexState*ls){
4434expdesc e;
4435int k;
4436expr(ls,&e);
4437k=e.k;
4438luaK_exp2nextreg(ls->fs,&e);
4439return k;
4440}
4441static void forbody(LexState*ls,int base,int line,int nvars,int isnum){
4442BlockCnt bl;
4443FuncState*fs=ls->fs;
4444int prep,endfor;
4445adjustlocalvars(ls,3);
4446checknext(ls,TK_DO);
4447prep=isnum?luaK_codeAsBx(fs,OP_FORPREP,base,(-1)):luaK_jump(fs);
4448enterblock(fs,&bl,0);
4449adjustlocalvars(ls,nvars);
4450luaK_reserveregs(fs,nvars);
4451block(ls);
4452leaveblock(fs);
4453luaK_patchtohere(fs,prep);
4454endfor=(isnum)?luaK_codeAsBx(fs,OP_FORLOOP,base,(-1)):
4455luaK_codeABC(fs,OP_TFORLOOP,base,0,nvars);
4456luaK_fixline(fs,line);
4457luaK_patchlist(fs,(isnum?endfor:luaK_jump(fs)),prep+1);
4458}
4459static void fornum(LexState*ls,TString*varname,int line){
4460FuncState*fs=ls->fs;
4461int base=fs->freereg;
4462new_localvarliteral(ls,"(for index)",0);
4463new_localvarliteral(ls,"(for limit)",1);
4464new_localvarliteral(ls,"(for step)",2);
4465new_localvar(ls,varname,3);
4466checknext(ls,'=');
4467exp1(ls);
4468checknext(ls,',');
4469exp1(ls);
4470if(testnext(ls,','))
4471exp1(ls);
4472else{
4473luaK_codeABx(fs,OP_LOADK,fs->freereg,luaK_numberK(fs,1));
4474luaK_reserveregs(fs,1);
4475}
4476forbody(ls,base,line,1,1);
4477}
4478static void forlist(LexState*ls,TString*indexname){
4479FuncState*fs=ls->fs;
4480expdesc e;
4481int nvars=0;
4482int line;
4483int base=fs->freereg;
4484new_localvarliteral(ls,"(for generator)",nvars++);
4485new_localvarliteral(ls,"(for state)",nvars++);
4486new_localvarliteral(ls,"(for control)",nvars++);
4487new_localvar(ls,indexname,nvars++);
4488while(testnext(ls,','))
4489new_localvar(ls,str_checkname(ls),nvars++);
4490checknext(ls,TK_IN);
4491line=ls->linenumber;
4492adjust_assign(ls,3,explist1(ls,&e),&e);
4493luaK_checkstack(fs,3);
4494forbody(ls,base,line,nvars-3,0);
4495}
4496static void forstat(LexState*ls,int line){
4497FuncState*fs=ls->fs;
4498TString*varname;
4499BlockCnt bl;
4500enterblock(fs,&bl,1);
4501luaX_next(ls);
4502varname=str_checkname(ls);
4503switch(ls->t.token){
4504case'=':fornum(ls,varname,line);break;
4505case',':case TK_IN:forlist(ls,varname);break;
4506default:luaX_syntaxerror(ls,LUA_QL("=")" or "LUA_QL("in")" expected");
4507}
4508check_match(ls,TK_END,TK_FOR,line);
4509leaveblock(fs);
4510}
4511static int test_then_block(LexState*ls){
4512int condexit;
4513luaX_next(ls);
4514condexit=cond(ls);
4515checknext(ls,TK_THEN);
4516block(ls);
4517return condexit;
4518}
4519static void ifstat(LexState*ls,int line){
4520FuncState*fs=ls->fs;
4521int flist;
4522int escapelist=(-1);
4523flist=test_then_block(ls);
4524while(ls->t.token==TK_ELSEIF){
4525luaK_concat(fs,&escapelist,luaK_jump(fs));
4526luaK_patchtohere(fs,flist);
4527flist=test_then_block(ls);
4528}
4529if(ls->t.token==TK_ELSE){
4530luaK_concat(fs,&escapelist,luaK_jump(fs));
4531luaK_patchtohere(fs,flist);
4532luaX_next(ls);
4533block(ls);
4534}
4535else
4536luaK_concat(fs,&escapelist,flist);
4537luaK_patchtohere(fs,escapelist);
4538check_match(ls,TK_END,TK_IF,line);
4539}
4540static void localfunc(LexState*ls){
4541expdesc v,b;
4542FuncState*fs=ls->fs;
4543new_localvar(ls,str_checkname(ls),0);
4544init_exp(&v,VLOCAL,fs->freereg);
4545luaK_reserveregs(fs,1);
4546adjustlocalvars(ls,1);
4547body(ls,&b,0,ls->linenumber);
4548luaK_storevar(fs,&v,&b);
4549getlocvar(fs,fs->nactvar-1).startpc=fs->pc;
4550}
4551static void localstat(LexState*ls){
4552int nvars=0;
4553int nexps;
4554expdesc e;
4555do{
4556new_localvar(ls,str_checkname(ls),nvars++);
4557}while(testnext(ls,','));
4558if(testnext(ls,'='))
4559nexps=explist1(ls,&e);
4560else{
4561e.k=VVOID;
4562nexps=0;
4563}
4564adjust_assign(ls,nvars,nexps,&e);
4565adjustlocalvars(ls,nvars);
4566}
4567static int funcname(LexState*ls,expdesc*v){
4568int needself=0;
4569singlevar(ls,v);
4570while(ls->t.token=='.')
4571field(ls,v);
4572if(ls->t.token==':'){
4573needself=1;
4574field(ls,v);
4575}
4576return needself;
4577}
4578static void funcstat(LexState*ls,int line){
4579int needself;
4580expdesc v,b;
4581luaX_next(ls);
4582needself=funcname(ls,&v);
4583body(ls,&b,needself,line);
4584luaK_storevar(ls->fs,&v,&b);
4585luaK_fixline(ls->fs,line);
4586}
4587static void exprstat(LexState*ls){
4588FuncState*fs=ls->fs;
4589struct LHS_assign v;
4590primaryexp(ls,&v.v);
4591if(v.v.k==VCALL)
4592SETARG_C(getcode(fs,&v.v),1);
4593else{
4594v.prev=NULL;
4595assignment(ls,&v,1);
4596}
4597}
4598static void retstat(LexState*ls){
4599FuncState*fs=ls->fs;
4600expdesc e;
4601int first,nret;
4602luaX_next(ls);
4603if(block_follow(ls->t.token)||ls->t.token==';')
4604first=nret=0;
4605else{
4606nret=explist1(ls,&e);
4607if(hasmultret(e.k)){
4608luaK_setmultret(fs,&e);
4609if(e.k==VCALL&&nret==1){
4610SET_OPCODE(getcode(fs,&e),OP_TAILCALL);
4611}
4612first=fs->nactvar;
4613nret=(-1);
4614}
4615else{
4616if(nret==1)
4617first=luaK_exp2anyreg(fs,&e);
4618else{
4619luaK_exp2nextreg(fs,&e);
4620first=fs->nactvar;
4621}
4622}
4623}
4624luaK_ret(fs,first,nret);
4625}
4626static int statement(LexState*ls){
4627int line=ls->linenumber;
4628switch(ls->t.token){
4629case TK_IF:{
4630ifstat(ls,line);
4631return 0;
4632}
4633case TK_WHILE:{
4634whilestat(ls,line);
4635return 0;
4636}
4637case TK_DO:{
4638luaX_next(ls);
4639block(ls);
4640check_match(ls,TK_END,TK_DO,line);
4641return 0;
4642}
4643case TK_FOR:{
4644forstat(ls,line);
4645return 0;
4646}
4647case TK_REPEAT:{
4648repeatstat(ls,line);
4649return 0;
4650}
4651case TK_FUNCTION:{
4652funcstat(ls,line);
4653return 0;
4654}
4655case TK_LOCAL:{
4656luaX_next(ls);
4657if(testnext(ls,TK_FUNCTION))
4658localfunc(ls);
4659else
4660localstat(ls);
4661return 0;
4662}
4663case TK_RETURN:{
4664retstat(ls);
4665return 1;
4666}
4667case TK_BREAK:{
4668luaX_next(ls);
4669breakstat(ls);
4670return 1;
4671}
4672default:{
4673exprstat(ls);
4674return 0;
4675}
4676}
4677}
4678static void chunk(LexState*ls){
4679int islast=0;
4680enterlevel(ls);
4681while(!islast&&!block_follow(ls->t.token)){
4682islast=statement(ls);
4683testnext(ls,';');
4684ls->fs->freereg=ls->fs->nactvar;
4685}
4686leavelevel(ls);
4687}
4688static const TValue*luaV_tonumber(const TValue*obj,TValue*n){
4689lua_Number num;
4690if(ttisnumber(obj))return obj;
4691if(ttisstring(obj)&&luaO_str2d(svalue(obj),&num)){
4692setnvalue(n,num);
4693return n;
4694}
4695else
4696return NULL;
4697}
4698static int luaV_tostring(lua_State*L,StkId obj){
4699if(!ttisnumber(obj))
4700return 0;
4701else{
4702char s[32];
4703lua_Number n=nvalue(obj);
4704lua_number2str(s,n);
4705setsvalue(L,obj,luaS_new(L,s));
4706return 1;
4707}
4708}
4709static void callTMres(lua_State*L,StkId res,const TValue*f,
4710const TValue*p1,const TValue*p2){
4711ptrdiff_t result=savestack(L,res);
4712setobj(L,L->top,f);
4713setobj(L,L->top+1,p1);
4714setobj(L,L->top+2,p2);
4715luaD_checkstack(L,3);
4716L->top+=3;
4717luaD_call(L,L->top-3,1);
4718res=restorestack(L,result);
4719L->top--;
4720setobj(L,res,L->top);
4721}
4722static void callTM(lua_State*L,const TValue*f,const TValue*p1,
4723const TValue*p2,const TValue*p3){
4724setobj(L,L->top,f);
4725setobj(L,L->top+1,p1);
4726setobj(L,L->top+2,p2);
4727setobj(L,L->top+3,p3);
4728luaD_checkstack(L,4);
4729L->top+=4;
4730luaD_call(L,L->top-4,0);
4731}
4732static void luaV_gettable(lua_State*L,const TValue*t,TValue*key,StkId val){
4733int loop;
4734for(loop=0;loop<100;loop++){
4735const TValue*tm;
4736if(ttistable(t)){
4737Table*h=hvalue(t);
4738const TValue*res=luaH_get(h,key);
4739if(!ttisnil(res)||
4740(tm=fasttm(L,h->metatable,TM_INDEX))==NULL){
4741setobj(L,val,res);
4742return;
4743}
4744}
4745else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_INDEX)))
4746luaG_typeerror(L,t,"index");
4747if(ttisfunction(tm)){
4748callTMres(L,val,tm,t,key);
4749return;
4750}
4751t=tm;
4752}
4753luaG_runerror(L,"loop in gettable");
4754}
4755static void luaV_settable(lua_State*L,const TValue*t,TValue*key,StkId val){
4756int loop;
4757TValue temp;
4758for(loop=0;loop<100;loop++){
4759const TValue*tm;
4760if(ttistable(t)){
4761Table*h=hvalue(t);
4762TValue*oldval=luaH_set(L,h,key);
4763if(!ttisnil(oldval)||
4764(tm=fasttm(L,h->metatable,TM_NEWINDEX))==NULL){
4765setobj(L,oldval,val);
4766h->flags=0;
4767luaC_barriert(L,h,val);
4768return;
4769}
4770}
4771else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_NEWINDEX)))
4772luaG_typeerror(L,t,"index");
4773if(ttisfunction(tm)){
4774callTM(L,tm,t,key,val);
4775return;
4776}
4777setobj(L,&temp,tm);
4778t=&temp;
4779}
4780luaG_runerror(L,"loop in settable");
4781}
4782static int call_binTM(lua_State*L,const TValue*p1,const TValue*p2,
4783StkId res,TMS event){
4784const TValue*tm=luaT_gettmbyobj(L,p1,event);
4785if(ttisnil(tm))
4786tm=luaT_gettmbyobj(L,p2,event);
4787if(ttisnil(tm))return 0;
4788callTMres(L,res,tm,p1,p2);
4789return 1;
4790}
4791static const TValue*get_compTM(lua_State*L,Table*mt1,Table*mt2,
4792TMS event){
4793const TValue*tm1=fasttm(L,mt1,event);
4794const TValue*tm2;
4795if(tm1==NULL)return NULL;
4796if(mt1==mt2)return tm1;
4797tm2=fasttm(L,mt2,event);
4798if(tm2==NULL)return NULL;
4799if(luaO_rawequalObj(tm1,tm2))
4800return tm1;
4801return NULL;
4802}
4803static int call_orderTM(lua_State*L,const TValue*p1,const TValue*p2,
4804TMS event){
4805const TValue*tm1=luaT_gettmbyobj(L,p1,event);
4806const TValue*tm2;
4807if(ttisnil(tm1))return-1;
4808tm2=luaT_gettmbyobj(L,p2,event);
4809if(!luaO_rawequalObj(tm1,tm2))
4810return-1;
4811callTMres(L,L->top,tm1,p1,p2);
4812return!l_isfalse(L->top);
4813}
4814static int l_strcmp(const TString*ls,const TString*rs){
4815const char*l=getstr(ls);
4816size_t ll=ls->tsv.len;
4817const char*r=getstr(rs);
4818size_t lr=rs->tsv.len;
4819for(;;){
4820int temp=strcoll(l,r);
4821if(temp!=0)return temp;
4822else{
4823size_t len=strlen(l);
4824if(len==lr)
4825return(len==ll)?0:1;
4826else if(len==ll)
4827return-1;
4828len++;
4829l+=len;ll-=len;r+=len;lr-=len;
4830}
4831}
4832}
4833static int luaV_lessthan(lua_State*L,const TValue*l,const TValue*r){
4834int res;
4835if(ttype(l)!=ttype(r))
4836return luaG_ordererror(L,l,r);
4837else if(ttisnumber(l))
4838return luai_numlt(nvalue(l),nvalue(r));
4839else if(ttisstring(l))
4840return l_strcmp(rawtsvalue(l),rawtsvalue(r))<0;
4841else if((res=call_orderTM(L,l,r,TM_LT))!=-1)
4842return res;
4843return luaG_ordererror(L,l,r);
4844}
4845static int lessequal(lua_State*L,const TValue*l,const TValue*r){
4846int res;
4847if(ttype(l)!=ttype(r))
4848return luaG_ordererror(L,l,r);
4849else if(ttisnumber(l))
4850return luai_numle(nvalue(l),nvalue(r));
4851else if(ttisstring(l))
4852return l_strcmp(rawtsvalue(l),rawtsvalue(r))<=0;
4853else if((res=call_orderTM(L,l,r,TM_LE))!=-1)
4854return res;
4855else if((res=call_orderTM(L,r,l,TM_LT))!=-1)
4856return!res;
4857return luaG_ordererror(L,l,r);
4858}
4859static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2){
4860const TValue*tm;
4861switch(ttype(t1)){
4862case 0:return 1;
4863case 3:return luai_numeq(nvalue(t1),nvalue(t2));
4864case 1:return bvalue(t1)==bvalue(t2);
4865case 2:return pvalue(t1)==pvalue(t2);
4866case 7:{
4867if(uvalue(t1)==uvalue(t2))return 1;
4868tm=get_compTM(L,uvalue(t1)->metatable,uvalue(t2)->metatable,
4869TM_EQ);
4870break;
4871}
4872case 5:{
4873if(hvalue(t1)==hvalue(t2))return 1;
4874tm=get_compTM(L,hvalue(t1)->metatable,hvalue(t2)->metatable,TM_EQ);
4875break;
4876}
4877default:return gcvalue(t1)==gcvalue(t2);
4878}
4879if(tm==NULL)return 0;
4880callTMres(L,L->top,tm,t1,t2);
4881return!l_isfalse(L->top);
4882}
4883static void luaV_concat(lua_State*L,int total,int last){
4884do{
4885StkId top=L->base+last+1;
4886int n=2;
4887if(!(ttisstring(top-2)||ttisnumber(top-2))||!tostring(L,top-1)){
4888if(!call_binTM(L,top-2,top-1,top-2,TM_CONCAT))
4889luaG_concaterror(L,top-2,top-1);
4890}else if(tsvalue(top-1)->len==0)
4891(void)tostring(L,top-2);
4892else{
4893size_t tl=tsvalue(top-1)->len;
4894char*buffer;
4895int i;
4896for(n=1;n<total&&tostring(L,top-n-1);n++){
4897size_t l=tsvalue(top-n-1)->len;
4898if(l>=((size_t)(~(size_t)0)-2)-tl)luaG_runerror(L,"string length overflow");
4899tl+=l;
4900}
4901buffer=luaZ_openspace(L,&G(L)->buff,tl);
4902tl=0;
4903for(i=n;i>0;i--){
4904size_t l=tsvalue(top-i)->len;
4905memcpy(buffer+tl,svalue(top-i),l);
4906tl+=l;
4907}
4908setsvalue(L,top-n,luaS_newlstr(L,buffer,tl));
4909}
4910total-=n-1;
4911last-=n-1;
4912}while(total>1);
4913}
4914static void Arith(lua_State*L,StkId ra,const TValue*rb,
4915const TValue*rc,TMS op){
4916TValue tempb,tempc;
4917const TValue*b,*c;
4918if((b=luaV_tonumber(rb,&tempb))!=NULL&&
4919(c=luaV_tonumber(rc,&tempc))!=NULL){
4920lua_Number nb=nvalue(b),nc=nvalue(c);
4921switch(op){
4922case TM_ADD:setnvalue(ra,luai_numadd(nb,nc));break;
4923case TM_SUB:setnvalue(ra,luai_numsub(nb,nc));break;
4924case TM_MUL:setnvalue(ra,luai_nummul(nb,nc));break;
4925case TM_DIV:setnvalue(ra,luai_numdiv(nb,nc));break;
4926case TM_MOD:setnvalue(ra,luai_nummod(nb,nc));break;
4927case TM_POW:setnvalue(ra,luai_numpow(nb,nc));break;
4928case TM_UNM:setnvalue(ra,luai_numunm(nb));break;
4929default:break;
4930}
4931}
4932else if(!call_binTM(L,rb,rc,ra,op))
4933luaG_aritherror(L,rb,rc);
4934}
4935#define runtime_check(L,c){if(!(c))break;}
4936#define RA(i)(base+GETARG_A(i))
4937#define RB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgR,base+GETARG_B(i))
4938#define RKB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_B(i))?k+INDEXK(GETARG_B(i)):base+GETARG_B(i))
4939#define RKC(i)check_exp(getCMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_C(i))?k+INDEXK(GETARG_C(i)):base+GETARG_C(i))
4940#define KBx(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,k+GETARG_Bx(i))
4941#define dojump(L,pc,i){(pc)+=(i);}
4942#define Protect(x){L->savedpc=pc;{x;};base=L->base;}
4943#define arith_op(op,tm){TValue*rb=RKB(i);TValue*rc=RKC(i);if(ttisnumber(rb)&&ttisnumber(rc)){lua_Number nb=nvalue(rb),nc=nvalue(rc);setnvalue(ra,op(nb,nc));}else Protect(Arith(L,ra,rb,rc,tm));}
4944static void luaV_execute(lua_State*L,int nexeccalls){
4945LClosure*cl;
4946StkId base;
4947TValue*k;
4948const Instruction*pc;
4949reentry:
4950pc=L->savedpc;
4951cl=&clvalue(L->ci->func)->l;
4952base=L->base;
4953k=cl->p->k;
4954for(;;){
4955const Instruction i=*pc++;
4956StkId ra;
4957ra=RA(i);
4958switch(GET_OPCODE(i)){
4959case OP_MOVE:{
4960setobj(L,ra,RB(i));
4961continue;
4962}
4963case OP_LOADK:{
4964setobj(L,ra,KBx(i));
4965continue;
4966}
4967case OP_LOADBOOL:{
4968setbvalue(ra,GETARG_B(i));
4969if(GETARG_C(i))pc++;
4970continue;
4971}
4972case OP_LOADNIL:{
4973TValue*rb=RB(i);
4974do{
4975setnilvalue(rb--);
4976}while(rb>=ra);
4977continue;
4978}
4979case OP_GETUPVAL:{
4980int b=GETARG_B(i);
4981setobj(L,ra,cl->upvals[b]->v);
4982continue;
4983}
4984case OP_GETGLOBAL:{
4985TValue g;
4986TValue*rb=KBx(i);
4987sethvalue(L,&g,cl->env);
4988Protect(luaV_gettable(L,&g,rb,ra));
4989continue;
4990}
4991case OP_GETTABLE:{
4992Protect(luaV_gettable(L,RB(i),RKC(i),ra));
4993continue;
4994}
4995case OP_SETGLOBAL:{
4996TValue g;
4997sethvalue(L,&g,cl->env);
4998Protect(luaV_settable(L,&g,KBx(i),ra));
4999continue;
5000}
5001case OP_SETUPVAL:{
5002UpVal*uv=cl->upvals[GETARG_B(i)];
5003setobj(L,uv->v,ra);
5004luaC_barrier(L,uv,ra);
5005continue;
5006}
5007case OP_SETTABLE:{
5008Protect(luaV_settable(L,ra,RKB(i),RKC(i)));
5009continue;
5010}
5011case OP_NEWTABLE:{
5012int b=GETARG_B(i);
5013int c=GETARG_C(i);
5014sethvalue(L,ra,luaH_new(L,luaO_fb2int(b),luaO_fb2int(c)));
5015Protect(luaC_checkGC(L));
5016continue;
5017}
5018case OP_SELF:{
5019StkId rb=RB(i);
5020setobj(L,ra+1,rb);
5021Protect(luaV_gettable(L,rb,RKC(i),ra));
5022continue;
5023}
5024case OP_ADD:{
5025arith_op(luai_numadd,TM_ADD);
5026continue;
5027}
5028case OP_SUB:{
5029arith_op(luai_numsub,TM_SUB);
5030continue;
5031}
5032case OP_MUL:{
5033arith_op(luai_nummul,TM_MUL);
5034continue;
5035}
5036case OP_DIV:{
5037arith_op(luai_numdiv,TM_DIV);
5038continue;
5039}
5040case OP_MOD:{
5041arith_op(luai_nummod,TM_MOD);
5042continue;
5043}
5044case OP_POW:{
5045arith_op(luai_numpow,TM_POW);
5046continue;
5047}
5048case OP_UNM:{
5049TValue*rb=RB(i);
5050if(ttisnumber(rb)){
5051lua_Number nb=nvalue(rb);
5052setnvalue(ra,luai_numunm(nb));
5053}
5054else{
5055Protect(Arith(L,ra,rb,rb,TM_UNM));
5056}
5057continue;
5058}
5059case OP_NOT:{
5060int res=l_isfalse(RB(i));
5061setbvalue(ra,res);
5062continue;
5063}
5064case OP_LEN:{
5065const TValue*rb=RB(i);
5066switch(ttype(rb)){
5067case 5:{
5068setnvalue(ra,cast_num(luaH_getn(hvalue(rb))));
5069break;
5070}
5071case 4:{
5072setnvalue(ra,cast_num(tsvalue(rb)->len));
5073break;
5074}
5075default:{
5076Protect(
5077if(!call_binTM(L,rb,(&luaO_nilobject_),ra,TM_LEN))
5078luaG_typeerror(L,rb,"get length of");
5079)
5080}
5081}
5082continue;
5083}
5084case OP_CONCAT:{
5085int b=GETARG_B(i);
5086int c=GETARG_C(i);
5087Protect(luaV_concat(L,c-b+1,c);luaC_checkGC(L));
5088setobj(L,RA(i),base+b);
5089continue;
5090}
5091case OP_JMP:{
5092dojump(L,pc,GETARG_sBx(i));
5093continue;
5094}
5095case OP_EQ:{
5096TValue*rb=RKB(i);
5097TValue*rc=RKC(i);
5098Protect(
5099if(equalobj(L,rb,rc)==GETARG_A(i))
5100dojump(L,pc,GETARG_sBx(*pc));
5101)
5102pc++;
5103continue;
5104}
5105case OP_LT:{
5106Protect(
5107if(luaV_lessthan(L,RKB(i),RKC(i))==GETARG_A(i))
5108dojump(L,pc,GETARG_sBx(*pc));
5109)
5110pc++;
5111continue;
5112}
5113case OP_LE:{
5114Protect(
5115if(lessequal(L,RKB(i),RKC(i))==GETARG_A(i))
5116dojump(L,pc,GETARG_sBx(*pc));
5117)
5118pc++;
5119continue;
5120}
5121case OP_TEST:{
5122if(l_isfalse(ra)!=GETARG_C(i))
5123dojump(L,pc,GETARG_sBx(*pc));
5124pc++;
5125continue;
5126}
5127case OP_TESTSET:{
5128TValue*rb=RB(i);
5129if(l_isfalse(rb)!=GETARG_C(i)){
5130setobj(L,ra,rb);
5131dojump(L,pc,GETARG_sBx(*pc));
5132}
5133pc++;
5134continue;
5135}
5136case OP_CALL:{
5137int b=GETARG_B(i);
5138int nresults=GETARG_C(i)-1;
5139if(b!=0)L->top=ra+b;
5140L->savedpc=pc;
5141switch(luaD_precall(L,ra,nresults)){
5142case 0:{
5143nexeccalls++;
5144goto reentry;
5145}
5146case 1:{
5147if(nresults>=0)L->top=L->ci->top;
5148base=L->base;
5149continue;
5150}
5151default:{
5152return;
5153}
5154}
5155}
5156case OP_TAILCALL:{
5157int b=GETARG_B(i);
5158if(b!=0)L->top=ra+b;
5159L->savedpc=pc;
5160switch(luaD_precall(L,ra,(-1))){
5161case 0:{
5162CallInfo*ci=L->ci-1;
5163int aux;
5164StkId func=ci->func;
5165StkId pfunc=(ci+1)->func;
5166if(L->openupval)luaF_close(L,ci->base);
5167L->base=ci->base=ci->func+((ci+1)->base-pfunc);
5168for(aux=0;pfunc+aux<L->top;aux++)
5169setobj(L,func+aux,pfunc+aux);
5170ci->top=L->top=func+aux;
5171ci->savedpc=L->savedpc;
5172ci->tailcalls++;
5173L->ci--;
5174goto reentry;
5175}
5176case 1:{
5177base=L->base;
5178continue;
5179}
5180default:{
5181return;
5182}
5183}
5184}
5185case OP_RETURN:{
5186int b=GETARG_B(i);
5187if(b!=0)L->top=ra+b-1;
5188if(L->openupval)luaF_close(L,base);
5189L->savedpc=pc;
5190b=luaD_poscall(L,ra);
5191if(--nexeccalls==0)
5192return;
5193else{
5194if(b)L->top=L->ci->top;
5195goto reentry;
5196}
5197}
5198case OP_FORLOOP:{
5199lua_Number step=nvalue(ra+2);
5200lua_Number idx=luai_numadd(nvalue(ra),step);
5201lua_Number limit=nvalue(ra+1);
5202if(luai_numlt(0,step)?luai_numle(idx,limit)
5203:luai_numle(limit,idx)){
5204dojump(L,pc,GETARG_sBx(i));
5205setnvalue(ra,idx);
5206setnvalue(ra+3,idx);
5207}
5208continue;
5209}
5210case OP_FORPREP:{
5211const TValue*init=ra;
5212const TValue*plimit=ra+1;
5213const TValue*pstep=ra+2;
5214L->savedpc=pc;
5215if(!tonumber(init,ra))
5216luaG_runerror(L,LUA_QL("for")" initial value must be a number");
5217else if(!tonumber(plimit,ra+1))
5218luaG_runerror(L,LUA_QL("for")" limit must be a number");
5219else if(!tonumber(pstep,ra+2))
5220luaG_runerror(L,LUA_QL("for")" step must be a number");
5221setnvalue(ra,luai_numsub(nvalue(ra),nvalue(pstep)));
5222dojump(L,pc,GETARG_sBx(i));
5223continue;
5224}
5225case OP_TFORLOOP:{
5226StkId cb=ra+3;
5227setobj(L,cb+2,ra+2);
5228setobj(L,cb+1,ra+1);
5229setobj(L,cb,ra);
5230L->top=cb+3;
5231Protect(luaD_call(L,cb,GETARG_C(i)));
5232L->top=L->ci->top;
5233cb=RA(i)+3;
5234if(!ttisnil(cb)){
5235setobj(L,cb-1,cb);
5236dojump(L,pc,GETARG_sBx(*pc));
5237}
5238pc++;
5239continue;
5240}
5241case OP_SETLIST:{
5242int n=GETARG_B(i);
5243int c=GETARG_C(i);
5244int last;
5245Table*h;
5246if(n==0){
5247n=cast_int(L->top-ra)-1;
5248L->top=L->ci->top;
5249}
5250if(c==0)c=cast_int(*pc++);
5251runtime_check(L,ttistable(ra));
5252h=hvalue(ra);
5253last=((c-1)*50)+n;
5254if(last>h->sizearray)
5255luaH_resizearray(L,h,last);
5256for(;n>0;n--){
5257TValue*val=ra+n;
5258setobj(L,luaH_setnum(L,h,last--),val);
5259luaC_barriert(L,h,val);
5260}
5261continue;
5262}
5263case OP_CLOSE:{
5264luaF_close(L,ra);
5265continue;
5266}
5267case OP_CLOSURE:{
5268Proto*p;
5269Closure*ncl;
5270int nup,j;
5271p=cl->p->p[GETARG_Bx(i)];
5272nup=p->nups;
5273ncl=luaF_newLclosure(L,nup,cl->env);
5274ncl->l.p=p;
5275for(j=0;j<nup;j++,pc++){
5276if(GET_OPCODE(*pc)==OP_GETUPVAL)
5277ncl->l.upvals[j]=cl->upvals[GETARG_B(*pc)];
5278else{
5279ncl->l.upvals[j]=luaF_findupval(L,base+GETARG_B(*pc));
5280}
5281}
5282setclvalue(L,ra,ncl);
5283Protect(luaC_checkGC(L));
5284continue;
5285}
5286case OP_VARARG:{
5287int b=GETARG_B(i)-1;
5288int j;
5289CallInfo*ci=L->ci;
5290int n=cast_int(ci->base-ci->func)-cl->p->numparams-1;
5291if(b==(-1)){
5292Protect(luaD_checkstack(L,n));
5293ra=RA(i);
5294b=n;
5295L->top=ra+n;
5296}
5297for(j=0;j<b;j++){
5298if(j<n){
5299setobj(L,ra+j,ci->base-n+j);
5300}
5301else{
5302setnilvalue(ra+j);
5303}
5304}
5305continue;
5306}
5307}
5308}
5309}
5310#define api_checknelems(L,n)luai_apicheck(L,(n)<=(L->top-L->base))
5311#define api_checkvalidindex(L,i)luai_apicheck(L,(i)!=(&luaO_nilobject_))
5312#define api_incr_top(L){luai_apicheck(L,L->top<L->ci->top);L->top++;}
5313static TValue*index2adr(lua_State*L,int idx){
5314if(idx>0){
5315TValue*o=L->base+(idx-1);
5316luai_apicheck(L,idx<=L->ci->top-L->base);
5317if(o>=L->top)return cast(TValue*,(&luaO_nilobject_));
5318else return o;
5319}
5320else if(idx>(-10000)){
5321luai_apicheck(L,idx!=0&&-idx<=L->top-L->base);
5322return L->top+idx;
5323}
5324else switch(idx){
5325case(-10000):return registry(L);
5326case(-10001):{
5327Closure*func=curr_func(L);
5328sethvalue(L,&L->env,func->c.env);
5329return&L->env;
5330}
5331case(-10002):return gt(L);
5332default:{
5333Closure*func=curr_func(L);
5334idx=(-10002)-idx;
5335return(idx<=func->c.nupvalues)
5336?&func->c.upvalue[idx-1]
5337:cast(TValue*,(&luaO_nilobject_));
5338}
5339}
5340}
5341static Table*getcurrenv(lua_State*L){
5342if(L->ci==L->base_ci)
5343return hvalue(gt(L));
5344else{
5345Closure*func=curr_func(L);
5346return func->c.env;
5347}
5348}
5349static int lua_checkstack(lua_State*L,int size){
5350int res=1;
5351if(size>8000||(L->top-L->base+size)>8000)
5352res=0;
5353else if(size>0){
5354luaD_checkstack(L,size);
5355if(L->ci->top<L->top+size)
5356L->ci->top=L->top+size;
5357}
5358return res;
5359}
5360static lua_CFunction lua_atpanic(lua_State*L,lua_CFunction panicf){
5361lua_CFunction old;
5362old=G(L)->panic;
5363G(L)->panic=panicf;
5364return old;
5365}
5366static int lua_gettop(lua_State*L){
5367return cast_int(L->top-L->base);
5368}
5369static void lua_settop(lua_State*L,int idx){
5370if(idx>=0){
5371luai_apicheck(L,idx<=L->stack_last-L->base);
5372while(L->top<L->base+idx)
5373setnilvalue(L->top++);
5374L->top=L->base+idx;
5375}
5376else{
5377luai_apicheck(L,-(idx+1)<=(L->top-L->base));
5378L->top+=idx+1;
5379}
5380}
5381static void lua_remove(lua_State*L,int idx){
5382StkId p;
5383p=index2adr(L,idx);
5384api_checkvalidindex(L,p);
5385while(++p<L->top)setobj(L,p-1,p);
5386L->top--;
5387}
5388static void lua_insert(lua_State*L,int idx){
5389StkId p;
5390StkId q;
5391p=index2adr(L,idx);
5392api_checkvalidindex(L,p);
5393for(q=L->top;q>p;q--)setobj(L,q,q-1);
5394setobj(L,p,L->top);
5395}
5396static void lua_replace(lua_State*L,int idx){
5397StkId o;
5398if(idx==(-10001)&&L->ci==L->base_ci)
5399luaG_runerror(L,"no calling environment");
5400api_checknelems(L,1);
5401o=index2adr(L,idx);
5402api_checkvalidindex(L,o);
5403if(idx==(-10001)){
5404Closure*func=curr_func(L);
5405luai_apicheck(L,ttistable(L->top-1));
5406func->c.env=hvalue(L->top-1);
5407luaC_barrier(L,func,L->top-1);
5408}
5409else{
5410setobj(L,o,L->top-1);
5411if(idx<(-10002))
5412luaC_barrier(L,curr_func(L),L->top-1);
5413}
5414L->top--;
5415}
5416static void lua_pushvalue(lua_State*L,int idx){
5417setobj(L,L->top,index2adr(L,idx));
5418api_incr_top(L);
5419}
5420static int lua_type(lua_State*L,int idx){
5421StkId o=index2adr(L,idx);
5422return(o==(&luaO_nilobject_))?(-1):ttype(o);
5423}
5424static const char*lua_typename(lua_State*L,int t){
5425UNUSED(L);
5426return(t==(-1))?"no value":luaT_typenames[t];
5427}
5428static int lua_iscfunction(lua_State*L,int idx){
5429StkId o=index2adr(L,idx);
5430return iscfunction(o);
5431}
5432static int lua_isnumber(lua_State*L,int idx){
5433TValue n;
5434const TValue*o=index2adr(L,idx);
5435return tonumber(o,&n);
5436}
5437static int lua_isstring(lua_State*L,int idx){
5438int t=lua_type(L,idx);
5439return(t==4||t==3);
5440}
5441static int lua_rawequal(lua_State*L,int index1,int index2){
5442StkId o1=index2adr(L,index1);
5443StkId o2=index2adr(L,index2);
5444return(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0
5445:luaO_rawequalObj(o1,o2);
5446}
5447static int lua_lessthan(lua_State*L,int index1,int index2){
5448StkId o1,o2;
5449int i;
5450o1=index2adr(L,index1);
5451o2=index2adr(L,index2);
5452i=(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0
5453:luaV_lessthan(L,o1,o2);
5454return i;
5455}
5456static lua_Number lua_tonumber(lua_State*L,int idx){
5457TValue n;
5458const TValue*o=index2adr(L,idx);
5459if(tonumber(o,&n))
5460return nvalue(o);
5461else
5462return 0;
5463}
5464static lua_Integer lua_tointeger(lua_State*L,int idx){
5465TValue n;
5466const TValue*o=index2adr(L,idx);
5467if(tonumber(o,&n)){
5468lua_Integer res;
5469lua_Number num=nvalue(o);
5470lua_number2integer(res,num);
5471return res;
5472}
5473else
5474return 0;
5475}
5476static int lua_toboolean(lua_State*L,int idx){
5477const TValue*o=index2adr(L,idx);
5478return!l_isfalse(o);
5479}
5480static const char*lua_tolstring(lua_State*L,int idx,size_t*len){
5481StkId o=index2adr(L,idx);
5482if(!ttisstring(o)){
5483if(!luaV_tostring(L,o)){
5484if(len!=NULL)*len=0;
5485return NULL;
5486}
5487luaC_checkGC(L);
5488o=index2adr(L,idx);
5489}
5490if(len!=NULL)*len=tsvalue(o)->len;
5491return svalue(o);
5492}
5493static size_t lua_objlen(lua_State*L,int idx){
5494StkId o=index2adr(L,idx);
5495switch(ttype(o)){
5496case 4:return tsvalue(o)->len;
5497case 7:return uvalue(o)->len;
5498case 5:return luaH_getn(hvalue(o));
5499case 3:{
5500size_t l;
5501l=(luaV_tostring(L,o)?tsvalue(o)->len:0);
5502return l;
5503}
5504default:return 0;
5505}
5506}
5507static lua_CFunction lua_tocfunction(lua_State*L,int idx){
5508StkId o=index2adr(L,idx);
5509return(!iscfunction(o))?NULL:clvalue(o)->c.f;
5510}
5511static void*lua_touserdata(lua_State*L,int idx){
5512StkId o=index2adr(L,idx);
5513switch(ttype(o)){
5514case 7:return(rawuvalue(o)+1);
5515case 2:return pvalue(o);
5516default:return NULL;
5517}
5518}
5519static void lua_pushnil(lua_State*L){
5520setnilvalue(L->top);
5521api_incr_top(L);
5522}
5523static void lua_pushnumber(lua_State*L,lua_Number n){
5524setnvalue(L->top,n);
5525api_incr_top(L);
5526}
5527static void lua_pushinteger(lua_State*L,lua_Integer n){
5528setnvalue(L->top,cast_num(n));
5529api_incr_top(L);
5530}
5531static void lua_pushlstring(lua_State*L,const char*s,size_t len){
5532luaC_checkGC(L);
5533setsvalue(L,L->top,luaS_newlstr(L,s,len));
5534api_incr_top(L);
5535}
5536static void lua_pushstring(lua_State*L,const char*s){
5537if(s==NULL)
5538lua_pushnil(L);
5539else
5540lua_pushlstring(L,s,strlen(s));
5541}
5542static const char*lua_pushvfstring(lua_State*L,const char*fmt,
5543va_list argp){
5544const char*ret;
5545luaC_checkGC(L);
5546ret=luaO_pushvfstring(L,fmt,argp);
5547return ret;
5548}
5549static const char*lua_pushfstring(lua_State*L,const char*fmt,...){
5550const char*ret;
5551va_list argp;
5552luaC_checkGC(L);
5553va_start(argp,fmt);
5554ret=luaO_pushvfstring(L,fmt,argp);
5555va_end(argp);
5556return ret;
5557}
5558static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n){
5559Closure*cl;
5560luaC_checkGC(L);
5561api_checknelems(L,n);
5562cl=luaF_newCclosure(L,n,getcurrenv(L));
5563cl->c.f=fn;
5564L->top-=n;
5565while(n--)
5566setobj(L,&cl->c.upvalue[n],L->top+n);
5567setclvalue(L,L->top,cl);
5568api_incr_top(L);
5569}
5570static void lua_pushboolean(lua_State*L,int b){
5571setbvalue(L->top,(b!=0));
5572api_incr_top(L);
5573}
5574static int lua_pushthread(lua_State*L){
5575setthvalue(L,L->top,L);
5576api_incr_top(L);
5577return(G(L)->mainthread==L);
5578}
5579static void lua_gettable(lua_State*L,int idx){
5580StkId t;
5581t=index2adr(L,idx);
5582api_checkvalidindex(L,t);
5583luaV_gettable(L,t,L->top-1,L->top-1);
5584}
5585static void lua_getfield(lua_State*L,int idx,const char*k){
5586StkId t;
5587TValue key;
5588t=index2adr(L,idx);
5589api_checkvalidindex(L,t);
5590setsvalue(L,&key,luaS_new(L,k));
5591luaV_gettable(L,t,&key,L->top);
5592api_incr_top(L);
5593}
5594static void lua_rawget(lua_State*L,int idx){
5595StkId t;
5596t=index2adr(L,idx);
5597luai_apicheck(L,ttistable(t));
5598setobj(L,L->top-1,luaH_get(hvalue(t),L->top-1));
5599}
5600static void lua_rawgeti(lua_State*L,int idx,int n){
5601StkId o;
5602o=index2adr(L,idx);
5603luai_apicheck(L,ttistable(o));
5604setobj(L,L->top,luaH_getnum(hvalue(o),n));
5605api_incr_top(L);
5606}
5607static void lua_createtable(lua_State*L,int narray,int nrec){
5608luaC_checkGC(L);
5609sethvalue(L,L->top,luaH_new(L,narray,nrec));
5610api_incr_top(L);
5611}
5612static int lua_getmetatable(lua_State*L,int objindex){
5613const TValue*obj;
5614Table*mt=NULL;
5615int res;
5616obj=index2adr(L,objindex);
5617switch(ttype(obj)){
5618case 5:
5619mt=hvalue(obj)->metatable;
5620break;
5621case 7:
5622mt=uvalue(obj)->metatable;
5623break;
5624default:
5625mt=G(L)->mt[ttype(obj)];
5626break;
5627}
5628if(mt==NULL)
5629res=0;
5630else{
5631sethvalue(L,L->top,mt);
5632api_incr_top(L);
5633res=1;
5634}
5635return res;
5636}
5637static void lua_getfenv(lua_State*L,int idx){
5638StkId o;
5639o=index2adr(L,idx);
5640api_checkvalidindex(L,o);
5641switch(ttype(o)){
5642case 6:
5643sethvalue(L,L->top,clvalue(o)->c.env);
5644break;
5645case 7:
5646sethvalue(L,L->top,uvalue(o)->env);
5647break;
5648case 8:
5649setobj(L,L->top,gt(thvalue(o)));
5650break;
5651default:
5652setnilvalue(L->top);
5653break;
5654}
5655api_incr_top(L);
5656}
5657static void lua_settable(lua_State*L,int idx){
5658StkId t;
5659api_checknelems(L,2);
5660t=index2adr(L,idx);
5661api_checkvalidindex(L,t);
5662luaV_settable(L,t,L->top-2,L->top-1);
5663L->top-=2;
5664}
5665static void lua_setfield(lua_State*L,int idx,const char*k){
5666StkId t;
5667TValue key;
5668api_checknelems(L,1);
5669t=index2adr(L,idx);
5670api_checkvalidindex(L,t);
5671setsvalue(L,&key,luaS_new(L,k));
5672luaV_settable(L,t,&key,L->top-1);
5673L->top--;
5674}
5675static void lua_rawset(lua_State*L,int idx){
5676StkId t;
5677api_checknelems(L,2);
5678t=index2adr(L,idx);
5679luai_apicheck(L,ttistable(t));
5680setobj(L,luaH_set(L,hvalue(t),L->top-2),L->top-1);
5681luaC_barriert(L,hvalue(t),L->top-1);
5682L->top-=2;
5683}
5684static void lua_rawseti(lua_State*L,int idx,int n){
5685StkId o;
5686api_checknelems(L,1);
5687o=index2adr(L,idx);
5688luai_apicheck(L,ttistable(o));
5689setobj(L,luaH_setnum(L,hvalue(o),n),L->top-1);
5690luaC_barriert(L,hvalue(o),L->top-1);
5691L->top--;
5692}
5693static int lua_setmetatable(lua_State*L,int objindex){
5694TValue*obj;
5695Table*mt;
5696api_checknelems(L,1);
5697obj=index2adr(L,objindex);
5698api_checkvalidindex(L,obj);
5699if(ttisnil(L->top-1))
5700mt=NULL;
5701else{
5702luai_apicheck(L,ttistable(L->top-1));
5703mt=hvalue(L->top-1);
5704}
5705switch(ttype(obj)){
5706case 5:{
5707hvalue(obj)->metatable=mt;
5708if(mt)
5709luaC_objbarriert(L,hvalue(obj),mt);
5710break;
5711}
5712case 7:{
5713uvalue(obj)->metatable=mt;
5714if(mt)
5715luaC_objbarrier(L,rawuvalue(obj),mt);
5716break;
5717}
5718default:{
5719G(L)->mt[ttype(obj)]=mt;
5720break;
5721}
5722}
5723L->top--;
5724return 1;
5725}
5726static int lua_setfenv(lua_State*L,int idx){
5727StkId o;
5728int res=1;
5729api_checknelems(L,1);
5730o=index2adr(L,idx);
5731api_checkvalidindex(L,o);
5732luai_apicheck(L,ttistable(L->top-1));
5733switch(ttype(o)){
5734case 6:
5735clvalue(o)->c.env=hvalue(L->top-1);
5736break;
5737case 7:
5738uvalue(o)->env=hvalue(L->top-1);
5739break;
5740case 8:
5741sethvalue(L,gt(thvalue(o)),hvalue(L->top-1));
5742break;
5743default:
5744res=0;
5745break;
5746}
5747if(res)luaC_objbarrier(L,gcvalue(o),hvalue(L->top-1));
5748L->top--;
5749return res;
5750}
5751#define adjustresults(L,nres){if(nres==(-1)&&L->top>=L->ci->top)L->ci->top=L->top;}
5752#define checkresults(L,na,nr)luai_apicheck(L,(nr)==(-1)||(L->ci->top-L->top>=(nr)-(na)))
5753static void lua_call(lua_State*L,int nargs,int nresults){
5754StkId func;
5755api_checknelems(L,nargs+1);
5756checkresults(L,nargs,nresults);
5757func=L->top-(nargs+1);
5758luaD_call(L,func,nresults);
5759adjustresults(L,nresults);
5760}
5761struct CallS{
5762StkId func;
5763int nresults;
5764};
5765static void f_call(lua_State*L,void*ud){
5766struct CallS*c=cast(struct CallS*,ud);
5767luaD_call(L,c->func,c->nresults);
5768}
5769static int lua_pcall(lua_State*L,int nargs,int nresults,int errfunc){
5770struct CallS c;
5771int status;
5772ptrdiff_t func;
5773api_checknelems(L,nargs+1);
5774checkresults(L,nargs,nresults);
5775if(errfunc==0)
5776func=0;
5777else{
5778StkId o=index2adr(L,errfunc);
5779api_checkvalidindex(L,o);
5780func=savestack(L,o);
5781}
5782c.func=L->top-(nargs+1);
5783c.nresults=nresults;
5784status=luaD_pcall(L,f_call,&c,savestack(L,c.func),func);
5785adjustresults(L,nresults);
5786return status;
5787}
5788static int lua_load(lua_State*L,lua_Reader reader,void*data,
5789const char*chunkname){
5790ZIO z;
5791int status;
5792if(!chunkname)chunkname="?";
5793luaZ_init(L,&z,reader,data);
5794status=luaD_protectedparser(L,&z,chunkname);
5795return status;
5796}
5797static int lua_error(lua_State*L){
5798api_checknelems(L,1);
5799luaG_errormsg(L);
5800return 0;
5801}
5802static int lua_next(lua_State*L,int idx){
5803StkId t;
5804int more;
5805t=index2adr(L,idx);
5806luai_apicheck(L,ttistable(t));
5807more=luaH_next(L,hvalue(t),L->top-1);
5808if(more){
5809api_incr_top(L);
5810}
5811else
5812L->top-=1;
5813return more;
5814}
5815static void lua_concat(lua_State*L,int n){
5816api_checknelems(L,n);
5817if(n>=2){
5818luaC_checkGC(L);
5819luaV_concat(L,n,cast_int(L->top-L->base)-1);
5820L->top-=(n-1);
5821}
5822else if(n==0){
5823setsvalue(L,L->top,luaS_newlstr(L,"",0));
5824api_incr_top(L);
5825}
5826}
5827static void*lua_newuserdata(lua_State*L,size_t size){
5828Udata*u;
5829luaC_checkGC(L);
5830u=luaS_newudata(L,size,getcurrenv(L));
5831setuvalue(L,L->top,u);
5832api_incr_top(L);
5833return u+1;
5834}
5835#define luaL_getn(L,i)((int)lua_objlen(L,i))
5836#define luaL_setn(L,i,j)((void)0)
5837typedef struct luaL_Reg{
5838const char*name;
5839lua_CFunction func;
5840}luaL_Reg;
5841static void luaI_openlib(lua_State*L,const char*libname,
5842const luaL_Reg*l,int nup);
5843static int luaL_argerror(lua_State*L,int numarg,const char*extramsg);
5844static const char* luaL_checklstring(lua_State*L,int numArg,
5845size_t*l);
5846static const char* luaL_optlstring(lua_State*L,int numArg,
5847const char*def,size_t*l);
5848static lua_Integer luaL_checkinteger(lua_State*L,int numArg);
5849static lua_Integer luaL_optinteger(lua_State*L,int nArg,
5850lua_Integer def);
5851static int luaL_error(lua_State*L,const char*fmt,...);
5852static const char* luaL_findtable(lua_State*L,int idx,
5853const char*fname,int szhint);
5854#define luaL_argcheck(L,cond,numarg,extramsg)((void)((cond)||luaL_argerror(L,(numarg),(extramsg))))
5855#define luaL_checkstring(L,n)(luaL_checklstring(L,(n),NULL))
5856#define luaL_optstring(L,n,d)(luaL_optlstring(L,(n),(d),NULL))
5857#define luaL_checkint(L,n)((int)luaL_checkinteger(L,(n)))
5858#define luaL_optint(L,n,d)((int)luaL_optinteger(L,(n),(d)))
5859#define luaL_typename(L,i)lua_typename(L,lua_type(L,(i)))
5860#define luaL_getmetatable(L,n)(lua_getfield(L,(-10000),(n)))
5861#define luaL_opt(L,f,n,d)(lua_isnoneornil(L,(n))?(d):f(L,(n)))
5862typedef struct luaL_Buffer{
5863char*p;
5864int lvl;
5865lua_State*L;
5866char buffer[BUFSIZ];
5867}luaL_Buffer;
5868#define luaL_addchar(B,c)((void)((B)->p<((B)->buffer+BUFSIZ)||luaL_prepbuffer(B)),(*(B)->p++=(char)(c)))
5869#define luaL_addsize(B,n)((B)->p+=(n))
5870static char* luaL_prepbuffer(luaL_Buffer*B);
5871static int luaL_argerror(lua_State*L,int narg,const char*extramsg){
5872lua_Debug ar;
5873if(!lua_getstack(L,0,&ar))
5874return luaL_error(L,"bad argument #%d (%s)",narg,extramsg);
5875lua_getinfo(L,"n",&ar);
5876if(strcmp(ar.namewhat,"method")==0){
5877narg--;
5878if(narg==0)
5879return luaL_error(L,"calling "LUA_QL("%s")" on bad self (%s)",
5880ar.name,extramsg);
5881}
5882if(ar.name==NULL)
5883ar.name="?";
5884return luaL_error(L,"bad argument #%d to "LUA_QL("%s")" (%s)",
5885narg,ar.name,extramsg);
5886}
5887static int luaL_typerror(lua_State*L,int narg,const char*tname){
5888const char*msg=lua_pushfstring(L,"%s expected, got %s",
5889tname,luaL_typename(L,narg));
5890return luaL_argerror(L,narg,msg);
5891}
5892static void tag_error(lua_State*L,int narg,int tag){
5893luaL_typerror(L,narg,lua_typename(L,tag));
5894}
5895static void luaL_where(lua_State*L,int level){
5896lua_Debug ar;
5897if(lua_getstack(L,level,&ar)){
5898lua_getinfo(L,"Sl",&ar);
5899if(ar.currentline>0){
5900lua_pushfstring(L,"%s:%d: ",ar.short_src,ar.currentline);
5901return;
5902}
5903}
5904lua_pushliteral(L,"");
5905}
5906static int luaL_error(lua_State*L,const char*fmt,...){
5907va_list argp;
5908va_start(argp,fmt);
5909luaL_where(L,1);
5910lua_pushvfstring(L,fmt,argp);
5911va_end(argp);
5912lua_concat(L,2);
5913return lua_error(L);
5914}
5915static int luaL_newmetatable(lua_State*L,const char*tname){
5916lua_getfield(L,(-10000),tname);
5917if(!lua_isnil(L,-1))
5918return 0;
5919lua_pop(L,1);
5920lua_newtable(L);
5921lua_pushvalue(L,-1);
5922lua_setfield(L,(-10000),tname);
5923return 1;
5924}
5925static void*luaL_checkudata(lua_State*L,int ud,const char*tname){
5926void*p=lua_touserdata(L,ud);
5927if(p!=NULL){
5928if(lua_getmetatable(L,ud)){
5929lua_getfield(L,(-10000),tname);
5930if(lua_rawequal(L,-1,-2)){
5931lua_pop(L,2);
5932return p;
5933}
5934}
5935}
5936luaL_typerror(L,ud,tname);
5937return NULL;
5938}
5939static void luaL_checkstack(lua_State*L,int space,const char*mes){
5940if(!lua_checkstack(L,space))
5941luaL_error(L,"stack overflow (%s)",mes);
5942}
5943static void luaL_checktype(lua_State*L,int narg,int t){
5944if(lua_type(L,narg)!=t)
5945tag_error(L,narg,t);
5946}
5947static void luaL_checkany(lua_State*L,int narg){
5948if(lua_type(L,narg)==(-1))
5949luaL_argerror(L,narg,"value expected");
5950}
5951static const char*luaL_checklstring(lua_State*L,int narg,size_t*len){
5952const char*s=lua_tolstring(L,narg,len);
5953if(!s)tag_error(L,narg,4);
5954return s;
5955}
5956static const char*luaL_optlstring(lua_State*L,int narg,
5957const char*def,size_t*len){
5958if(lua_isnoneornil(L,narg)){
5959if(len)
5960*len=(def?strlen(def):0);
5961return def;
5962}
5963else return luaL_checklstring(L,narg,len);
5964}
5965static lua_Number luaL_checknumber(lua_State*L,int narg){
5966lua_Number d=lua_tonumber(L,narg);
5967if(d==0&&!lua_isnumber(L,narg))
5968tag_error(L,narg,3);
5969return d;
5970}
5971static lua_Integer luaL_checkinteger(lua_State*L,int narg){
5972lua_Integer d=lua_tointeger(L,narg);
5973if(d==0&&!lua_isnumber(L,narg))
5974tag_error(L,narg,3);
5975return d;
5976}
5977static lua_Integer luaL_optinteger(lua_State*L,int narg,
5978lua_Integer def){
5979return luaL_opt(L,luaL_checkinteger,narg,def);
5980}
5981static int luaL_getmetafield(lua_State*L,int obj,const char*event){
5982if(!lua_getmetatable(L,obj))
5983return 0;
5984lua_pushstring(L,event);
5985lua_rawget(L,-2);
5986if(lua_isnil(L,-1)){
5987lua_pop(L,2);
5988return 0;
5989}
5990else{
5991lua_remove(L,-2);
5992return 1;
5993}
5994}
5995static void luaL_register(lua_State*L,const char*libname,
5996const luaL_Reg*l){
5997luaI_openlib(L,libname,l,0);
5998}
5999static int libsize(const luaL_Reg*l){
6000int size=0;
6001for(;l->name;l++)size++;
6002return size;
6003}
6004static void luaI_openlib(lua_State*L,const char*libname,
6005const luaL_Reg*l,int nup){
6006if(libname){
6007int size=libsize(l);
6008luaL_findtable(L,(-10000),"_LOADED",1);
6009lua_getfield(L,-1,libname);
6010if(!lua_istable(L,-1)){
6011lua_pop(L,1);
6012if(luaL_findtable(L,(-10002),libname,size)!=NULL)
6013luaL_error(L,"name conflict for module "LUA_QL("%s"),libname);
6014lua_pushvalue(L,-1);
6015lua_setfield(L,-3,libname);
6016}
6017lua_remove(L,-2);
6018lua_insert(L,-(nup+1));
6019}
6020for(;l->name;l++){
6021int i;
6022for(i=0;i<nup;i++)
6023lua_pushvalue(L,-nup);
6024lua_pushcclosure(L,l->func,nup);
6025lua_setfield(L,-(nup+2),l->name);
6026}
6027lua_pop(L,nup);
6028}
6029static const char*luaL_findtable(lua_State*L,int idx,
6030const char*fname,int szhint){
6031const char*e;
6032lua_pushvalue(L,idx);
6033do{
6034e=strchr(fname,'.');
6035if(e==NULL)e=fname+strlen(fname);
6036lua_pushlstring(L,fname,e-fname);
6037lua_rawget(L,-2);
6038if(lua_isnil(L,-1)){
6039lua_pop(L,1);
6040lua_createtable(L,0,(*e=='.'?1:szhint));
6041lua_pushlstring(L,fname,e-fname);
6042lua_pushvalue(L,-2);
6043lua_settable(L,-4);
6044}
6045else if(!lua_istable(L,-1)){
6046lua_pop(L,2);
6047return fname;
6048}
6049lua_remove(L,-2);
6050fname=e+1;
6051}while(*e=='.');
6052return NULL;
6053}
6054#define bufflen(B)((B)->p-(B)->buffer)
6055#define bufffree(B)((size_t)(BUFSIZ-bufflen(B)))
6056static int emptybuffer(luaL_Buffer*B){
6057size_t l=bufflen(B);
6058if(l==0)return 0;
6059else{
6060lua_pushlstring(B->L,B->buffer,l);
6061B->p=B->buffer;
6062B->lvl++;
6063return 1;
6064}
6065}
6066static void adjuststack(luaL_Buffer*B){
6067if(B->lvl>1){
6068lua_State*L=B->L;
6069int toget=1;
6070size_t toplen=lua_strlen(L,-1);
6071do{
6072size_t l=lua_strlen(L,-(toget+1));
6073if(B->lvl-toget+1>=(20/2)||toplen>l){
6074toplen+=l;
6075toget++;
6076}
6077else break;
6078}while(toget<B->lvl);
6079lua_concat(L,toget);
6080B->lvl=B->lvl-toget+1;
6081}
6082}
6083static char*luaL_prepbuffer(luaL_Buffer*B){
6084if(emptybuffer(B))
6085adjuststack(B);
6086return B->buffer;
6087}
6088static void luaL_addlstring(luaL_Buffer*B,const char*s,size_t l){
6089while(l--)
6090luaL_addchar(B,*s++);
6091}
6092static void luaL_pushresult(luaL_Buffer*B){
6093emptybuffer(B);
6094lua_concat(B->L,B->lvl);
6095B->lvl=1;
6096}
6097static void luaL_addvalue(luaL_Buffer*B){
6098lua_State*L=B->L;
6099size_t vl;
6100const char*s=lua_tolstring(L,-1,&vl);
6101if(vl<=bufffree(B)){
6102memcpy(B->p,s,vl);
6103B->p+=vl;
6104lua_pop(L,1);
6105}
6106else{
6107if(emptybuffer(B))
6108lua_insert(L,-2);
6109B->lvl++;
6110adjuststack(B);
6111}
6112}
6113static void luaL_buffinit(lua_State*L,luaL_Buffer*B){
6114B->L=L;
6115B->p=B->buffer;
6116B->lvl=0;
6117}
6118typedef struct LoadF{
6119int extraline;
6120FILE*f;
6121char buff[BUFSIZ];
6122}LoadF;
6123static const char*getF(lua_State*L,void*ud,size_t*size){
6124LoadF*lf=(LoadF*)ud;
6125(void)L;
6126if(lf->extraline){
6127lf->extraline=0;
6128*size=1;
6129return"\n";
6130}
6131if(feof(lf->f))return NULL;
6132*size=fread(lf->buff,1,sizeof(lf->buff),lf->f);
6133return(*size>0)?lf->buff:NULL;
6134}
6135static int errfile(lua_State*L,const char*what,int fnameindex){
6136const char*serr=strerror(errno);
6137const char*filename=lua_tostring(L,fnameindex)+1;
6138lua_pushfstring(L,"cannot %s %s: %s",what,filename,serr);
6139lua_remove(L,fnameindex);
6140return(5+1);
6141}
6142static int luaL_loadfile(lua_State*L,const char*filename){
6143LoadF lf;
6144int status,readstatus;
6145int c;
6146int fnameindex=lua_gettop(L)+1;
6147lf.extraline=0;
6148if(filename==NULL){
6149lua_pushliteral(L,"=stdin");
6150lf.f=stdin;
6151}
6152else{
6153lua_pushfstring(L,"@%s",filename);
6154lf.f=fopen(filename,"r");
6155if(lf.f==NULL)return errfile(L,"open",fnameindex);
6156}
6157c=getc(lf.f);
6158if(c=='#'){
6159lf.extraline=1;
6160while((c=getc(lf.f))!=EOF&&c!='\n');
6161if(c=='\n')c=getc(lf.f);
6162}
6163if(c=="\033Lua"[0]&&filename){
6164lf.f=freopen(filename,"rb",lf.f);
6165if(lf.f==NULL)return errfile(L,"reopen",fnameindex);
6166while((c=getc(lf.f))!=EOF&&c!="\033Lua"[0]);
6167lf.extraline=0;
6168}
6169ungetc(c,lf.f);
6170status=lua_load(L,getF,&lf,lua_tostring(L,-1));
6171readstatus=ferror(lf.f);
6172if(filename)fclose(lf.f);
6173if(readstatus){
6174lua_settop(L,fnameindex);
6175return errfile(L,"read",fnameindex);
6176}
6177lua_remove(L,fnameindex);
6178return status;
6179}
6180typedef struct LoadS{
6181const char*s;
6182size_t size;
6183}LoadS;
6184static const char*getS(lua_State*L,void*ud,size_t*size){
6185LoadS*ls=(LoadS*)ud;
6186(void)L;
6187if(ls->size==0)return NULL;
6188*size=ls->size;
6189ls->size=0;
6190return ls->s;
6191}
6192static int luaL_loadbuffer(lua_State*L,const char*buff,size_t size,
6193const char*name){
6194LoadS ls;
6195ls.s=buff;
6196ls.size=size;
6197return lua_load(L,getS,&ls,name);
6198}
6199static void*l_alloc(void*ud,void*ptr,size_t osize,size_t nsize){
6200(void)ud;
6201(void)osize;
6202if(nsize==0){
6203free(ptr);
6204return NULL;
6205}
6206else
6207return realloc(ptr,nsize);
6208}
6209static int panic(lua_State*L){
6210(void)L;
6211fprintf(stderr,"PANIC: unprotected error in call to Lua API (%s)\n",
6212lua_tostring(L,-1));
6213return 0;
6214}
6215static lua_State*luaL_newstate(void){
6216lua_State*L=lua_newstate(l_alloc,NULL);
6217if(L)lua_atpanic(L,&panic);
6218return L;
6219}
6220static int luaB_tonumber(lua_State*L){
6221int base=luaL_optint(L,2,10);
6222if(base==10){
6223luaL_checkany(L,1);
6224if(lua_isnumber(L,1)){
6225lua_pushnumber(L,lua_tonumber(L,1));
6226return 1;
6227}
6228}
6229else{
6230const char*s1=luaL_checkstring(L,1);
6231char*s2;
6232unsigned long n;
6233luaL_argcheck(L,2<=base&&base<=36,2,"base out of range");
6234n=strtoul(s1,&s2,base);
6235if(s1!=s2){
6236while(isspace((unsigned char)(*s2)))s2++;
6237if(*s2=='\0'){
6238lua_pushnumber(L,(lua_Number)n);
6239return 1;
6240}
6241}
6242}
6243lua_pushnil(L);
6244return 1;
6245}
6246static int luaB_error(lua_State*L){
6247int level=luaL_optint(L,2,1);
6248lua_settop(L,1);
6249if(lua_isstring(L,1)&&level>0){
6250luaL_where(L,level);
6251lua_pushvalue(L,1);
6252lua_concat(L,2);
6253}
6254return lua_error(L);
6255}
6256static int luaB_setmetatable(lua_State*L){
6257int t=lua_type(L,2);
6258luaL_checktype(L,1,5);
6259luaL_argcheck(L,t==0||t==5,2,
6260"nil or table expected");
6261if(luaL_getmetafield(L,1,"__metatable"))
6262luaL_error(L,"cannot change a protected metatable");
6263lua_settop(L,2);
6264lua_setmetatable(L,1);
6265return 1;
6266}
6267static void getfunc(lua_State*L,int opt){
6268if(lua_isfunction(L,1))lua_pushvalue(L,1);
6269else{
6270lua_Debug ar;
6271int level=opt?luaL_optint(L,1,1):luaL_checkint(L,1);
6272luaL_argcheck(L,level>=0,1,"level must be non-negative");
6273if(lua_getstack(L,level,&ar)==0)
6274luaL_argerror(L,1,"invalid level");
6275lua_getinfo(L,"f",&ar);
6276if(lua_isnil(L,-1))
6277luaL_error(L,"no function environment for tail call at level %d",
6278level);
6279}
6280}
6281static int luaB_setfenv(lua_State*L){
6282luaL_checktype(L,2,5);
6283getfunc(L,0);
6284lua_pushvalue(L,2);
6285if(lua_isnumber(L,1)&&lua_tonumber(L,1)==0){
6286lua_pushthread(L);
6287lua_insert(L,-2);
6288lua_setfenv(L,-2);
6289return 0;
6290}
6291else if(lua_iscfunction(L,-2)||lua_setfenv(L,-2)==0)
6292luaL_error(L,
6293LUA_QL("setfenv")" cannot change environment of given object");
6294return 1;
6295}
6296static int luaB_rawget(lua_State*L){
6297luaL_checktype(L,1,5);
6298luaL_checkany(L,2);
6299lua_settop(L,2);
6300lua_rawget(L,1);
6301return 1;
6302}
6303static int luaB_type(lua_State*L){
6304luaL_checkany(L,1);
6305lua_pushstring(L,luaL_typename(L,1));
6306return 1;
6307}
6308static int luaB_next(lua_State*L){
6309luaL_checktype(L,1,5);
6310lua_settop(L,2);
6311if(lua_next(L,1))
6312return 2;
6313else{
6314lua_pushnil(L);
6315return 1;
6316}
6317}
6318static int luaB_pairs(lua_State*L){
6319luaL_checktype(L,1,5);
6320lua_pushvalue(L,lua_upvalueindex(1));
6321lua_pushvalue(L,1);
6322lua_pushnil(L);
6323return 3;
6324}
6325static int ipairsaux(lua_State*L){
6326int i=luaL_checkint(L,2);
6327luaL_checktype(L,1,5);
6328i++;
6329lua_pushinteger(L,i);
6330lua_rawgeti(L,1,i);
6331return(lua_isnil(L,-1))?0:2;
6332}
6333static int luaB_ipairs(lua_State*L){
6334luaL_checktype(L,1,5);
6335lua_pushvalue(L,lua_upvalueindex(1));
6336lua_pushvalue(L,1);
6337lua_pushinteger(L,0);
6338return 3;
6339}
6340static int load_aux(lua_State*L,int status){
6341if(status==0)
6342return 1;
6343else{
6344lua_pushnil(L);
6345lua_insert(L,-2);
6346return 2;
6347}
6348}
6349static int luaB_loadstring(lua_State*L){
6350size_t l;
6351const char*s=luaL_checklstring(L,1,&l);
6352const char*chunkname=luaL_optstring(L,2,s);
6353return load_aux(L,luaL_loadbuffer(L,s,l,chunkname));
6354}
6355static int luaB_loadfile(lua_State*L){
6356const char*fname=luaL_optstring(L,1,NULL);
6357return load_aux(L,luaL_loadfile(L,fname));
6358}
6359static int luaB_assert(lua_State*L){
6360luaL_checkany(L,1);
6361if(!lua_toboolean(L,1))
6362return luaL_error(L,"%s",luaL_optstring(L,2,"assertion failed!"));
6363return lua_gettop(L);
6364}
6365static int luaB_unpack(lua_State*L){
6366int i,e,n;
6367luaL_checktype(L,1,5);
6368i=luaL_optint(L,2,1);
6369e=luaL_opt(L,luaL_checkint,3,luaL_getn(L,1));
6370if(i>e)return 0;
6371n=e-i+1;
6372if(n<=0||!lua_checkstack(L,n))
6373return luaL_error(L,"too many results to unpack");
6374lua_rawgeti(L,1,i);
6375while(i++<e)
6376lua_rawgeti(L,1,i);
6377return n;
6378}
6379static int luaB_pcall(lua_State*L){
6380int status;
6381luaL_checkany(L,1);
6382status=lua_pcall(L,lua_gettop(L)-1,(-1),0);
6383lua_pushboolean(L,(status==0));
6384lua_insert(L,1);
6385return lua_gettop(L);
6386}
6387static int luaB_newproxy(lua_State*L){
6388lua_settop(L,1);
6389lua_newuserdata(L,0);
6390if(lua_toboolean(L,1)==0)
6391return 1;
6392else if(lua_isboolean(L,1)){
6393lua_newtable(L);
6394lua_pushvalue(L,-1);
6395lua_pushboolean(L,1);
6396lua_rawset(L,lua_upvalueindex(1));
6397}
6398else{
6399int validproxy=0;
6400if(lua_getmetatable(L,1)){
6401lua_rawget(L,lua_upvalueindex(1));
6402validproxy=lua_toboolean(L,-1);
6403lua_pop(L,1);
6404}
6405luaL_argcheck(L,validproxy,1,"boolean or proxy expected");
6406lua_getmetatable(L,1);
6407}
6408lua_setmetatable(L,2);
6409return 1;
6410}
6411static const luaL_Reg base_funcs[]={
6412{"assert",luaB_assert},
6413{"error",luaB_error},
6414{"loadfile",luaB_loadfile},
6415{"loadstring",luaB_loadstring},
6416{"next",luaB_next},
6417{"pcall",luaB_pcall},
6418{"rawget",luaB_rawget},
6419{"setfenv",luaB_setfenv},
6420{"setmetatable",luaB_setmetatable},
6421{"tonumber",luaB_tonumber},
6422{"type",luaB_type},
6423{"unpack",luaB_unpack},
6424{NULL,NULL}
6425};
6426static void auxopen(lua_State*L,const char*name,
6427lua_CFunction f,lua_CFunction u){
6428lua_pushcfunction(L,u);
6429lua_pushcclosure(L,f,1);
6430lua_setfield(L,-2,name);
6431}
6432static void base_open(lua_State*L){
6433lua_pushvalue(L,(-10002));
6434lua_setglobal(L,"_G");
6435luaL_register(L,"_G",base_funcs);
6436lua_pushliteral(L,"Lua 5.1");
6437lua_setglobal(L,"_VERSION");
6438auxopen(L,"ipairs",luaB_ipairs,ipairsaux);
6439auxopen(L,"pairs",luaB_pairs,luaB_next);
6440lua_createtable(L,0,1);
6441lua_pushvalue(L,-1);
6442lua_setmetatable(L,-2);
6443lua_pushliteral(L,"kv");
6444lua_setfield(L,-2,"__mode");
6445lua_pushcclosure(L,luaB_newproxy,1);
6446lua_setglobal(L,"newproxy");
6447}
6448static int luaopen_base(lua_State*L){
6449base_open(L);
6450return 1;
6451}
6452#define aux_getn(L,n)(luaL_checktype(L,n,5),luaL_getn(L,n))
6453static int tinsert(lua_State*L){
6454int e=aux_getn(L,1)+1;
6455int pos;
6456switch(lua_gettop(L)){
6457case 2:{
6458pos=e;
6459break;
6460}
6461case 3:{
6462int i;
6463pos=luaL_checkint(L,2);
6464if(pos>e)e=pos;
6465for(i=e;i>pos;i--){
6466lua_rawgeti(L,1,i-1);
6467lua_rawseti(L,1,i);
6468}
6469break;
6470}
6471default:{
6472return luaL_error(L,"wrong number of arguments to "LUA_QL("insert"));
6473}
6474}
6475luaL_setn(L,1,e);
6476lua_rawseti(L,1,pos);
6477return 0;
6478}
6479static int tremove(lua_State*L){
6480int e=aux_getn(L,1);
6481int pos=luaL_optint(L,2,e);
6482if(!(1<=pos&&pos<=e))
6483return 0;
6484luaL_setn(L,1,e-1);
6485lua_rawgeti(L,1,pos);
6486for(;pos<e;pos++){
6487lua_rawgeti(L,1,pos+1);
6488lua_rawseti(L,1,pos);
6489}
6490lua_pushnil(L);
6491lua_rawseti(L,1,e);
6492return 1;
6493}
6494static void addfield(lua_State*L,luaL_Buffer*b,int i){
6495lua_rawgeti(L,1,i);
6496if(!lua_isstring(L,-1))
6497luaL_error(L,"invalid value (%s) at index %d in table for "
6498LUA_QL("concat"),luaL_typename(L,-1),i);
6499luaL_addvalue(b);
6500}
6501static int tconcat(lua_State*L){
6502luaL_Buffer b;
6503size_t lsep;
6504int i,last;
6505const char*sep=luaL_optlstring(L,2,"",&lsep);
6506luaL_checktype(L,1,5);
6507i=luaL_optint(L,3,1);
6508last=luaL_opt(L,luaL_checkint,4,luaL_getn(L,1));
6509luaL_buffinit(L,&b);
6510for(;i<last;i++){
6511addfield(L,&b,i);
6512luaL_addlstring(&b,sep,lsep);
6513}
6514if(i==last)
6515addfield(L,&b,i);
6516luaL_pushresult(&b);
6517return 1;
6518}
6519static void set2(lua_State*L,int i,int j){
6520lua_rawseti(L,1,i);
6521lua_rawseti(L,1,j);
6522}
6523static int sort_comp(lua_State*L,int a,int b){
6524if(!lua_isnil(L,2)){
6525int res;
6526lua_pushvalue(L,2);
6527lua_pushvalue(L,a-1);
6528lua_pushvalue(L,b-2);
6529lua_call(L,2,1);
6530res=lua_toboolean(L,-1);
6531lua_pop(L,1);
6532return res;
6533}
6534else
6535return lua_lessthan(L,a,b);
6536}
6537static void auxsort(lua_State*L,int l,int u){
6538while(l<u){
6539int i,j;
6540lua_rawgeti(L,1,l);
6541lua_rawgeti(L,1,u);
6542if(sort_comp(L,-1,-2))
6543set2(L,l,u);
6544else
6545lua_pop(L,2);
6546if(u-l==1)break;
6547i=(l+u)/2;
6548lua_rawgeti(L,1,i);
6549lua_rawgeti(L,1,l);
6550if(sort_comp(L,-2,-1))
6551set2(L,i,l);
6552else{
6553lua_pop(L,1);
6554lua_rawgeti(L,1,u);
6555if(sort_comp(L,-1,-2))
6556set2(L,i,u);
6557else
6558lua_pop(L,2);
6559}
6560if(u-l==2)break;
6561lua_rawgeti(L,1,i);
6562lua_pushvalue(L,-1);
6563lua_rawgeti(L,1,u-1);
6564set2(L,i,u-1);
6565i=l;j=u-1;
6566for(;;){
6567while(lua_rawgeti(L,1,++i),sort_comp(L,-1,-2)){
6568if(i>u)luaL_error(L,"invalid order function for sorting");
6569lua_pop(L,1);
6570}
6571while(lua_rawgeti(L,1,--j),sort_comp(L,-3,-1)){
6572if(j<l)luaL_error(L,"invalid order function for sorting");
6573lua_pop(L,1);
6574}
6575if(j<i){
6576lua_pop(L,3);
6577break;
6578}
6579set2(L,i,j);
6580}
6581lua_rawgeti(L,1,u-1);
6582lua_rawgeti(L,1,i);
6583set2(L,u-1,i);
6584if(i-l<u-i){
6585j=l;i=i-1;l=i+2;
6586}
6587else{
6588j=i+1;i=u;u=j-2;
6589}
6590auxsort(L,j,i);
6591}
6592}
6593static int sort(lua_State*L){
6594int n=aux_getn(L,1);
6595luaL_checkstack(L,40,"");
6596if(!lua_isnoneornil(L,2))
6597luaL_checktype(L,2,6);
6598lua_settop(L,2);
6599auxsort(L,1,n);
6600return 0;
6601}
6602static const luaL_Reg tab_funcs[]={
6603{"concat",tconcat},
6604{"insert",tinsert},
6605{"remove",tremove},
6606{"sort",sort},
6607{NULL,NULL}
6608};
6609static int luaopen_table(lua_State*L){
6610luaL_register(L,"table",tab_funcs);
6611return 1;
6612}
6613static const char*const fnames[]={"input","output"};
6614static int pushresult(lua_State*L,int i,const char*filename){
6615int en=errno;
6616if(i){
6617lua_pushboolean(L,1);
6618return 1;
6619}
6620else{
6621lua_pushnil(L);
6622if(filename)
6623lua_pushfstring(L,"%s: %s",filename,strerror(en));
6624else
6625lua_pushfstring(L,"%s",strerror(en));
6626lua_pushinteger(L,en);
6627return 3;
6628}
6629}
6630static void fileerror(lua_State*L,int arg,const char*filename){
6631lua_pushfstring(L,"%s: %s",filename,strerror(errno));
6632luaL_argerror(L,arg,lua_tostring(L,-1));
6633}
6634#define tofilep(L)((FILE**)luaL_checkudata(L,1,"FILE*"))
6635static int io_type(lua_State*L){
6636void*ud;
6637luaL_checkany(L,1);
6638ud=lua_touserdata(L,1);
6639lua_getfield(L,(-10000),"FILE*");
6640if(ud==NULL||!lua_getmetatable(L,1)||!lua_rawequal(L,-2,-1))
6641lua_pushnil(L);
6642else if(*((FILE**)ud)==NULL)
6643lua_pushliteral(L,"closed file");
6644else
6645lua_pushliteral(L,"file");
6646return 1;
6647}
6648static FILE*tofile(lua_State*L){
6649FILE**f=tofilep(L);
6650if(*f==NULL)
6651luaL_error(L,"attempt to use a closed file");
6652return*f;
6653}
6654static FILE**newfile(lua_State*L){
6655FILE**pf=(FILE**)lua_newuserdata(L,sizeof(FILE*));
6656*pf=NULL;
6657luaL_getmetatable(L,"FILE*");
6658lua_setmetatable(L,-2);
6659return pf;
6660}
6661static int io_noclose(lua_State*L){
6662lua_pushnil(L);
6663lua_pushliteral(L,"cannot close standard file");
6664return 2;
6665}
6666static int io_pclose(lua_State*L){
6667FILE**p=tofilep(L);
6668int ok=lua_pclose(L,*p);
6669*p=NULL;
6670return pushresult(L,ok,NULL);
6671}
6672static int io_fclose(lua_State*L){
6673FILE**p=tofilep(L);
6674int ok=(fclose(*p)==0);
6675*p=NULL;
6676return pushresult(L,ok,NULL);
6677}
6678static int aux_close(lua_State*L){
6679lua_getfenv(L,1);
6680lua_getfield(L,-1,"__close");
6681return(lua_tocfunction(L,-1))(L);
6682}
6683static int io_close(lua_State*L){
6684if(lua_isnone(L,1))
6685lua_rawgeti(L,(-10001),2);
6686tofile(L);
6687return aux_close(L);
6688}
6689static int io_gc(lua_State*L){
6690FILE*f=*tofilep(L);
6691if(f!=NULL)
6692aux_close(L);
6693return 0;
6694}
6695static int io_open(lua_State*L){
6696const char*filename=luaL_checkstring(L,1);
6697const char*mode=luaL_optstring(L,2,"r");
6698FILE**pf=newfile(L);
6699*pf=fopen(filename,mode);
6700return(*pf==NULL)?pushresult(L,0,filename):1;
6701}
6702static FILE*getiofile(lua_State*L,int findex){
6703FILE*f;
6704lua_rawgeti(L,(-10001),findex);
6705f=*(FILE**)lua_touserdata(L,-1);
6706if(f==NULL)
6707luaL_error(L,"standard %s file is closed",fnames[findex-1]);
6708return f;
6709}
6710static int g_iofile(lua_State*L,int f,const char*mode){
6711if(!lua_isnoneornil(L,1)){
6712const char*filename=lua_tostring(L,1);
6713if(filename){
6714FILE**pf=newfile(L);
6715*pf=fopen(filename,mode);
6716if(*pf==NULL)
6717fileerror(L,1,filename);
6718}
6719else{
6720tofile(L);
6721lua_pushvalue(L,1);
6722}
6723lua_rawseti(L,(-10001),f);
6724}
6725lua_rawgeti(L,(-10001),f);
6726return 1;
6727}
6728static int io_input(lua_State*L){
6729return g_iofile(L,1,"r");
6730}
6731static int io_output(lua_State*L){
6732return g_iofile(L,2,"w");
6733}
6734static int io_readline(lua_State*L);
6735static void aux_lines(lua_State*L,int idx,int toclose){
6736lua_pushvalue(L,idx);
6737lua_pushboolean(L,toclose);
6738lua_pushcclosure(L,io_readline,2);
6739}
6740static int f_lines(lua_State*L){
6741tofile(L);
6742aux_lines(L,1,0);
6743return 1;
6744}
6745static int io_lines(lua_State*L){
6746if(lua_isnoneornil(L,1)){
6747lua_rawgeti(L,(-10001),1);
6748return f_lines(L);
6749}
6750else{
6751const char*filename=luaL_checkstring(L,1);
6752FILE**pf=newfile(L);
6753*pf=fopen(filename,"r");
6754if(*pf==NULL)
6755fileerror(L,1,filename);
6756aux_lines(L,lua_gettop(L),1);
6757return 1;
6758}
6759}
6760static int read_number(lua_State*L,FILE*f){
6761lua_Number d;
6762if(fscanf(f,"%lf",&d)==1){
6763lua_pushnumber(L,d);
6764return 1;
6765}
6766else{
6767lua_pushnil(L);
6768return 0;
6769}
6770}
6771static int test_eof(lua_State*L,FILE*f){
6772int c=getc(f);
6773ungetc(c,f);
6774lua_pushlstring(L,NULL,0);
6775return(c!=EOF);
6776}
6777static int read_line(lua_State*L,FILE*f){
6778luaL_Buffer b;
6779luaL_buffinit(L,&b);
6780for(;;){
6781size_t l;
6782char*p=luaL_prepbuffer(&b);
6783if(fgets(p,BUFSIZ,f)==NULL){
6784luaL_pushresult(&b);
6785return(lua_objlen(L,-1)>0);
6786}
6787l=strlen(p);
6788if(l==0||p[l-1]!='\n')
6789luaL_addsize(&b,l);
6790else{
6791luaL_addsize(&b,l-1);
6792luaL_pushresult(&b);
6793return 1;
6794}
6795}
6796}
6797static int read_chars(lua_State*L,FILE*f,size_t n){
6798size_t rlen;
6799size_t nr;
6800luaL_Buffer b;
6801luaL_buffinit(L,&b);
6802rlen=BUFSIZ;
6803do{
6804char*p=luaL_prepbuffer(&b);
6805if(rlen>n)rlen=n;
6806nr=fread(p,sizeof(char),rlen,f);
6807luaL_addsize(&b,nr);
6808n-=nr;
6809}while(n>0&&nr==rlen);
6810luaL_pushresult(&b);
6811return(n==0||lua_objlen(L,-1)>0);
6812}
6813static int g_read(lua_State*L,FILE*f,int first){
6814int nargs=lua_gettop(L)-1;
6815int success;
6816int n;
6817clearerr(f);
6818if(nargs==0){
6819success=read_line(L,f);
6820n=first+1;
6821}
6822else{
6823luaL_checkstack(L,nargs+20,"too many arguments");
6824success=1;
6825for(n=first;nargs--&&success;n++){
6826if(lua_type(L,n)==3){
6827size_t l=(size_t)lua_tointeger(L,n);
6828success=(l==0)?test_eof(L,f):read_chars(L,f,l);
6829}
6830else{
6831const char*p=lua_tostring(L,n);
6832luaL_argcheck(L,p&&p[0]=='*',n,"invalid option");
6833switch(p[1]){
6834case'n':
6835success=read_number(L,f);
6836break;
6837case'l':
6838success=read_line(L,f);
6839break;
6840case'a':
6841read_chars(L,f,~((size_t)0));
6842success=1;
6843break;
6844default:
6845return luaL_argerror(L,n,"invalid format");
6846}
6847}
6848}
6849}
6850if(ferror(f))
6851return pushresult(L,0,NULL);
6852if(!success){
6853lua_pop(L,1);
6854lua_pushnil(L);
6855}
6856return n-first;
6857}
6858static int io_read(lua_State*L){
6859return g_read(L,getiofile(L,1),1);
6860}
6861static int f_read(lua_State*L){
6862return g_read(L,tofile(L),2);
6863}
6864static int io_readline(lua_State*L){
6865FILE*f=*(FILE**)lua_touserdata(L,lua_upvalueindex(1));
6866int sucess;
6867if(f==NULL)
6868luaL_error(L,"file is already closed");
6869sucess=read_line(L,f);
6870if(ferror(f))
6871return luaL_error(L,"%s",strerror(errno));
6872if(sucess)return 1;
6873else{
6874if(lua_toboolean(L,lua_upvalueindex(2))){
6875lua_settop(L,0);
6876lua_pushvalue(L,lua_upvalueindex(1));
6877aux_close(L);
6878}
6879return 0;
6880}
6881}
6882static int g_write(lua_State*L,FILE*f,int arg){
6883int nargs=lua_gettop(L)-1;
6884int status=1;
6885for(;nargs--;arg++){
6886if(lua_type(L,arg)==3){
6887status=status&&
6888fprintf(f,"%.14g",lua_tonumber(L,arg))>0;
6889}
6890else{
6891size_t l;
6892const char*s=luaL_checklstring(L,arg,&l);
6893status=status&&(fwrite(s,sizeof(char),l,f)==l);
6894}
6895}
6896return pushresult(L,status,NULL);
6897}
6898static int io_write(lua_State*L){
6899return g_write(L,getiofile(L,2),1);
6900}
6901static int f_write(lua_State*L){
6902return g_write(L,tofile(L),2);
6903}
6904static int io_flush(lua_State*L){
6905return pushresult(L,fflush(getiofile(L,2))==0,NULL);
6906}
6907static int f_flush(lua_State*L){
6908return pushresult(L,fflush(tofile(L))==0,NULL);
6909}
6910static const luaL_Reg iolib[]={
6911{"close",io_close},
6912{"flush",io_flush},
6913{"input",io_input},
6914{"lines",io_lines},
6915{"open",io_open},
6916{"output",io_output},
6917{"read",io_read},
6918{"type",io_type},
6919{"write",io_write},
6920{NULL,NULL}
6921};
6922static const luaL_Reg flib[]={
6923{"close",io_close},
6924{"flush",f_flush},
6925{"lines",f_lines},
6926{"read",f_read},
6927{"write",f_write},
6928{"__gc",io_gc},
6929{NULL,NULL}
6930};
6931static void createmeta(lua_State*L){
6932luaL_newmetatable(L,"FILE*");
6933lua_pushvalue(L,-1);
6934lua_setfield(L,-2,"__index");
6935luaL_register(L,NULL,flib);
6936}
6937static void createstdfile(lua_State*L,FILE*f,int k,const char*fname){
6938*newfile(L)=f;
6939if(k>0){
6940lua_pushvalue(L,-1);
6941lua_rawseti(L,(-10001),k);
6942}
6943lua_pushvalue(L,-2);
6944lua_setfenv(L,-2);
6945lua_setfield(L,-3,fname);
6946}
6947static void newfenv(lua_State*L,lua_CFunction cls){
6948lua_createtable(L,0,1);
6949lua_pushcfunction(L,cls);
6950lua_setfield(L,-2,"__close");
6951}
6952static int luaopen_io(lua_State*L){
6953createmeta(L);
6954newfenv(L,io_fclose);
6955lua_replace(L,(-10001));
6956luaL_register(L,"io",iolib);
6957newfenv(L,io_noclose);
6958createstdfile(L,stdin,1,"stdin");
6959createstdfile(L,stdout,2,"stdout");
6960createstdfile(L,stderr,0,"stderr");
6961lua_pop(L,1);
6962lua_getfield(L,-1,"popen");
6963newfenv(L,io_pclose);
6964lua_setfenv(L,-2);
6965lua_pop(L,1);
6966return 1;
6967}
6968static int os_pushresult(lua_State*L,int i,const char*filename){
6969int en=errno;
6970if(i){
6971lua_pushboolean(L,1);
6972return 1;
6973}
6974else{
6975lua_pushnil(L);
6976lua_pushfstring(L,"%s: %s",filename,strerror(en));
6977lua_pushinteger(L,en);
6978return 3;
6979}
6980}
6981static int os_remove(lua_State*L){
6982const char*filename=luaL_checkstring(L,1);
6983return os_pushresult(L,remove(filename)==0,filename);
6984}
6985static int os_exit(lua_State*L){
6986exit(luaL_optint(L,1,EXIT_SUCCESS));
6987}
6988static const luaL_Reg syslib[]={
6989{"exit",os_exit},
6990{"remove",os_remove},
6991{NULL,NULL}
6992};
6993static int luaopen_os(lua_State*L){
6994luaL_register(L,"os",syslib);
6995return 1;
6996}
6997#define uchar(c)((unsigned char)(c))
6998static ptrdiff_t posrelat(ptrdiff_t pos,size_t len){
6999if(pos<0)pos+=(ptrdiff_t)len+1;
7000return(pos>=0)?pos:0;
7001}
7002static int str_sub(lua_State*L){
7003size_t l;
7004const char*s=luaL_checklstring(L,1,&l);
7005ptrdiff_t start=posrelat(luaL_checkinteger(L,2),l);
7006ptrdiff_t end=posrelat(luaL_optinteger(L,3,-1),l);
7007if(start<1)start=1;
7008if(end>(ptrdiff_t)l)end=(ptrdiff_t)l;
7009if(start<=end)
7010lua_pushlstring(L,s+start-1,end-start+1);
7011else lua_pushliteral(L,"");
7012return 1;
7013}
7014static int str_lower(lua_State*L){
7015size_t l;
7016size_t i;
7017luaL_Buffer b;
7018const char*s=luaL_checklstring(L,1,&l);
7019luaL_buffinit(L,&b);
7020for(i=0;i<l;i++)
7021luaL_addchar(&b,tolower(uchar(s[i])));
7022luaL_pushresult(&b);
7023return 1;
7024}
7025static int str_upper(lua_State*L){
7026size_t l;
7027size_t i;
7028luaL_Buffer b;
7029const char*s=luaL_checklstring(L,1,&l);
7030luaL_buffinit(L,&b);
7031for(i=0;i<l;i++)
7032luaL_addchar(&b,toupper(uchar(s[i])));
7033luaL_pushresult(&b);
7034return 1;
7035}
7036static int str_rep(lua_State*L){
7037size_t l;
7038luaL_Buffer b;
7039const char*s=luaL_checklstring(L,1,&l);
7040int n=luaL_checkint(L,2);
7041luaL_buffinit(L,&b);
7042while(n-->0)
7043luaL_addlstring(&b,s,l);
7044luaL_pushresult(&b);
7045return 1;
7046}
7047static int str_byte(lua_State*L){
7048size_t l;
7049const char*s=luaL_checklstring(L,1,&l);
7050ptrdiff_t posi=posrelat(luaL_optinteger(L,2,1),l);
7051ptrdiff_t pose=posrelat(luaL_optinteger(L,3,posi),l);
7052int n,i;
7053if(posi<=0)posi=1;
7054if((size_t)pose>l)pose=l;
7055if(posi>pose)return 0;
7056n=(int)(pose-posi+1);
7057if(posi+n<=pose)
7058luaL_error(L,"string slice too long");
7059luaL_checkstack(L,n,"string slice too long");
7060for(i=0;i<n;i++)
7061lua_pushinteger(L,uchar(s[posi+i-1]));
7062return n;
7063}
7064static int str_char(lua_State*L){
7065int n=lua_gettop(L);
7066int i;
7067luaL_Buffer b;
7068luaL_buffinit(L,&b);
7069for(i=1;i<=n;i++){
7070int c=luaL_checkint(L,i);
7071luaL_argcheck(L,uchar(c)==c,i,"invalid value");
7072luaL_addchar(&b,uchar(c));
7073}
7074luaL_pushresult(&b);
7075return 1;
7076}
7077typedef struct MatchState{
7078const char*src_init;
7079const char*src_end;
7080lua_State*L;
7081int level;
7082struct{
7083const char*init;
7084ptrdiff_t len;
7085}capture[32];
7086}MatchState;
7087static int check_capture(MatchState*ms,int l){
7088l-='1';
7089if(l<0||l>=ms->level||ms->capture[l].len==(-1))
7090return luaL_error(ms->L,"invalid capture index");
7091return l;
7092}
7093static int capture_to_close(MatchState*ms){
7094int level=ms->level;
7095for(level--;level>=0;level--)
7096if(ms->capture[level].len==(-1))return level;
7097return luaL_error(ms->L,"invalid pattern capture");
7098}
7099static const char*classend(MatchState*ms,const char*p){
7100switch(*p++){
7101case'%':{
7102if(*p=='\0')
7103luaL_error(ms->L,"malformed pattern (ends with "LUA_QL("%%")")");
7104return p+1;
7105}
7106case'[':{
7107if(*p=='^')p++;
7108do{
7109if(*p=='\0')
7110luaL_error(ms->L,"malformed pattern (missing "LUA_QL("]")")");
7111if(*(p++)=='%'&&*p!='\0')
7112p++;
7113}while(*p!=']');
7114return p+1;
7115}
7116default:{
7117return p;
7118}
7119}
7120}
7121static int match_class(int c,int cl){
7122int res;
7123switch(tolower(cl)){
7124case'a':res=isalpha(c);break;
7125case'c':res=iscntrl(c);break;
7126case'd':res=isdigit(c);break;
7127case'l':res=islower(c);break;
7128case'p':res=ispunct(c);break;
7129case's':res=isspace(c);break;
7130case'u':res=isupper(c);break;
7131case'w':res=isalnum(c);break;
7132case'x':res=isxdigit(c);break;
7133case'z':res=(c==0);break;
7134default:return(cl==c);
7135}
7136return(islower(cl)?res:!res);
7137}
7138static int matchbracketclass(int c,const char*p,const char*ec){
7139int sig=1;
7140if(*(p+1)=='^'){
7141sig=0;
7142p++;
7143}
7144while(++p<ec){
7145if(*p=='%'){
7146p++;
7147if(match_class(c,uchar(*p)))
7148return sig;
7149}
7150else if((*(p+1)=='-')&&(p+2<ec)){
7151p+=2;
7152if(uchar(*(p-2))<=c&&c<=uchar(*p))
7153return sig;
7154}
7155else if(uchar(*p)==c)return sig;
7156}
7157return!sig;
7158}
7159static int singlematch(int c,const char*p,const char*ep){
7160switch(*p){
7161case'.':return 1;
7162case'%':return match_class(c,uchar(*(p+1)));
7163case'[':return matchbracketclass(c,p,ep-1);
7164default:return(uchar(*p)==c);
7165}
7166}
7167static const char*match(MatchState*ms,const char*s,const char*p);
7168static const char*matchbalance(MatchState*ms,const char*s,
7169const char*p){
7170if(*p==0||*(p+1)==0)
7171luaL_error(ms->L,"unbalanced pattern");
7172if(*s!=*p)return NULL;
7173else{
7174int b=*p;
7175int e=*(p+1);
7176int cont=1;
7177while(++s<ms->src_end){
7178if(*s==e){
7179if(--cont==0)return s+1;
7180}
7181else if(*s==b)cont++;
7182}
7183}
7184return NULL;
7185}
7186static const char*max_expand(MatchState*ms,const char*s,
7187const char*p,const char*ep){
7188ptrdiff_t i=0;
7189while((s+i)<ms->src_end&&singlematch(uchar(*(s+i)),p,ep))
7190i++;
7191while(i>=0){
7192const char*res=match(ms,(s+i),ep+1);
7193if(res)return res;
7194i--;
7195}
7196return NULL;
7197}
7198static const char*min_expand(MatchState*ms,const char*s,
7199const char*p,const char*ep){
7200for(;;){
7201const char*res=match(ms,s,ep+1);
7202if(res!=NULL)
7203return res;
7204else if(s<ms->src_end&&singlematch(uchar(*s),p,ep))
7205s++;
7206else return NULL;
7207}
7208}
7209static const char*start_capture(MatchState*ms,const char*s,
7210const char*p,int what){
7211const char*res;
7212int level=ms->level;
7213if(level>=32)luaL_error(ms->L,"too many captures");
7214ms->capture[level].init=s;
7215ms->capture[level].len=what;
7216ms->level=level+1;
7217if((res=match(ms,s,p))==NULL)
7218ms->level--;
7219return res;
7220}
7221static const char*end_capture(MatchState*ms,const char*s,
7222const char*p){
7223int l=capture_to_close(ms);
7224const char*res;
7225ms->capture[l].len=s-ms->capture[l].init;
7226if((res=match(ms,s,p))==NULL)
7227ms->capture[l].len=(-1);
7228return res;
7229}
7230static const char*match_capture(MatchState*ms,const char*s,int l){
7231size_t len;
7232l=check_capture(ms,l);
7233len=ms->capture[l].len;
7234if((size_t)(ms->src_end-s)>=len&&
7235memcmp(ms->capture[l].init,s,len)==0)
7236return s+len;
7237else return NULL;
7238}
7239static const char*match(MatchState*ms,const char*s,const char*p){
7240init:
7241switch(*p){
7242case'(':{
7243if(*(p+1)==')')
7244return start_capture(ms,s,p+2,(-2));
7245else
7246return start_capture(ms,s,p+1,(-1));
7247}
7248case')':{
7249return end_capture(ms,s,p+1);
7250}
7251case'%':{
7252switch(*(p+1)){
7253case'b':{
7254s=matchbalance(ms,s,p+2);
7255if(s==NULL)return NULL;
7256p+=4;goto init;
7257}
7258case'f':{
7259const char*ep;char previous;
7260p+=2;
7261if(*p!='[')
7262luaL_error(ms->L,"missing "LUA_QL("[")" after "
7263LUA_QL("%%f")" in pattern");
7264ep=classend(ms,p);
7265previous=(s==ms->src_init)?'\0':*(s-1);
7266if(matchbracketclass(uchar(previous),p,ep-1)||
7267!matchbracketclass(uchar(*s),p,ep-1))return NULL;
7268p=ep;goto init;
7269}
7270default:{
7271if(isdigit(uchar(*(p+1)))){
7272s=match_capture(ms,s,uchar(*(p+1)));
7273if(s==NULL)return NULL;
7274p+=2;goto init;
7275}
7276goto dflt;
7277}
7278}
7279}
7280case'\0':{
7281return s;
7282}
7283case'$':{
7284if(*(p+1)=='\0')
7285return(s==ms->src_end)?s:NULL;
7286else goto dflt;
7287}
7288default:dflt:{
7289const char*ep=classend(ms,p);
7290int m=s<ms->src_end&&singlematch(uchar(*s),p,ep);
7291switch(*ep){
7292case'?':{
7293const char*res;
7294if(m&&((res=match(ms,s+1,ep+1))!=NULL))
7295return res;
7296p=ep+1;goto init;
7297}
7298case'*':{
7299return max_expand(ms,s,p,ep);
7300}
7301case'+':{
7302return(m?max_expand(ms,s+1,p,ep):NULL);
7303}
7304case'-':{
7305return min_expand(ms,s,p,ep);
7306}
7307default:{
7308if(!m)return NULL;
7309s++;p=ep;goto init;
7310}
7311}
7312}
7313}
7314}
7315static const char*lmemfind(const char*s1,size_t l1,
7316const char*s2,size_t l2){
7317if(l2==0)return s1;
7318else if(l2>l1)return NULL;
7319else{
7320const char*init;
7321l2--;
7322l1=l1-l2;
7323while(l1>0&&(init=(const char*)memchr(s1,*s2,l1))!=NULL){
7324init++;
7325if(memcmp(init,s2+1,l2)==0)
7326return init-1;
7327else{
7328l1-=init-s1;
7329s1=init;
7330}
7331}
7332return NULL;
7333}
7334}
7335static void push_onecapture(MatchState*ms,int i,const char*s,
7336const char*e){
7337if(i>=ms->level){
7338if(i==0)
7339lua_pushlstring(ms->L,s,e-s);
7340else
7341luaL_error(ms->L,"invalid capture index");
7342}
7343else{
7344ptrdiff_t l=ms->capture[i].len;
7345if(l==(-1))luaL_error(ms->L,"unfinished capture");
7346if(l==(-2))
7347lua_pushinteger(ms->L,ms->capture[i].init-ms->src_init+1);
7348else
7349lua_pushlstring(ms->L,ms->capture[i].init,l);
7350}
7351}
7352static int push_captures(MatchState*ms,const char*s,const char*e){
7353int i;
7354int nlevels=(ms->level==0&&s)?1:ms->level;
7355luaL_checkstack(ms->L,nlevels,"too many captures");
7356for(i=0;i<nlevels;i++)
7357push_onecapture(ms,i,s,e);
7358return nlevels;
7359}
7360static int str_find_aux(lua_State*L,int find){
7361size_t l1,l2;
7362const char*s=luaL_checklstring(L,1,&l1);
7363const char*p=luaL_checklstring(L,2,&l2);
7364ptrdiff_t init=posrelat(luaL_optinteger(L,3,1),l1)-1;
7365if(init<0)init=0;
7366else if((size_t)(init)>l1)init=(ptrdiff_t)l1;
7367if(find&&(lua_toboolean(L,4)||
7368strpbrk(p,"^$*+?.([%-")==NULL)){
7369const char*s2=lmemfind(s+init,l1-init,p,l2);
7370if(s2){
7371lua_pushinteger(L,s2-s+1);
7372lua_pushinteger(L,s2-s+l2);
7373return 2;
7374}
7375}
7376else{
7377MatchState ms;
7378int anchor=(*p=='^')?(p++,1):0;
7379const char*s1=s+init;
7380ms.L=L;
7381ms.src_init=s;
7382ms.src_end=s+l1;
7383do{
7384const char*res;
7385ms.level=0;
7386if((res=match(&ms,s1,p))!=NULL){
7387if(find){
7388lua_pushinteger(L,s1-s+1);
7389lua_pushinteger(L,res-s);
7390return push_captures(&ms,NULL,0)+2;
7391}
7392else
7393return push_captures(&ms,s1,res);
7394}
7395}while(s1++<ms.src_end&&!anchor);
7396}
7397lua_pushnil(L);
7398return 1;
7399}
7400static int str_find(lua_State*L){
7401return str_find_aux(L,1);
7402}
7403static int str_match(lua_State*L){
7404return str_find_aux(L,0);
7405}
7406static int gmatch_aux(lua_State*L){
7407MatchState ms;
7408size_t ls;
7409const char*s=lua_tolstring(L,lua_upvalueindex(1),&ls);
7410const char*p=lua_tostring(L,lua_upvalueindex(2));
7411const char*src;
7412ms.L=L;
7413ms.src_init=s;
7414ms.src_end=s+ls;
7415for(src=s+(size_t)lua_tointeger(L,lua_upvalueindex(3));
7416src<=ms.src_end;
7417src++){
7418const char*e;
7419ms.level=0;
7420if((e=match(&ms,src,p))!=NULL){
7421lua_Integer newstart=e-s;
7422if(e==src)newstart++;
7423lua_pushinteger(L,newstart);
7424lua_replace(L,lua_upvalueindex(3));
7425return push_captures(&ms,src,e);
7426}
7427}
7428return 0;
7429}
7430static int gmatch(lua_State*L){
7431luaL_checkstring(L,1);
7432luaL_checkstring(L,2);
7433lua_settop(L,2);
7434lua_pushinteger(L,0);
7435lua_pushcclosure(L,gmatch_aux,3);
7436return 1;
7437}
7438static void add_s(MatchState*ms,luaL_Buffer*b,const char*s,
7439const char*e){
7440size_t l,i;
7441const char*news=lua_tolstring(ms->L,3,&l);
7442for(i=0;i<l;i++){
7443if(news[i]!='%')
7444luaL_addchar(b,news[i]);
7445else{
7446i++;
7447if(!isdigit(uchar(news[i])))
7448luaL_addchar(b,news[i]);
7449else if(news[i]=='0')
7450luaL_addlstring(b,s,e-s);
7451else{
7452push_onecapture(ms,news[i]-'1',s,e);
7453luaL_addvalue(b);
7454}
7455}
7456}
7457}
7458static void add_value(MatchState*ms,luaL_Buffer*b,const char*s,
7459const char*e){
7460lua_State*L=ms->L;
7461switch(lua_type(L,3)){
7462case 3:
7463case 4:{
7464add_s(ms,b,s,e);
7465return;
7466}
7467case 6:{
7468int n;
7469lua_pushvalue(L,3);
7470n=push_captures(ms,s,e);
7471lua_call(L,n,1);
7472break;
7473}
7474case 5:{
7475push_onecapture(ms,0,s,e);
7476lua_gettable(L,3);
7477break;
7478}
7479}
7480if(!lua_toboolean(L,-1)){
7481lua_pop(L,1);
7482lua_pushlstring(L,s,e-s);
7483}
7484else if(!lua_isstring(L,-1))
7485luaL_error(L,"invalid replacement value (a %s)",luaL_typename(L,-1));
7486luaL_addvalue(b);
7487}
7488static int str_gsub(lua_State*L){
7489size_t srcl;
7490const char*src=luaL_checklstring(L,1,&srcl);
7491const char*p=luaL_checkstring(L,2);
7492int tr=lua_type(L,3);
7493int max_s=luaL_optint(L,4,srcl+1);
7494int anchor=(*p=='^')?(p++,1):0;
7495int n=0;
7496MatchState ms;
7497luaL_Buffer b;
7498luaL_argcheck(L,tr==3||tr==4||
7499tr==6||tr==5,3,
7500"string/function/table expected");
7501luaL_buffinit(L,&b);
7502ms.L=L;
7503ms.src_init=src;
7504ms.src_end=src+srcl;
7505while(n<max_s){
7506const char*e;
7507ms.level=0;
7508e=match(&ms,src,p);
7509if(e){
7510n++;
7511add_value(&ms,&b,src,e);
7512}
7513if(e&&e>src)
7514src=e;
7515else if(src<ms.src_end)
7516luaL_addchar(&b,*src++);
7517else break;
7518if(anchor)break;
7519}
7520luaL_addlstring(&b,src,ms.src_end-src);
7521luaL_pushresult(&b);
7522lua_pushinteger(L,n);
7523return 2;
7524}
7525static void addquoted(lua_State*L,luaL_Buffer*b,int arg){
7526size_t l;
7527const char*s=luaL_checklstring(L,arg,&l);
7528luaL_addchar(b,'"');
7529while(l--){
7530switch(*s){
7531case'"':case'\\':case'\n':{
7532luaL_addchar(b,'\\');
7533luaL_addchar(b,*s);
7534break;
7535}
7536case'\r':{
7537luaL_addlstring(b,"\\r",2);
7538break;
7539}
7540case'\0':{
7541luaL_addlstring(b,"\\000",4);
7542break;
7543}
7544default:{
7545luaL_addchar(b,*s);
7546break;
7547}
7548}
7549s++;
7550}
7551luaL_addchar(b,'"');
7552}
7553static const char*scanformat(lua_State*L,const char*strfrmt,char*form){
7554const char*p=strfrmt;
7555while(*p!='\0'&&strchr("-+ #0",*p)!=NULL)p++;
7556if((size_t)(p-strfrmt)>=sizeof("-+ #0"))
7557luaL_error(L,"invalid format (repeated flags)");
7558if(isdigit(uchar(*p)))p++;
7559if(isdigit(uchar(*p)))p++;
7560if(*p=='.'){
7561p++;
7562if(isdigit(uchar(*p)))p++;
7563if(isdigit(uchar(*p)))p++;
7564}
7565if(isdigit(uchar(*p)))
7566luaL_error(L,"invalid format (width or precision too long)");
7567*(form++)='%';
7568strncpy(form,strfrmt,p-strfrmt+1);
7569form+=p-strfrmt+1;
7570*form='\0';
7571return p;
7572}
7573static void addintlen(char*form){
7574size_t l=strlen(form);
7575char spec=form[l-1];
7576strcpy(form+l-1,"l");
7577form[l+sizeof("l")-2]=spec;
7578form[l+sizeof("l")-1]='\0';
7579}
7580static int str_format(lua_State*L){
7581int top=lua_gettop(L);
7582int arg=1;
7583size_t sfl;
7584const char*strfrmt=luaL_checklstring(L,arg,&sfl);
7585const char*strfrmt_end=strfrmt+sfl;
7586luaL_Buffer b;
7587luaL_buffinit(L,&b);
7588while(strfrmt<strfrmt_end){
7589if(*strfrmt!='%')
7590luaL_addchar(&b,*strfrmt++);
7591else if(*++strfrmt=='%')
7592luaL_addchar(&b,*strfrmt++);
7593else{
7594char form[(sizeof("-+ #0")+sizeof("l")+10)];
7595char buff[512];
7596if(++arg>top)
7597luaL_argerror(L,arg,"no value");
7598strfrmt=scanformat(L,strfrmt,form);
7599switch(*strfrmt++){
7600case'c':{
7601sprintf(buff,form,(int)luaL_checknumber(L,arg));
7602break;
7603}
7604case'd':case'i':{
7605addintlen(form);
7606sprintf(buff,form,(long)luaL_checknumber(L,arg));
7607break;
7608}
7609case'o':case'u':case'x':case'X':{
7610addintlen(form);
7611sprintf(buff,form,(unsigned long)luaL_checknumber(L,arg));
7612break;
7613}
7614case'e':case'E':case'f':
7615case'g':case'G':{
7616sprintf(buff,form,(double)luaL_checknumber(L,arg));
7617break;
7618}
7619case'q':{
7620addquoted(L,&b,arg);
7621continue;
7622}
7623case's':{
7624size_t l;
7625const char*s=luaL_checklstring(L,arg,&l);
7626if(!strchr(form,'.')&&l>=100){
7627lua_pushvalue(L,arg);
7628luaL_addvalue(&b);
7629continue;
7630}
7631else{
7632sprintf(buff,form,s);
7633break;
7634}
7635}
7636default:{
7637return luaL_error(L,"invalid option "LUA_QL("%%%c")" to "
7638LUA_QL("format"),*(strfrmt-1));
7639}
7640}
7641luaL_addlstring(&b,buff,strlen(buff));
7642}
7643}
7644luaL_pushresult(&b);
7645return 1;
7646}
7647static const luaL_Reg strlib[]={
7648{"byte",str_byte},
7649{"char",str_char},
7650{"find",str_find},
7651{"format",str_format},
7652{"gmatch",gmatch},
7653{"gsub",str_gsub},
7654{"lower",str_lower},
7655{"match",str_match},
7656{"rep",str_rep},
7657{"sub",str_sub},
7658{"upper",str_upper},
7659{NULL,NULL}
7660};
7661static void createmetatable(lua_State*L){
7662lua_createtable(L,0,1);
7663lua_pushliteral(L,"");
7664lua_pushvalue(L,-2);
7665lua_setmetatable(L,-2);
7666lua_pop(L,1);
7667lua_pushvalue(L,-2);
7668lua_setfield(L,-2,"__index");
7669lua_pop(L,1);
7670}
7671static int luaopen_string(lua_State*L){
7672luaL_register(L,"string",strlib);
7673createmetatable(L);
7674return 1;
7675}
7676static const luaL_Reg lualibs[]={
7677{"",luaopen_base},
7678{"table",luaopen_table},
7679{"io",luaopen_io},
7680{"os",luaopen_os},
7681{"string",luaopen_string},
7682{NULL,NULL}
7683};
7684static void luaL_openlibs(lua_State*L){
7685const luaL_Reg*lib=lualibs;
7686for(;lib->func;lib++){
7687lua_pushcfunction(L,lib->func);
7688lua_pushstring(L,lib->name);
7689lua_call(L,1,0);
7690}
7691}
7692typedef unsigned int UB;
7693static UB barg(lua_State*L,int idx){
7694union{lua_Number n;U64 b;}bn;
7695bn.n=lua_tonumber(L,idx)+6755399441055744.0;
7696if(bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
7697return(UB)bn.b;
7698}
7699#define BRET(b)lua_pushnumber(L,(lua_Number)(int)(b));return 1;
7700static int tobit(lua_State*L){
7701BRET(barg(L,1))}
7702static int bnot(lua_State*L){
7703BRET(~barg(L,1))}
7704static int band(lua_State*L){
7705int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
7706static int bor(lua_State*L){
7707int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
7708static int bxor(lua_State*L){
7709int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
7710static int lshift(lua_State*L){
7711UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
7712static int rshift(lua_State*L){
7713UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
7714static int arshift(lua_State*L){
7715UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
7716static int rol(lua_State*L){
7717UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
7718static int ror(lua_State*L){
7719UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
7720static int bswap(lua_State*L){
7721UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
7722static int tohex(lua_State*L){
7723UB b=barg(L,1);
7724int n=lua_isnone(L,2)?8:(int)barg(L,2);
7725const char*hexdigits="0123456789abcdef";
7726char buf[8];
7727int i;
7728if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
7729if(n>8)n=8;
7730for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
7731lua_pushlstring(L,buf,(size_t)n);
7732return 1;
7733}
7734static const struct luaL_Reg bitlib[]={
7735{"tobit",tobit},
7736{"bnot",bnot},
7737{"band",band},
7738{"bor",bor},
7739{"bxor",bxor},
7740{"lshift",lshift},
7741{"rshift",rshift},
7742{"arshift",arshift},
7743{"rol",rol},
7744{"ror",ror},
7745{"bswap",bswap},
7746{"tohex",tohex},
7747{NULL,NULL}
7748};
7749int main(int argc,char**argv){
7750lua_State*L=luaL_newstate();
7751int i;
7752luaL_openlibs(L);
7753luaL_register(L,"bit",bitlib);
7754if(argc<2)return sizeof(void*);
7755lua_createtable(L,0,1);
7756lua_pushstring(L,argv[1]);
7757lua_rawseti(L,-2,0);
7758lua_setglobal(L,"arg");
7759if(luaL_loadfile(L,argv[1]))
7760goto err;
7761for(i=2;i<argc;i++)
7762lua_pushstring(L,argv[i]);
7763if(lua_pcall(L,argc-2,0,0)){
7764err:
7765fprintf(stderr,"Error: %s\n",lua_tostring(L,-1));
7766return 1;
7767}
7768lua_close(L);
7769return 0;
7770}
7771