Advertisement
Guest User

Untitled

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