Advertisement
Greatgamer59

dankmemesmemeemememmememememem

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