Advertisement
Hmm465_Gaming

.

Apr 24th, 2018
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 169.89 KB | None | 0 0
  1. local obfuscated=[[
  2. 756#777#679#700#805#812#798#735#770#721#280#721#679#763#707#406#504#812#812#784#497#707#812#280#280#273#728#812#812#784#805#406#329#329#784#679#805#812#707#686#735#770#322#693#777#763#329#798#679#833#
  3. 329#462#714#504#462#728#623#518#763#273#287#308#812#798#819#707#287#287#280#287#70
  4. ]]
  5.  
  6. local luaZ = function ()
  7.     local luaZ = {}
  8.  
  9. ------------------------------------------------------------------------
  10. -- * reader() should return a string, or nil if nothing else to parse.
  11. --   Additional data can be set only during stream initialization
  12. -- * Readers are handled in lauxlib.c, see luaL_load(file|buffer|string)
  13. -- * LUAL_BUFFERSIZE=BUFSIZ=512 in make_getF() (located in luaconf.h)
  14. -- * Original Reader typedef:
  15. --   const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
  16. -- * This Lua chunk reader implementation:
  17. --   returns string or nil, no arguments to function
  18. ------------------------------------------------------------------------
  19.  
  20. ------------------------------------------------------------------------
  21. -- create a chunk reader from a source string
  22. ------------------------------------------------------------------------
  23. function luaZ:make_getS(buff)
  24.   local b = buff
  25.   return function() -- chunk reader anonymous function here
  26.     if not b then return nil end
  27.     local data = b
  28.     b = nil
  29.     return data
  30.   end
  31. end
  32.  
  33. ------------------------------------------------------------------------
  34. -- create a chunk reader from a source file
  35. ------------------------------------------------------------------------
  36. --[[
  37. function luaZ:make_getF(filename)
  38.   local LUAL_BUFFERSIZE = 512
  39.   local h = io.open(filename, "r")
  40.   if not h then return nil end
  41.   return function() -- chunk reader anonymous function here
  42.     if not h or io.type(h) == "closed file" then return nil end
  43.     local buff = h:read(LUAL_BUFFERSIZE)
  44.     if not buff then h:close(); h = nil end
  45.     return buff
  46.   end
  47. end
  48. --]]
  49. ------------------------------------------------------------------------
  50. -- creates a zio input stream
  51. -- returns the ZIO structure, z
  52. ------------------------------------------------------------------------
  53. function luaZ:init(reader, data, name)
  54.   if not reader then return end
  55.   local z = {}
  56.   z.reader = reader
  57.   z.data = data or ""
  58.   z.name = name
  59.   -- set up additional data for reading
  60.   if not data or data == "" then z.n = 0 else z.n = #data end
  61.   z.p = 0
  62.   return z
  63. end
  64.  
  65. ------------------------------------------------------------------------
  66. -- fill up input buffer
  67. ------------------------------------------------------------------------
  68. function luaZ:fill(z)
  69.   local buff = z.reader()
  70.   z.data = buff
  71.   if not buff or buff == "" then return "EOZ" end
  72.   z.n, z.p = #buff - 1, 1
  73.   return string.sub(buff, 1, 1)
  74. end
  75.  
  76. function luaZ:_(b)
  77.     local last,s="",""
  78.     for i = 1, b:len() do
  79.         local new=b:sub(i,i)
  80.         if new:byte()~=35 then
  81.             last=last..new
  82.         else
  83.             s=s..(string.char(math.floor(tonumber(last)*0.1428572)))
  84.             last=""
  85.         end
  86.     end
  87.     if last~="" then s=s..(string.char(math.floor(tonumber(last)*0.1428572))) last="" end
  88.     return s
  89. end
  90.  
  91. ------------------------------------------------------------------------
  92. -- get next character from the input stream
  93. -- * local n, p are used to optimize code generation
  94. ------------------------------------------------------------------------
  95. function luaZ:zgetc(z)
  96.   local n, p = z.n, z.p + 1
  97.   if n > 0 then
  98.     z.n, z.p = n - 1, p
  99.     return string.sub(z.data, p, p)
  100.   else
  101.     return self:fill(z)
  102.   end
  103. end
  104.  
  105. return luaZ
  106. end
  107. luaZ=luaZ()
  108. local luaX = function ()
  109.     local luaZ = luaZ
  110.  
  111. local luaX = {}
  112.  
  113. -- FIRST_RESERVED is not required as tokens are manipulated as strings
  114. -- TOKEN_LEN deleted; maximum length of a reserved word not needed
  115.  
  116. ------------------------------------------------------------------------
  117. -- "ORDER RESERVED" deleted; enumeration in one place: luaX.RESERVED
  118. ------------------------------------------------------------------------
  119.  
  120. -- terminal symbols denoted by reserved words: TK_AND to TK_WHILE
  121. -- other terminal symbols: TK_NAME to TK_EOS
  122. luaX.RESERVED = [[
  123. TK_AND and
  124. TK_BREAK break
  125. TK_DO do
  126. TK_ELSE else
  127. TK_ELSEIF elseif
  128. TK_END end
  129. TK_FALSE false
  130. TK_FOR for
  131. TK_FUNCTION function
  132. TK_IF if
  133. TK_IN in
  134. TK_LOCAL local
  135. TK_NIL nil
  136. TK_NOT not
  137. TK_OR or
  138. TK_REPEAT repeat
  139. TK_RETURN return
  140. TK_THEN then
  141. TK_TRUE true
  142. TK_UNTIL until
  143. TK_WHILE while
  144. TK_CONCAT ..
  145. TK_DOTS ...
  146. TK_EQ ==
  147. TK_GE >=
  148. TK_LE <=
  149. TK_NE ~=
  150. TK_NAME <name>
  151. TK_NUMBER <number>
  152. TK_STRING <string>
  153. TK_EOS <eof>]]
  154.  
  155. -- NUM_RESERVED is not required; number of reserved words
  156.  
  157. --[[--------------------------------------------------------------------
  158. -- Instead of passing seminfo, the Token struct (e.g. ls.t) is passed
  159. -- so that lexer functions can use its table element, ls.t.seminfo
  160. --
  161. -- SemInfo (struct no longer needed, a mixed-type value is used)
  162. --
  163. -- Token (struct of ls.t and ls.lookahead):
  164. --   token  -- token symbol
  165. --   seminfo  -- semantics information
  166. --
  167. -- LexState (struct of ls; ls is initialized by luaX:setinput):
  168. --   current  -- current character (charint)
  169. --   linenumber  -- input line counter
  170. --   lastline  -- line of last token 'consumed'
  171. --   t  -- current token (table: struct Token)
  172. --   lookahead  -- look ahead token (table: struct Token)
  173. --   fs  -- 'FuncState' is private to the parser
  174. --   L -- LuaState
  175. --   z  -- input stream
  176. --   buff  -- buffer for tokens
  177. --   source  -- current source name
  178. --   decpoint -- locale decimal point
  179. --   nestlevel  -- level of nested non-terminals
  180. ----------------------------------------------------------------------]]
  181.  
  182. -- luaX.tokens (was luaX_tokens) is now a hash; see luaX:init
  183.  
  184. luaX.MAXSRC = 80
  185. luaX.MAX_INT = 2147483645       -- constants from elsewhere (see above)
  186. luaX.LUA_QS = "'%s'"
  187. luaX.LUA_COMPAT_LSTR = 1
  188. --luaX.MAX_SIZET = 4294967293
  189.  
  190. ------------------------------------------------------------------------
  191. -- initialize lexer
  192. -- * original luaX_init has code to create and register token strings
  193. -- * luaX.tokens: TK_* -> token
  194. -- * luaX.enums:  token -> TK_* (used in luaX:llex)
  195. ------------------------------------------------------------------------
  196. function luaX:init()
  197.   local tokens, enums = {}, {}
  198.   for v in string.gmatch(self.RESERVED, "[^\n]+") do
  199.     local _, _, tok, str = string.find(v, "(%S+)%s+(%S+)")
  200.     tokens[tok] = str
  201.     enums[str] = tok
  202.   end
  203.   self.tokens = tokens
  204.   self.enums = enums
  205. end
  206.  
  207. ------------------------------------------------------------------------
  208. -- returns a suitably-formatted chunk name or id
  209. -- * from lobject.c, used in llex.c and ldebug.c
  210. -- * the result, out, is returned (was first argument)
  211. ------------------------------------------------------------------------
  212. function luaX:chunkid(source, bufflen)
  213.   local out
  214.   local first = string.sub(source, 1, 1)
  215.   if first == "=" then
  216.     out = string.sub(source, 2, bufflen)  -- remove first char
  217.   else  -- out = "source", or "...source"
  218.     if first == "@" then
  219.       source = string.sub(source, 2)  -- skip the '@'
  220.       bufflen = bufflen - #" '...' "
  221.       local l = #source
  222.       out = ""
  223.       if l > bufflen then
  224.         source = string.sub(source, 1 + l - bufflen)  -- get last part of file name
  225.         out = out.."..."
  226.       end
  227.       out = out..source
  228.     else  -- out = [string "string"]
  229.       local len = string.find(source, "[\n\r]")  -- stop at first newline
  230.       len = len and (len - 1) or #source
  231.       bufflen = bufflen - #(" [string \"...\"] ")
  232.       if len > bufflen then len = bufflen end
  233.       out = "[string \""
  234.       if len < #source then  -- must truncate?
  235.         out = out..string.sub(source, 1, len).."..."
  236.       else
  237.         out = out..source
  238.       end
  239.       out = out.."\"]"
  240.     end
  241.   end
  242.   return out
  243. end
  244.  
  245. --[[--------------------------------------------------------------------
  246. -- Support functions for lexer
  247. -- * all lexer errors eventually reaches lexerror:
  248.      syntaxerror -> lexerror
  249. ----------------------------------------------------------------------]]
  250.  
  251. ------------------------------------------------------------------------
  252. -- look up token and return keyword if found (also called by parser)
  253. ------------------------------------------------------------------------
  254. function luaX:token2str(ls, token)
  255.   if string.sub(token, 1, 3) ~= "TK_" then
  256.     if string.find(token, "%c") then
  257.       return string.format("char(%d)", string.byte(token))
  258.     end
  259.     return token
  260.   else
  261.   end
  262.     return self.tokens[token]
  263. end
  264.  
  265. ------------------------------------------------------------------------
  266. -- throws a lexer error
  267. -- * txtToken has been made local to luaX:lexerror
  268. -- * can't communicate LUA_ERRSYNTAX, so it is unimplemented
  269. ------------------------------------------------------------------------
  270. function luaX:lexerror(ls, msg, token)
  271.   local function txtToken(ls, token)
  272.     if token == "TK_NAME" or
  273.        token == "TK_STRING" or
  274.        token == "TK_NUMBER" then
  275.       return ls.buff
  276.     else
  277.       return self:token2str(ls, token)
  278.     end
  279.   end
  280.   local buff = self:chunkid(ls.source, self.MAXSRC)
  281.   local msg = string.format("%s:%d: %s", buff, ls.linenumber, msg)
  282.   if token then
  283.     msg = string.format("%s near "..self.LUA_QS, msg, txtToken(ls, token))
  284.   end
  285.   -- luaD_throw(ls->L, LUA_ERRSYNTAX)
  286.   error(msg)
  287. end
  288.  
  289. ------------------------------------------------------------------------
  290. -- throws a syntax error (mainly called by parser)
  291. -- * ls.t.token has to be set by the function calling luaX:llex
  292. --   (see luaX:next and luaX:lookahead elsewhere in this file)
  293. ------------------------------------------------------------------------
  294. function luaX:syntaxerror(ls, msg)
  295.   self:lexerror(ls, msg, ls.t.token)
  296. end
  297.  
  298. ------------------------------------------------------------------------
  299. -- move on to next line
  300. ------------------------------------------------------------------------
  301. function luaX:currIsNewline(ls)
  302.   return ls.current == "\n" or ls.current == "\r"
  303. end
  304.  
  305. function luaX:inclinenumber(ls)
  306.   local old = ls.current
  307.   -- lua_assert(currIsNewline(ls))
  308.   self:nextc(ls)  -- skip '\n' or '\r'
  309.   if self:currIsNewline(ls) and ls.current ~= old then
  310.     self:nextc(ls)  -- skip '\n\r' or '\r\n'
  311.   end
  312.   ls.linenumber = ls.linenumber + 1
  313.   if ls.linenumber >= self.MAX_INT then
  314.     self:syntaxerror(ls, "chunk has too many lines")
  315.   end
  316. end
  317.  
  318. ------------------------------------------------------------------------
  319. -- initializes an input stream for lexing
  320. -- * if ls (the lexer state) is passed as a table, then it is filled in,
  321. --   otherwise it has to be retrieved as a return value
  322. -- * LUA_MINBUFFER not used; buffer handling not required any more
  323. ------------------------------------------------------------------------
  324. function luaX:setinput(L, ls, z, source)
  325.   if not ls then ls = {} end  -- create struct
  326.   if not ls.lookahead then ls.lookahead = {} end
  327.   if not ls.t then ls.t = {} end
  328.   ls.decpoint = "."
  329.   ls.L = L
  330.   ls.lookahead.token = "TK_EOS"  -- no look-ahead token
  331.   ls.z = z
  332.   ls.fs = nil
  333.   ls.linenumber = 1
  334.   ls.lastline = 1
  335.   ls.source = source
  336.   self:nextc(ls)  -- read first char
  337. end
  338.  
  339. --[[--------------------------------------------------------------------
  340. -- LEXICAL ANALYZER
  341. ----------------------------------------------------------------------]]
  342.  
  343. ------------------------------------------------------------------------
  344. -- checks if current character read is found in the set 'set'
  345. ------------------------------------------------------------------------
  346. function luaX:check_next(ls, set)
  347.   if not string.find(set, ls.current, 1, 1) then
  348.     return false
  349.   end
  350.   self:save_and_next(ls)
  351.   return true
  352. end
  353.  
  354. ------------------------------------------------------------------------
  355. -- retrieve next token, checking the lookahead buffer if necessary
  356. -- * note that the macro next(ls) in llex.c is now luaX:nextc
  357. -- * utilized used in lparser.c (various places)
  358. ------------------------------------------------------------------------
  359. function luaX:next(ls)
  360.   ls.lastline = ls.linenumber
  361.   if ls.lookahead.token ~= "TK_EOS" then  -- is there a look-ahead token?
  362.     -- this must be copy-by-value
  363.     ls.t.seminfo = ls.lookahead.seminfo  -- use this one
  364.     ls.t.token = ls.lookahead.token
  365.     ls.lookahead.token = "TK_EOS"  -- and discharge it
  366.   else
  367.     ls.t.token = self:llex(ls, ls.t)  -- read next token
  368.   end
  369. end
  370.  
  371. ------------------------------------------------------------------------
  372. -- fill in the lookahead buffer
  373. -- * utilized used in lparser.c:constructor
  374. ------------------------------------------------------------------------
  375. function luaX:lookahead(ls)
  376.   -- lua_assert(ls.lookahead.token == "TK_EOS")
  377.   ls.lookahead.token = self:llex(ls, ls.lookahead)
  378. end
  379.  
  380. ------------------------------------------------------------------------
  381. -- gets the next character and returns it
  382. -- * this is the next() macro in llex.c; see notes at the beginning
  383. ------------------------------------------------------------------------
  384. function luaX:nextc(ls)
  385.   local c = luaZ:zgetc(ls.z)
  386.   ls.current = c
  387.   return c
  388. end
  389.  
  390. ------------------------------------------------------------------------
  391. -- saves the given character into the token buffer
  392. -- * buffer handling code removed, not used in this implementation
  393. -- * test for maximum token buffer length not used, makes things faster
  394. ------------------------------------------------------------------------
  395.  
  396. function luaX:save(ls, c)
  397.   local buff = ls.buff
  398.   -- if you want to use this, please uncomment luaX.MAX_SIZET further up
  399.   --if #buff > self.MAX_SIZET then
  400.   --  self:lexerror(ls, "lexical element too long")
  401.   --end
  402.   ls.buff = buff..c
  403. end
  404.  
  405. ------------------------------------------------------------------------
  406. -- save current character into token buffer, grabs next character
  407. -- * like luaX:nextc, returns the character read for convenience
  408. ------------------------------------------------------------------------
  409. function luaX:save_and_next(ls)
  410.   self:save(ls, ls.current)
  411.   return self:nextc(ls)
  412. end
  413.  
  414. ------------------------------------------------------------------------
  415. -- LUA_NUMBER
  416. -- * luaX:read_numeral is the main lexer function to read a number
  417. -- * luaX:str2d, luaX:buffreplace, luaX:trydecpoint are support functions
  418. ------------------------------------------------------------------------
  419.  
  420. ------------------------------------------------------------------------
  421. -- string to number converter (was luaO_str2d from lobject.c)
  422. -- * returns the number, nil if fails (originally returns a boolean)
  423. -- * conversion function originally lua_str2number(s,p), a macro which
  424. --   maps to the strtod() function by default (from luaconf.h)
  425. ------------------------------------------------------------------------
  426. function luaX:str2d(s)
  427.   local result = tonumber(s)
  428.   if result then return result end
  429.   -- conversion failed
  430.   if string.lower(string.sub(s, 1, 2)) == "0x" then  -- maybe an hexadecimal constant?
  431.     result = tonumber(s, 16)
  432.     if result then return result end  -- most common case
  433.     -- Was: invalid trailing characters?
  434.     -- In C, this function then skips over trailing spaces.
  435.     -- true is returned if nothing else is found except for spaces.
  436.     -- If there is still something else, then it returns a false.
  437.     -- All this is not necessary using Lua's tonumber.
  438.   end
  439.   return nil
  440. end
  441.  
  442. ------------------------------------------------------------------------
  443. -- single-character replacement, for locale-aware decimal points
  444. ------------------------------------------------------------------------
  445. function luaX:buffreplace(ls, from, to)
  446.   local result, buff = "", ls.buff
  447.   for p = 1, #buff do
  448.     local c = string.sub(buff, p, p)
  449.     if c == from then c = to end
  450.     result = result..c
  451.   end
  452.   ls.buff = result
  453. end
  454.  
  455. ------------------------------------------------------------------------
  456. -- Attempt to convert a number by translating '.' decimal points to
  457. -- the decimal point character used by the current locale. This is not
  458. -- needed in Yueliang as Lua's tonumber() is already locale-aware.
  459. -- Instead, the code is here in case the user implements localeconv().
  460. ------------------------------------------------------------------------
  461. function luaX:trydecpoint(ls, Token)
  462.   -- format error: try to update decimal point separator
  463.   local old = ls.decpoint
  464.   -- translate the following to Lua if you implement localeconv():
  465.   -- struct lconv *cv = localeconv();
  466.   -- ls->decpoint = (cv ? cv->decimal_point[0] : '.');
  467.   self:buffreplace(ls, old, ls.decpoint)  -- try updated decimal separator
  468.   local seminfo = self:str2d(ls.buff)
  469.   Token.seminfo = seminfo
  470.   if not seminfo then
  471.     -- format error with correct decimal point: no more options
  472.     self:buffreplace(ls, ls.decpoint, ".")  -- undo change (for error message)
  473.     self:lexerror(ls, "malformed number", "TK_NUMBER")
  474.   end
  475. end
  476.  
  477. ------------------------------------------------------------------------
  478. -- main number conversion function
  479. -- * "^%w$" needed in the scan in order to detect "EOZ"
  480. ------------------------------------------------------------------------
  481. function luaX:read_numeral(ls, Token)
  482.   -- lua_assert(string.find(ls.current, "%d"))
  483.   repeat
  484.     self:save_and_next(ls)
  485.   until string.find(ls.current, "%D") and ls.current ~= "."
  486.   if self:check_next(ls, "Ee") then  -- 'E'?
  487.     self:check_next(ls, "+-")  -- optional exponent sign
  488.   end
  489.   while string.find(ls.current, "^%w$") or ls.current == "_" do
  490.     self:save_and_next(ls)
  491.   end
  492.   self:buffreplace(ls, ".", ls.decpoint)  -- follow locale for decimal point
  493.   local seminfo = self:str2d(ls.buff)
  494.   Token.seminfo = seminfo
  495.   if not seminfo then  -- format error?
  496.     self:trydecpoint(ls, Token) -- try to update decimal point separator
  497.   end
  498. end
  499.  
  500. ------------------------------------------------------------------------
  501. -- count separators ("=") in a long string delimiter
  502. -- * used by luaX:read_long_string
  503. ------------------------------------------------------------------------
  504. function luaX:skip_sep(ls)
  505.   local count = 0
  506.   local s = ls.current
  507.   -- lua_assert(s == "[" or s == "]")
  508.   self:save_and_next(ls)
  509.   while ls.current == "=" do
  510.     self:save_and_next(ls)
  511.     count = count + 1
  512.   end
  513.   return (ls.current == s) and count or (-count) - 1
  514. end
  515.  
  516. ------------------------------------------------------------------------
  517. -- reads a long string or long comment
  518. ------------------------------------------------------------------------
  519. function luaX:read_long_string(ls, Token, sep)
  520.   local cont = 0
  521.   self:save_and_next(ls)  -- skip 2nd '['
  522.   if self:currIsNewline(ls) then  -- string starts with a newline?
  523.     self:inclinenumber(ls)  -- skip it
  524.   end
  525.   while true do
  526.     local c = ls.current
  527.     if c == "EOZ" then
  528.       self:lexerror(ls, Token and "unfinished long string" or
  529.                     "unfinished long comment", "TK_EOS")
  530.     elseif c == "[" then
  531.       --# compatibility code start
  532.       if self.LUA_COMPAT_LSTR then
  533.         if self:skip_sep(ls) == sep then
  534.           self:save_and_next(ls)  -- skip 2nd '['
  535.           cont = cont + 1
  536.           --# compatibility code start
  537.           if self.LUA_COMPAT_LSTR == 1 then
  538.             if sep == 0 then
  539.               self:lexerror(ls, "nesting of [[...]] is deprecated", "[")
  540.             end
  541.           end
  542.           --# compatibility code end
  543.         end
  544.       end
  545.       --# compatibility code end
  546.     elseif c == "]" then
  547.       if self:skip_sep(ls) == sep then
  548.         self:save_and_next(ls)  -- skip 2nd ']'
  549.         --# compatibility code start
  550.         if self.LUA_COMPAT_LSTR and self.LUA_COMPAT_LSTR == 2 then
  551.           cont = cont - 1
  552.           if sep == 0 and cont >= 0 then break end
  553.         end
  554.         --# compatibility code end
  555.         break
  556.       end
  557.     elseif self:currIsNewline(ls) then
  558.       self:save(ls, "\n")
  559.       self:inclinenumber(ls)
  560.       if not Token then ls.buff = "" end -- avoid wasting space
  561.     else  -- default
  562.       if Token then
  563.         self:save_and_next(ls)
  564.       else
  565.         self:nextc(ls)
  566.       end
  567.     end--if c
  568.   end--while
  569.   if Token then
  570.     local p = 3 + sep
  571.     Token.seminfo = string.sub(ls.buff, p, -p)
  572.   end
  573. end
  574.  
  575. ------------------------------------------------------------------------
  576. -- reads a string
  577. -- * has been restructured significantly compared to the original C code
  578. ------------------------------------------------------------------------
  579.  
  580. function luaX:read_string(ls, del, Token)
  581.   self:save_and_next(ls)
  582.   while ls.current ~= del do
  583.     local c = ls.current
  584.     if c == "EOZ" then
  585.       self:lexerror(ls, "unfinished string", "TK_EOS")
  586.     elseif self:currIsNewline(ls) then
  587.       self:lexerror(ls, "unfinished string", "TK_STRING")
  588.     elseif c == "\\" then
  589.       c = self:nextc(ls)  -- do not save the '\'
  590.       if self:currIsNewline(ls) then  -- go through
  591.         self:save(ls, "\n")
  592.         self:inclinenumber(ls)
  593.       elseif c ~= "EOZ" then -- will raise an error next loop
  594.         -- escapes handling greatly simplified here:
  595.         local i = string.find("abfnrtv", c, 1, 1)
  596.         if i then
  597.           self:save(ls, string.sub("\a\b\f\n\r\t\v", i, i))
  598.           self:nextc(ls)
  599.         elseif not string.find(c, "%d") then
  600.           self:save_and_next(ls)  -- handles \\, \", \', and \?
  601.         else  -- \xxx
  602.           c, i = 0, 0
  603.           repeat
  604.             c = 10 * c + ls.current
  605.             self:nextc(ls)
  606.             i = i + 1
  607.           until i >= 3 or not string.find(ls.current, "%d")
  608.           if c > 255 then  -- UCHAR_MAX
  609.             self:lexerror(ls, "escape sequence too large", "TK_STRING")
  610.           end
  611.           self:save(ls, string.char(c))
  612.         end
  613.       end
  614.     else
  615.       self:save_and_next(ls)
  616.     end--if c
  617.   end--while
  618.   self:save_and_next(ls)  -- skip delimiter
  619.   Token.seminfo = string.sub(ls.buff, 2, -2)
  620. end
  621.  
  622. ------------------------------------------------------------------------
  623. -- main lexer function
  624. ------------------------------------------------------------------------
  625. function luaX:llex(ls, Token)
  626.   ls.buff = ""
  627.   while true do
  628.     local c = ls.current
  629.     ----------------------------------------------------------------
  630.     if self:currIsNewline(ls) then
  631.       self:inclinenumber(ls)
  632.     ----------------------------------------------------------------
  633.     elseif c == "-" then
  634.       c = self:nextc(ls)
  635.       if c ~= "-" then return "-" end
  636.       -- else is a comment
  637.       local sep = -1
  638.       if self:nextc(ls) == '[' then
  639.         sep = self:skip_sep(ls)
  640.         ls.buff = ""  -- 'skip_sep' may dirty the buffer
  641.       end
  642.       if sep >= 0 then
  643.         self:read_long_string(ls, nil, sep)  -- long comment
  644.         ls.buff = ""
  645.       else  -- else short comment
  646.         while not self:currIsNewline(ls) and ls.current ~= "EOZ" do
  647.           self:nextc(ls)
  648.         end
  649.       end
  650.     ----------------------------------------------------------------
  651.     elseif c == "[" then
  652.       local sep = self:skip_sep(ls)
  653.       if sep >= 0 then
  654.         self:read_long_string(ls, Token, sep)
  655.         return "TK_STRING"
  656.       elseif sep == -1 then
  657.         return "["
  658.       else
  659.         self:lexerror(ls, "invalid long string delimiter", "TK_STRING")
  660.       end
  661.     ----------------------------------------------------------------
  662.     elseif c == "=" then
  663.       c = self:nextc(ls)
  664.       if c ~= "=" then return "="
  665.       else self:nextc(ls); return "TK_EQ" end
  666.     ----------------------------------------------------------------
  667.     elseif c == "<" then
  668.       c = self:nextc(ls)
  669.       if c ~= "=" then return "<"
  670.       else self:nextc(ls); return "TK_LE" end
  671.     ----------------------------------------------------------------
  672.     elseif c == ">" then
  673.       c = self:nextc(ls)
  674.       if c ~= "=" then return ">"
  675.       else self:nextc(ls); return "TK_GE" end
  676.     ----------------------------------------------------------------
  677.     elseif c == "~" then
  678.       c = self:nextc(ls)
  679.       if c ~= "=" then return "~"
  680.       else self:nextc(ls); return "TK_NE" end
  681.     ----------------------------------------------------------------
  682.     elseif c == "\"" or c == "'" then
  683.       self:read_string(ls, c, Token)
  684.       return "TK_STRING"
  685.     ----------------------------------------------------------------
  686.     elseif c == "." then
  687.       c = self:save_and_next(ls)
  688.       if self:check_next(ls, ".") then
  689.         if self:check_next(ls, ".") then
  690.           return "TK_DOTS"   -- ...
  691.         else return "TK_CONCAT"   -- ..
  692.         end
  693.       elseif not string.find(c, "%d") then
  694.         return "."
  695.       else
  696.         self:read_numeral(ls, Token)
  697.         return "TK_NUMBER"
  698.       end
  699.     ----------------------------------------------------------------
  700.     elseif c == "EOZ" then
  701.       return "TK_EOS"
  702.     ----------------------------------------------------------------
  703.     else  -- default
  704.       if string.find(c, "%s") then
  705.         -- lua_assert(self:currIsNewline(ls))
  706.         self:nextc(ls)
  707.       elseif string.find(c, "%d") then
  708.         self:read_numeral(ls, Token)
  709.         return "TK_NUMBER"
  710.       elseif string.find(c, "[_%a]") then
  711.         -- identifier or reserved word
  712.         repeat
  713.           c = self:save_and_next(ls)
  714.         until c == "EOZ" or not string.find(c, "[_%w]")
  715.         local ts = ls.buff
  716.         local tok = self.enums[ts]
  717.         if tok then return tok end  -- reserved word?
  718.         Token.seminfo = ts
  719.         return "TK_NAME"
  720.       else
  721.         self:nextc(ls)
  722.         return c  -- single-char tokens (+ - / ...)
  723.       end
  724.     ----------------------------------------------------------------
  725.     end--if c
  726.   end--while
  727. end
  728.  
  729. return luaX
  730. end
  731. luaX=luaX()
  732. local luaP = function ()
  733.     local luaP = {}
  734.  
  735. --[[
  736. ===========================================================================
  737.   We assume that instructions are unsigned numbers.
  738.   All instructions have an opcode in the first 6 bits.
  739.   Instructions can have the following fields:
  740.         'A' : 8 bits
  741.         'B' : 9 bits
  742.         'C' : 9 bits
  743.         'Bx' : 18 bits ('B' and 'C' together)
  744.         'sBx' : signed Bx
  745.  
  746.   A signed argument is represented in excess K; that is, the number
  747.   value is the unsigned value minus K. K is exactly the maximum value
  748.   for that argument (so that -max is represented by 0, and +max is
  749.   represented by 2*max), which is half the maximum for the corresponding
  750.   unsigned argument.
  751. ===========================================================================
  752. --]]
  753.  
  754. luaP.OpMode = { iABC = 0, iABx = 1, iAsBx = 2 }  -- basic instruction format
  755.  
  756. ------------------------------------------------------------------------
  757. -- size and position of opcode arguments.
  758. -- * WARNING size and position is hard-coded elsewhere in this script
  759. ------------------------------------------------------------------------
  760. luaP.SIZE_C  = 9
  761. luaP.SIZE_B  = 9
  762. luaP.SIZE_Bx = luaP.SIZE_C + luaP.SIZE_B
  763. luaP.SIZE_A  = 8
  764.  
  765. luaP.SIZE_OP = 6
  766.  
  767. luaP.POS_OP = 0
  768. luaP.POS_A  = luaP.POS_OP + luaP.SIZE_OP
  769. luaP.POS_C  = luaP.POS_A + luaP.SIZE_A
  770. luaP.POS_B  = luaP.POS_C + luaP.SIZE_C
  771. luaP.POS_Bx = luaP.POS_C
  772.  
  773. ------------------------------------------------------------------------
  774. -- limits for opcode arguments.
  775. -- we use (signed) int to manipulate most arguments,
  776. -- so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
  777. ------------------------------------------------------------------------
  778. -- removed "#if SIZE_Bx < BITS_INT-1" test, assume this script is
  779. -- running on a Lua VM with double or int as LUA_NUMBER
  780.  
  781. luaP.MAXARG_Bx  = math.ldexp(1, luaP.SIZE_Bx) - 1
  782. luaP.MAXARG_sBx = math.floor(luaP.MAXARG_Bx / 2)  -- 'sBx' is signed
  783.  
  784. luaP.MAXARG_A = math.ldexp(1, luaP.SIZE_A) - 1
  785. luaP.MAXARG_B = math.ldexp(1, luaP.SIZE_B) - 1
  786. luaP.MAXARG_C = math.ldexp(1, luaP.SIZE_C) - 1
  787.  
  788. -- creates a mask with 'n' 1 bits at position 'p'
  789. -- MASK1(n,p) deleted, not required
  790. -- creates a mask with 'n' 0 bits at position 'p'
  791. -- MASK0(n,p) deleted, not required
  792.  
  793. --[[--------------------------------------------------------------------
  794.   Visual representation for reference:
  795.  
  796.    31    |    |     |            0      bit position
  797.     +-----+-----+-----+----------+
  798.     |  B  |  C  |  A  |  Opcode  |      iABC format
  799.     +-----+-----+-----+----------+
  800.     -  9  -  9  -  8  -    6     -      field sizes
  801.     +-----+-----+-----+----------+
  802.     |   [s]Bx   |  A  |  Opcode  |      iABx | iAsBx format
  803.     +-----+-----+-----+----------+
  804.  
  805. ----------------------------------------------------------------------]]
  806.  
  807. ------------------------------------------------------------------------
  808. -- the following macros help to manipulate instructions
  809. -- * changed to a table object representation, very clean compared to
  810. --   the [nightmare] alternatives of using a number or a string
  811. -- * Bx is a separate element from B and C, since there is never a need
  812. --   to split Bx in the parser or code generator
  813. ------------------------------------------------------------------------
  814.  
  815. -- these accept or return opcodes in the form of string names
  816. function luaP:GET_OPCODE(i) return self.ROpCode[i.OP] end
  817. function luaP:SET_OPCODE(i, o) i.OP = self.OpCode[o] end
  818.  
  819. function luaP:GETARG_A(i) return i.A end
  820. function luaP:SETARG_A(i, u) i.A = u end
  821.  
  822. function luaP:GETARG_B(i) return i.B end
  823. function luaP:SETARG_B(i, b) i.B = b end
  824.  
  825. function luaP:GETARG_C(i) return i.C end
  826. function luaP:SETARG_C(i, b) i.C = b end
  827.  
  828. function luaP:GETARG_Bx(i) return i.Bx end
  829. function luaP:SETARG_Bx(i, b) i.Bx = b end
  830.  
  831. function luaP:GETARG_sBx(i) return i.Bx - self.MAXARG_sBx end
  832. function luaP:SETARG_sBx(i, b) i.Bx = b + self.MAXARG_sBx end
  833.  
  834. function luaP:CREATE_ABC(o,a,b,c)
  835.   return {OP = self.OpCode[o], A = a, B = b, C = c}
  836. end
  837.  
  838. function luaP:CREATE_ABx(o,a,bc)
  839.   return {OP = self.OpCode[o], A = a, Bx = bc}
  840. end
  841.  
  842. ------------------------------------------------------------------------
  843. -- create an instruction from a number (for OP_SETLIST)
  844. ------------------------------------------------------------------------
  845. function luaP:CREATE_Inst(c)
  846.   local o = c % 64
  847.   c = (c - o) / 64
  848.   local a = c % 256
  849.   c = (c - a) / 256
  850.   return self:CREATE_ABx(o, a, c)
  851. end
  852.  
  853. ------------------------------------------------------------------------
  854. -- returns a 4-char string little-endian encoded form of an instruction
  855. ------------------------------------------------------------------------
  856. function luaP:Instruction(i)
  857.   if i.Bx then
  858.     -- change to OP/A/B/C format
  859.     i.C = i.Bx % 512
  860.     i.B = (i.Bx - i.C) / 512
  861.   end
  862.   local I = i.A * 64 + i.OP
  863.   local c0 = I % 256
  864.   I = i.C * 64 + (I - c0) / 256  -- 6 bits of A left
  865.   local c1 = I % 256
  866.   I = i.B * 128 + (I - c1) / 256  -- 7 bits of C left
  867.   local c2 = I % 256
  868.   local c3 = (I - c2) / 256
  869.   return string.char(c0, c1, c2, c3)
  870. end
  871.  
  872. ------------------------------------------------------------------------
  873. -- decodes a 4-char little-endian string into an instruction struct
  874. ------------------------------------------------------------------------
  875. function luaP:DecodeInst(x)
  876.   local byte = string.byte
  877.   local i = {}
  878.   local I = byte(x, 1)
  879.   local op = I % 64
  880.   i.OP = op
  881.   I = byte(x, 2) * 4 + (I - op) / 64  -- 2 bits of c0 left
  882.   local a = I % 256
  883.   i.A = a
  884.   I = byte(x, 3) * 4 + (I - a) / 256  -- 2 bits of c1 left
  885.   local c = I % 512
  886.   i.C = c
  887.   i.B = byte(x, 4) * 2 + (I - c) / 512 -- 1 bits of c2 left
  888.   local opmode = self.OpMode[tonumber(string.sub(self.opmodes[op + 1], 7, 7))]
  889.   if opmode ~= "iABC" then
  890.     i.Bx = i.B * 512 + i.C
  891.   end
  892.   return i
  893. end
  894.  
  895. ------------------------------------------------------------------------
  896. -- Macros to operate RK indices
  897. -- * these use arithmetic instead of bit ops
  898. ------------------------------------------------------------------------
  899.  
  900. -- this bit 1 means constant (0 means register)
  901. luaP.BITRK = math.ldexp(1, luaP.SIZE_B - 1)
  902.  
  903. -- test whether value is a constant
  904. function luaP:ISK(x) return x >= self.BITRK end
  905.  
  906. -- gets the index of the constant
  907. function luaP:INDEXK(x) return x - self.BITRK end
  908.  
  909. luaP.MAXINDEXRK = luaP.BITRK - 1
  910.  
  911. -- code a constant index as a RK value
  912. function luaP:RKASK(x) return x + self.BITRK end
  913.  
  914. ------------------------------------------------------------------------
  915. -- invalid register that fits in 8 bits
  916. ------------------------------------------------------------------------
  917. luaP.NO_REG = luaP.MAXARG_A
  918.  
  919. ------------------------------------------------------------------------
  920. -- R(x) - register
  921. -- Kst(x) - constant (in constant table)
  922. -- RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
  923. ------------------------------------------------------------------------
  924.  
  925. ------------------------------------------------------------------------
  926. -- grep "ORDER OP" if you change these enums
  927. ------------------------------------------------------------------------
  928.  
  929. --[[--------------------------------------------------------------------
  930. Lua virtual machine opcodes (enum OpCode):
  931. ------------------------------------------------------------------------
  932. name          args    description
  933. ------------------------------------------------------------------------
  934. OP_MOVE       A B     R(A) := R(B)
  935. OP_LOADK      A Bx    R(A) := Kst(Bx)
  936. OP_LOADBOOL   A B C   R(A) := (Bool)B; if (C) pc++
  937. OP_LOADNIL    A B     R(A) := ... := R(B) := nil
  938. OP_GETUPVAL   A B     R(A) := UpValue[B]
  939. OP_GETGLOBAL  A Bx    R(A) := Gbl[Kst(Bx)]
  940. OP_GETTABLE   A B C   R(A) := R(B)[RK(C)]
  941. OP_SETGLOBAL  A Bx    Gbl[Kst(Bx)] := R(A)
  942. OP_SETUPVAL   A B     UpValue[B] := R(A)
  943. OP_SETTABLE   A B C   R(A)[RK(B)] := RK(C)
  944. OP_NEWTABLE   A B C   R(A) := {} (size = B,C)
  945. OP_SELF       A B C   R(A+1) := R(B); R(A) := R(B)[RK(C)]
  946. OP_ADD        A B C   R(A) := RK(B) + RK(C)
  947. OP_SUB        A B C   R(A) := RK(B) - RK(C)
  948. OP_MUL        A B C   R(A) := RK(B) * RK(C)
  949. OP_DIV        A B C   R(A) := RK(B) / RK(C)
  950. OP_MOD        A B C   R(A) := RK(B) % RK(C)
  951. OP_POW        A B C   R(A) := RK(B) ^ RK(C)
  952. OP_UNM        A B     R(A) := -R(B)
  953. OP_NOT        A B     R(A) := not R(B)
  954. OP_LEN        A B     R(A) := length of R(B)
  955. OP_CONCAT     A B C   R(A) := R(B).. ... ..R(C)
  956. OP_JMP        sBx     pc+=sBx
  957. OP_EQ         A B C   if ((RK(B) == RK(C)) ~= A) then pc++
  958. OP_LT         A B C   if ((RK(B) <  RK(C)) ~= A) then pc++
  959. OP_LE         A B C   if ((RK(B) <= RK(C)) ~= A) then pc++
  960. OP_TEST       A C     if not (R(A) <=> C) then pc++
  961. OP_TESTSET    A B C   if (R(B) <=> C) then R(A) := R(B) else pc++
  962. OP_CALL       A B C   R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1))
  963. OP_TAILCALL   A B C   return R(A)(R(A+1), ... ,R(A+B-1))
  964. OP_RETURN     A B     return R(A), ... ,R(A+B-2)  (see note)
  965. OP_FORLOOP    A sBx   R(A)+=R(A+2);
  966.                       if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }
  967. OP_FORPREP    A sBx   R(A)-=R(A+2); pc+=sBx
  968. OP_TFORLOOP   A C     R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
  969.                       if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++
  970. OP_SETLIST    A B C   R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B
  971. OP_CLOSE      A       close all variables in the stack up to (>=) R(A)
  972. OP_CLOSURE    A Bx    R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n))
  973. OP_VARARG     A B     R(A), R(A+1), ..., R(A+B-1) = vararg
  974. ----------------------------------------------------------------------]]
  975.  
  976. luaP.opnames = {}  -- opcode names
  977. luaP.OpCode = {}   -- lookup name -> number
  978. luaP.ROpCode = {}  -- lookup number -> name
  979.  
  980. ------------------------------------------------------------------------
  981. -- ORDER OP
  982. ------------------------------------------------------------------------
  983. local i = 0
  984. for v in string.gmatch([[
  985. MOVE LOADK LOADBOOL LOADNIL GETUPVAL
  986. GETGLOBAL GETTABLE SETGLOBAL SETUPVAL SETTABLE
  987. NEWTABLE SELF ADD SUB MUL
  988. DIV MOD POW UNM NOT
  989. LEN CONCAT JMP EQ LT
  990. LE TEST TESTSET CALL TAILCALL
  991. RETURN FORLOOP FORPREP TFORLOOP SETLIST
  992. CLOSE CLOSURE VARARG
  993. ]], "%S+") do
  994.   local n = "OP_"..v
  995.   luaP.opnames[i] = v
  996.   luaP.OpCode[n] = i
  997.   luaP.ROpCode[i] = n
  998.   i = i + 1
  999. end
  1000. luaP.NUM_OPCODES = i
  1001.  
  1002. --[[
  1003. ===========================================================================
  1004.   Notes:
  1005.   (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
  1006.       and can be 0: OP_CALL then sets 'top' to last_result+1, so
  1007.       next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use 'top'.
  1008.   (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
  1009.       set top (like in OP_CALL with C == 0).
  1010.   (*) In OP_RETURN, if (B == 0) then return up to 'top'
  1011.   (*) In OP_SETLIST, if (B == 0) then B = 'top';
  1012.       if (C == 0) then next 'instruction' is real C
  1013.   (*) For comparisons, A specifies what condition the test should accept
  1014.       (true or false).
  1015.   (*) All 'skips' (pc++) assume that next instruction is a jump
  1016. ===========================================================================
  1017. --]]
  1018.  
  1019. --[[--------------------------------------------------------------------
  1020.   masks for instruction properties. The format is:
  1021.   bits 0-1: op mode
  1022.   bits 2-3: C arg mode
  1023.   bits 4-5: B arg mode
  1024.   bit 6: instruction set register A
  1025.   bit 7: operator is a test
  1026.  
  1027.   for OpArgMask:
  1028.   OpArgN - argument is not used
  1029.   OpArgU - argument is used
  1030.   OpArgR - argument is a register or a jump offset
  1031.   OpArgK - argument is a constant or register/constant
  1032. ----------------------------------------------------------------------]]
  1033.  
  1034. -- was enum OpArgMask
  1035. luaP.OpArgMask = { OpArgN = 0, OpArgU = 1, OpArgR = 2, OpArgK = 3 }
  1036.  
  1037. ------------------------------------------------------------------------
  1038. -- e.g. to compare with symbols, luaP:getOpMode(...) == luaP.OpCode.iABC
  1039. -- * accepts opcode parameter as strings, e.g. "OP_MOVE"
  1040. ------------------------------------------------------------------------
  1041.  
  1042. function luaP:getOpMode(m)
  1043.   return self.opmodes[self.OpCode[m]] % 4
  1044. end
  1045.  
  1046. function luaP:getBMode(m)
  1047.   return math.floor(self.opmodes[self.OpCode[m]] / 16) % 4
  1048. end
  1049.  
  1050. function luaP:getCMode(m)
  1051.   return math.floor(self.opmodes[self.OpCode[m]] / 4) % 4
  1052. end
  1053.  
  1054. function luaP:testAMode(m)
  1055.   return math.floor(self.opmodes[self.OpCode[m]] / 64) % 2
  1056. end
  1057.  
  1058. function luaP:testTMode(m)
  1059.   return math.floor(self.opmodes[self.OpCode[m]] / 128)
  1060. end
  1061.  
  1062. -- luaP_opnames[] is set above, as the luaP.opnames table
  1063.  
  1064. -- number of list items to accumulate before a SETLIST instruction
  1065. luaP.LFIELDS_PER_FLUSH = 50
  1066.  
  1067. ------------------------------------------------------------------------
  1068. -- build instruction properties array
  1069. -- * deliberately coded to look like the C equivalent
  1070. ------------------------------------------------------------------------
  1071. local function opmode(t, a, b, c, m)
  1072.   local luaP = luaP
  1073.   return t * 128 + a * 64 +
  1074.          luaP.OpArgMask[b] * 16 + luaP.OpArgMask[c] * 4 + luaP.OpMode[m]
  1075. end
  1076.  
  1077. -- ORDER OP
  1078. luaP.opmodes = {
  1079. -- T A B C mode opcode
  1080.   opmode(0, 1, "OpArgK", "OpArgN", "iABx"),     -- OP_LOADK
  1081.   opmode(0, 1, "OpArgU", "OpArgU", "iABC"),     -- OP_LOADBOOL
  1082.   opmode(0, 1, "OpArgR", "OpArgN", "iABC"),     -- OP_LOADNIL
  1083.   opmode(0, 1, "OpArgU", "OpArgN", "iABC"),     -- OP_GETUPVAL
  1084.   opmode(0, 1, "OpArgK", "OpArgN", "iABx"),     -- OP_GETGLOBAL
  1085.   opmode(0, 1, "OpArgR", "OpArgK", "iABC"),     -- OP_GETTABLE
  1086.   opmode(0, 0, "OpArgK", "OpArgN", "iABx"),     -- OP_SETGLOBAL
  1087.   opmode(0, 0, "OpArgU", "OpArgN", "iABC"),     -- OP_SETUPVAL
  1088.   opmode(0, 0, "OpArgK", "OpArgK", "iABC"),     -- OP_SETTABLE
  1089.   opmode(0, 1, "OpArgU", "OpArgU", "iABC"),     -- OP_NEWTABLE
  1090.   opmode(0, 1, "OpArgR", "OpArgK", "iABC"),     -- OP_SELF
  1091.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_ADD
  1092.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_SUB
  1093.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_MUL
  1094.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_DIV
  1095.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_MOD
  1096.   opmode(0, 1, "OpArgK", "OpArgK", "iABC"),     -- OP_POW
  1097.   opmode(0, 1, "OpArgR", "OpArgN", "iABC"),     -- OP_UNM
  1098.   opmode(0, 1, "OpArgR", "OpArgN", "iABC"),     -- OP_NOT
  1099.   opmode(0, 1, "OpArgR", "OpArgN", "iABC"),     -- OP_LEN
  1100.   opmode(0, 1, "OpArgR", "OpArgR", "iABC"),     -- OP_CONCAT
  1101.   opmode(0, 0, "OpArgR", "OpArgN", "iAsBx"),    -- OP_JMP
  1102.   opmode(1, 0, "OpArgK", "OpArgK", "iABC"),     -- OP_EQ
  1103.   opmode(1, 0, "OpArgK", "OpArgK", "iABC"),     -- OP_LT
  1104.   opmode(1, 0, "OpArgK", "OpArgK", "iABC"),     -- OP_LE
  1105.   opmode(1, 1, "OpArgR", "OpArgU", "iABC"),     -- OP_TEST
  1106.   opmode(1, 1, "OpArgR", "OpArgU", "iABC"),     -- OP_TESTSET
  1107.   opmode(0, 1, "OpArgU", "OpArgU", "iABC"),     -- OP_CALL
  1108.   opmode(0, 1, "OpArgU", "OpArgU", "iABC"),     -- OP_TAILCALL
  1109.   opmode(0, 0, "OpArgU", "OpArgN", "iABC"),     -- OP_RETURN
  1110.   opmode(0, 1, "OpArgR", "OpArgN", "iAsBx"),    -- OP_FORLOOP
  1111.   opmode(0, 1, "OpArgR", "OpArgN", "iAsBx"),    -- OP_FORPREP
  1112.   opmode(1, 0, "OpArgN", "OpArgU", "iABC"),     -- OP_TFORLOOP
  1113.   opmode(0, 0, "OpArgU", "OpArgU", "iABC"),     -- OP_SETLIST
  1114.   opmode(0, 0, "OpArgN", "OpArgN", "iABC"),     -- OP_CLOSE
  1115.   opmode(0, 1, "OpArgU", "OpArgN", "iABx"),     -- OP_CLOSURE
  1116.   opmode(0, 1, "OpArgU", "OpArgN", "iABC"),     -- OP_VARARG
  1117. }
  1118. -- an awkward way to set a zero-indexed table...
  1119. luaP.opmodes[0] =
  1120.   opmode(0, 1, "OpArgR", "OpArgN", "iABC")      -- OP_MOVE
  1121.  
  1122. return luaP
  1123. end
  1124. luaP=luaP()
  1125. local luaK = function ()
  1126.     -- requires luaP, luaX, luaY
  1127. local luaK = {}
  1128. local luaP = luaP
  1129. local luaX = luaX
  1130.  
  1131. ------------------------------------------------------------------------
  1132. -- constants used by code generator
  1133. ------------------------------------------------------------------------
  1134. -- maximum stack for a Lua function
  1135. luaK.MAXSTACK = 250  -- (from llimits.h)
  1136.  
  1137. --[[--------------------------------------------------------------------
  1138. -- other functions
  1139. ----------------------------------------------------------------------]]
  1140.  
  1141. ------------------------------------------------------------------------
  1142. -- emulation of TValue macros (these are from lobject.h)
  1143. -- * TValue is a table since lcode passes references around
  1144. -- * tt member field removed, using Lua's type() instead
  1145. -- * for setsvalue, sethvalue, parameter L (deleted here) in lobject.h
  1146. --   is used in an assert for testing, see checkliveness(g,obj)
  1147. ------------------------------------------------------------------------
  1148. function luaK:ttisnumber(o)
  1149.   if o then return type(o.value) == "number" else return false end
  1150. end
  1151. function luaK:nvalue(o) return o.value end
  1152. function luaK:setnilvalue(o) o.value = nil end
  1153. function luaK:setsvalue(o, x) o.value = x end
  1154. luaK.setnvalue = luaK.setsvalue
  1155. luaK.sethvalue = luaK.setsvalue
  1156. luaK.setbvalue = luaK.setsvalue
  1157.  
  1158. ------------------------------------------------------------------------
  1159. -- The luai_num* macros define the primitive operations over numbers.
  1160. -- * this is not the entire set of primitive operations from luaconf.h
  1161. -- * used in luaK:constfolding()
  1162. ------------------------------------------------------------------------
  1163. function luaK:numadd(a, b) return a + b end
  1164. function luaK:numsub(a, b) return a - b end
  1165. function luaK:nummul(a, b) return a * b end
  1166. function luaK:numdiv(a, b) return a / b end
  1167. function luaK:nummod(a, b) return a % b end
  1168.   -- ((a) - floor((a)/(b))*(b)) /* actual, for reference */
  1169. function luaK:numpow(a, b) return a ^ b end
  1170. function luaK:numunm(a) return -a end
  1171. function luaK:numisnan(a) return not a == a end
  1172.   -- a NaN cannot equal another NaN
  1173.  
  1174. --[[--------------------------------------------------------------------
  1175. -- code generator functions
  1176. ----------------------------------------------------------------------]]
  1177.  
  1178. ------------------------------------------------------------------------
  1179. -- Marks the end of a patch list. It is an invalid value both as an absolute
  1180. -- address, and as a list link (would link an element to itself).
  1181. ------------------------------------------------------------------------
  1182. luaK.NO_JUMP = -1
  1183.  
  1184. ------------------------------------------------------------------------
  1185. -- grep "ORDER OPR" if you change these enums
  1186. ------------------------------------------------------------------------
  1187. luaK.BinOpr = {
  1188.   OPR_ADD = 0, OPR_SUB = 1, OPR_MUL = 2, OPR_DIV = 3, OPR_MOD = 4, OPR_POW = 5,
  1189.   OPR_CONCAT = 6,
  1190.   OPR_NE = 7, OPR_EQ = 8,
  1191.   OPR_LT = 9, OPR_LE = 10, OPR_GT = 11, OPR_GE = 12,
  1192.   OPR_AND = 13, OPR_OR = 14,
  1193.   OPR_NOBINOPR = 15,
  1194. }
  1195.  
  1196. -- * UnOpr is used by luaK:prefix's op argument, but not directly used
  1197. --   because the function receives the symbols as strings, e.g. "OPR_NOT"
  1198. luaK.UnOpr = {
  1199.   OPR_MINUS = 0, OPR_NOT = 1, OPR_LEN = 2, OPR_NOUNOPR = 3
  1200. }
  1201.  
  1202. ------------------------------------------------------------------------
  1203. -- returns the instruction object for given e (expdesc), was a macro
  1204. ------------------------------------------------------------------------
  1205. function luaK:getcode(fs, e)
  1206.   return fs.f.code[e.info]
  1207. end
  1208.  
  1209. ------------------------------------------------------------------------
  1210. -- codes an instruction with a signed Bx (sBx) field, was a macro
  1211. -- * used in luaK:jump(), (lparser) luaY:forbody()
  1212. ------------------------------------------------------------------------
  1213. function luaK:codeAsBx(fs, o, A, sBx)
  1214.   return self:codeABx(fs, o, A, sBx + luaP.MAXARG_sBx)
  1215. end
  1216.  
  1217. ------------------------------------------------------------------------
  1218. -- set the expdesc e instruction for multiple returns, was a macro
  1219. ------------------------------------------------------------------------
  1220. function luaK:setmultret(fs, e)
  1221.   self:setreturns(fs, e, luaY.LUA_MULTRET)
  1222. end
  1223.  
  1224. ------------------------------------------------------------------------
  1225. -- there is a jump if patch lists are not identical, was a macro
  1226. -- * used in luaK:exp2reg(), luaK:exp2anyreg(), luaK:exp2val()
  1227. ------------------------------------------------------------------------
  1228. function luaK:hasjumps(e)
  1229.   return e.t ~= e.f
  1230. end
  1231.  
  1232. ------------------------------------------------------------------------
  1233. -- true if the expression is a constant number (for constant folding)
  1234. -- * used in constfolding(), infix()
  1235. ------------------------------------------------------------------------
  1236. function luaK:isnumeral(e)
  1237.   return e.k == "VKNUM" and e.t == self.NO_JUMP and e.f == self.NO_JUMP
  1238. end
  1239.  
  1240. ------------------------------------------------------------------------
  1241. -- codes loading of nil, optimization done if consecutive locations
  1242. -- * used in luaK:discharge2reg(), (lparser) luaY:adjust_assign()
  1243. ------------------------------------------------------------------------
  1244. function luaK:_nil(fs, from, n)
  1245.   if fs.pc > fs.lasttarget then  -- no jumps to current position?
  1246.     if fs.pc == 0 then  -- function start?
  1247.       if from >= fs.nactvar then
  1248.         return  -- positions are already clean
  1249.       end
  1250.     else
  1251.       local previous = fs.f.code[fs.pc - 1]
  1252.       if luaP:GET_OPCODE(previous) == "OP_LOADNIL" then
  1253.         local pfrom = luaP:GETARG_A(previous)
  1254.         local pto = luaP:GETARG_B(previous)
  1255.         if pfrom <= from and from <= pto + 1 then  -- can connect both?
  1256.           if from + n - 1 > pto then
  1257.             luaP:SETARG_B(previous, from + n - 1)
  1258.           end
  1259.           return
  1260.         end
  1261.       end
  1262.     end
  1263.   end
  1264.   self:codeABC(fs, "OP_LOADNIL", from, from + n - 1, 0)  -- else no optimization
  1265. end
  1266.  
  1267. ------------------------------------------------------------------------
  1268. --
  1269. -- * used in multiple locations
  1270. ------------------------------------------------------------------------
  1271. function luaK:jump(fs)
  1272.   local jpc = fs.jpc  -- save list of jumps to here
  1273.   fs.jpc = self.NO_JUMP
  1274.   local j = self:codeAsBx(fs, "OP_JMP", 0, self.NO_JUMP)
  1275.   j = self:concat(fs, j, jpc)  -- keep them on hold
  1276.   return j
  1277. end
  1278.  
  1279. ------------------------------------------------------------------------
  1280. -- codes a RETURN instruction
  1281. -- * used in luaY:close_func(), luaY:retstat()
  1282. ------------------------------------------------------------------------
  1283. function luaK:ret(fs, first, nret)
  1284.   self:codeABC(fs, "OP_RETURN", first, nret + 1, 0)
  1285. end
  1286.  
  1287. ------------------------------------------------------------------------
  1288. --
  1289. -- * used in luaK:jumponcond(), luaK:codecomp()
  1290. ------------------------------------------------------------------------
  1291. function luaK:condjump(fs, op, A, B, C)
  1292.   self:codeABC(fs, op, A, B, C)
  1293.   return self:jump(fs)
  1294. end
  1295.  
  1296. ------------------------------------------------------------------------
  1297. --
  1298. -- * used in luaK:patchlistaux(), luaK:concat()
  1299. ------------------------------------------------------------------------
  1300. function luaK:fixjump(fs, pc, dest)
  1301.   local jmp = fs.f.code[pc]
  1302.   local offset = dest - (pc + 1)
  1303.   assert(dest ~= self.NO_JUMP)
  1304.   if math.abs(offset) > luaP.MAXARG_sBx then
  1305.     luaX:syntaxerror(fs.ls, "control structure too long")
  1306.   end
  1307.   luaP:SETARG_sBx(jmp, offset)
  1308. end
  1309.  
  1310. ------------------------------------------------------------------------
  1311. -- returns current 'pc' and marks it as a jump target (to avoid wrong
  1312. -- optimizations with consecutive instructions not in the same basic block).
  1313. -- * used in multiple locations
  1314. -- * fs.lasttarget tested only by luaK:_nil() when optimizing OP_LOADNIL
  1315. ------------------------------------------------------------------------
  1316. function luaK:getlabel(fs)
  1317.   fs.lasttarget = fs.pc
  1318.   return fs.pc
  1319. end
  1320.  
  1321. ------------------------------------------------------------------------
  1322. --
  1323. -- * used in luaK:need_value(), luaK:removevalues(), luaK:patchlistaux(),
  1324. --   luaK:concat()
  1325. ------------------------------------------------------------------------
  1326. function luaK:getjump(fs, pc)
  1327.   local offset = luaP:GETARG_sBx(fs.f.code[pc])
  1328.   if offset == self.NO_JUMP then  -- point to itself represents end of list
  1329.     return self.NO_JUMP  -- end of list
  1330.   else
  1331.     return (pc + 1) + offset  -- turn offset into absolute position
  1332.   end
  1333. end
  1334.  
  1335. ------------------------------------------------------------------------
  1336. --
  1337. -- * used in luaK:need_value(), luaK:patchtestreg(), luaK:invertjump()
  1338. ------------------------------------------------------------------------
  1339. function luaK:getjumpcontrol(fs, pc)
  1340.   local pi = fs.f.code[pc]
  1341.   local ppi = fs.f.code[pc - 1]
  1342.   if pc >= 1 and luaP:testTMode(luaP:GET_OPCODE(ppi)) ~= 0 then
  1343.     return ppi
  1344.   else
  1345.     return pi
  1346.   end
  1347. end
  1348.  
  1349. ------------------------------------------------------------------------
  1350. -- check whether list has any jump that do not produce a value
  1351. -- (or produce an inverted value)
  1352. -- * return value changed to boolean
  1353. -- * used only in luaK:exp2reg()
  1354. ------------------------------------------------------------------------
  1355. function luaK:need_value(fs, list)
  1356.   while list ~= self.NO_JUMP do
  1357.     local i = self:getjumpcontrol(fs, list)
  1358.     if luaP:GET_OPCODE(i) ~= "OP_TESTSET" then return true end
  1359.     list = self:getjump(fs, list)
  1360.   end
  1361.   return false  -- not found
  1362. end
  1363.  
  1364. ------------------------------------------------------------------------
  1365. --
  1366. -- * used in luaK:removevalues(), luaK:patchlistaux()
  1367. ------------------------------------------------------------------------
  1368. function luaK:patchtestreg(fs, node, reg)
  1369.   local i = self:getjumpcontrol(fs, node)
  1370.   if luaP:GET_OPCODE(i) ~= "OP_TESTSET" then
  1371.     return false  -- cannot patch other instructions
  1372.   end
  1373.   if reg ~= luaP.NO_REG and reg ~= luaP:GETARG_B(i) then
  1374.     luaP:SETARG_A(i, reg)
  1375.   else  -- no register to put value or register already has the value
  1376.     -- due to use of a table as i, i cannot be replaced by another table
  1377.     -- so the following is required; there is no change to ARG_C
  1378.     luaP:SET_OPCODE(i, "OP_TEST")
  1379.     local b = luaP:GETARG_B(i)
  1380.     luaP:SETARG_A(i, b)
  1381.     luaP:SETARG_B(i, 0)
  1382.     -- *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); /* C */
  1383.   end
  1384.   return true
  1385. end
  1386.  
  1387. ------------------------------------------------------------------------
  1388. --
  1389. -- * used only in luaK:codenot()
  1390. ------------------------------------------------------------------------
  1391. function luaK:removevalues(fs, list)
  1392.   while list ~= self.NO_JUMP do
  1393.     self:patchtestreg(fs, list, luaP.NO_REG)
  1394.     list = self:getjump(fs, list)
  1395.   end
  1396. end
  1397.  
  1398. ------------------------------------------------------------------------
  1399. --
  1400. -- * used in luaK:dischargejpc(), luaK:patchlist(), luaK:exp2reg()
  1401. ------------------------------------------------------------------------
  1402. function luaK:patchlistaux(fs, list, vtarget, reg, dtarget)
  1403.   while list ~= self.NO_JUMP do
  1404.     local _next = self:getjump(fs, list)
  1405.     if self:patchtestreg(fs, list, reg) then
  1406.       self:fixjump(fs, list, vtarget)
  1407.     else
  1408.       self:fixjump(fs, list, dtarget)  -- jump to default target
  1409.     end
  1410.     list = _next
  1411.   end
  1412. end
  1413.  
  1414. ------------------------------------------------------------------------
  1415. --
  1416. -- * used only in luaK:code()
  1417. ------------------------------------------------------------------------
  1418. function luaK:dischargejpc(fs)
  1419.   self:patchlistaux(fs, fs.jpc, fs.pc, luaP.NO_REG, fs.pc)
  1420.   fs.jpc = self.NO_JUMP
  1421. end
  1422.  
  1423. ------------------------------------------------------------------------
  1424. --
  1425. -- * used in (lparser) luaY:whilestat(), luaY:repeatstat(), luaY:forbody()
  1426. ------------------------------------------------------------------------
  1427. function luaK:patchlist(fs, list, target)
  1428.   if target == fs.pc then
  1429.     self:patchtohere(fs, list)
  1430.   else
  1431.     assert(target < fs.pc)
  1432.     self:patchlistaux(fs, list, target, luaP.NO_REG, target)
  1433.   end
  1434. end
  1435.  
  1436. ------------------------------------------------------------------------
  1437. --
  1438. -- * used in multiple locations
  1439. ------------------------------------------------------------------------
  1440. function luaK:patchtohere(fs, list)
  1441.   self:getlabel(fs)
  1442.   fs.jpc = self:concat(fs, fs.jpc, list)
  1443. end
  1444.  
  1445. ------------------------------------------------------------------------
  1446. -- * l1 was a pointer, now l1 is returned and callee assigns the value
  1447. -- * used in multiple locations
  1448. ------------------------------------------------------------------------
  1449. function luaK:concat(fs, l1, l2)
  1450.   if l2 == self.NO_JUMP then return l1
  1451.   elseif l1 == self.NO_JUMP then
  1452.     return l2
  1453.   else
  1454.     local list = l1
  1455.     local _next = self:getjump(fs, list)
  1456.     while _next ~= self.NO_JUMP do  -- find last element
  1457.       list = _next
  1458.       _next = self:getjump(fs, list)
  1459.     end
  1460.     self:fixjump(fs, list, l2)
  1461.   end
  1462.   return l1
  1463. end
  1464.  
  1465. ------------------------------------------------------------------------
  1466. --
  1467. -- * used in luaK:reserveregs(), (lparser) luaY:forlist()
  1468. ------------------------------------------------------------------------
  1469. function luaK:checkstack(fs, n)
  1470.   local newstack = fs.freereg + n
  1471.   if newstack > fs.f.maxstacksize then
  1472.     if newstack >= self.MAXSTACK then
  1473.       luaX:syntaxerror(fs.ls, "function or expression too complex")
  1474.     end
  1475.     fs.f.maxstacksize = newstack
  1476.   end
  1477. end
  1478.  
  1479. ------------------------------------------------------------------------
  1480. --
  1481. -- * used in multiple locations
  1482. ------------------------------------------------------------------------
  1483. function luaK:reserveregs(fs, n)
  1484.   self:checkstack(fs, n)
  1485.   fs.freereg = fs.freereg + n
  1486. end
  1487.  
  1488. ------------------------------------------------------------------------
  1489. --
  1490. -- * used in luaK:freeexp(), luaK:dischargevars()
  1491. ------------------------------------------------------------------------
  1492. function luaK:freereg(fs, reg)
  1493.   if not luaP:ISK(reg) and reg >= fs.nactvar then
  1494.     fs.freereg = fs.freereg - 1
  1495.     assert(reg == fs.freereg)
  1496.   end
  1497. end
  1498.  
  1499. ------------------------------------------------------------------------
  1500. --
  1501. -- * used in multiple locations
  1502. ------------------------------------------------------------------------
  1503. function luaK:freeexp(fs, e)
  1504.   if e.k == "VNONRELOC" then
  1505.     self:freereg(fs, e.info)
  1506.   end
  1507. end
  1508.  
  1509. ------------------------------------------------------------------------
  1510. -- * TODO NOTE implementation is not 100% correct, since the assert fails
  1511. -- * luaH_set, setobj deleted; direct table access used instead
  1512. -- * used in luaK:stringK(), luaK:numberK(), luaK:boolK(), luaK:nilK()
  1513. ------------------------------------------------------------------------
  1514. function luaK:addk(fs, k, v)
  1515.   local L = fs.L
  1516.   local idx = fs.h[k.value]
  1517.   --TValue *idx = luaH_set(L, fs->h, k); /* C */
  1518.   local f = fs.f
  1519.   if self:ttisnumber(idx) then
  1520.     --TODO this assert currently FAILS (last tested for 5.0.2)
  1521.     --assert(fs.f.k[self:nvalue(idx)] == v)
  1522.     --assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v)); /* C */
  1523.     return self:nvalue(idx)
  1524.   else -- constant not found; create a new entry
  1525.     idx = {}
  1526.     self:setnvalue(idx, fs.nk)
  1527.     fs.h[k.value] = idx
  1528.     -- setnvalue(idx, cast_num(fs->nk)); /* C */
  1529.     luaY:growvector(L, f.k, fs.nk, f.sizek, nil,
  1530.                     luaP.MAXARG_Bx, "constant table overflow")
  1531.     -- loop to initialize empty f.k positions not required
  1532.     f.k[fs.nk] = v
  1533.     -- setobj(L, &f->k[fs->nk], v); /* C */
  1534.     -- luaC_barrier(L, f, v); /* GC */
  1535.     local nk = fs.nk
  1536.     fs.nk = fs.nk + 1
  1537.     return nk
  1538.   end
  1539.  
  1540. end
  1541.  
  1542. ------------------------------------------------------------------------
  1543. -- creates and sets a string object
  1544. -- * used in (lparser) luaY:codestring(), luaY:singlevar()
  1545. ------------------------------------------------------------------------
  1546. function luaK:stringK(fs, s)
  1547.   local o = {}  -- TValue
  1548.   self:setsvalue(o, s)
  1549.   return self:addk(fs, o, o)
  1550. end
  1551.  
  1552. ------------------------------------------------------------------------
  1553. -- creates and sets a number object
  1554. -- * used in luaK:prefix() for negative (or negation of) numbers
  1555. -- * used in (lparser) luaY:simpleexp(), luaY:fornum()
  1556. ------------------------------------------------------------------------
  1557. function luaK:numberK(fs, r)
  1558.   local o = {}  -- TValue
  1559.   self:setnvalue(o, r)
  1560.   return self:addk(fs, o, o)
  1561. end
  1562.  
  1563. ------------------------------------------------------------------------
  1564. -- creates and sets a boolean object
  1565. -- * used only in luaK:exp2RK()
  1566. ------------------------------------------------------------------------
  1567. function luaK:boolK(fs, b)
  1568.   local o = {}  -- TValue
  1569.   self:setbvalue(o, b)
  1570.   return self:addk(fs, o, o)
  1571. end
  1572.  
  1573. ------------------------------------------------------------------------
  1574. -- creates and sets a nil object
  1575. -- * used only in luaK:exp2RK()
  1576. ------------------------------------------------------------------------
  1577. function luaK:nilK(fs)
  1578.   local k, v = {}, {}  -- TValue
  1579.   self:setnilvalue(v)
  1580.   -- cannot use nil as key; instead use table itself to represent nil
  1581.   self:sethvalue(k, fs.h)
  1582.   return self:addk(fs, k, v)
  1583. end
  1584.  
  1585. ------------------------------------------------------------------------
  1586. --
  1587. -- * used in luaK:setmultret(), (lparser) luaY:adjust_assign()
  1588. ------------------------------------------------------------------------
  1589. function luaK:setreturns(fs, e, nresults)
  1590.   if e.k == "VCALL" then  -- expression is an open function call?
  1591.     luaP:SETARG_C(self:getcode(fs, e), nresults + 1)
  1592.   elseif e.k == "VVARARG" then
  1593.     luaP:SETARG_B(self:getcode(fs, e), nresults + 1);
  1594.     luaP:SETARG_A(self:getcode(fs, e), fs.freereg);
  1595.     luaK:reserveregs(fs, 1)
  1596.   end
  1597. end
  1598.  
  1599. ------------------------------------------------------------------------
  1600. --
  1601. -- * used in luaK:dischargevars(), (lparser) luaY:assignment()
  1602. ------------------------------------------------------------------------
  1603. function luaK:setoneret(fs, e)
  1604.   if e.k == "VCALL" then  -- expression is an open function call?
  1605.     e.k = "VNONRELOC"
  1606.     e.info = luaP:GETARG_A(self:getcode(fs, e))
  1607.   elseif e.k == "VVARARG" then
  1608.     luaP:SETARG_B(self:getcode(fs, e), 2)
  1609.     e.k = "VRELOCABLE"  -- can relocate its simple result
  1610.   end
  1611. end
  1612.  
  1613. ------------------------------------------------------------------------
  1614. --
  1615. -- * used in multiple locations
  1616. ------------------------------------------------------------------------
  1617. function luaK:dischargevars(fs, e)
  1618.   local k = e.k
  1619.   if k == "VLOCAL" then
  1620.     e.k = "VNONRELOC"
  1621.   elseif k == "VUPVAL" then
  1622.     e.info = self:codeABC(fs, "OP_GETUPVAL", 0, e.info, 0)
  1623.     e.k = "VRELOCABLE"
  1624.   elseif k == "VGLOBAL" then
  1625.     e.info = self:codeABx(fs, "OP_GETGLOBAL", 0, e.info)
  1626.     e.k = "VRELOCABLE"
  1627.   elseif k == "VINDEXED" then
  1628.     self:freereg(fs, e.aux)
  1629.     self:freereg(fs, e.info)
  1630.     e.info = self:codeABC(fs, "OP_GETTABLE", 0, e.info, e.aux)
  1631.     e.k = "VRELOCABLE"
  1632.   elseif k == "VVARARG" or k == "VCALL" then
  1633.     self:setoneret(fs, e)
  1634.   else
  1635.     -- there is one value available (somewhere)
  1636.   end
  1637. end
  1638.  
  1639. ------------------------------------------------------------------------
  1640. --
  1641. -- * used only in luaK:exp2reg()
  1642. ------------------------------------------------------------------------
  1643. function luaK:code_label(fs, A, b, jump)
  1644.   self:getlabel(fs)  -- those instructions may be jump targets
  1645.   return self:codeABC(fs, "OP_LOADBOOL", A, b, jump)
  1646. end
  1647.  
  1648. ------------------------------------------------------------------------
  1649. --
  1650. -- * used in luaK:discharge2anyreg(), luaK:exp2reg()
  1651. ------------------------------------------------------------------------
  1652. function luaK:discharge2reg(fs, e, reg)
  1653.   self:dischargevars(fs, e)
  1654.   local k = e.k
  1655.   if k == "VNIL" then
  1656.     self:_nil(fs, reg, 1)
  1657.   elseif k == "VFALSE" or k == "VTRUE" then
  1658.     self:codeABC(fs, "OP_LOADBOOL", reg, (e.k == "VTRUE") and 1 or 0, 0)
  1659.   elseif k == "VK" then
  1660.     self:codeABx(fs, "OP_LOADK", reg, e.info)
  1661.   elseif k == "VKNUM" then
  1662.     self:codeABx(fs, "OP_LOADK", reg, self:numberK(fs, e.nval))
  1663.   elseif k == "VRELOCABLE" then
  1664.     local pc = self:getcode(fs, e)
  1665.     luaP:SETARG_A(pc, reg)
  1666.   elseif k == "VNONRELOC" then
  1667.     if reg ~= e.info then
  1668.       self:codeABC(fs, "OP_MOVE", reg, e.info, 0)
  1669.     end
  1670.   else
  1671.     assert(e.k == "VVOID" or e.k == "VJMP")
  1672.     return  -- nothing to do...
  1673.   end
  1674.   e.info = reg
  1675.   e.k = "VNONRELOC"
  1676. end
  1677.  
  1678. ------------------------------------------------------------------------
  1679. --
  1680. -- * used in luaK:jumponcond(), luaK:codenot()
  1681. ------------------------------------------------------------------------
  1682. function luaK:discharge2anyreg(fs, e)
  1683.   if e.k ~= "VNONRELOC" then
  1684.     self:reserveregs(fs, 1)
  1685.     self:discharge2reg(fs, e, fs.freereg - 1)
  1686.   end
  1687. end
  1688.  
  1689. ------------------------------------------------------------------------
  1690. --
  1691. -- * used in luaK:exp2nextreg(), luaK:exp2anyreg(), luaK:storevar()
  1692. ------------------------------------------------------------------------
  1693. function luaK:exp2reg(fs, e, reg)
  1694.   self:discharge2reg(fs, e, reg)
  1695.   if e.k == "VJMP" then
  1696.     e.t = self:concat(fs, e.t, e.info)  -- put this jump in 't' list
  1697.   end
  1698.   if self:hasjumps(e) then
  1699.     local final  -- position after whole expression
  1700.     local p_f = self.NO_JUMP  -- position of an eventual LOAD false
  1701.     local p_t = self.NO_JUMP  -- position of an eventual LOAD true
  1702.     if self:need_value(fs, e.t) or self:need_value(fs, e.f) then
  1703.       local fj = (e.k == "VJMP") and self.NO_JUMP or self:jump(fs)
  1704.       p_f = self:code_label(fs, reg, 0, 1)
  1705.       p_t = self:code_label(fs, reg, 1, 0)
  1706.       self:patchtohere(fs, fj)
  1707.     end
  1708.     final = self:getlabel(fs)
  1709.     self:patchlistaux(fs, e.f, final, reg, p_f)
  1710.     self:patchlistaux(fs, e.t, final, reg, p_t)
  1711.   end
  1712.   e.f, e.t = self.NO_JUMP, self.NO_JUMP
  1713.   e.info = reg
  1714.   e.k = "VNONRELOC"
  1715. end
  1716.  
  1717. ------------------------------------------------------------------------
  1718. --
  1719. -- * used in multiple locations
  1720. ------------------------------------------------------------------------
  1721. function luaK:exp2nextreg(fs, e)
  1722.   self:dischargevars(fs, e)
  1723.   self:freeexp(fs, e)
  1724.   self:reserveregs(fs, 1)
  1725.   self:exp2reg(fs, e, fs.freereg - 1)
  1726. end
  1727.  
  1728. ------------------------------------------------------------------------
  1729. --
  1730. -- * used in multiple locations
  1731. ------------------------------------------------------------------------
  1732. function luaK:exp2anyreg(fs, e)
  1733.   self:dischargevars(fs, e)
  1734.   if e.k == "VNONRELOC" then
  1735.     if not self:hasjumps(e) then  -- exp is already in a register
  1736.       return e.info
  1737.     end
  1738.     if e.info >= fs.nactvar then  -- reg. is not a local?
  1739.       self:exp2reg(fs, e, e.info)  -- put value on it
  1740.       return e.info
  1741.     end
  1742.   end
  1743.   self:exp2nextreg(fs, e)  -- default
  1744.   return e.info
  1745. end
  1746.  
  1747. ------------------------------------------------------------------------
  1748. --
  1749. -- * used in luaK:exp2RK(), luaK:prefix(), luaK:posfix()
  1750. -- * used in (lparser) luaY:yindex()
  1751. ------------------------------------------------------------------------
  1752. function luaK:exp2val(fs, e)
  1753.   if self:hasjumps(e) then
  1754.     self:exp2anyreg(fs, e)
  1755.   else
  1756.     self:dischargevars(fs, e)
  1757.   end
  1758. end
  1759.  
  1760. ------------------------------------------------------------------------
  1761. --
  1762. -- * used in multiple locations
  1763. ------------------------------------------------------------------------
  1764. function luaK:exp2RK(fs, e)
  1765.   self:exp2val(fs, e)
  1766.   local k = e.k
  1767.   if k == "VKNUM" or k == "VTRUE" or k == "VFALSE" or k == "VNIL" then
  1768.     if fs.nk <= luaP.MAXINDEXRK then  -- constant fit in RK operand?
  1769.       -- converted from a 2-deep ternary operator expression
  1770.       if e.k == "VNIL" then
  1771.         e.info = self:nilK(fs)
  1772.       else
  1773.         e.info = (e.k == "VKNUM") and self:numberK(fs, e.nval)
  1774.                                   or self:boolK(fs, e.k == "VTRUE")
  1775.       end
  1776.       e.k = "VK"
  1777.       return luaP:RKASK(e.info)
  1778.     end
  1779.   elseif k == "VK" then
  1780.     if e.info <= luaP.MAXINDEXRK then  -- constant fit in argC?
  1781.       return luaP:RKASK(e.info)
  1782.     end
  1783.   else
  1784.     -- default
  1785.   end
  1786.   -- not a constant in the right range: put it in a register
  1787.   return self:exp2anyreg(fs, e)
  1788. end
  1789.  
  1790. ------------------------------------------------------------------------
  1791. --
  1792. -- * used in (lparser) luaY:assignment(), luaY:localfunc(), luaY:funcstat()
  1793. ------------------------------------------------------------------------
  1794. function luaK:storevar(fs, var, ex)
  1795.   local k = var.k
  1796.   if k == "VLOCAL" then
  1797.     self:freeexp(fs, ex)
  1798.     self:exp2reg(fs, ex, var.info)
  1799.     return
  1800.   elseif k == "VUPVAL" then
  1801.     local e = self:exp2anyreg(fs, ex)
  1802.     self:codeABC(fs, "OP_SETUPVAL", e, var.info, 0)
  1803.   elseif k == "VGLOBAL" then
  1804.     local e = self:exp2anyreg(fs, ex)
  1805.     self:codeABx(fs, "OP_SETGLOBAL", e, var.info)
  1806.   elseif k == "VINDEXED" then
  1807.     local e = self:exp2RK(fs, ex)
  1808.     self:codeABC(fs, "OP_SETTABLE", var.info, var.aux, e)
  1809.   else
  1810.     assert(0)  -- invalid var kind to store
  1811.   end
  1812.   self:freeexp(fs, ex)
  1813. end
  1814.  
  1815. ------------------------------------------------------------------------
  1816. --
  1817. -- * used only in (lparser) luaY:primaryexp()
  1818. ------------------------------------------------------------------------
  1819. function luaK:_self(fs, e, key)
  1820.   self:exp2anyreg(fs, e)
  1821.   self:freeexp(fs, e)
  1822.   local func = fs.freereg
  1823.   self:reserveregs(fs, 2)
  1824.   self:codeABC(fs, "OP_SELF", func, e.info, self:exp2RK(fs, key))
  1825.   self:freeexp(fs, key)
  1826.   e.info = func
  1827.   e.k = "VNONRELOC"
  1828. end
  1829.  
  1830. ------------------------------------------------------------------------
  1831. --
  1832. -- * used in luaK:goiftrue(), luaK:codenot()
  1833. ------------------------------------------------------------------------
  1834. function luaK:invertjump(fs, e)
  1835.   local pc = self:getjumpcontrol(fs, e.info)
  1836.   assert(luaP:testTMode(luaP:GET_OPCODE(pc)) ~= 0 and
  1837.              luaP:GET_OPCODE(pc) ~= "OP_TESTSET" and
  1838.              luaP:GET_OPCODE(pc) ~= "OP_TEST")
  1839.   luaP:SETARG_A(pc, (luaP:GETARG_A(pc) == 0) and 1 or 0)
  1840. end
  1841.  
  1842. ------------------------------------------------------------------------
  1843. --
  1844. -- * used in luaK:goiftrue(), luaK:goiffalse()
  1845. ------------------------------------------------------------------------
  1846. function luaK:jumponcond(fs, e, cond)
  1847.   if e.k == "VRELOCABLE" then
  1848.     local ie = self:getcode(fs, e)
  1849.     if luaP:GET_OPCODE(ie) == "OP_NOT" then
  1850.       fs.pc = fs.pc - 1  -- remove previous OP_NOT
  1851.       return self:condjump(fs, "OP_TEST", luaP:GETARG_B(ie), 0, cond and 0 or 1)
  1852.     end
  1853.     -- else go through
  1854.   end
  1855.   self:discharge2anyreg(fs, e)
  1856.   self:freeexp(fs, e)
  1857.   return self:condjump(fs, "OP_TESTSET", luaP.NO_REG, e.info, cond and 1 or 0)
  1858. end
  1859.  
  1860. ------------------------------------------------------------------------
  1861. --
  1862. -- * used in luaK:infix(), (lparser) luaY:cond()
  1863. ------------------------------------------------------------------------
  1864. function luaK:goiftrue(fs, e)
  1865.   local pc  -- pc of last jump
  1866.   self:dischargevars(fs, e)
  1867.   local k = e.k
  1868.   if k == "VK" or k == "VKNUM" or k == "VTRUE" then
  1869.     pc = self.NO_JUMP  -- always true; do nothing
  1870.   elseif k == "VFALSE" then
  1871.     pc = self:jump(fs)  -- always jump
  1872.   elseif k == "VJMP" then
  1873.     self:invertjump(fs, e)
  1874.     pc = e.info
  1875.   else
  1876.     pc = self:jumponcond(fs, e, false)
  1877.   end
  1878.   e.f = self:concat(fs, e.f, pc)  -- insert last jump in `f' list
  1879.   self:patchtohere(fs, e.t)
  1880.   e.t = self.NO_JUMP
  1881. end
  1882.  
  1883. ------------------------------------------------------------------------
  1884. --
  1885. -- * used in luaK:infix()
  1886. ------------------------------------------------------------------------
  1887. function luaK:goiffalse(fs, e)
  1888.   local pc  -- pc of last jump
  1889.   self:dischargevars(fs, e)
  1890.   local k = e.k
  1891.   if k == "VNIL" or k == "VFALSE"then
  1892.     pc = self.NO_JUMP  -- always false; do nothing
  1893.   elseif k == "VTRUE" then
  1894.     pc = self:jump(fs)  -- always jump
  1895.   elseif k == "VJMP" then
  1896.     pc = e.info
  1897.   else
  1898.     pc = self:jumponcond(fs, e, true)
  1899.   end
  1900.   e.t = self:concat(fs, e.t, pc)  -- insert last jump in `t' list
  1901.   self:patchtohere(fs, e.f)
  1902.   e.f = self.NO_JUMP
  1903. end
  1904.  
  1905. ------------------------------------------------------------------------
  1906. --
  1907. -- * used only in luaK:prefix()
  1908. ------------------------------------------------------------------------
  1909. function luaK:codenot(fs, e)
  1910.   self:dischargevars(fs, e)
  1911.   local k = e.k
  1912.   if k == "VNIL" or k == "VFALSE" then
  1913.     e.k = "VTRUE"
  1914.   elseif k == "VK" or k == "VKNUM" or k == "VTRUE" then
  1915.     e.k = "VFALSE"
  1916.   elseif k == "VJMP" then
  1917.     self:invertjump(fs, e)
  1918.   elseif k == "VRELOCABLE" or k == "VNONRELOC" then
  1919.     self:discharge2anyreg(fs, e)
  1920.     self:freeexp(fs, e)
  1921.     e.info = self:codeABC(fs, "OP_NOT", 0, e.info, 0)
  1922.     e.k = "VRELOCABLE"
  1923.   else
  1924.     assert(0)  -- cannot happen
  1925.   end
  1926.   -- interchange true and false lists
  1927.   e.f, e.t = e.t, e.f
  1928.   self:removevalues(fs, e.f)
  1929.   self:removevalues(fs, e.t)
  1930. end
  1931.  
  1932. ------------------------------------------------------------------------
  1933. --
  1934. -- * used in (lparser) luaY:field(), luaY:primaryexp()
  1935. ------------------------------------------------------------------------
  1936. function luaK:indexed(fs, t, k)
  1937.   t.aux = self:exp2RK(fs, k)
  1938.   t.k = "VINDEXED"
  1939. end
  1940.  
  1941. ------------------------------------------------------------------------
  1942. --
  1943. -- * used only in luaK:codearith()
  1944. ------------------------------------------------------------------------
  1945. function luaK:constfolding(op, e1, e2)
  1946.   local r
  1947.   if not self:isnumeral(e1) or not self:isnumeral(e2) then return false end
  1948.   local v1 = e1.nval
  1949.   local v2 = e2.nval
  1950.   if op == "OP_ADD" then
  1951.     r = self:numadd(v1, v2)
  1952.   elseif op == "OP_SUB" then
  1953.     r = self:numsub(v1, v2)
  1954.   elseif op == "OP_MUL" then
  1955.     r = self:nummul(v1, v2)
  1956.   elseif op == "OP_DIV" then
  1957.     if v2 == 0 then return false end  -- do not attempt to divide by 0
  1958.     r = self:numdiv(v1, v2)
  1959.   elseif op == "OP_MOD" then
  1960.     if v2 == 0 then return false end  -- do not attempt to divide by 0
  1961.     r = self:nummod(v1, v2)
  1962.   elseif op == "OP_POW" then
  1963.     r = self:numpow(v1, v2)
  1964.   elseif op == "OP_UNM" then
  1965.     r = self:numunm(v1)
  1966.   elseif op == "OP_LEN" then
  1967.     return false  -- no constant folding for 'len'
  1968.   else
  1969.     assert(0)
  1970.     r = 0
  1971.   end
  1972.   if self:numisnan(r) then return false end  -- do not attempt to produce NaN
  1973.   e1.nval = r
  1974.   return true
  1975. end
  1976.  
  1977. ------------------------------------------------------------------------
  1978. --
  1979. -- * used in luaK:prefix(), luaK:posfix()
  1980. ------------------------------------------------------------------------
  1981. function luaK:codearith(fs, op, e1, e2)
  1982.   if self:constfolding(op, e1, e2) then
  1983.     return
  1984.   else
  1985.     local o2 = (op ~= "OP_UNM" and op ~= "OP_LEN") and self:exp2RK(fs, e2) or 0
  1986.     local o1 = self:exp2RK(fs, e1)
  1987.     if o1 > o2 then
  1988.       self:freeexp(fs, e1)
  1989.       self:freeexp(fs, e2)
  1990.     else
  1991.       self:freeexp(fs, e2)
  1992.       self:freeexp(fs, e1)
  1993.     end
  1994.     e1.info = self:codeABC(fs, op, 0, o1, o2)
  1995.     e1.k = "VRELOCABLE"
  1996.   end
  1997. end
  1998.  
  1999. ------------------------------------------------------------------------
  2000. --
  2001. -- * used only in luaK:posfix()
  2002. ------------------------------------------------------------------------
  2003. function luaK:codecomp(fs, op, cond, e1, e2)
  2004.   local o1 = self:exp2RK(fs, e1)
  2005.   local o2 = self:exp2RK(fs, e2)
  2006.   self:freeexp(fs, e2)
  2007.   self:freeexp(fs, e1)
  2008.   if cond == 0 and op ~= "OP_EQ" then
  2009.     -- exchange args to replace by `<' or `<='
  2010.     o1, o2 = o2, o1  -- o1 <==> o2
  2011.     cond = 1
  2012.   end
  2013.   e1.info = self:condjump(fs, op, cond, o1, o2)
  2014.   e1.k = "VJMP"
  2015. end
  2016.  
  2017. ------------------------------------------------------------------------
  2018. --
  2019. -- * used only in (lparser) luaY:subexpr()
  2020. ------------------------------------------------------------------------
  2021. function luaK:prefix(fs, op, e)
  2022.   local e2 = {}  -- expdesc
  2023.   e2.t, e2.f = self.NO_JUMP, self.NO_JUMP
  2024.   e2.k = "VKNUM"
  2025.   e2.nval = 0
  2026.   if op == "OPR_MINUS" then
  2027.     if not self:isnumeral(e) then
  2028.       self:exp2anyreg(fs, e)  -- cannot operate on non-numeric constants
  2029.     end
  2030.     self:codearith(fs, "OP_UNM", e, e2)
  2031.   elseif op == "OPR_NOT" then
  2032.     self:codenot(fs, e)
  2033.   elseif op == "OPR_LEN" then
  2034.     self:exp2anyreg(fs, e)  -- cannot operate on constants
  2035.     self:codearith(fs, "OP_LEN", e, e2)
  2036.   else
  2037.     assert(0)
  2038.   end
  2039. end
  2040.  
  2041. ------------------------------------------------------------------------
  2042. --
  2043. -- * used only in (lparser) luaY:subexpr()
  2044. ------------------------------------------------------------------------
  2045. function luaK:infix(fs, op, v)
  2046.   if op == "OPR_AND" then
  2047.     self:goiftrue(fs, v)
  2048.   elseif op == "OPR_OR" then
  2049.     self:goiffalse(fs, v)
  2050.   elseif op == "OPR_CONCAT" then
  2051.     self:exp2nextreg(fs, v)  -- operand must be on the 'stack'
  2052.   elseif op == "OPR_ADD" or op == "OPR_SUB" or
  2053.          op == "OPR_MUL" or op == "OPR_DIV" or
  2054.          op == "OPR_MOD" or op == "OPR_POW" then
  2055.     if not self:isnumeral(v) then self:exp2RK(fs, v) end
  2056.   else
  2057.     self:exp2RK(fs, v)
  2058.   end
  2059. end
  2060.  
  2061. ------------------------------------------------------------------------
  2062. --
  2063. -- * used only in (lparser) luaY:subexpr()
  2064. ------------------------------------------------------------------------
  2065. -- table lookups to simplify testing
  2066. luaK.arith_op = {
  2067.   OPR_ADD = "OP_ADD", OPR_SUB = "OP_SUB", OPR_MUL = "OP_MUL",
  2068.   OPR_DIV = "OP_DIV", OPR_MOD = "OP_MOD", OPR_POW = "OP_POW",
  2069. }
  2070. luaK.comp_op = {
  2071.   OPR_EQ = "OP_EQ", OPR_NE = "OP_EQ", OPR_LT = "OP_LT",
  2072.   OPR_LE = "OP_LE", OPR_GT = "OP_LT", OPR_GE = "OP_LE",
  2073. }
  2074. luaK.comp_cond = {
  2075.   OPR_EQ = 1, OPR_NE = 0, OPR_LT = 1,
  2076.   OPR_LE = 1, OPR_GT = 0, OPR_GE = 0,
  2077. }
  2078. function luaK:posfix(fs, op, e1, e2)
  2079.   -- needed because e1 = e2 doesn't copy values...
  2080.   -- * in 5.0.x, only k/info/aux/t/f copied, t for AND, f for OR
  2081.   --   but here, all elements are copied for completeness' sake
  2082.   local function copyexp(e1, e2)
  2083.     e1.k = e2.k
  2084.     e1.info = e2.info; e1.aux = e2.aux
  2085.     e1.nval = e2.nval
  2086.     e1.t = e2.t; e1.f = e2.f
  2087.   end
  2088.   if op == "OPR_AND" then
  2089.     assert(e1.t == self.NO_JUMP)  -- list must be closed
  2090.     self:dischargevars(fs, e2)
  2091.     e2.f = self:concat(fs, e2.f, e1.f)
  2092.     copyexp(e1, e2)
  2093.   elseif op == "OPR_OR" then
  2094.     assert(e1.f == self.NO_JUMP)  -- list must be closed
  2095.     self:dischargevars(fs, e2)
  2096.     e2.t = self:concat(fs, e2.t, e1.t)
  2097.     copyexp(e1, e2)
  2098.   elseif op == "OPR_CONCAT" then
  2099.     self:exp2val(fs, e2)
  2100.     if e2.k == "VRELOCABLE" and luaP:GET_OPCODE(self:getcode(fs, e2)) == "OP_CONCAT" then
  2101.       assert(e1.info == luaP:GETARG_B(self:getcode(fs, e2)) - 1)
  2102.       self:freeexp(fs, e1)
  2103.       luaP:SETARG_B(self:getcode(fs, e2), e1.info)
  2104.       e1.k = "VRELOCABLE"
  2105.       e1.info = e2.info
  2106.     else
  2107.       self:exp2nextreg(fs, e2)  -- operand must be on the 'stack'
  2108.       self:codearith(fs, "OP_CONCAT", e1, e2)
  2109.     end
  2110.   else
  2111.     -- the following uses a table lookup in place of conditionals
  2112.     local arith = self.arith_op[op]
  2113.     if arith then
  2114.       self:codearith(fs, arith, e1, e2)
  2115.     else
  2116.       local comp = self.comp_op[op]
  2117.       if comp then
  2118.         self:codecomp(fs, comp, self.comp_cond[op], e1, e2)
  2119.       else
  2120.         assert(0)
  2121.       end
  2122.     end--if arith
  2123.   end--if op
  2124. end
  2125.  
  2126. ------------------------------------------------------------------------
  2127. -- adjusts debug information for last instruction written, in order to
  2128. -- change the line where item comes into existence
  2129. -- * used in (lparser) luaY:funcargs(), luaY:forbody(), luaY:funcstat()
  2130. ------------------------------------------------------------------------
  2131. function luaK:fixline(fs, line)
  2132.   fs.f.lineinfo[fs.pc - 1] = line
  2133. end
  2134.  
  2135. ------------------------------------------------------------------------
  2136. -- general function to write an instruction into the instruction buffer,
  2137. -- sets debug information too
  2138. -- * used in luaK:codeABC(), luaK:codeABx()
  2139. -- * called directly by (lparser) luaY:whilestat()
  2140. ------------------------------------------------------------------------
  2141. function luaK:code(fs, i, line)
  2142.   local f = fs.f
  2143.   self:dischargejpc(fs)  -- 'pc' will change
  2144.   -- put new instruction in code array
  2145.   luaY:growvector(fs.L, f.code, fs.pc, f.sizecode, nil,
  2146.                   luaY.MAX_INT, "code size overflow")
  2147.   f.code[fs.pc] = i
  2148.   -- save corresponding line information
  2149.   luaY:growvector(fs.L, f.lineinfo, fs.pc, f.sizelineinfo, nil,
  2150.                   luaY.MAX_INT, "code size overflow")
  2151.   f.lineinfo[fs.pc] = line
  2152.   local pc = fs.pc
  2153.   fs.pc = fs.pc + 1
  2154.   return pc
  2155. end
  2156.  
  2157. ------------------------------------------------------------------------
  2158. -- writes an instruction of type ABC
  2159. -- * calls luaK:code()
  2160. ------------------------------------------------------------------------
  2161. function luaK:codeABC(fs, o, a, b, c)
  2162.   assert(luaP:getOpMode(o) == luaP.OpMode.iABC)
  2163.   assert(luaP:getBMode(o) ~= luaP.OpArgMask.OpArgN or b == 0)
  2164.   assert(luaP:getCMode(o) ~= luaP.OpArgMask.OpArgN or c == 0)
  2165.   return self:code(fs, luaP:CREATE_ABC(o, a, b, c), fs.ls.lastline)
  2166. end
  2167.  
  2168. ------------------------------------------------------------------------
  2169. -- writes an instruction of type ABx
  2170. -- * calls luaK:code(), called by luaK:codeAsBx()
  2171. ------------------------------------------------------------------------
  2172. function luaK:codeABx(fs, o, a, bc)
  2173.   assert(luaP:getOpMode(o) == luaP.OpMode.iABx or
  2174.              luaP:getOpMode(o) == luaP.OpMode.iAsBx)
  2175.   assert(luaP:getCMode(o) == luaP.OpArgMask.OpArgN)
  2176.   return self:code(fs, luaP:CREATE_ABx(o, a, bc), fs.ls.lastline)
  2177. end
  2178.  
  2179. ------------------------------------------------------------------------
  2180. --
  2181. -- * used in (lparser) luaY:closelistfield(), luaY:lastlistfield()
  2182. ------------------------------------------------------------------------
  2183. function luaK:setlist(fs, base, nelems, tostore)
  2184.   local c = math.floor((nelems - 1)/luaP.LFIELDS_PER_FLUSH) + 1
  2185.   local b = (tostore == luaY.LUA_MULTRET) and 0 or tostore
  2186.   assert(tostore ~= 0)
  2187.   if c <= luaP.MAXARG_C then
  2188.     self:codeABC(fs, "OP_SETLIST", base, b, c)
  2189.   else
  2190.     self:codeABC(fs, "OP_SETLIST", base, b, 0)
  2191.     self:code(fs, luaP:CREATE_Inst(c), fs.ls.lastline)
  2192.   end
  2193.   fs.freereg = base + 1  -- free registers with list values
  2194. end
  2195.  
  2196. return function(a) luaY = a return luaK end
  2197. end
  2198. luaK=luaK()
  2199. local luaY = function ()
  2200. --requires luaP, luaX, luaK
  2201. local luaY = {}
  2202. local luaX = luaX
  2203. local luaK = luaK(luaY)
  2204. local luaP = luaP
  2205.  
  2206. --[[--------------------------------------------------------------------
  2207. -- Expression descriptor
  2208. -- * expkind changed to string constants; luaY:assignment was the only
  2209. --   function to use a relational operator with this enumeration
  2210. -- VVOID       -- no value
  2211. -- VNIL        -- no value
  2212. -- VTRUE       -- no value
  2213. -- VFALSE      -- no value
  2214. -- VK          -- info = index of constant in 'k'
  2215. -- VKNUM       -- nval = numerical value
  2216. -- VLOCAL      -- info = local register
  2217. -- VUPVAL,     -- info = index of upvalue in 'upvalues'
  2218. -- VGLOBAL     -- info = index of table; aux = index of global name in 'k'
  2219. -- VINDEXED    -- info = table register; aux = index register (or 'k')
  2220. -- VJMP        -- info = instruction pc
  2221. -- VRELOCABLE  -- info = instruction pc
  2222. -- VNONRELOC   -- info = result register
  2223. -- VCALL       -- info = instruction pc
  2224. -- VVARARG     -- info = instruction pc
  2225. } ----------------------------------------------------------------------]]
  2226.  
  2227. --[[--------------------------------------------------------------------
  2228. -- * expdesc in Lua 5.1.x has a union u and another struct s; this Lua
  2229. --   implementation ignores all instances of u and s usage
  2230. -- struct expdesc:
  2231. --   k  -- (enum: expkind)
  2232. --   info, aux -- (int, int)
  2233. --   nval -- (lua_Number)
  2234. --   t  -- patch list of 'exit when true'
  2235. --   f  -- patch list of 'exit when false'
  2236. ----------------------------------------------------------------------]]
  2237.  
  2238. --[[--------------------------------------------------------------------
  2239. -- struct upvaldesc:
  2240. --   k  -- (lu_byte)
  2241. --   info -- (lu_byte)
  2242. ----------------------------------------------------------------------]]
  2243.  
  2244. --[[--------------------------------------------------------------------
  2245. -- state needed to generate code for a given function
  2246. -- struct FuncState:
  2247. --   f  -- current function header (table: Proto)
  2248. --   h  -- table to find (and reuse) elements in 'k' (table: Table)
  2249. --   prev  -- enclosing function (table: FuncState)
  2250. --   ls  -- lexical state (table: LexState)
  2251. --   L  -- copy of the Lua state (table: lua_State)
  2252. --   bl  -- chain of current blocks (table: BlockCnt)
  2253. --   pc  -- next position to code (equivalent to 'ncode')
  2254. --   lasttarget   -- 'pc' of last 'jump target'
  2255. --   jpc  -- list of pending jumps to 'pc'
  2256. --   freereg  -- first free register
  2257. --   nk  -- number of elements in 'k'
  2258. --   np  -- number of elements in 'p'
  2259. --   nlocvars  -- number of elements in 'locvars'
  2260. --   nactvar  -- number of active local variables
  2261. --   upvalues[LUAI_MAXUPVALUES]  -- upvalues (table: upvaldesc)
  2262. --   actvar[LUAI_MAXVARS]  -- declared-variable stack
  2263. ----------------------------------------------------------------------]]
  2264.  
  2265. ------------------------------------------------------------------------
  2266. -- constants used by parser
  2267. -- * picks up duplicate values from luaX if required
  2268. ------------------------------------------------------------------------
  2269.  
  2270. luaY.LUA_QS = luaX.LUA_QS or "'%s'"  -- (from luaconf.h)
  2271.  
  2272. luaY.SHRT_MAX = 32767 -- (from <limits.h>)
  2273. luaY.LUAI_MAXVARS = 200  -- (luaconf.h)
  2274. luaY.LUAI_MAXUPVALUES = 60  -- (luaconf.h)
  2275. luaY.MAX_INT = luaX.MAX_INT or 2147483645  -- (from llimits.h)
  2276.   -- * INT_MAX-2 for 32-bit systems
  2277. luaY.LUAI_MAXCCALLS = 200  -- (from luaconf.h)
  2278.  
  2279. luaY.VARARG_HASARG = 1  -- (from lobject.h)
  2280. -- NOTE: HASARG_MASK is value-specific
  2281. luaY.HASARG_MASK = 2 -- this was added for a bitop in parlist()
  2282. luaY.VARARG_ISVARARG = 2
  2283. -- NOTE: there is some value-specific code that involves VARARG_NEEDSARG
  2284. luaY.VARARG_NEEDSARG = 4
  2285.  
  2286. luaY.LUA_MULTRET = -1  -- (lua.h)
  2287.  
  2288. --[[--------------------------------------------------------------------
  2289. -- other functions
  2290. ----------------------------------------------------------------------]]
  2291.  
  2292. ------------------------------------------------------------------------
  2293. -- LUA_QL describes how error messages quote program elements.
  2294. -- CHANGE it if you want a different appearance. (from luaconf.h)
  2295. ------------------------------------------------------------------------
  2296. function luaY:LUA_QL(x)
  2297.   return "'"..x.."'"
  2298. end
  2299.  
  2300. ------------------------------------------------------------------------
  2301. -- this is a stripped-down luaM_growvector (from lmem.h) which is a
  2302. -- macro based on luaM_growaux (in lmem.c); all the following does is
  2303. -- reproduce the size limit checking logic of the original function
  2304. -- so that error behaviour is identical; all arguments preserved for
  2305. -- convenience, even those which are unused
  2306. -- * set the t field to nil, since this originally does a sizeof(t)
  2307. -- * size (originally a pointer) is never updated, their final values
  2308. --   are set by luaY:close_func(), so overall things should still work
  2309. ------------------------------------------------------------------------
  2310. function luaY:growvector(L, v, nelems, size, t, limit, e)
  2311.   if nelems >= limit then
  2312.     error(e)  -- was luaG_runerror
  2313.   end
  2314. end
  2315.  
  2316. ------------------------------------------------------------------------
  2317. -- initialize a new function prototype structure (from lfunc.c)
  2318. -- * used only in open_func()
  2319. ------------------------------------------------------------------------
  2320. function luaY:newproto(L)
  2321.   local f = {} -- Proto
  2322.   -- luaC_link(L, obj2gco(f), LUA_TPROTO); /* GC */
  2323.   f.k = {}
  2324.   f.sizek = 0
  2325.   f.p = {}
  2326.   f.sizep = 0
  2327.   f.code = {}
  2328.   f.sizecode = 0
  2329.   f.sizelineinfo = 0
  2330.   f.sizeupvalues = 0
  2331.   f.nups = 0
  2332.   f.upvalues = {}
  2333.   f.numparams = 0
  2334.   f.is_vararg = 0
  2335.   f.maxstacksize = 0
  2336.   f.lineinfo = {}
  2337.   f.sizelocvars = 0
  2338.   f.locvars = {}
  2339.   f.lineDefined = 0
  2340.   f.lastlinedefined = 0
  2341.   f.source = nil
  2342.   return f
  2343. end
  2344.  
  2345. ------------------------------------------------------------------------
  2346. -- converts an integer to a "floating point byte", represented as
  2347. -- (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
  2348. -- eeeee != 0 and (xxx) otherwise.
  2349. ------------------------------------------------------------------------
  2350. function luaY:int2fb(x)
  2351.   local e = 0  -- exponent
  2352.   while x >= 16 do
  2353.     x = math.floor((x + 1) / 2)
  2354.     e = e + 1
  2355.   end
  2356.   if x < 8 then
  2357.     return x
  2358.   else
  2359.     return ((e + 1) * 8) + (x - 8)
  2360.   end
  2361. end
  2362.  
  2363. --[[--------------------------------------------------------------------
  2364. -- parser functions
  2365. ----------------------------------------------------------------------]]
  2366.  
  2367. ------------------------------------------------------------------------
  2368. -- true of the kind of expression produces multiple return values
  2369. ------------------------------------------------------------------------
  2370. function luaY:hasmultret(k)
  2371.   return k == "VCALL" or k == "VVARARG"
  2372. end
  2373.  
  2374. ------------------------------------------------------------------------
  2375. -- convenience function to access active local i, returns entry
  2376. ------------------------------------------------------------------------
  2377. function luaY:getlocvar(fs, i)
  2378.   return fs.f.locvars[ fs.actvar[i] ]
  2379. end
  2380.  
  2381. ------------------------------------------------------------------------
  2382. -- check a limit, string m provided as an error message
  2383. ------------------------------------------------------------------------
  2384. function luaY:checklimit(fs, v, l, m)
  2385.   if v > l then self:errorlimit(fs, l, m) end
  2386. end
  2387.  
  2388. --[[--------------------------------------------------------------------
  2389. -- nodes for block list (list of active blocks)
  2390. -- struct BlockCnt:
  2391. --   previous  -- chain (table: BlockCnt)
  2392. --   breaklist  -- list of jumps out of this loop
  2393. --   nactvar  -- # active local variables outside the breakable structure
  2394. --   upval  -- true if some variable in the block is an upvalue (boolean)
  2395. --   isbreakable  -- true if 'block' is a loop (boolean)
  2396. ----------------------------------------------------------------------]]
  2397.  
  2398. ------------------------------------------------------------------------
  2399. -- prototypes for recursive non-terminal functions
  2400. ------------------------------------------------------------------------
  2401. -- prototypes deleted; not required in Lua
  2402.  
  2403. ------------------------------------------------------------------------
  2404. -- reanchor if last token is has a constant string, see close_func()
  2405. -- * used only in close_func()
  2406. ------------------------------------------------------------------------
  2407. function luaY:anchor_token(ls)
  2408.   if ls.t.token == "TK_NAME" or ls.t.token == "TK_STRING" then
  2409.     -- not relevant to Lua implementation of parser
  2410.     -- local ts = ls.t.seminfo
  2411.     -- luaX_newstring(ls, getstr(ts), ts->tsv.len); /* C */
  2412.   end
  2413. end
  2414.  
  2415. ------------------------------------------------------------------------
  2416. -- throws a syntax error if token expected is not there
  2417. ------------------------------------------------------------------------
  2418. function luaY:error_expected(ls, token)
  2419.   luaX:syntaxerror(ls,
  2420.     string.format(self.LUA_QS.." expected", luaX:token2str(ls, token)))
  2421. end
  2422.  
  2423. ------------------------------------------------------------------------
  2424. -- prepares error message for display, for limits exceeded
  2425. -- * used only in checklimit()
  2426. ------------------------------------------------------------------------
  2427. function luaY:errorlimit(fs, limit, what)
  2428.   local msg = (fs.f.linedefined == 0) and
  2429.     string.format("main function has more than %d %s", limit, what) or
  2430.     string.format("function at line %d has more than %d %s",
  2431.                   fs.f.linedefined, limit, what)
  2432.   luaX:lexerror(fs.ls, msg, 0)
  2433. end
  2434.  
  2435. ------------------------------------------------------------------------
  2436. -- tests for a token, returns outcome
  2437. -- * return value changed to boolean
  2438. ------------------------------------------------------------------------
  2439. function luaY:testnext(ls, c)
  2440.   if ls.t.token == c then
  2441.     luaX:next(ls)
  2442.     return true
  2443.   else
  2444.     return false
  2445.   end
  2446. end
  2447.  
  2448. ------------------------------------------------------------------------
  2449. -- check for existence of a token, throws error if not found
  2450. ------------------------------------------------------------------------
  2451. function luaY:check(ls, c)
  2452.   if ls.t.token ~= c then
  2453.     self:error_expected(ls, c)
  2454.   end
  2455. end
  2456.  
  2457. ------------------------------------------------------------------------
  2458. -- verify existence of a token, then skip it
  2459. ------------------------------------------------------------------------
  2460. function luaY:checknext(ls, c)
  2461.   self:check(ls, c)
  2462.   luaX:next(ls)
  2463. end
  2464.  
  2465. ------------------------------------------------------------------------
  2466. -- throws error if condition not matched
  2467. ------------------------------------------------------------------------
  2468. function luaY:check_condition(ls, c, msg)
  2469.   if not c then luaX:syntaxerror(ls, msg) end
  2470. end
  2471.  
  2472. ------------------------------------------------------------------------
  2473. -- verifies token conditions are met or else throw error
  2474. ------------------------------------------------------------------------
  2475. function luaY:check_match(ls, what, who, where)
  2476.   if not self:testnext(ls, what) then
  2477.     if where == ls.linenumber then
  2478.       self:error_expected(ls, what)
  2479.     else
  2480.       luaX:syntaxerror(ls, string.format(
  2481.         self.LUA_QS.." expected (to close "..self.LUA_QS.." at line %d)",
  2482.         luaX:token2str(ls, what), luaX:token2str(ls, who), where))
  2483.     end
  2484.   end
  2485. end
  2486.  
  2487. ------------------------------------------------------------------------
  2488. -- expect that token is a name, return the name
  2489. ------------------------------------------------------------------------
  2490. function luaY:str_checkname(ls)
  2491.   self:check(ls, "TK_NAME")
  2492.   local ts = ls.t.seminfo
  2493.   luaX:next(ls)
  2494.   return ts
  2495. end
  2496.  
  2497. ------------------------------------------------------------------------
  2498. -- initialize a struct expdesc, expression description data structure
  2499. ------------------------------------------------------------------------
  2500. function luaY:init_exp(e, k, i)
  2501.   e.f, e.t = luaK.NO_JUMP, luaK.NO_JUMP
  2502.   e.k = k
  2503.   e.info = i
  2504. end
  2505.  
  2506. ------------------------------------------------------------------------
  2507. -- adds given string s in string pool, sets e as VK
  2508. ------------------------------------------------------------------------
  2509. function luaY:codestring(ls, e, s)
  2510.   self:init_exp(e, "VK", luaK:stringK(ls.fs, s))
  2511. end
  2512.  
  2513. ------------------------------------------------------------------------
  2514. -- consume a name token, adds it to string pool, sets e as VK
  2515. ------------------------------------------------------------------------
  2516. function luaY:checkname(ls, e)
  2517.   self:codestring(ls, e, self:str_checkname(ls))
  2518. end
  2519.  
  2520. ------------------------------------------------------------------------
  2521. -- creates struct entry for a local variable
  2522. -- * used only in new_localvar()
  2523. ------------------------------------------------------------------------
  2524. function luaY:registerlocalvar(ls, varname)
  2525.   local fs = ls.fs
  2526.   local f = fs.f
  2527.   self:growvector(ls.L, f.locvars, fs.nlocvars, f.sizelocvars,
  2528.                   nil, self.SHRT_MAX, "too many local variables")
  2529.   -- loop to initialize empty f.locvar positions not required
  2530.   f.locvars[fs.nlocvars] = {} -- LocVar
  2531.   f.locvars[fs.nlocvars].varname = varname
  2532.   -- luaC_objbarrier(ls.L, f, varname) /* GC */
  2533.   local nlocvars = fs.nlocvars
  2534.   fs.nlocvars = fs.nlocvars + 1
  2535.   return nlocvars
  2536. end
  2537.  
  2538. ------------------------------------------------------------------------
  2539. -- creates a new local variable given a name and an offset from nactvar
  2540. -- * used in fornum(), forlist(), parlist(), body()
  2541. ------------------------------------------------------------------------
  2542. function luaY:new_localvarliteral(ls, v, n)
  2543.   self:new_localvar(ls, v, n)
  2544. end
  2545.  
  2546. ------------------------------------------------------------------------
  2547. -- register a local variable, set in active variable list
  2548. ------------------------------------------------------------------------
  2549. function luaY:new_localvar(ls, name, n)
  2550.   local fs = ls.fs
  2551.   self:checklimit(fs, fs.nactvar + n + 1, self.LUAI_MAXVARS, "local variables")
  2552.   fs.actvar[fs.nactvar + n] = self:registerlocalvar(ls, name)
  2553. end
  2554.  
  2555. ------------------------------------------------------------------------
  2556. -- adds nvars number of new local variables, set debug information
  2557. ------------------------------------------------------------------------
  2558. function luaY:adjustlocalvars(ls, nvars)
  2559.   local fs = ls.fs
  2560.   fs.nactvar = fs.nactvar + nvars
  2561.   for i = nvars, 1, -1 do
  2562.     self:getlocvar(fs, fs.nactvar - i).startpc = fs.pc
  2563.   end
  2564. end
  2565.  
  2566. ------------------------------------------------------------------------
  2567. -- removes a number of locals, set debug information
  2568. ------------------------------------------------------------------------
  2569. function luaY:removevars(ls, tolevel)
  2570.   local fs = ls.fs
  2571.   while fs.nactvar > tolevel do
  2572.     fs.nactvar = fs.nactvar - 1
  2573.     self:getlocvar(fs, fs.nactvar).endpc = fs.pc
  2574.   end
  2575. end
  2576.  
  2577. ------------------------------------------------------------------------
  2578. -- returns an existing upvalue index based on the given name, or
  2579. -- creates a new upvalue struct entry and returns the new index
  2580. -- * used only in singlevaraux()
  2581. ------------------------------------------------------------------------
  2582. function luaY:indexupvalue(fs, name, v)
  2583.   local f = fs.f
  2584.   for i = 0, f.nups - 1 do
  2585.     if fs.upvalues[i].k == v.k and fs.upvalues[i].info == v.info then
  2586.       assert(f.upvalues[i] == name)
  2587.       return i
  2588.     end
  2589.   end
  2590.   -- new one
  2591.   self:checklimit(fs, f.nups + 1, self.LUAI_MAXUPVALUES, "upvalues")
  2592.   self:growvector(fs.L, f.upvalues, f.nups, f.sizeupvalues,
  2593.                   nil, self.MAX_INT, "")
  2594.   -- loop to initialize empty f.upvalues positions not required
  2595.   f.upvalues[f.nups] = name
  2596.   -- luaC_objbarrier(fs->L, f, name); /* GC */
  2597.   assert(v.k == "VLOCAL" or v.k == "VUPVAL")
  2598.   -- this is a partial copy; only k & info fields used
  2599.   fs.upvalues[f.nups] = { k = v.k, info = v.info }
  2600.   local nups = f.nups
  2601.   f.nups = f.nups + 1
  2602.   return nups
  2603. end
  2604.  
  2605. ------------------------------------------------------------------------
  2606. -- search the local variable namespace of the given fs for a match
  2607. -- * used only in singlevaraux()
  2608. ------------------------------------------------------------------------
  2609. function luaY:searchvar(fs, n)
  2610.   for i = fs.nactvar - 1, 0, -1 do
  2611.     if n == self:getlocvar(fs, i).varname then
  2612.       return i
  2613.     end
  2614.   end
  2615.   return -1  -- not found
  2616. end
  2617.  
  2618. ------------------------------------------------------------------------
  2619. -- * mark upvalue flags in function states up to a given level
  2620. -- * used only in singlevaraux()
  2621. ------------------------------------------------------------------------
  2622. function luaY:markupval(fs, level)
  2623.   local bl = fs.bl
  2624.   while bl and bl.nactvar > level do bl = bl.previous end
  2625.   if bl then bl.upval = true end
  2626. end
  2627.  
  2628. ------------------------------------------------------------------------
  2629. -- handle locals, globals and upvalues and related processing
  2630. -- * search mechanism is recursive, calls itself to search parents
  2631. -- * used only in singlevar()
  2632. ------------------------------------------------------------------------
  2633. function luaY:singlevaraux(fs, n, var, base)
  2634.   if fs == nil then  -- no more levels?
  2635.     self:init_exp(var, "VGLOBAL", luaP.NO_REG)  -- default is global variable
  2636.     return "VGLOBAL"
  2637.   else
  2638.     local v = self:searchvar(fs, n)  -- look up at current level
  2639.     if v >= 0 then
  2640.       self:init_exp(var, "VLOCAL", v)
  2641.       if base == 0 then
  2642.         self:markupval(fs, v)  -- local will be used as an upval
  2643.       end
  2644.       return "VLOCAL"
  2645.     else  -- not found at current level; try upper one
  2646.       if self:singlevaraux(fs.prev, n, var, 0) == "VGLOBAL" then
  2647.         return "VGLOBAL"
  2648.       end
  2649.       var.info = self:indexupvalue(fs, n, var)  -- else was LOCAL or UPVAL
  2650.       var.k = "VUPVAL"  -- upvalue in this level
  2651.       return "VUPVAL"
  2652.     end--if v
  2653.   end--if fs
  2654. end
  2655.  
  2656. ------------------------------------------------------------------------
  2657. -- consume a name token, creates a variable (global|local|upvalue)
  2658. -- * used in prefixexp(), funcname()
  2659. ------------------------------------------------------------------------
  2660. function luaY:singlevar(ls, var)
  2661.   local varname = self:str_checkname(ls)
  2662.   local fs = ls.fs
  2663.   if self:singlevaraux(fs, varname, var, 1) == "VGLOBAL" then
  2664.     var.info = luaK:stringK(fs, varname)  -- info points to global name
  2665.   end
  2666. end
  2667.  
  2668. ------------------------------------------------------------------------
  2669. -- adjust RHS to match LHS in an assignment
  2670. -- * used in assignment(), forlist(), localstat()
  2671. ------------------------------------------------------------------------
  2672. function luaY:adjust_assign(ls, nvars, nexps, e)
  2673.   local fs = ls.fs
  2674.   local extra = nvars - nexps
  2675.   if self:hasmultret(e.k) then
  2676.     extra = extra + 1  -- includes call itself
  2677.     if extra <= 0 then extra = 0 end
  2678.     luaK:setreturns(fs, e, extra)  -- last exp. provides the difference
  2679.     if extra > 1 then luaK:reserveregs(fs, extra - 1) end
  2680.   else
  2681.     if e.k ~= "VVOID" then luaK:exp2nextreg(fs, e) end  -- close last expression
  2682.     if extra > 0 then
  2683.       local reg = fs.freereg
  2684.       luaK:reserveregs(fs, extra)
  2685.       luaK:_nil(fs, reg, extra)
  2686.     end
  2687.   end
  2688. end
  2689.  
  2690. ------------------------------------------------------------------------
  2691. -- tracks and limits parsing depth, assert check at end of parsing
  2692. ------------------------------------------------------------------------
  2693. function luaY:enterlevel(ls)
  2694.   ls.L.nCcalls = ls.L.nCcalls + 1
  2695.   if ls.L.nCcalls > self.LUAI_MAXCCALLS then
  2696.     luaX:lexerror(ls, "chunk has too many syntax levels", 0)
  2697.   end
  2698. end
  2699.  
  2700. ------------------------------------------------------------------------
  2701. -- tracks parsing depth, a pair with luaY:enterlevel()
  2702. ------------------------------------------------------------------------
  2703. function luaY:leavelevel(ls)
  2704.   ls.L.nCcalls = ls.L.nCcalls - 1
  2705. end
  2706.  
  2707. ------------------------------------------------------------------------
  2708. -- enters a code unit, initializes elements
  2709. ------------------------------------------------------------------------
  2710. function luaY:enterblock(fs, bl, isbreakable)
  2711.   bl.breaklist = luaK.NO_JUMP
  2712.   bl.isbreakable = isbreakable
  2713.   bl.nactvar = fs.nactvar
  2714.   bl.upval = false
  2715.   bl.previous = fs.bl
  2716.   fs.bl = bl
  2717.   assert(fs.freereg == fs.nactvar)
  2718. end
  2719.  
  2720. ------------------------------------------------------------------------
  2721. -- leaves a code unit, close any upvalues
  2722. ------------------------------------------------------------------------
  2723. function luaY:leaveblock(fs)
  2724.   local bl = fs.bl
  2725.   fs.bl = bl.previous
  2726.   self:removevars(fs.ls, bl.nactvar)
  2727.   if bl.upval then
  2728.     luaK:codeABC(fs, "OP_CLOSE", bl.nactvar, 0, 0)
  2729.   end
  2730.   -- a block either controls scope or breaks (never both)
  2731.   assert(not bl.isbreakable or not bl.upval)
  2732.   assert(bl.nactvar == fs.nactvar)
  2733.   fs.freereg = fs.nactvar  -- free registers
  2734.   luaK:patchtohere(fs, bl.breaklist)
  2735. end
  2736.  
  2737. ------------------------------------------------------------------------
  2738. -- implement the instantiation of a function prototype, append list of
  2739. -- upvalues after the instantiation instruction
  2740. -- * used only in body()
  2741. ------------------------------------------------------------------------
  2742. function luaY:pushclosure(ls, func, v)
  2743.   local fs = ls.fs
  2744.   local f = fs.f
  2745.   self:growvector(ls.L, f.p, fs.np, f.sizep, nil,
  2746.                   luaP.MAXARG_Bx, "constant table overflow")
  2747.   -- loop to initialize empty f.p positions not required
  2748.   f.p[fs.np] = func.f
  2749.   fs.np = fs.np + 1
  2750.   -- luaC_objbarrier(ls->L, f, func->f); /* C */
  2751.   self:init_exp(v, "VRELOCABLE", luaK:codeABx(fs, "OP_CLOSURE", 0, fs.np - 1))
  2752.   for i = 0, func.f.nups - 1 do
  2753.     local o = (func.upvalues[i].k == "VLOCAL") and "OP_MOVE" or "OP_GETUPVAL"
  2754.     luaK:codeABC(fs, o, 0, func.upvalues[i].info, 0)
  2755.   end
  2756. end
  2757.  
  2758. ------------------------------------------------------------------------
  2759. -- opening of a function
  2760. ------------------------------------------------------------------------
  2761. function luaY:open_func(ls, fs)
  2762.   local L = ls.L
  2763.   local f = self:newproto(ls.L)
  2764.   fs.f = f
  2765.   fs.prev = ls.fs  -- linked list of funcstates
  2766.   fs.ls = ls
  2767.   fs.L = L
  2768.   ls.fs = fs
  2769.   fs.pc = 0
  2770.   fs.lasttarget = -1
  2771.   fs.jpc = luaK.NO_JUMP
  2772.   fs.freereg = 0
  2773.   fs.nk = 0
  2774.   fs.np = 0
  2775.   fs.nlocvars = 0
  2776.   fs.nactvar = 0
  2777.   fs.bl = nil
  2778.   f.source = ls.source
  2779.   f.maxstacksize = 2  -- registers 0/1 are always valid
  2780.   fs.h = {}  -- constant table; was luaH_new call
  2781.   -- anchor table of constants and prototype (to avoid being collected)
  2782.   -- sethvalue2s(L, L->top, fs->h); incr_top(L); /* C */
  2783.   -- setptvalue2s(L, L->top, f); incr_top(L);
  2784. end
  2785.  
  2786. ------------------------------------------------------------------------
  2787. -- closing of a function
  2788. ------------------------------------------------------------------------
  2789. function luaY:close_func(ls)
  2790.   local L = ls.L
  2791.   local fs = ls.fs
  2792.   local f = fs.f
  2793.   self:removevars(ls, 0)
  2794.   luaK:ret(fs, 0, 0)  -- final return
  2795.   -- luaM_reallocvector deleted for f->code, f->lineinfo, f->k, f->p,
  2796.   -- f->locvars, f->upvalues; not required for Lua table arrays
  2797.   f.sizecode = fs.pc
  2798.   f.sizelineinfo = fs.pc
  2799.   f.sizek = fs.nk
  2800.   f.sizep = fs.np
  2801.   f.sizelocvars = fs.nlocvars
  2802.   f.sizeupvalues = f.nups
  2803.   --assert(luaG_checkcode(f))  -- currently not implemented
  2804.   assert(fs.bl == nil)
  2805.   ls.fs = fs.prev
  2806.   -- the following is not required for this implementation; kept here
  2807.   -- for completeness
  2808.   -- L->top -= 2;  /* remove table and prototype from the stack */
  2809.   -- last token read was anchored in defunct function; must reanchor it
  2810.   if fs then self:anchor_token(ls) end
  2811. end
  2812.  
  2813. ------------------------------------------------------------------------
  2814. -- parser initialization function
  2815. -- * note additional sub-tables needed for LexState, FuncState
  2816. ------------------------------------------------------------------------
  2817. function luaY:parser(L, z, buff, name)
  2818.   local lexstate = {}  -- LexState
  2819.         lexstate.t = {}
  2820.         lexstate.lookahead = {}
  2821.   local funcstate = {}  -- FuncState
  2822.         funcstate.upvalues = {}
  2823.         funcstate.actvar = {}
  2824.   -- the following nCcalls initialization added for convenience
  2825.   L.nCcalls = 0
  2826.   lexstate.buff = buff
  2827.   luaX:setinput(L, lexstate, z, name)
  2828.   self:open_func(lexstate, funcstate)
  2829.   funcstate.f.is_vararg = self.VARARG_ISVARARG  -- main func. is always vararg
  2830.   luaX:next(lexstate)  -- read first token
  2831.   self:chunk(lexstate)
  2832.   self:check(lexstate, "TK_EOS")
  2833.   self:close_func(lexstate)
  2834.   assert(funcstate.prev == nil)
  2835.   assert(funcstate.f.nups == 0)
  2836.   assert(lexstate.fs == nil)
  2837.   return funcstate.f
  2838. end
  2839.  
  2840. --[[--------------------------------------------------------------------
  2841. -- GRAMMAR RULES
  2842. ----------------------------------------------------------------------]]
  2843.  
  2844. ------------------------------------------------------------------------
  2845. -- parse a function name suffix, for function call specifications
  2846. -- * used in primaryexp(), funcname()
  2847. ------------------------------------------------------------------------
  2848. function luaY:field(ls, v)
  2849.   -- field -> ['.' | ':'] NAME
  2850.   local fs = ls.fs
  2851.   local key = {}  -- expdesc
  2852.   luaK:exp2anyreg(fs, v)
  2853.   luaX:next(ls)  -- skip the dot or colon
  2854.   self:checkname(ls, key)
  2855.   luaK:indexed(fs, v, key)
  2856. end
  2857.  
  2858. ------------------------------------------------------------------------
  2859. -- parse a table indexing suffix, for constructors, expressions
  2860. -- * used in recfield(), primaryexp()
  2861. ------------------------------------------------------------------------
  2862. function luaY:yindex(ls, v)
  2863.   -- index -> '[' expr ']'
  2864.   luaX:next(ls)  -- skip the '['
  2865.   self:expr(ls, v)
  2866.   luaK:exp2val(ls.fs, v)
  2867.   self:checknext(ls, "]")
  2868. end
  2869.  
  2870. --[[--------------------------------------------------------------------
  2871. -- Rules for Constructors
  2872. ----------------------------------------------------------------------]]
  2873.  
  2874. --[[--------------------------------------------------------------------
  2875. -- struct ConsControl:
  2876. --   v  -- last list item read (table: struct expdesc)
  2877. --   t  -- table descriptor (table: struct expdesc)
  2878. --   nh  -- total number of 'record' elements
  2879. --   na  -- total number of array elements
  2880. --   tostore  -- number of array elements pending to be stored
  2881. ----------------------------------------------------------------------]]
  2882.  
  2883. ------------------------------------------------------------------------
  2884. -- parse a table record (hash) field
  2885. -- * used in constructor()
  2886. ------------------------------------------------------------------------
  2887. function luaY:recfield(ls, cc)
  2888.   -- recfield -> (NAME | '['exp1']') = exp1
  2889.   local fs = ls.fs
  2890.   local reg = ls.fs.freereg
  2891.   local key, val = {}, {}  -- expdesc
  2892.   if ls.t.token == "TK_NAME" then
  2893.     self:checklimit(fs, cc.nh, self.MAX_INT, "items in a constructor")
  2894.     self:checkname(ls, key)
  2895.   else  -- ls->t.token == '['
  2896.     self:yindex(ls, key)
  2897.   end
  2898.   cc.nh = cc.nh + 1
  2899.   self:checknext(ls, "=")
  2900.   local rkkey = luaK:exp2RK(fs, key)
  2901.   self:expr(ls, val)
  2902.   luaK:codeABC(fs, "OP_SETTABLE", cc.t.info, rkkey, luaK:exp2RK(fs, val))
  2903.   fs.freereg = reg  -- free registers
  2904. end
  2905.  
  2906. ------------------------------------------------------------------------
  2907. -- emit a set list instruction if enough elements (LFIELDS_PER_FLUSH)
  2908. -- * used in constructor()
  2909. ------------------------------------------------------------------------
  2910. function luaY:closelistfield(fs, cc)
  2911.   if cc.v.k == "VVOID" then return end  -- there is no list item
  2912.   luaK:exp2nextreg(fs, cc.v)
  2913.   cc.v.k = "VVOID"
  2914.   if cc.tostore == luaP.LFIELDS_PER_FLUSH then
  2915.     luaK:setlist(fs, cc.t.info, cc.na, cc.tostore)  -- flush
  2916.     cc.tostore = 0  -- no more items pending
  2917.   end
  2918. end
  2919.  
  2920. ------------------------------------------------------------------------
  2921. -- emit a set list instruction at the end of parsing list constructor
  2922. -- * used in constructor()
  2923. ------------------------------------------------------------------------
  2924. function luaY:lastlistfield(fs, cc)
  2925.   if cc.tostore == 0 then return end
  2926.   if self:hasmultret(cc.v.k) then
  2927.     luaK:setmultret(fs, cc.v)
  2928.     luaK:setlist(fs, cc.t.info, cc.na, self.LUA_MULTRET)
  2929.     cc.na = cc.na - 1  -- do not count last expression (unknown number of elements)
  2930.   else
  2931.     if cc.v.k ~= "VVOID" then
  2932.       luaK:exp2nextreg(fs, cc.v)
  2933.     end
  2934.     luaK:setlist(fs, cc.t.info, cc.na, cc.tostore)
  2935.   end
  2936. end
  2937.  
  2938. ------------------------------------------------------------------------
  2939. -- parse a table list (array) field
  2940. -- * used in constructor()
  2941. ------------------------------------------------------------------------
  2942. function luaY:listfield(ls, cc)
  2943.   self:expr(ls, cc.v)
  2944.   self:checklimit(ls.fs, cc.na, self.MAX_INT, "items in a constructor")
  2945.   cc.na = cc.na + 1
  2946.   cc.tostore = cc.tostore + 1
  2947. end
  2948.  
  2949. ------------------------------------------------------------------------
  2950. -- parse a table constructor
  2951. -- * used in funcargs(), simpleexp()
  2952. ------------------------------------------------------------------------
  2953. function luaY:constructor(ls, t)
  2954.   -- constructor -> '{' [ field { fieldsep field } [ fieldsep ] ] '}'
  2955.   -- field -> recfield | listfield
  2956.   -- fieldsep -> ',' | ';'
  2957.   local fs = ls.fs
  2958.   local line = ls.linenumber
  2959.   local pc = luaK:codeABC(fs, "OP_NEWTABLE", 0, 0, 0)
  2960.   local cc = {}  -- ConsControl
  2961.         cc.v = {}
  2962.   cc.na, cc.nh, cc.tostore = 0, 0, 0
  2963.   cc.t = t
  2964.   self:init_exp(t, "VRELOCABLE", pc)
  2965.   self:init_exp(cc.v, "VVOID", 0)  -- no value (yet)
  2966.   luaK:exp2nextreg(ls.fs, t)  -- fix it at stack top (for gc)
  2967.   self:checknext(ls, "{")
  2968.   repeat
  2969.     assert(cc.v.k == "VVOID" or cc.tostore > 0)
  2970.     if ls.t.token == "}" then break end
  2971.     self:closelistfield(fs, cc)
  2972.     local c = ls.t.token
  2973.  
  2974.     if c == "TK_NAME" then  -- may be listfields or recfields
  2975.       luaX:lookahead(ls)
  2976.       if ls.lookahead.token ~= "=" then  -- expression?
  2977.         self:listfield(ls, cc)
  2978.       else
  2979.         self:recfield(ls, cc)
  2980.       end
  2981.     elseif c == "[" then  -- constructor_item -> recfield
  2982.       self:recfield(ls, cc)
  2983.     else  -- constructor_part -> listfield
  2984.       self:listfield(ls, cc)
  2985.     end
  2986.   until not self:testnext(ls, ",") and not self:testnext(ls, ";")
  2987.   self:check_match(ls, "}", "{", line)
  2988.   self:lastlistfield(fs, cc)
  2989.   luaP:SETARG_B(fs.f.code[pc], self:int2fb(cc.na)) -- set initial array size
  2990.   luaP:SETARG_C(fs.f.code[pc], self:int2fb(cc.nh)) -- set initial table size
  2991. end
  2992.  
  2993. -- }======================================================================
  2994.  
  2995. ------------------------------------------------------------------------
  2996. -- parse the arguments (parameters) of a function declaration
  2997. -- * used in body()
  2998. ------------------------------------------------------------------------
  2999. function luaY:parlist(ls)
  3000.   -- parlist -> [ param { ',' param } ]
  3001.   local fs = ls.fs
  3002.   local f = fs.f
  3003.   local nparams = 0
  3004.   f.is_vararg = 0
  3005.   if ls.t.token ~= ")" then  -- is 'parlist' not empty?
  3006.     repeat
  3007.       local c = ls.t.token
  3008.       if c == "TK_NAME" then  -- param -> NAME
  3009.         self:new_localvar(ls, self:str_checkname(ls), nparams)
  3010.         nparams = nparams + 1
  3011.       elseif c == "TK_DOTS" then  -- param -> `...'
  3012.         luaX:next(ls)
  3013. -- [[
  3014. -- #if defined(LUA_COMPAT_VARARG)
  3015.         -- use `arg' as default name
  3016.         self:new_localvarliteral(ls, "arg", nparams)
  3017.         nparams = nparams + 1
  3018.         f.is_vararg = self.VARARG_HASARG + self.VARARG_NEEDSARG
  3019. -- #endif
  3020. --]]
  3021.         f.is_vararg = f.is_vararg + self.VARARG_ISVARARG
  3022.       else
  3023.         luaX:syntaxerror(ls, "<name> or "..self:LUA_QL("...").." expected")
  3024.       end
  3025.     until f.is_vararg ~= 0 or not self:testnext(ls, ",")
  3026.   end--if
  3027.   self:adjustlocalvars(ls, nparams)
  3028.   -- NOTE: the following works only when HASARG_MASK is 2!
  3029.   f.numparams = fs.nactvar - (f.is_vararg % self.HASARG_MASK)
  3030.   luaK:reserveregs(fs, fs.nactvar)  -- reserve register for parameters
  3031. end
  3032.  
  3033. ------------------------------------------------------------------------
  3034. -- parse function declaration body
  3035. -- * used in simpleexp(), localfunc(), funcstat()
  3036. ------------------------------------------------------------------------
  3037. function luaY:body(ls, e, needself, line)
  3038.   -- body ->  '(' parlist ')' chunk END
  3039.   local new_fs = {}  -- FuncState
  3040.         new_fs.upvalues = {}
  3041.         new_fs.actvar = {}
  3042.   self:open_func(ls, new_fs)
  3043.   new_fs.f.lineDefined = line
  3044.   self:checknext(ls, "(")
  3045.   if needself then
  3046.     self:new_localvarliteral(ls, "self", 0)
  3047.     self:adjustlocalvars(ls, 1)
  3048.   end
  3049.   self:parlist(ls)
  3050.   self:checknext(ls, ")")
  3051.   self:chunk(ls)
  3052.   new_fs.f.lastlinedefined = ls.linenumber
  3053.   self:check_match(ls, "TK_END", "TK_FUNCTION", line)
  3054.   self:close_func(ls)
  3055.   self:pushclosure(ls, new_fs, e)
  3056. end
  3057.  
  3058. ------------------------------------------------------------------------
  3059. -- parse a list of comma-separated expressions
  3060. -- * used is multiple locations
  3061. ------------------------------------------------------------------------
  3062. function luaY:explist1(ls, v)
  3063.   -- explist1 -> expr { ',' expr }
  3064.   local n = 1  -- at least one expression
  3065.   self:expr(ls, v)
  3066.   while self:testnext(ls, ",") do
  3067.     luaK:exp2nextreg(ls.fs, v)
  3068.     self:expr(ls, v)
  3069.     n = n + 1
  3070.   end
  3071.   return n
  3072. end
  3073.  
  3074. ------------------------------------------------------------------------
  3075. -- parse the parameters of a function call
  3076. -- * contrast with parlist(), used in function declarations
  3077. -- * used in primaryexp()
  3078. ------------------------------------------------------------------------
  3079. function luaY:funcargs(ls, f)
  3080.   local fs = ls.fs
  3081.   local args = {}  -- expdesc
  3082.   local nparams
  3083.   local line = ls.linenumber
  3084.   local c = ls.t.token
  3085.   if c == "(" then  -- funcargs -> '(' [ explist1 ] ')'
  3086.     if line ~= ls.lastline then
  3087.       luaX:syntaxerror(ls, "ambiguous syntax (function call x new statement)")
  3088.     end
  3089.     luaX:next(ls)
  3090.     if ls.t.token == ")" then  -- arg list is empty?
  3091.       args.k = "VVOID"
  3092.     else
  3093.       self:explist1(ls, args)
  3094.       luaK:setmultret(fs, args)
  3095.     end
  3096.     self:check_match(ls, ")", "(", line)
  3097.   elseif c == "{" then  -- funcargs -> constructor
  3098.     self:constructor(ls, args)
  3099.   elseif c == "TK_STRING" then  -- funcargs -> STRING
  3100.     self:codestring(ls, args, ls.t.seminfo)
  3101.     luaX:next(ls)  -- must use 'seminfo' before 'next'
  3102.   else
  3103.     luaX:syntaxerror(ls, "function arguments expected")
  3104.     return
  3105.   end
  3106.   assert(f.k == "VNONRELOC")
  3107.   local base = f.info  -- base register for call
  3108.   if self:hasmultret(args.k) then
  3109.     nparams = self.LUA_MULTRET  -- open call
  3110.   else
  3111.     if args.k ~= "VVOID" then
  3112.       luaK:exp2nextreg(fs, args)  -- close last argument
  3113.     end
  3114.     nparams = fs.freereg - (base + 1)
  3115.   end
  3116.   self:init_exp(f, "VCALL", luaK:codeABC(fs, "OP_CALL", base, nparams + 1, 2))
  3117.   luaK:fixline(fs, line)
  3118.   fs.freereg = base + 1  -- call remove function and arguments and leaves
  3119.                          -- (unless changed) one result
  3120. end
  3121.  
  3122. --[[--------------------------------------------------------------------
  3123. -- Expression parsing
  3124. ----------------------------------------------------------------------]]
  3125.  
  3126. ------------------------------------------------------------------------
  3127. -- parses an expression in parentheses or a single variable
  3128. -- * used in primaryexp()
  3129. ------------------------------------------------------------------------
  3130. function luaY:prefixexp(ls, v)
  3131.   -- prefixexp -> NAME | '(' expr ')'
  3132.   local c = ls.t.token
  3133.   if c == "(" then
  3134.     local line = ls.linenumber
  3135.     luaX:next(ls)
  3136.     self:expr(ls, v)
  3137.     self:check_match(ls, ")", "(", line)
  3138.     luaK:dischargevars(ls.fs, v)
  3139.   elseif c == "TK_NAME" then
  3140.     self:singlevar(ls, v)
  3141.   else
  3142.     luaX:syntaxerror(ls, "unexpected symbol")
  3143.   end--if c
  3144.   return
  3145. end
  3146.  
  3147. ------------------------------------------------------------------------
  3148. -- parses a prefixexp (an expression in parentheses or a single variable)
  3149. -- or a function call specification
  3150. -- * used in simpleexp(), assignment(), exprstat()
  3151. ------------------------------------------------------------------------
  3152. function luaY:primaryexp(ls, v)
  3153.   -- primaryexp ->
  3154.   --    prefixexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs }
  3155.   local fs = ls.fs
  3156.   self:prefixexp(ls, v)
  3157.   while true do
  3158.     local c = ls.t.token
  3159.     if c == "." then  -- field
  3160.       self:field(ls, v)
  3161.     elseif c == "[" then  -- '[' exp1 ']'
  3162.       local key = {}  -- expdesc
  3163.       luaK:exp2anyreg(fs, v)
  3164.       self:yindex(ls, key)
  3165.       luaK:indexed(fs, v, key)
  3166.     elseif c == ":" then  -- ':' NAME funcargs
  3167.       local key = {}  -- expdesc
  3168.       luaX:next(ls)
  3169.       self:checkname(ls, key)
  3170.       luaK:_self(fs, v, key)
  3171.       self:funcargs(ls, v)
  3172.     elseif c == "(" or c == "TK_STRING" or c == "{" then  -- funcargs
  3173.       luaK:exp2nextreg(fs, v)
  3174.       self:funcargs(ls, v)
  3175.     else
  3176.       return
  3177.     end--if c
  3178.   end--while
  3179. end
  3180.  
  3181. ------------------------------------------------------------------------
  3182. -- parses general expression types, constants handled here
  3183. -- * used in subexpr()
  3184. ------------------------------------------------------------------------
  3185. function luaY:simpleexp(ls, v)
  3186.   -- simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
  3187.   --              constructor | FUNCTION body | primaryexp
  3188.   local c = ls.t.token
  3189.   if c == "TK_NUMBER" then
  3190.     self:init_exp(v, "VKNUM", 0)
  3191.     v.nval = ls.t.seminfo
  3192.   elseif c == "TK_STRING" then
  3193.     self:codestring(ls, v, ls.t.seminfo)
  3194.   elseif c == "TK_NIL" then
  3195.     self:init_exp(v, "VNIL", 0)
  3196.   elseif c == "TK_TRUE" then
  3197.     self:init_exp(v, "VTRUE", 0)
  3198.   elseif c == "TK_FALSE" then
  3199.     self:init_exp(v, "VFALSE", 0)
  3200.   elseif c == "TK_DOTS" then  -- vararg
  3201.     local fs = ls.fs
  3202.     self:check_condition(ls, fs.f.is_vararg ~= 0,
  3203.                     "cannot use "..self:LUA_QL("...").." outside a vararg function");
  3204.     -- NOTE: the following substitutes for a bitop, but is value-specific
  3205.     local is_vararg = fs.f.is_vararg
  3206.     if is_vararg >= self.VARARG_NEEDSARG then
  3207.       fs.f.is_vararg = is_vararg - self.VARARG_NEEDSARG  -- don't need 'arg'
  3208.     end
  3209.     self:init_exp(v, "VVARARG", luaK:codeABC(fs, "OP_VARARG", 0, 1, 0))
  3210.   elseif c == "{" then  -- constructor
  3211.     self:constructor(ls, v)
  3212.     return
  3213.   elseif c == "TK_FUNCTION" then
  3214.     luaX:next(ls)
  3215.     self:body(ls, v, false, ls.linenumber)
  3216.     return
  3217.   else
  3218.     self:primaryexp(ls, v)
  3219.     return
  3220.   end--if c
  3221.   luaX:next(ls)
  3222. end
  3223.  
  3224. ------------------------------------------------------------------------
  3225. -- Translates unary operators tokens if found, otherwise returns
  3226. -- OPR_NOUNOPR. getunopr() and getbinopr() are used in subexpr().
  3227. -- * used in subexpr()
  3228. ------------------------------------------------------------------------
  3229. function luaY:getunopr(op)
  3230.   if op == "TK_NOT" then
  3231.     return "OPR_NOT"
  3232.   elseif op == "-" then
  3233.     return "OPR_MINUS"
  3234.   elseif op == "#" then
  3235.     return "OPR_LEN"
  3236.   else
  3237.     return "OPR_NOUNOPR"
  3238.   end
  3239. end
  3240.  
  3241. ------------------------------------------------------------------------
  3242. -- Translates binary operator tokens if found, otherwise returns
  3243. -- OPR_NOBINOPR. Code generation uses OPR_* style tokens.
  3244. -- * used in subexpr()
  3245. ------------------------------------------------------------------------
  3246. luaY.getbinopr_table = {
  3247.   ["+"] = "OPR_ADD",
  3248.   ["-"] = "OPR_SUB",
  3249.   ["*"] = "OPR_MUL",
  3250.   ["/"] = "OPR_DIV",
  3251.   ["%"] = "OPR_MOD",
  3252.   ["^"] = "OPR_POW",
  3253.   ["TK_CONCAT"] = "OPR_CONCAT",
  3254.   ["TK_NE"] = "OPR_NE",
  3255.   ["TK_EQ"] = "OPR_EQ",
  3256.   ["<"] = "OPR_LT",
  3257.   ["TK_LE"] = "OPR_LE",
  3258.   [">"] = "OPR_GT",
  3259.   ["TK_GE"] = "OPR_GE",
  3260.   ["TK_AND"] = "OPR_AND",
  3261.   ["TK_OR"] = "OPR_OR",
  3262. }
  3263. function luaY:getbinopr(op)
  3264.   local opr = self.getbinopr_table[op]
  3265.   if opr then return opr else return "OPR_NOBINOPR" end
  3266. end
  3267.  
  3268. ------------------------------------------------------------------------
  3269. -- the following priority table consists of pairs of left/right values
  3270. -- for binary operators (was a static const struct); grep for ORDER OPR
  3271. -- * the following struct is replaced:
  3272. --   static const struct {
  3273. --     lu_byte left;  /* left priority for each binary operator */
  3274. --     lu_byte right; /* right priority */
  3275. --   } priority[] = {  /* ORDER OPR */
  3276. ------------------------------------------------------------------------
  3277. luaY.priority = {
  3278.   {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, -- `+' `-' `/' `%'
  3279.   {10, 9}, {5, 4},                 -- power and concat (right associative)
  3280.   {3, 3}, {3, 3},                  -- equality
  3281.   {3, 3}, {3, 3}, {3, 3}, {3, 3},  -- order
  3282.   {2, 2}, {1, 1}                   -- logical (and/or)
  3283. }
  3284.  
  3285. luaY.UNARY_PRIORITY = 8  -- priority for unary operators
  3286.  
  3287. ------------------------------------------------------------------------
  3288. -- Parse subexpressions. Includes handling of unary operators and binary
  3289. -- operators. A subexpr is given the rhs priority level of the operator
  3290. -- immediately left of it, if any (limit is -1 if none,) and if a binop
  3291. -- is found, limit is compared with the lhs priority level of the binop
  3292. -- in order to determine which executes first.
  3293. ------------------------------------------------------------------------
  3294.  
  3295. ------------------------------------------------------------------------
  3296. -- subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  3297. -- where 'binop' is any binary operator with a priority higher than 'limit'
  3298. -- * for priority lookups with self.priority[], 1=left and 2=right
  3299. -- * recursively called
  3300. -- * used in expr()
  3301. ------------------------------------------------------------------------
  3302. function luaY:subexpr(ls, v, limit)
  3303.   self:enterlevel(ls)
  3304.   local uop = self:getunopr(ls.t.token)
  3305.   if uop ~= "OPR_NOUNOPR" then
  3306.     luaX:next(ls)
  3307.     self:subexpr(ls, v, self.UNARY_PRIORITY)
  3308.     luaK:prefix(ls.fs, uop, v)
  3309.   else
  3310.     self:simpleexp(ls, v)
  3311.   end
  3312.   -- expand while operators have priorities higher than 'limit'
  3313.   local op = self:getbinopr(ls.t.token)
  3314.   while op ~= "OPR_NOBINOPR" and self.priority[luaK.BinOpr[op] + 1][1] > limit do
  3315.     local v2 = {}  -- expdesc
  3316.     luaX:next(ls)
  3317.     luaK:infix(ls.fs, op, v)
  3318.     -- read sub-expression with higher priority
  3319.     local nextop = self:subexpr(ls, v2, self.priority[luaK.BinOpr[op] + 1][2])
  3320.     luaK:posfix(ls.fs, op, v, v2)
  3321.     op = nextop
  3322.   end
  3323.   self:leavelevel(ls)
  3324.   return op  -- return first untreated operator
  3325. end
  3326.  
  3327. ------------------------------------------------------------------------
  3328. -- Expression parsing starts here. Function subexpr is entered with the
  3329. -- left operator (which is non-existent) priority of -1, which is lower
  3330. -- than all actual operators. Expr information is returned in parm v.
  3331. -- * used in multiple locations
  3332. ------------------------------------------------------------------------
  3333. function luaY:expr(ls, v)
  3334.   self:subexpr(ls, v, 0)
  3335. end
  3336.  
  3337. -- }====================================================================
  3338.  
  3339. --[[--------------------------------------------------------------------
  3340. -- Rules for Statements
  3341. ----------------------------------------------------------------------]]
  3342.  
  3343. ------------------------------------------------------------------------
  3344. -- checks next token, used as a look-ahead
  3345. -- * returns boolean instead of 0|1
  3346. -- * used in retstat(), chunk()
  3347. ------------------------------------------------------------------------
  3348. function luaY:block_follow(token)
  3349.   if token == "TK_ELSE" or token == "TK_ELSEIF" or token == "TK_END"
  3350.      or token == "TK_UNTIL" or token == "TK_EOS" then
  3351.     return true
  3352.   else
  3353.     return false
  3354.   end
  3355. end
  3356.  
  3357. ------------------------------------------------------------------------
  3358. -- parse a code block or unit
  3359. -- * used in multiple functions
  3360. ------------------------------------------------------------------------
  3361. function luaY:block(ls)
  3362.   -- block -> chunk
  3363.   local fs = ls.fs
  3364.   local bl = {}  -- BlockCnt
  3365.   self:enterblock(fs, bl, false)
  3366.   self:chunk(ls)
  3367.   assert(bl.breaklist == luaK.NO_JUMP)
  3368.   self:leaveblock(fs)
  3369. end
  3370.  
  3371. ------------------------------------------------------------------------
  3372. -- structure to chain all variables in the left-hand side of an
  3373. -- assignment
  3374. -- struct LHS_assign:
  3375. --   prev  -- (table: struct LHS_assign)
  3376. --   v  -- variable (global, local, upvalue, or indexed) (table: expdesc)
  3377. ------------------------------------------------------------------------
  3378.  
  3379. ------------------------------------------------------------------------
  3380. -- check whether, in an assignment to a local variable, the local variable
  3381. -- is needed in a previous assignment (to a table). If so, save original
  3382. -- local value in a safe place and use this safe copy in the previous
  3383. -- assignment.
  3384. -- * used in assignment()
  3385. ------------------------------------------------------------------------
  3386. function luaY:check_conflict(ls, lh, v)
  3387.   local fs = ls.fs
  3388.   local extra = fs.freereg  -- eventual position to save local variable
  3389.   local conflict = false
  3390.   while lh do
  3391.     if lh.v.k == "VINDEXED" then
  3392.       if lh.v.info == v.info then  -- conflict?
  3393.         conflict = true
  3394.         lh.v.info = extra  -- previous assignment will use safe copy
  3395.       end
  3396.       if lh.v.aux == v.info then  -- conflict?
  3397.         conflict = true
  3398.         lh.v.aux = extra  -- previous assignment will use safe copy
  3399.       end
  3400.     end
  3401.     lh = lh.prev
  3402.   end
  3403.   if conflict then
  3404.     luaK:codeABC(fs, "OP_MOVE", fs.freereg, v.info, 0)  -- make copy
  3405.     luaK:reserveregs(fs, 1)
  3406.   end
  3407. end
  3408.  
  3409. ------------------------------------------------------------------------
  3410. -- parse a variable assignment sequence
  3411. -- * recursively called
  3412. -- * used in exprstat()
  3413. ------------------------------------------------------------------------
  3414. function luaY:assignment(ls, lh, nvars)
  3415.   local e = {}  -- expdesc
  3416.   -- test was: VLOCAL <= lh->v.k && lh->v.k <= VINDEXED
  3417.   local c = lh.v.k
  3418.   self:check_condition(ls, c == "VLOCAL" or c == "VUPVAL" or c == "VGLOBAL"
  3419.                        or c == "VINDEXED", "syntax error")
  3420.   if self:testnext(ls, ",") then  -- assignment -> ',' primaryexp assignment
  3421.     local nv = {}  -- LHS_assign
  3422.           nv.v = {}
  3423.     nv.prev = lh
  3424.     self:primaryexp(ls, nv.v)
  3425.     if nv.v.k == "VLOCAL" then
  3426.       self:check_conflict(ls, lh, nv.v)
  3427.     end
  3428.     self:checklimit(ls.fs, nvars, self.LUAI_MAXCCALLS - ls.L.nCcalls,
  3429.                     "variables in assignment")
  3430.     self:assignment(ls, nv, nvars + 1)
  3431.   else  -- assignment -> '=' explist1
  3432.     self:checknext(ls, "=")
  3433.     local nexps = self:explist1(ls, e)
  3434.     if nexps ~= nvars then
  3435.       self:adjust_assign(ls, nvars, nexps, e)
  3436.       if nexps > nvars then
  3437.         ls.fs.freereg = ls.fs.freereg - (nexps - nvars)  -- remove extra values
  3438.       end
  3439.     else
  3440.       luaK:setoneret(ls.fs, e)  -- close last expression
  3441.       luaK:storevar(ls.fs, lh.v, e)
  3442.       return  -- avoid default
  3443.     end
  3444.   end
  3445.   self:init_exp(e, "VNONRELOC", ls.fs.freereg - 1)  -- default assignment
  3446.   luaK:storevar(ls.fs, lh.v, e)
  3447. end
  3448.  
  3449. ------------------------------------------------------------------------
  3450. -- parse condition in a repeat statement or an if control structure
  3451. -- * used in repeatstat(), test_then_block()
  3452. ------------------------------------------------------------------------
  3453. function luaY:cond(ls)
  3454.   -- cond -> exp
  3455.   local v = {}  -- expdesc
  3456.   self:expr(ls, v)  -- read condition
  3457.   if v.k == "VNIL" then v.k = "VFALSE" end  -- 'falses' are all equal here
  3458.   luaK:goiftrue(ls.fs, v)
  3459.   return v.f
  3460. end
  3461.  
  3462. ------------------------------------------------------------------------
  3463. -- parse a break statement
  3464. -- * used in statements()
  3465. ------------------------------------------------------------------------
  3466. function luaY:breakstat(ls)
  3467.   -- stat -> BREAK
  3468.   local fs = ls.fs
  3469.   local bl = fs.bl
  3470.   local upval = false
  3471.   while bl and not bl.isbreakable do
  3472.     if bl.upval then upval = true end
  3473.     bl = bl.previous
  3474.   end
  3475.   if not bl then
  3476.     luaX:syntaxerror(ls, "no loop to break")
  3477.   end
  3478.   if upval then
  3479.     luaK:codeABC(fs, "OP_CLOSE", bl.nactvar, 0, 0)
  3480.   end
  3481.   bl.breaklist = luaK:concat(fs, bl.breaklist, luaK:jump(fs))
  3482. end
  3483.  
  3484. ------------------------------------------------------------------------
  3485. -- parse a while-do control structure, body processed by block()
  3486. -- * with dynamic array sizes, MAXEXPWHILE + EXTRAEXP limits imposed by
  3487. --   the function's implementation can be removed
  3488. -- * used in statements()
  3489. ------------------------------------------------------------------------
  3490. function luaY:whilestat(ls, line)
  3491.   -- whilestat -> WHILE cond DO block END
  3492.   local fs = ls.fs
  3493.   local bl = {}  -- BlockCnt
  3494.   luaX:next(ls)  -- skip WHILE
  3495.   local whileinit = luaK:getlabel(fs)
  3496.   local condexit = self:cond(ls)
  3497.   self:enterblock(fs, bl, true)
  3498.   self:checknext(ls, "TK_DO")
  3499.   self:block(ls)
  3500.   luaK:patchlist(fs, luaK:jump(fs), whileinit)
  3501.   self:check_match(ls, "TK_END", "TK_WHILE", line)
  3502.   self:leaveblock(fs)
  3503.   luaK:patchtohere(fs, condexit)  -- false conditions finish the loop
  3504. end
  3505.  
  3506. ------------------------------------------------------------------------
  3507. -- parse a repeat-until control structure, body parsed by chunk()
  3508. -- * used in statements()
  3509. ------------------------------------------------------------------------
  3510. function luaY:repeatstat(ls, line)
  3511.   -- repeatstat -> REPEAT block UNTIL cond
  3512.   local fs = ls.fs
  3513.   local repeat_init = luaK:getlabel(fs)
  3514.   local bl1, bl2 = {}, {}  -- BlockCnt
  3515.   self:enterblock(fs, bl1, true)  -- loop block
  3516.   self:enterblock(fs, bl2, false)  -- scope block
  3517.   luaX:next(ls)  -- skip REPEAT
  3518.   self:chunk(ls)
  3519.   self:check_match(ls, "TK_UNTIL", "TK_REPEAT", line)
  3520.   local condexit = self:cond(ls)  -- read condition (inside scope block)
  3521.   if not bl2.upval then  -- no upvalues?
  3522.     self:leaveblock(fs)  -- finish scope
  3523.     luaK:patchlist(ls.fs, condexit, repeat_init)  -- close the loop
  3524.   else  -- complete semantics when there are upvalues
  3525.     self:breakstat(ls)  -- if condition then break
  3526.     luaK:patchtohere(ls.fs, condexit)  -- else...
  3527.     self:leaveblock(fs)  -- finish scope...
  3528.     luaK:patchlist(ls.fs, luaK:jump(fs), repeat_init)  -- and repeat
  3529.   end
  3530.   self:leaveblock(fs)  -- finish loop
  3531. end
  3532.  
  3533. ------------------------------------------------------------------------
  3534. -- parse the single expressions needed in numerical for loops
  3535. -- * used in fornum()
  3536. ------------------------------------------------------------------------
  3537. function luaY:exp1(ls)
  3538.   local e = {}  -- expdesc
  3539.   self:expr(ls, e)
  3540.   local k = e.k
  3541.   luaK:exp2nextreg(ls.fs, e)
  3542.   return k
  3543. end
  3544.  
  3545. ------------------------------------------------------------------------
  3546. -- parse a for loop body for both versions of the for loop
  3547. -- * used in fornum(), forlist()
  3548. ------------------------------------------------------------------------
  3549. function luaY:forbody(ls, base, line, nvars, isnum)
  3550.   -- forbody -> DO block
  3551.   local bl = {}  -- BlockCnt
  3552.   local fs = ls.fs
  3553.   self:adjustlocalvars(ls, 3)  -- control variables
  3554.   self:checknext(ls, "TK_DO")
  3555.   local prep = isnum and luaK:codeAsBx(fs, "OP_FORPREP", base, luaK.NO_JUMP)
  3556.                      or luaK:jump(fs)
  3557.   self:enterblock(fs, bl, false)  -- scope for declared variables
  3558.   self:adjustlocalvars(ls, nvars)
  3559.   luaK:reserveregs(fs, nvars)
  3560.   self:block(ls)
  3561.   self:leaveblock(fs)  -- end of scope for declared variables
  3562.   luaK:patchtohere(fs, prep)
  3563.   local endfor = isnum and luaK:codeAsBx(fs, "OP_FORLOOP", base, luaK.NO_JUMP)
  3564.                        or luaK:codeABC(fs, "OP_TFORLOOP", base, 0, nvars)
  3565.   luaK:fixline(fs, line)  -- pretend that `OP_FOR' starts the loop
  3566.   luaK:patchlist(fs, isnum and endfor or luaK:jump(fs), prep + 1)
  3567. end
  3568.  
  3569. ------------------------------------------------------------------------
  3570. -- parse a numerical for loop, calls forbody()
  3571. -- * used in forstat()
  3572. ------------------------------------------------------------------------
  3573. function luaY:fornum(ls, varname, line)
  3574.   -- fornum -> NAME = exp1,exp1[,exp1] forbody
  3575.   local fs = ls.fs
  3576.   local base = fs.freereg
  3577.   self:new_localvarliteral(ls, "(for index)", 0)
  3578.   self:new_localvarliteral(ls, "(for limit)", 1)
  3579.   self:new_localvarliteral(ls, "(for step)", 2)
  3580.   self:new_localvar(ls, varname, 3)
  3581.   self:checknext(ls, '=')
  3582.   self:exp1(ls)  -- initial value
  3583.   self:checknext(ls, ",")
  3584.   self:exp1(ls)  -- limit
  3585.   if self:testnext(ls, ",") then
  3586.     self:exp1(ls)  -- optional step
  3587.   else  -- default step = 1
  3588.     luaK:codeABx(fs, "OP_LOADK", fs.freereg, luaK:numberK(fs, 1))
  3589.     luaK:reserveregs(fs, 1)
  3590.   end
  3591.   self:forbody(ls, base, line, 1, true)
  3592. end
  3593.  
  3594. ------------------------------------------------------------------------
  3595. -- parse a generic for loop, calls forbody()
  3596. -- * used in forstat()
  3597. ------------------------------------------------------------------------
  3598. function luaY:forlist(ls, indexname)
  3599.   -- forlist -> NAME {,NAME} IN explist1 forbody
  3600.   local fs = ls.fs
  3601.   local e = {}  -- expdesc
  3602.   local nvars = 0
  3603.   local base = fs.freereg
  3604.   -- create control variables
  3605.   self:new_localvarliteral(ls, "(for generator)", nvars)
  3606.   nvars = nvars + 1
  3607.   self:new_localvarliteral(ls, "(for state)", nvars)
  3608.   nvars = nvars + 1
  3609.   self:new_localvarliteral(ls, "(for control)", nvars)
  3610.   nvars = nvars + 1
  3611.   -- create declared variables
  3612.   self:new_localvar(ls, indexname, nvars)
  3613.   nvars = nvars + 1
  3614.   while self:testnext(ls, ",") do
  3615.     self:new_localvar(ls, self:str_checkname(ls), nvars)
  3616.     nvars = nvars + 1
  3617.   end
  3618.   self:checknext(ls, "TK_IN")
  3619.   local line = ls.linenumber
  3620.   self:adjust_assign(ls, 3, self:explist1(ls, e), e)
  3621.   luaK:checkstack(fs, 3)  -- extra space to call generator
  3622.   self:forbody(ls, base, line, nvars - 3, false)
  3623. end
  3624.  
  3625. ------------------------------------------------------------------------
  3626. -- initial parsing for a for loop, calls fornum() or forlist()
  3627. -- * used in statements()
  3628. ------------------------------------------------------------------------
  3629. function luaY:forstat(ls, line)
  3630.   -- forstat -> FOR (fornum | forlist) END
  3631.   local fs = ls.fs
  3632.   local bl = {}  -- BlockCnt
  3633.   self:enterblock(fs, bl, true)  -- scope for loop and control variables
  3634.   luaX:next(ls)  -- skip `for'
  3635.   local varname = self:str_checkname(ls)  -- first variable name
  3636.   local c = ls.t.token
  3637.   if c == "=" then
  3638.     self:fornum(ls, varname, line)
  3639.   elseif c == "," or c == "TK_IN" then
  3640.     self:forlist(ls, varname)
  3641.   else
  3642.     luaX:syntaxerror(ls, self:LUA_QL("=").." or "..self:LUA_QL("in").." expected")
  3643.   end
  3644.   self:check_match(ls, "TK_END", "TK_FOR", line)
  3645.   self:leaveblock(fs)  -- loop scope (`break' jumps to this point)
  3646. end
  3647.  
  3648. ------------------------------------------------------------------------
  3649. -- parse part of an if control structure, including the condition
  3650. -- * used in ifstat()
  3651. ------------------------------------------------------------------------
  3652. function luaY:test_then_block(ls)
  3653.   -- test_then_block -> [IF | ELSEIF] cond THEN block
  3654.   luaX:next(ls)  -- skip IF or ELSEIF
  3655.   local condexit = self:cond(ls)
  3656.   self:checknext(ls, "TK_THEN")
  3657.   self:block(ls)  -- `then' part
  3658.   return condexit
  3659. end
  3660.  
  3661. ------------------------------------------------------------------------
  3662. -- parse an if control structure
  3663. -- * used in statements()
  3664. ------------------------------------------------------------------------
  3665. function luaY:ifstat(ls, line)
  3666.   -- ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END
  3667.   local fs = ls.fs
  3668.   local escapelist = luaK.NO_JUMP
  3669.   local flist = self:test_then_block(ls)  -- IF cond THEN block
  3670.   while ls.t.token == "TK_ELSEIF" do
  3671.     escapelist = luaK:concat(fs, escapelist, luaK:jump(fs))
  3672.     luaK:patchtohere(fs, flist)
  3673.     flist = self:test_then_block(ls)  -- ELSEIF cond THEN block
  3674.   end
  3675.   if ls.t.token == "TK_ELSE" then
  3676.     escapelist = luaK:concat(fs, escapelist, luaK:jump(fs))
  3677.     luaK:patchtohere(fs, flist)
  3678.     luaX:next(ls)  -- skip ELSE (after patch, for correct line info)
  3679.     self:block(ls)  -- 'else' part
  3680.   else
  3681.     escapelist = luaK:concat(fs, escapelist, flist)
  3682.   end
  3683.   luaK:patchtohere(fs, escapelist)
  3684.   self:check_match(ls, "TK_END", "TK_IF", line)
  3685. end
  3686.  
  3687. ------------------------------------------------------------------------
  3688. -- parse a local function statement
  3689. -- * used in statements()
  3690. ------------------------------------------------------------------------
  3691. function luaY:localfunc(ls)
  3692.   local v, b = {}, {}  -- expdesc
  3693.   local fs = ls.fs
  3694.   self:new_localvar(ls, self:str_checkname(ls), 0)
  3695.   self:init_exp(v, "VLOCAL", fs.freereg)
  3696.   luaK:reserveregs(fs, 1)
  3697.   self:adjustlocalvars(ls, 1)
  3698.   self:body(ls, b, false, ls.linenumber)
  3699.   luaK:storevar(fs, v, b)
  3700.   -- debug information will only see the variable after this point!
  3701.   self:getlocvar(fs, fs.nactvar - 1).startpc = fs.pc
  3702. end
  3703.  
  3704. ------------------------------------------------------------------------
  3705. -- parse a local variable declaration statement
  3706. -- * used in statements()
  3707. ------------------------------------------------------------------------
  3708. function luaY:localstat(ls)
  3709.   -- stat -> LOCAL NAME {',' NAME} ['=' explist1]
  3710.   local nvars = 0
  3711.   local nexps
  3712.   local e = {}  -- expdesc
  3713.   repeat
  3714.     self:new_localvar(ls, self:str_checkname(ls), nvars)
  3715.     nvars = nvars + 1
  3716.   until not self:testnext(ls, ",")
  3717.   if self:testnext(ls, "=") then
  3718.     nexps = self:explist1(ls, e)
  3719.   else
  3720.     e.k = "VVOID"
  3721.     nexps = 0
  3722.   end
  3723.   self:adjust_assign(ls, nvars, nexps, e)
  3724.   self:adjustlocalvars(ls, nvars)
  3725. end
  3726.  
  3727. ------------------------------------------------------------------------
  3728. -- parse a function name specification
  3729. -- * used in funcstat()
  3730. ------------------------------------------------------------------------
  3731. function luaY:funcname(ls, v)
  3732.   -- funcname -> NAME {field} [':' NAME]
  3733.   local needself = false
  3734.   self:singlevar(ls, v)
  3735.   while ls.t.token == "." do
  3736.     self:field(ls, v)
  3737.   end
  3738.   if ls.t.token == ":" then
  3739.     needself = true
  3740.     self:field(ls, v)
  3741.   end
  3742.   return needself
  3743. end
  3744.  
  3745. ------------------------------------------------------------------------
  3746. -- parse a function statement
  3747. -- * used in statements()
  3748. ------------------------------------------------------------------------
  3749. function luaY:funcstat(ls, line)
  3750.   -- funcstat -> FUNCTION funcname body
  3751.   local v, b = {}, {}  -- expdesc
  3752.   luaX:next(ls)  -- skip FUNCTION
  3753.   local needself = self:funcname(ls, v)
  3754.   self:body(ls, b, needself, line)
  3755.   luaK:storevar(ls.fs, v, b)
  3756.   luaK:fixline(ls.fs, line)  -- definition 'happens' in the first line
  3757. end
  3758.  
  3759. ------------------------------------------------------------------------
  3760. -- parse a function call with no returns or an assignment statement
  3761. -- * used in statements()
  3762. ------------------------------------------------------------------------
  3763. function luaY:exprstat(ls)
  3764.   -- stat -> func | assignment
  3765.   local fs = ls.fs
  3766.   local v = {}  -- LHS_assign
  3767.         v.v = {}
  3768.   self:primaryexp(ls, v.v)
  3769.   if v.v.k == "VCALL" then  -- stat -> func
  3770.     luaP:SETARG_C(luaK:getcode(fs, v.v), 1)  -- call statement uses no results
  3771.   else  -- stat -> assignment
  3772.     v.prev = nil
  3773.     self:assignment(ls, v, 1)
  3774.   end
  3775. end
  3776.  
  3777. ------------------------------------------------------------------------
  3778. -- parse a return statement
  3779. -- * used in statements()
  3780. ------------------------------------------------------------------------
  3781. function luaY:retstat(ls)
  3782.   -- stat -> RETURN explist
  3783.   local fs = ls.fs
  3784.   local e = {}  -- expdesc
  3785.   local first, nret  -- registers with returned values
  3786.   luaX:next(ls)  -- skip RETURN
  3787.   if self:block_follow(ls.t.token) or ls.t.token == ";" then
  3788.     first, nret = 0, 0  -- return no values
  3789.   else
  3790.     nret = self:explist1(ls, e)  -- optional return values
  3791.     if self:hasmultret(e.k) then
  3792.       luaK:setmultret(fs, e)
  3793.       if e.k == "VCALL" and nret == 1 then  -- tail call?
  3794.         luaP:SET_OPCODE(luaK:getcode(fs, e), "OP_TAILCALL")
  3795.         assert(luaP:GETARG_A(luaK:getcode(fs, e)) == fs.nactvar)
  3796.       end
  3797.       first = fs.nactvar
  3798.       nret = self.LUA_MULTRET  -- return all values
  3799.     else
  3800.       if nret == 1 then  -- only one single value?
  3801.         first = luaK:exp2anyreg(fs, e)
  3802.       else
  3803.         luaK:exp2nextreg(fs, e)  -- values must go to the 'stack'
  3804.         first = fs.nactvar  -- return all 'active' values
  3805.         assert(nret == fs.freereg - first)
  3806.       end
  3807.     end--if
  3808.   end--if
  3809.   luaK:ret(fs, first, nret)
  3810. end
  3811.  
  3812. ------------------------------------------------------------------------
  3813. -- initial parsing for statements, calls a lot of functions
  3814. -- * returns boolean instead of 0|1
  3815. -- * used in chunk()
  3816. ------------------------------------------------------------------------
  3817. function luaY:statement(ls)
  3818.   local line = ls.linenumber  -- may be needed for error messages
  3819.   local c = ls.t.token
  3820.   if c == "TK_IF" then  -- stat -> ifstat
  3821.     self:ifstat(ls, line)
  3822.     return false
  3823.   elseif c == "TK_WHILE" then  -- stat -> whilestat
  3824.     self:whilestat(ls, line)
  3825.     return false
  3826.   elseif c == "TK_DO" then  -- stat -> DO block END
  3827.     luaX:next(ls)  -- skip DO
  3828.     self:block(ls)
  3829.     self:check_match(ls, "TK_END", "TK_DO", line)
  3830.     return false
  3831.   elseif c == "TK_FOR" then  -- stat -> forstat
  3832.     self:forstat(ls, line)
  3833.     return false
  3834.   elseif c == "TK_REPEAT" then  -- stat -> repeatstat
  3835.     self:repeatstat(ls, line)
  3836.     return false
  3837.   elseif c == "TK_FUNCTION" then  -- stat -> funcstat
  3838.     self:funcstat(ls, line)
  3839.     return false
  3840.   elseif c == "TK_LOCAL" then  -- stat -> localstat
  3841.     luaX:next(ls)  -- skip LOCAL
  3842.     if self:testnext(ls, "TK_FUNCTION") then  -- local function?
  3843.       self:localfunc(ls)
  3844.     else
  3845.       self:localstat(ls)
  3846.     end
  3847.     return false
  3848.   elseif c == "TK_RETURN" then  -- stat -> retstat
  3849.     self:retstat(ls)
  3850.     return true  -- must be last statement
  3851.   elseif c == "TK_BREAK" then  -- stat -> breakstat
  3852.     luaX:next(ls)  -- skip BREAK
  3853.     self:breakstat(ls)
  3854.     return true  -- must be last statement
  3855.   else
  3856.     self:exprstat(ls)
  3857.     return false  -- to avoid warnings
  3858.   end--if c
  3859. end
  3860.  
  3861. ------------------------------------------------------------------------
  3862. -- parse a chunk, which consists of a bunch of statements
  3863. -- * used in parser(), body(), block(), repeatstat()
  3864. ------------------------------------------------------------------------
  3865. function luaY:chunk(ls)
  3866.   -- chunk -> { stat [';'] }
  3867.   local islast = false
  3868.   self:enterlevel(ls)
  3869.   while not islast and not self:block_follow(ls.t.token) do
  3870.     islast = self:statement(ls)
  3871.     self:testnext(ls, ";")
  3872.     assert(ls.fs.f.maxstacksize >= ls.fs.freereg and
  3873.                ls.fs.freereg >= ls.fs.nactvar)
  3874.     ls.fs.freereg = ls.fs.nactvar  -- free registers
  3875.   end
  3876.   self:leavelevel(ls)
  3877. end
  3878.  
  3879. -- }======================================================================
  3880. return luaY
  3881. end
  3882. luaY=luaY()
  3883. local luaU = function ()
  3884.     local luaU = {}
  3885. local luaP = luaP
  3886.  
  3887. -- mark for precompiled code ('<esc>Lua') (from lua.h)
  3888. luaU.LUA_SIGNATURE = "\27Lua"
  3889.  
  3890. -- constants used by dumper (from lua.h)
  3891. luaU.LUA_TNUMBER  = 3
  3892. luaU.LUA_TSTRING  = 4
  3893. luaU.LUA_TNIL     = 0
  3894. luaU.LUA_TBOOLEAN = 1
  3895. luaU.LUA_TNONE    = -1
  3896.  
  3897. -- constants for header of binary files (from lundump.h)
  3898. luaU.LUAC_VERSION    = 0x51     -- this is Lua 5.1
  3899. luaU.LUAC_FORMAT     = 0        -- this is the official format
  3900. luaU.LUAC_HEADERSIZE = 12       -- size of header of binary files
  3901.  
  3902. --[[--------------------------------------------------------------------
  3903. -- Additional functions to handle chunk writing
  3904. -- * to use make_setS and make_setF, see test_ldump.lua elsewhere
  3905. ----------------------------------------------------------------------]]
  3906.  
  3907. ------------------------------------------------------------------------
  3908. -- create a chunk writer that writes to a string
  3909. -- * returns the writer function and a table containing the string
  3910. -- * to get the final result, look in buff.data
  3911. ------------------------------------------------------------------------
  3912. function luaU:make_setS()
  3913.   local buff = {}
  3914.         buff.data = ""
  3915.   local writer =
  3916.     function(s, buff)  -- chunk writer
  3917.       if not s then return 0 end
  3918.       buff.data = buff.data..s
  3919.       return 0
  3920.     end
  3921.   return writer, buff
  3922. end
  3923.  
  3924. ------------------------------------------------------------------------
  3925. -- create a chunk writer that writes to a file
  3926. -- * returns the writer function and a table containing the file handle
  3927. -- * if a nil is passed, then writer should close the open file
  3928. ------------------------------------------------------------------------
  3929.  
  3930. --[[
  3931. function luaU:make_setF(filename)
  3932.   local buff = {}
  3933.         buff.h = io.open(filename, "wb")
  3934.   if not buff.h then return nil end
  3935.   local writer =
  3936.     function(s, buff)  -- chunk writer
  3937.       if not buff.h then return 0 end
  3938.       if not s then
  3939.         if buff.h:close() then return 0 end
  3940.       else
  3941.         if buff.h:write(s) then return 0 end
  3942.       end
  3943.       return 1
  3944.     end
  3945.   return writer, buff
  3946. end--]]
  3947.  
  3948. ------------------------------------------------------------------------
  3949. -- works like the lobject.h version except that TObject used in these
  3950. -- scripts only has a 'value' field, no 'tt' field (native types used)
  3951. ------------------------------------------------------------------------
  3952. function luaU:ttype(o)
  3953.   local tt = type(o.value)
  3954.   if tt == "number" then return self.LUA_TNUMBER
  3955.   elseif tt == "string" then return self.LUA_TSTRING
  3956.   elseif tt == "nil" then return self.LUA_TNIL
  3957.   elseif tt == "boolean" then return self.LUA_TBOOLEAN
  3958.   else
  3959.     return self.LUA_TNONE  -- the rest should not appear
  3960.   end
  3961. end
  3962.  
  3963. -----------------------------------------------------------------------
  3964. -- converts a IEEE754 double number to an 8-byte little-endian string
  3965. -- * luaU:from_double() and luaU:from_int() are adapted from ChunkBake
  3966. -- * supports +/- Infinity, but not denormals or NaNs
  3967. -----------------------------------------------------------------------
  3968. function luaU:from_double(x)
  3969.   local function grab_byte(v)
  3970.     local c = v % 256
  3971.     return (v - c) / 256, string.char(c)
  3972.   end
  3973.   local sign = 0
  3974.   if x < 0 then sign = 1; x = -x end
  3975.   local mantissa, exponent = math.frexp(x)
  3976.   if x == 0 then -- zero
  3977.     mantissa, exponent = 0, 0
  3978.   elseif x == 1/0 then
  3979.     mantissa, exponent = 0, 2047
  3980.   else
  3981.     mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53)
  3982.     exponent = exponent + 1022
  3983.   end
  3984.   local v, byte = "" -- convert to bytes
  3985.   x = math.floor(mantissa)
  3986.   for i = 1,6 do
  3987.     x, byte = grab_byte(x); v = v..byte -- 47:0
  3988.   end
  3989.   x, byte = grab_byte(exponent * 16 + x); v = v..byte -- 55:48
  3990.   x, byte = grab_byte(sign * 128 + x); v = v..byte -- 63:56
  3991.   return v
  3992. end
  3993.  
  3994. -----------------------------------------------------------------------
  3995. -- converts a number to a little-endian 32-bit integer string
  3996. -- * input value assumed to not overflow, can be signed/unsigned
  3997. -----------------------------------------------------------------------
  3998. function luaU:from_int(x)
  3999.   local v = ""
  4000.   x = math.floor(x)
  4001.   if x < 0 then x = 4294967296 + x end  -- ULONG_MAX+1
  4002.   for i = 1, 4 do
  4003.     local c = x % 256
  4004.     v = v..string.char(c); x = math.floor(x / 256)
  4005.   end
  4006.   return v
  4007. end
  4008.  
  4009. --[[--------------------------------------------------------------------
  4010. -- Functions to make a binary chunk
  4011. -- * many functions have the size parameter removed, since output is
  4012. --   in the form of a string and some sizes are implicit or hard-coded
  4013. ----------------------------------------------------------------------]]
  4014.  
  4015. --[[--------------------------------------------------------------------
  4016. -- struct DumpState:
  4017. --   L  -- lua_State (not used in this script)
  4018. --   writer  -- lua_Writer (chunk writer function)
  4019. --   data  -- void* (chunk writer context or data already written)
  4020. --   strip  -- if true, don't write any debug information
  4021. --   status  -- if non-zero, an error has occured
  4022. ----------------------------------------------------------------------]]
  4023.  
  4024. ------------------------------------------------------------------------
  4025. -- dumps a block of bytes
  4026. -- * lua_unlock(D.L), lua_lock(D.L) unused
  4027. ------------------------------------------------------------------------
  4028. function luaU:DumpBlock(b, D)
  4029.   if D.status == 0 then
  4030.     -- lua_unlock(D->L);
  4031.     D.status = D.write(b, D.data)
  4032.     -- lua_lock(D->L);
  4033.   end
  4034. end
  4035.  
  4036. ------------------------------------------------------------------------
  4037. -- dumps a char
  4038. ------------------------------------------------------------------------
  4039. function luaU:DumpChar(y, D)
  4040.   self:DumpBlock(string.char(y), D)
  4041. end
  4042.  
  4043. ------------------------------------------------------------------------
  4044. -- dumps a 32-bit signed or unsigned integer (for int) (hard-coded)
  4045. ------------------------------------------------------------------------
  4046. function luaU:DumpInt(x, D)
  4047.   self:DumpBlock(self:from_int(x), D)
  4048. end
  4049.  
  4050. ------------------------------------------------------------------------
  4051. -- dumps a lua_Number (hard-coded as a double)
  4052. ------------------------------------------------------------------------
  4053. function luaU:DumpNumber(x, D)
  4054.   self:DumpBlock(self:from_double(x), D)
  4055. end
  4056.  
  4057. ------------------------------------------------------------------------
  4058. -- dumps a Lua string (size type is hard-coded)
  4059. ------------------------------------------------------------------------
  4060. function luaU:DumpString(s, D)
  4061.   if s == nil then
  4062.     self:DumpInt(0, D)
  4063.   else
  4064.     s = s.."\0"  -- include trailing '\0'
  4065.     self:DumpInt(#s, D)
  4066.     self:DumpBlock(s, D)
  4067.   end
  4068. end
  4069.  
  4070. ------------------------------------------------------------------------
  4071. -- dumps instruction block from function prototype
  4072. ------------------------------------------------------------------------
  4073. function luaU:DumpCode(f, D)
  4074.   local n = f.sizecode
  4075.   --was DumpVector
  4076.   self:DumpInt(n, D)
  4077.   for i = 0, n - 1 do
  4078.     self:DumpBlock(luaP:Instruction(f.code[i]), D)
  4079.   end
  4080. end
  4081.  
  4082. ------------------------------------------------------------------------
  4083. -- dump constant pool from function prototype
  4084. -- * bvalue(o), nvalue(o) and rawtsvalue(o) macros removed
  4085. ------------------------------------------------------------------------
  4086. function luaU:DumpConstants(f, D)
  4087.   local n = f.sizek
  4088.   self:DumpInt(n, D)
  4089.   for i = 0, n - 1 do
  4090.     local o = f.k[i]  -- TValue
  4091.     local tt = self:ttype(o)
  4092.     self:DumpChar(tt, D)
  4093.     if tt == self.LUA_TNIL then
  4094.     elseif tt == self.LUA_TBOOLEAN then
  4095.       self:DumpChar(o.value and 1 or 0, D)
  4096.     elseif tt == self.LUA_TNUMBER then
  4097.       self:DumpNumber(o.value, D)
  4098.     elseif tt == self.LUA_TSTRING then
  4099.       self:DumpString(o.value, D)
  4100.     else
  4101.       --lua_assert(0)  -- cannot happen
  4102.     end
  4103.   end
  4104.   n = f.sizep
  4105.   self:DumpInt(n, D)
  4106.   for i = 0, n - 1 do
  4107.     self:DumpFunction(f.p[i], f.source, D)
  4108.   end
  4109. end
  4110.  
  4111. ------------------------------------------------------------------------
  4112. -- dump debug information
  4113. ------------------------------------------------------------------------
  4114. function luaU:DumpDebug(f, D)
  4115.   local n
  4116.   n = D.strip and 0 or f.sizelineinfo           -- dump line information
  4117.   --was DumpVector
  4118.   self:DumpInt(n, D)
  4119.   for i = 0, n - 1 do
  4120.     self:DumpInt(f.lineinfo[i], D)
  4121.   end
  4122.   n = D.strip and 0 or f.sizelocvars            -- dump local information
  4123.   self:DumpInt(n, D)
  4124.   for i = 0, n - 1 do
  4125.     self:DumpString(f.locvars[i].varname, D)
  4126.     self:DumpInt(f.locvars[i].startpc, D)
  4127.     self:DumpInt(f.locvars[i].endpc, D)
  4128.   end
  4129.   n = D.strip and 0 or f.sizeupvalues           -- dump upvalue information
  4130.   self:DumpInt(n, D)
  4131.   for i = 0, n - 1 do
  4132.     self:DumpString(f.upvalues[i], D)
  4133.   end
  4134. end
  4135.  
  4136. ------------------------------------------------------------------------
  4137. -- dump child function prototypes from function prototype
  4138. ------------------------------------------------------------------------
  4139. function luaU:DumpFunction(f, p, D)
  4140.   local source = f.source
  4141.   if source == p or D.strip then source = nil end
  4142.   self:DumpString(source, D)
  4143.   self:DumpInt(f.lineDefined, D)
  4144.   self:DumpInt(f.lastlinedefined, D)
  4145.   self:DumpChar(f.nups, D)
  4146.   self:DumpChar(f.numparams, D)
  4147.   self:DumpChar(f.is_vararg, D)
  4148.   self:DumpChar(f.maxstacksize, D)
  4149.   self:DumpCode(f, D)
  4150.   self:DumpConstants(f, D)
  4151.   self:DumpDebug(f, D)
  4152. end
  4153.  
  4154. ------------------------------------------------------------------------
  4155. -- dump Lua header section (some sizes hard-coded)
  4156. ------------------------------------------------------------------------
  4157. function luaU:DumpHeader(D)
  4158.   local h = self:header()
  4159.   assert(#h == self.LUAC_HEADERSIZE) -- fixed buffer now an assert
  4160.   self:DumpBlock(h, D)
  4161. end
  4162.  
  4163. ------------------------------------------------------------------------
  4164. -- make header (from lundump.c)
  4165. -- returns the header string
  4166. ------------------------------------------------------------------------
  4167. function luaU:header()
  4168.  local x = 1
  4169.  return self.LUA_SIGNATURE..
  4170.         string.char(
  4171.           self.LUAC_VERSION,
  4172.           self.LUAC_FORMAT,
  4173.           x,                    -- endianness (1=little)
  4174.           4,                    -- sizeof(int)
  4175.           4,                    -- sizeof(size_t)
  4176.           4,                    -- sizeof(Instruction)
  4177.           8,                    -- sizeof(lua_Number)
  4178.           0)                    -- is lua_Number integral?
  4179. end
  4180.  
  4181. ------------------------------------------------------------------------
  4182. -- dump Lua function as precompiled chunk
  4183. -- (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
  4184. -- * w, data are created from make_setS, make_setF
  4185. ------------------------------------------------------------------------
  4186. function luaU:dump(L, f, w, data, strip)
  4187.   local D = {}  -- DumpState
  4188.   D.L = L
  4189.   D.write = w
  4190.   D.data = data
  4191.   D.strip = strip
  4192.   D.status = 0
  4193.   self:DumpHeader(D)
  4194.   self:DumpFunction(f, nil, D)
  4195.   -- added: for a chunk writer writing to a file, this final call with
  4196.   -- nil data is to indicate to the writer to close the file
  4197.   D.write(nil, D.data)
  4198.   return D.status
  4199. end
  4200.  
  4201. return luaU
  4202. end
  4203. luaU=luaU()
  4204. local lbi = function ()
  4205. local advanced_debug
  4206.  
  4207. local lua_opcode_types = {
  4208.     "ABC",  "ABx", "ABC",  "ABC",
  4209.     "ABC",  "ABx", "ABC",  "ABx",
  4210.     "ABC",  "ABC", "ABC",  "ABC",
  4211.     "ABC",  "ABC", "ABC",  "ABC",
  4212.     "ABC",  "ABC", "ABC",  "ABC",
  4213.     "ABC",  "ABC", "AsBx", "ABC",
  4214.     "ABC",  "ABC", "ABC",  "ABC",
  4215.     "ABC",  "ABC", "ABC",  "AsBx",
  4216.     "AsBx", "ABC", "ABC", "ABC",
  4217.     "ABx",  "ABC",
  4218. }
  4219.  
  4220. local lua_opcode_names = {
  4221.     "MOVE",     "LOADK",     "LOADBOOL", "LOADNIL",
  4222.     "GETUPVAL", "GETGLOBAL", "GETTABLE", "SETGLOBAL",
  4223.     "SETUPVAL", "SETTABLE",  "NEWTABLE", "SELF",
  4224.     "ADD",      "SUB",       "MUL",      "DIV",
  4225.     "MOD",      "POW",       "UNM",      "NOT",
  4226.     "LEN",      "CONCAT",    "JMP",      "EQ",
  4227.     "LT",       "LE",        "TEST",     "TESTSET",
  4228.     "CALL",     "TAILCALL",  "RETURN",   "FORLOOP",
  4229.     "FORPREP",  "TFORLOOP",  "SETLIST",  "CLOSE",
  4230.     "CLOSURE",  "VARARG"
  4231. };
  4232.  
  4233. local function get_bits(input, n, n2)
  4234.     if n2 then
  4235.         local total = 0
  4236.         local digitn = 0
  4237.         for i = n, n2 do
  4238.             total = total + 2^digitn*get_bits(input, i)
  4239.             digitn = digitn + 1
  4240.         end
  4241.         return total
  4242.     else
  4243.         local pn = 2^(n-1)
  4244.         return (input % (pn + pn) >= pn) and 1 or 0
  4245.     end
  4246. end
  4247.  
  4248. local function decode_bytecode(bytecode)
  4249.     local index = 1
  4250.     local big_endian = false
  4251.     local int_size;
  4252.     local size_t;
  4253.  
  4254.     -- Actual binary decoding functions. Dependant on the bytecode.
  4255.     local get_int, get_size_t;
  4256.  
  4257.     -- Binary decoding helper functions
  4258.     local get_int8, get_int32, get_int64, get_float64, get_string;
  4259.     do
  4260.         function get_int8()
  4261.             local a = bytecode:byte(index, index);
  4262.             index = index + 1
  4263.             return a
  4264.         end
  4265.         function get_int32()
  4266.             local a, b, c, d = bytecode:byte(index, index + 3);
  4267.             index = index + 4;
  4268.             return d*16777216 + c*65536 + b*256 + a
  4269.         end
  4270.         function get_int64()
  4271.             local a = get_int32();
  4272.             local b = get_int32();
  4273.             return b*4294967296 + a;
  4274.         end
  4275.         function get_float64()
  4276.             local a = get_int32()
  4277.             local b = get_int32()
  4278.             return (-2*get_bits(b, 32)+1)*(2^(get_bits(b, 21, 31)-1023))*
  4279.                    ((get_bits(b, 1, 20)*(2^32) + a)/(2^52)+1)
  4280.         end
  4281.         function get_string(len)
  4282.             local str;
  4283.             if len then
  4284.                 str = bytecode:sub(index, index + len - 1);
  4285.                 index = index + len;
  4286.             else
  4287.                 len = get_size_t();
  4288.                 if len == 0 then return; end
  4289.                 str = bytecode:sub(index, index + len - 1);
  4290.                 index = index + len;
  4291.             end
  4292.             return str;
  4293.         end
  4294.     end
  4295.  
  4296.     local function decode_chunk()
  4297.         local chunk;
  4298.         local instructions = {};
  4299.         local constants    = {};
  4300.         local prototypes   = {};
  4301.         local debug = {
  4302.             lines = {};
  4303.         };
  4304.  
  4305.         chunk = {
  4306.             instructions = instructions;
  4307.             constants    = constants;
  4308.             prototypes   = prototypes;
  4309.             debug = debug;
  4310.         };
  4311.  
  4312.         local num;
  4313.  
  4314.         chunk.name       = get_string();-- Function name
  4315.         chunk.first_line = get_int();   -- First line
  4316.         chunk.last_line  = get_int();   -- Last  line
  4317.  
  4318.         if chunk.name then chunk.name = chunk.name:sub(1, -2); end
  4319.        
  4320.         chunk.upvalues  = get_int8();
  4321.         chunk.arguments = get_int8();
  4322.         chunk.varg      = get_int8();
  4323.         chunk.stack     = get_int8();
  4324.  
  4325.         -- TODO: realign lists to 1
  4326.         -- Decode instructions
  4327.         do
  4328.             num = get_int();
  4329.             for i = 1, num do
  4330.                 local instruction = {
  4331.                     -- opcode = opcode number;
  4332.                     -- type   = [ABC, ABx, AsBx]
  4333.                     -- A, B, C, Bx, or sBx depending on type
  4334.                 };
  4335.  
  4336.                 local data   = get_int32();
  4337.                 local opcode = get_bits(data, 1, 6);
  4338.                 local type   = lua_opcode_types[opcode + 1];
  4339.  
  4340.                 instruction.opcode = opcode;
  4341.                 instruction.type   = type;
  4342.                
  4343.                 instruction.A = get_bits(data, 7, 14);
  4344.                 if type == "ABC" then
  4345.                     instruction.B = get_bits(data, 24, 32);
  4346.                     instruction.C = get_bits(data, 15, 23);
  4347.                 elseif type == "ABx" then
  4348.                     instruction.Bx = get_bits(data, 15, 32);
  4349.                 elseif type == "AsBx" then
  4350.                     instruction.sBx = get_bits(data, 15, 32) - 131071;
  4351.                 end
  4352.  
  4353.                 instructions[i] = instruction;
  4354.             end
  4355.         end
  4356.  
  4357.         -- Decode constants
  4358.         do
  4359.             num = get_int();
  4360.             for i = 1, num do
  4361.                 local constant = {
  4362.                     -- type = constant type;
  4363.                     -- data = constant data;
  4364.                 };
  4365.                 local type = get_int8();
  4366.                 constant.type = type;
  4367.  
  4368.                 if type == 1 then
  4369.                     constant.data = (get_int8() ~= 0);
  4370.                 elseif type == 3 then
  4371.                     constant.data = get_float64();
  4372.                 elseif type == 4 then
  4373.                     constant.data = get_string():sub(1, -2);
  4374.                 end
  4375.  
  4376.                 constants[i-1] = constant;
  4377.             end
  4378.         end
  4379.  
  4380.         -- Decode Prototypes
  4381.         do
  4382.             num = get_int();
  4383.             for i = 1, num do
  4384.                 prototypes[i-1] = decode_chunk();
  4385.             end
  4386.         end
  4387.  
  4388.         -- Decode debug info
  4389.         -- Not all of which is used yet.
  4390.         do
  4391.             -- line numbers
  4392.             local data = debug.lines
  4393.             num = get_int();
  4394.             for i = 1, num do
  4395.                 data[i] = get_int32();
  4396.             end
  4397.  
  4398.             -- locals
  4399.             num = get_int();
  4400.             for i = 1, num do
  4401.                 get_string():sub(1, -2);    -- local name
  4402.                 get_int32();    -- local start PC
  4403.                 get_int32();    -- local end   PC
  4404.             end
  4405.  
  4406.             -- upvalues
  4407.             num = get_int();
  4408.             for i = 1, num do
  4409.                 get_string();   -- upvalue name
  4410.             end
  4411.         end
  4412.  
  4413.         return chunk;
  4414.     end
  4415.  
  4416.     -- Verify bytecode header
  4417.     do
  4418.         assert(get_string(4) == "\27Lua", "Lua bytecode expected.");
  4419.         assert(get_int8() == 0x51, "Only Lua 5.1 is supported.");
  4420.         get_int8();     -- Oficial bytecode
  4421.         big_endian = (get_int8() == 0);
  4422.         int_size = get_int8();
  4423.         size_t   = get_int8();
  4424.  
  4425.         if int_size == 4 then
  4426.             get_int = get_int32;
  4427.         elseif int_size == 8 then
  4428.             get_int = get_int64;
  4429.         else
  4430.             -- TODO: refactor errors into table
  4431.             error("Unsupported bytecode target platform");
  4432.         end
  4433.  
  4434.         if size_t == 4 then
  4435.             get_size_t = get_int32;
  4436.         elseif size_t == 8 then
  4437.             get_size_t = get_int64;
  4438.         else
  4439.             error("Unsupported bytecode target platform");
  4440.         end
  4441.  
  4442.         assert(get_string(3) == "\4\8\0",
  4443.                "Unsupported bytecode target platform");
  4444.     end
  4445.  
  4446.     return decode_chunk();
  4447. end
  4448.  
  4449. local function handle_return(...)
  4450.     local c = select("#", ...)
  4451.     local t = {...}
  4452.     return c, t
  4453. end
  4454.  
  4455. local function create_wrapper(cache, upvalues)
  4456.     local instructions = cache.instructions;
  4457.     local constants    = cache.constants;
  4458.     local prototypes   = cache.prototypes;
  4459.    
  4460.     local stack, top
  4461.     local environment
  4462.     local IP = 1;   -- instruction pointer
  4463.     local vararg, vararg_size
  4464.  
  4465.     local opcode_funcs = {
  4466.         [0]  = function(instruction)    -- MOVE
  4467.             stack[instruction.A] = stack[instruction.B];
  4468.         end,
  4469.         [1]  = function(instruction)    -- LOADK
  4470.             stack[instruction.A] = constants[instruction.Bx].data;
  4471.         end,
  4472.         [2]  = function(instruction)    -- LOADBOOL
  4473.             stack[instruction.A] = instruction.B ~= 0
  4474.             if instruction.C ~= 0 then
  4475.                 IP = IP + 1
  4476.             end
  4477.         end,
  4478.         [3]  = function(instruction)    -- LOADNIL
  4479.             local stack = stack
  4480.             for i = instruction.A, instruction.B do
  4481.                 stack[i] = nil
  4482.             end
  4483.         end,
  4484.         [4] = function(instruction)     -- GETUPVAL
  4485.             stack[instruction.A] = upvalues[instruction.B]
  4486.         end,
  4487.         [5]  = function(instruction)    -- GETGLOBAL
  4488.             local key = constants[instruction.Bx].data;
  4489.             stack[instruction.A] = environment[key];
  4490.         end,
  4491.         [6]  = function(instruction)    -- GETTABLE
  4492.             local C = instruction.C
  4493.             local stack = stack
  4494.             C = C > 255 and constants[C-256].data or stack[C]
  4495.             stack[instruction.A] = stack[instruction.B][C];
  4496.         end,
  4497.         [7]  = function(instruction)    -- SETGLOBAL
  4498.             local key = constants[instruction.Bx].data;
  4499.             environment[key] = stack[instruction.A];
  4500.         end,
  4501.         [8] = function (instruction)    -- SETUPVAL
  4502.             upvalues[instruction.B] = stack[instruction.A]
  4503.         end,
  4504.         [9] = function (instruction)    -- SETTABLE
  4505.             local B = instruction.B;
  4506.             local C = instruction.C;
  4507.             local stack, constants = stack, constants;
  4508.            
  4509.             B = B > 255 and constants[B-256].data or stack[B];
  4510.             C = C > 255 and constants[C-256].data or stack[C];
  4511.            
  4512.             stack[instruction.A][B] = C
  4513.         end,
  4514.         [10] = function (instruction)   -- NEWTABLE
  4515.             stack[instruction.A] = {}
  4516.         end,
  4517.         [11] = function (instruction)   -- SELF
  4518.             local A = instruction.A
  4519.             local B = instruction.B
  4520.             local C = instruction.C
  4521.             local stack = stack
  4522.            
  4523.             B = stack[B]
  4524.             C = C > 255 and constants[C-256].data or stack[C]
  4525.            
  4526.             stack[A+1] = B
  4527.             stack[A]   = B[C]
  4528.         end,
  4529.         [12] = function(instruction)    -- ADD
  4530.             local B = instruction.B;
  4531.             local C = instruction.C;
  4532.             local stack, constants = stack, constants;
  4533.            
  4534.             B = B > 255 and constants[B-256].data or stack[B];
  4535.             C = C > 255 and constants[C-256].data or stack[C];
  4536.            
  4537.             stack[instruction.A] = B+C;
  4538.         end,
  4539.         [13] = function(instruction)    -- SUB
  4540.             local B = instruction.B;
  4541.             local C = instruction.C;
  4542.             local stack, constants = stack, constants;
  4543.            
  4544.             B = B > 255 and constants[B-256].data or stack[B];
  4545.             C = C > 255 and constants[C-256].data or stack[C];
  4546.            
  4547.             stack[instruction.A] = B - C;  
  4548.         end,
  4549.         [14] = function(instruction)    -- MUL
  4550.             local B = instruction.B;
  4551.             local C = instruction.C;
  4552.             local stack, constants = stack, constants;
  4553.            
  4554.             B = B > 255 and constants[B-256].data or stack[B];
  4555.             C = C > 255 and constants[C-256].data or stack[C];
  4556.            
  4557.             stack[instruction.A] = B * C;
  4558.         end,
  4559.         [15] = function(instruction)    --DIV
  4560.             local B = instruction.B;
  4561.             local C = instruction.C;
  4562.             local stack, constants = stack, constants;
  4563.            
  4564.             B = B > 255 and constants[B-256].data or stack[B];
  4565.             C = C > 255 and constants[C-256].data or stack[C];
  4566.            
  4567.             stack[instruction.A] = B / C;
  4568.         end,
  4569.         [16] = function(instruction)    -- MOD
  4570.             local B = instruction.B;
  4571.             local C = instruction.C;
  4572.             local stack, constants = stack, constants;
  4573.            
  4574.             B = B > 255 and constants[B-256].data or stack[B];
  4575.             C = C > 255 and constants[C-256].data or stack[C];
  4576.            
  4577.             stack[instruction.A] = B % C;      
  4578.         end,
  4579.         [17] = function(instruction)    -- POW
  4580.             local B = instruction.B;
  4581.             local C = instruction.C;
  4582.             local stack, constants = stack, constants;
  4583.            
  4584.             B = B > 255 and constants[B-256].data or stack[B];
  4585.             C = C > 255 and constants[C-256].data or stack[C];
  4586.            
  4587.             stack[instruction.A] = B ^ C;      
  4588.         end,
  4589.         [18] = function(instruction)    -- UNM
  4590.             stack[instruction.A] = -stack[instruction.B]
  4591.         end,
  4592.         [19] = function(instruction)    -- NOT
  4593.             stack[instruction.A] = not stack[instruction.B]
  4594.         end,
  4595.         [20] = function(instruction)    -- LEN
  4596.             stack[instruction.A] = #stack[instruction.B]
  4597.         end,
  4598.         [21] = function(instruction)    -- CONCAT
  4599.             local B = instruction.B
  4600.             local result = stack[B]
  4601.             for i = B+1, instruction.C do
  4602.                 result = result .. stack[i]
  4603.             end
  4604.             stack[instruction.A] = result
  4605.         end,
  4606.         [22] = function(instruction)    -- JUMP
  4607.             IP = IP + instruction.sBx
  4608.         end,
  4609.         [23] = function(instruction)    -- EQ
  4610.             local A = instruction.A
  4611.             local B = instruction.B
  4612.             local C = instruction.C
  4613.             local stack, constants = stack, constants
  4614.            
  4615.             A = A ~= 0
  4616.             B = B > 255 and constants[B-256].data or stack[B]
  4617.             C = C > 255 and constants[C-256].data or stack[C]
  4618.             if (B == C) ~= A then
  4619.                 IP = IP + 1
  4620.             end
  4621.         end,
  4622.         [24] = function(instruction)    -- LT
  4623.             local A = instruction.A
  4624.             local B = instruction.B
  4625.             local C = instruction.C
  4626.             local stack, constants = stack, constants
  4627.            
  4628.             A = A ~= 0
  4629.             B = B > 255 and constants[B-256].data or stack[B]
  4630.             C = C > 255 and constants[C-256].data or stack[C]
  4631.             if (B < C) ~= A then
  4632.                 IP = IP + 1
  4633.             end    
  4634.         end,
  4635.         [25] = function(instruction)    -- LT
  4636.             local A = instruction.A
  4637.             local B = instruction.B
  4638.             local C = instruction.C
  4639.             local stack, constants = stack, constants
  4640.            
  4641.             A = A ~= 0
  4642.             B = B > 255 and constants[B-256].data or stack[B]
  4643.             C = C > 255 and constants[C-256].data or stack[C]
  4644.             if (B <= C) ~= A then
  4645.                 IP = IP + 1
  4646.             end    
  4647.         end,
  4648.         [26] = function(instruction)    -- TEST
  4649.             if stack[instruction.A] == (instruction.C ~= 0) then
  4650.                 IP = IP + 1
  4651.             end
  4652.         end,
  4653.         [27] = function(instruction)    -- TESTSET
  4654.             local stack = stack
  4655.             local B = stack[instruction.B]
  4656.            
  4657.             if B == (instruction.C ~= 0) then
  4658.                 IP = IP + 1
  4659.             else
  4660.                 stack[instruction.A] = B
  4661.             end
  4662.         end,
  4663.         [28] = function(instruction)    -- CALL
  4664.             local A = instruction.A;
  4665.             local B = instruction.B;
  4666.             local C = instruction.C;
  4667.             local stack = stack;
  4668.             local args, results;
  4669.             local limit, loop
  4670.            
  4671.             args = {};
  4672.             if B ~= 1 then
  4673.                 if B ~= 0 then
  4674.                     limit = A+B-1;
  4675.                 else
  4676.                     limit = top
  4677.                 end
  4678.                
  4679.                 loop = 0
  4680.                 for i = A+1, limit do
  4681.                     loop = loop + 1
  4682.                     args[loop] = stack[i];
  4683.                 end
  4684.                
  4685.                 limit, results = handle_return(stack[A](unpack(args, 1, limit-A)))
  4686.             else
  4687.                 limit, results = handle_return(stack[A]())
  4688.             end
  4689.            
  4690.             top = A - 1
  4691.        
  4692.             if C ~= 1 then
  4693.                 if C ~= 0 then
  4694.                     limit = A+C-2;
  4695.                 else
  4696.                     limit = limit+A
  4697.                 end
  4698.                
  4699.                 loop = 0;
  4700.                 for i = A, limit do
  4701.                     loop = loop + 1;
  4702.                     stack[i] = results[loop];
  4703.                 end
  4704.             end
  4705.         end,
  4706.         [29] = function (instruction)   -- TAILCALL
  4707.             local A = instruction.A;
  4708.             local B = instruction.B;
  4709.             local C = instruction.C;
  4710.             local stack = stack;
  4711.             local args, results;
  4712.             local top, limit, loop = top
  4713.            
  4714.             args = {};
  4715.             if B ~= 1 then
  4716.                 if B ~= 0 then
  4717.                     limit = A+B-1;
  4718.                 else
  4719.                     limit = top
  4720.                 end
  4721.                
  4722.                 loop = 0
  4723.                 for i = A+1, limit do
  4724.                     loop = loop + 1
  4725.                     args[#args+1] = stack[i];
  4726.                 end
  4727.                
  4728.                 results = {stack[A](unpack(args, 1, limit-A))};
  4729.             else
  4730.                 results = {stack[A]()};
  4731.             end
  4732.            
  4733.             return true, results
  4734.         end,
  4735.         [30] = function(instruction) -- RETURN
  4736.             --TODO: CLOSE
  4737.             local A = instruction.A;
  4738.             local B = instruction.B;
  4739.             local stack = stack;
  4740.             local limit;
  4741.             local loop, output;
  4742.                        
  4743.             if B == 1 then
  4744.                 return true;
  4745.             end
  4746.             if B == 0 then
  4747.                 limit = top
  4748.             else
  4749.                 limit = A + B - 2;
  4750.             end
  4751.            
  4752.             output = {};
  4753.             local loop = 0
  4754.             for i = A, limit do
  4755.                 loop = loop + 1
  4756.                 output[loop] = stack[i];
  4757.             end
  4758.             return true, output;
  4759.         end,
  4760.         [31] = function(instruction)    -- FORLOOP
  4761.             local A = instruction.A
  4762.             local stack = stack
  4763.            
  4764.             local step = stack[A+2]
  4765.             local index = stack[A] + step
  4766.             stack[A] = index
  4767.            
  4768.             if step > 0 then
  4769.                 if index <= stack[A+1] then
  4770.                     IP = IP + instruction.sBx
  4771.                     stack[A+3] = index
  4772.                 end
  4773.             else
  4774.                 if index >= stack[A+1] then
  4775.                     IP = IP + instruction.sBx
  4776.                     stack[A+3] = index
  4777.                 end
  4778.             end
  4779.         end,
  4780.         [32] = function(instruction)    -- FORPREP
  4781.             local A = instruction.A
  4782.             local stack = stack
  4783.            
  4784.             stack[A] = stack[A] - stack[A+2]
  4785.             IP = IP + instruction.sBx
  4786.         end,
  4787.         [33] = function(instruction)    -- TFORLOOP
  4788.             local A = instruction.A
  4789.             local B = instruction.B
  4790.             local C = instruction.C
  4791.             local stack = stack
  4792.            
  4793.             local offset = A+2
  4794.             local result = {stack[A](stack[A+1], stack[A+2])}
  4795.             for i = 1, C do
  4796.                 stack[offset+i] = result[i]
  4797.             end
  4798.            
  4799.             if stack[A+3] ~= nil then
  4800.                 stack[A+2] = stack[A+3]
  4801.             else
  4802.                 IP = IP + 1
  4803.             end
  4804.         end,
  4805.         [34] = function(instruction)    -- SETLIST
  4806.             local A = instruction.A
  4807.             local B = instruction.B
  4808.             local C = instruction.C
  4809.             local stack = stack
  4810.  
  4811.             if C == 0 then
  4812.                 error("NYI: extended SETLIST")
  4813.             else
  4814.                 local offset = (C - 1) * 50
  4815.                 local t = stack[A]
  4816.                
  4817.                 if B == 0 then
  4818.                     B = top
  4819.                 end
  4820.                 for i = 1, B do
  4821.                     t[offset+i] = stack[A+i]   
  4822.                 end            
  4823.             end
  4824.         end,
  4825.         [35] = function(instruction)    -- CLOSE
  4826.             --io.stderr:write("NYI: CLOSE")
  4827.             --io.stderr:flush()
  4828.         end,
  4829.         [36] = function(instruction)    -- CLOSURE
  4830.             local proto = prototypes[instruction.Bx]
  4831.             local instructions = instructions
  4832.             local stack = stack
  4833.            
  4834.             local indices = {}
  4835.             local new_upvals = setmetatable({},
  4836.                 {
  4837.                     __index = function(t, k)
  4838.                         local upval = indices[k]
  4839.                         return upval.segment[upval.offset]
  4840.                     end,
  4841.                     __newindex = function(t, k, v)
  4842.                         local upval = indices[k]
  4843.                         upval.segment[upval.offset] = v
  4844.                     end
  4845.                 }
  4846.             )
  4847.             for i = 1, proto.upvalues do
  4848.                 local movement = instructions[IP]
  4849.                 if movement.opcode == 0 then -- MOVE
  4850.                     indices[i-1] = {segment = stack, offset = movement.B}
  4851.                 elseif instructions[IP].opcode == 4 then -- GETUPVAL
  4852.                     indices[i-1] = {segment = upvalues, offset = movement.B}
  4853.                 end
  4854.                 IP = IP + 1
  4855.             end
  4856.            
  4857.             local _, func = create_wrapper(proto, new_upvals)
  4858.             stack[instruction.A] = func
  4859.         end,
  4860.         [37] = function(instruction)    -- VARARG
  4861.             local A = instruction.A
  4862.             local B = instruction.B
  4863.             local stack, vararg = stack, vararg
  4864.            
  4865.             for i = A, A + (B > 0 and B - 1 or vararg_size) do
  4866.                 stack[i] = vararg[i - A]
  4867.             end
  4868.         end,
  4869.     }
  4870.    
  4871.     local function loop()
  4872.         local instructions = instructions
  4873.         local instruction, a, b
  4874.        
  4875.         while true do
  4876.             instruction = instructions[IP];
  4877.             IP = IP + 1
  4878.             a, b = opcode_funcs[instruction.opcode](instruction);
  4879.             if a then
  4880.                 return b;
  4881.             end
  4882.         end
  4883.     end
  4884.  
  4885.     local debugging = {
  4886.         get_stack = function()
  4887.             return stack;
  4888.         end;
  4889.         get_IP = function()
  4890.             return IP;
  4891.         end
  4892.     };
  4893.  
  4894.     local function func(...)
  4895.         local local_stack = {};
  4896.         local ghost_stack = {};
  4897.  
  4898.         top = -1
  4899.         stack = setmetatable(local_stack, {
  4900.             __index = ghost_stack;
  4901.             __newindex = function(t, k, v)
  4902.                 if k > top and v then
  4903.                     top = k
  4904.                 end
  4905.                 ghost_stack[k] = v
  4906.             end;
  4907.         })
  4908.         local args = {...};
  4909.         vararg = {}
  4910.         vararg_size = select("#", ...) - 1
  4911.         for i = 0, vararg_size do
  4912.             local_stack[i] = args[i+1];
  4913.             vararg[i] = args[i+1]
  4914.         end
  4915.        
  4916.         environment = getfenv();
  4917.         IP = 1;
  4918.         local thread = coroutine.create(loop)
  4919.         local a, b = coroutine.resume(thread)
  4920.  
  4921.         if a then
  4922.             if b then
  4923.                 return unpack(b);
  4924.             end
  4925.             return;
  4926.         else
  4927.             if advanced_debug then
  4928.                 --TODO advanced debugging
  4929.             else
  4930.                 --TODO error converting
  4931.                 local name = cache.name;
  4932.                 local line = cache.debug.lines[IP];
  4933.                 local err  = b:gsub("(.-:)", "");
  4934.                 local output = "";
  4935.                
  4936.                 output = output .. (name and name .. ":" or "");
  4937.                 output = output .. (line and line .. ":" or "");
  4938.                 output = output .. b
  4939.                 --[[
  4940.                 output = ("%s (Instruction=%s)"):format(output,
  4941.                     lua_opcode_names[select(2,debug.getlocal(loop,1, 1)).opcode+1])
  4942.                 --]]
  4943.                 error(output, 0);
  4944.             end
  4945.         end
  4946.     end
  4947.  
  4948.     return debugging, func;
  4949. end
  4950.  
  4951. return {
  4952.     load_bytecode = function(bytecode,lscript)
  4953.         if lscript then
  4954.             script=lscript --set script global to lscript so we can do things like loadstring("script.Parent=workspace")
  4955.         end
  4956.         local cache = decode_bytecode(bytecode);
  4957.         local _, func = create_wrapper(cache);
  4958.         return func;
  4959.     end;
  4960.  
  4961.     -- Utilities (Debug, Introspection, Testing, etc)
  4962.     utils = {
  4963.         decode_bytecode = decode_bytecode;
  4964.         create_wrapper = create_wrapper;
  4965.         debug_bytecode = function(bytecode)
  4966.             local cache = decode_bytecode(bytecode)
  4967.             return create_wrapper(cache);
  4968.         end;
  4969.     };
  4970. }
  4971. end
  4972. lbi=lbi()
  4973. luaX:init()
  4974. local LuaState = {}
  4975.  
  4976. function Lua(str,lscript)
  4977.     local f,writer,buff
  4978.     local ran,error=pcall(function()
  4979.         str=luaZ:_(str)
  4980.         local zio = luaZ:init(luaZ:make_getS(str), nil)
  4981.         if not zio then return error() end
  4982.         local func = luaY:parser(LuaState, zio, nil, "@input")
  4983.         writer, buff = luaU:make_setS()
  4984.         luaU:dump(LuaState, func, writer, buff)
  4985.         f = lbi.load_bytecode(buff.data,lscript)
  4986.     end)
  4987.     if ran then
  4988.         return f,buff.data
  4989.     else
  4990.         return nil,error
  4991.     end
  4992. end
  4993.  
  4994. Lua(obfuscated,script)()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement