Compare commits

..

254 Commits

Author SHA1 Message Date
Roberto Ierusalimschy
e2fc2ce8df new way to handle -E option (write a mark in the registry to avoid
reading environment variables)
2011-12-12 14:34:03 -02:00
Roberto Ierusalimschy
a241b6cb3c removed redundant definition for FILEHANDLE 2011-12-08 10:11:37 -02:00
Roberto Ierusalimschy
f0d143f30f avoid a few warnings (casts) 2011-12-07 16:03:47 -02:00
Roberto Ierusalimschy
c82087b8dd cast from 'bool' to 'int' (for C++) 2011-12-07 12:43:55 -02:00
Roberto Ierusalimschy
138be5b843 no more explicit support for 'luaall_c': unifying file can do
the work
2011-12-06 14:58:36 -02:00
Roberto Ierusalimschy
e320b5b672 small bug: format '%d' for lua_Number argument 2011-12-06 14:33:55 -02:00
Roberto Ierusalimschy
ca9c405fef some compilers (e.g., gcc C++) do not accept NULL as a pointer in
that context
2011-12-02 11:26:54 -02:00
Roberto Ierusalimschy
e2feb886d6 macro 'luaL_getmetatable' seems more appropriate when getting
metatables in registry
2011-12-02 11:25:57 -02:00
Roberto Ierusalimschy
5999e14ad9 old error messages may be misleading 2011-12-02 11:23:56 -02:00
Roberto Ierusalimschy
01747f2c24 error message: "tag method" -> "metamethod" 2011-12-02 11:18:41 -02:00
Roberto Ierusalimschy
7377fbdebc function prototype did not match one in .h 2011-11-30 17:30:16 -02:00
Roberto Ierusalimschy
f1d2ac3a98 allow non-integer arguments to integer formats (%d, %x, etc.),
but check range
2011-11-30 16:24:56 -02:00
Roberto Ierusalimschy
c5da4f4cd0 unused variable removed 2011-11-30 11:03:24 -02:00
Roberto Ierusalimschy
7bcb2462e4 comments 2011-11-30 10:58:57 -02:00
Roberto Ierusalimschy
0bd99b327b avoid "unreachable" 'break' 2011-11-30 10:44:26 -02:00
Roberto Ierusalimschy
6d8b672094 more uses of 'l_noret' 2011-11-30 10:43:51 -02:00
Roberto Ierusalimschy
e21b26a964 avoid 'return' "to avoid warnings" 2011-11-30 10:42:49 -02:00
Roberto Ierusalimschy
0f388193b3 'lUA' -> 'LUA' 2011-11-30 10:35:05 -02:00
Roberto Ierusalimschy
7948b8568e when available, use '*_r' versions of 'gmtime' and 'localtime' 2011-11-29 15:15:42 -02:00
Roberto Ierusalimschy
61b1d9a466 another try to avoid warnings about unreachable 'return' after 'exit' 2011-11-29 13:55:51 -02:00
Roberto Ierusalimschy
3617e04e97 'lua_load' has an extra argument 'mode' 2011-11-29 13:55:08 -02:00
Roberto Ierusalimschy
8c62bde36f comment 2011-11-29 13:54:38 -02:00
Roberto Ierusalimschy
51650eac78 small change to avoid warnings of non-specified order of access
to volatile fields
2011-11-29 13:39:48 -02:00
Roberto Ierusalimschy
aea68e5c54 explicit option RTLD_LOCAL instead of 0 (Posix does not fix
a default for dlopen)
2011-11-28 15:27:51 -02:00
Roberto Ierusalimschy
ece042fef0 'table.pack' does not return 'n' (may be confusing when
using table.pack as last argument in a call)
2011-11-28 15:26:30 -02:00
Roberto Ierusalimschy
217b65e6d9 avoid some warnings about converting 32-bit shifts into 64-bit results 2011-11-28 15:25:48 -02:00
Roberto Ierusalimschy
8119374e74 avoid warnings of unreacheable 'break's 2011-11-28 15:25:16 -02:00
Roberto Ierusalimschy
3a997eefb5 MS_ASMTRICK is only valid on MS compilers (not any Windows compiler) 2011-11-25 10:52:27 -02:00
Roberto Ierusalimschy
5184ff2096 'LUA_DL_DLL' is not yet defined before the inclusion of 'lua.h' 2011-11-25 10:52:03 -02:00
Roberto Ierusalimschy
b0cbe77816 '_fseeki64' and family not available in all Windows platforms 2011-11-25 10:50:03 -02:00
Roberto Ierusalimschy
6e899850b9 details 2011-11-24 11:25:41 -02:00
Roberto Ierusalimschy
fded7bef19 options for 'collectgarbage' renamed: "inc" -> "incremental";
"gen" -> "generational"
2011-11-23 15:29:04 -02:00
Roberto Ierusalimschy
b5d7255034 small changes to avoid some warnings 2011-11-16 16:51:36 -02:00
Roberto Ierusalimschy
6cce5c0601 new function 'luaL_loadfilex' 2011-11-14 15:10:24 -02:00
Roberto Ierusalimschy
eb70f58279 'luaIO_Stream' -> 'luaL_Stream' 2011-11-14 14:55:35 -02:00
Roberto Ierusalimschy
ef900f224c strutcture for file handles exported in 'lauxlib.h' 2011-11-11 17:59:17 -02:00
Roberto Ierusalimschy
3105febf9a using Lua buffers to build error messages 2011-11-10 09:42:58 -02:00
Roberto Ierusalimschy
7133e20c94 make treatment of 'pcall' and 'xpcall' more similar 2011-11-09 17:38:00 -02:00
Roberto Ierusalimschy
888d39ea75 refactoring of common parts of 'pcall' and 'xpcall' + avoids
stack errors on these functions (return error code instead)
2011-11-09 17:28:27 -02:00
Roberto Ierusalimschy
eef22fa4ce create error messages with a single concat, to avoid problems with
creating strings piecemeal
2011-11-09 17:11:20 -02:00
Roberto Ierusalimschy
eda87f1156 in 'luaL_checkstack', include extra stack space in test to allow
correct execution of error routines, if necessary
2011-11-09 17:08:55 -02:00
Roberto Ierusalimschy
e0e406ead3 extra argument to instruction 'checkstack' (in 'testC') 2011-11-09 17:08:07 -02:00
Roberto Ierusalimschy
30cea671a7 configurable 'directory separator' in 'package.searchpath' 2011-11-09 13:18:04 -02:00
Roberto Ierusalimschy
a716ae1f50 avoids including 'stdio.h' everywhere (because of definitions for
luai_writestring/luai_writeline)
2011-11-09 12:47:14 -02:00
Roberto Ierusalimschy
ea382b0be1 small bug: error message in 'io.lines' is not the error number 2011-11-09 12:10:43 -02:00
Roberto Ierusalimschy
6d8d282e0f avoid calling "extra value" as if it were a function option 2011-11-06 11:59:12 -02:00
Roberto Ierusalimschy
00c8a17a2d by default, do not use Windows' goodies in Windows CE build 2011-11-05 13:29:05 -02:00
Roberto Ierusalimschy
166ce15512 cannot apply macro 'getstr' over NULL 2011-10-31 15:48:51 -02:00
Roberto Ierusalimschy
87cf2bf711 extra comments about what fields are optional debug information 2011-10-31 15:48:22 -02:00
Roberto Ierusalimschy
fd8a849621 detail (avoid applying macro 'getstr' with a function-call argument) 2011-10-31 15:46:04 -02:00
Roberto Ierusalimschy
5a568a3b01 detail (comment) 2011-10-25 10:01:20 -02:00
Roberto Ierusalimschy
475e6c5352 'lua_setglobal/lua_getglobal' implemented as functions to avoid
problems with stack indices
(e.g., lua_getglobal(L, lua_tostring(L, -1)) )
2011-10-24 14:53:05 -02:00
Roberto Ierusalimschy
af00a0772c new functions lua_rawsetp/lua_rawgetp 2011-10-24 12:54:05 -02:00
Roberto Ierusalimschy
6819c2a98a silly bug in 5.2 beta: assignment conflict code did not test to check
whether variable was a table element
2011-10-24 12:51:44 -02:00
Roberto Ierusalimschy
1dd8af67b6 BUG: parser may collect a prototype while building it. 2011-10-21 17:34:23 -02:00
Roberto Ierusalimschy
1350a2bcb5 more macros to try to make NaN trick work with other sizes of
IEEE float numbers. (It has not been tested with such different
sizes...)
2011-10-17 12:46:13 -02:00
Roberto Ierusalimschy
217e67cb22 new type 'l_noret' for function that do not return 2011-10-07 17:45:19 -03:00
Roberto Ierusalimschy
9bbfe9f3fd avoid the word 'TRICKLE' in macro name (as it has nothing to do
with its meaning)
2011-10-07 16:53:05 -03:00
Roberto Ierusalimschy
788a0ecd27 'luaC_separateudata' renamed to 'separatetobefnz' and called only
from 'lgc.c'
2011-10-03 14:54:25 -03:00
Roberto Ierusalimschy
6d86b937e4 'luaC_separateudata' called from 'luaC_freeallobjects' + removed
extra 'luaF_close' (already being called by 'close_state')
2011-10-03 14:54:25 -03:00
Roberto Ierusalimschy
bc90cf4b83 retraverse all gray lists together to avoid traversing some weak
tables twice (as they may change lists when traversed)
2011-10-03 13:22:05 -03:00
Roberto Ierusalimschy
d79190e27f missing 'LUA_CORE' definition 2011-10-03 13:19:23 -03:00
Roberto Ierusalimschy
9caf5b4f79 lint (unused definition) 2011-09-30 09:46:06 -03:00
Roberto Ierusalimschy
50cddefeeb lint (wrong identation) 2011-09-30 09:45:45 -03:00
Roberto Ierusalimschy
e24f1ee9ff lint (unreachable code) 2011-09-30 09:44:45 -03:00
Roberto Ierusalimschy
f3b0eb3ecf lint (unused macros) 2011-09-30 09:44:19 -03:00
Roberto Ierusalimschy
162ce8256e lint (unused struct field) 2011-09-30 09:43:54 -03:00
Roberto Ierusalimschy
ad90447eb6 detail: new macros for non-valid values 2011-09-26 17:17:27 -03:00
Roberto Ierusalimschy
87912786af dead objects are not collectable. 2011-09-24 18:12:01 -03:00
Roberto Ierusalimschy
5645a84368 detail about 'trick' function (nil turn it off) 2011-09-24 18:11:29 -03:00
Roberto Ierusalimschy
95ed6c1127 better(?) scheme for cleaning weak tables; all ressurected objects
are removed from weak values before finalization
2011-09-24 18:00:40 -03:00
Roberto Ierusalimschy
12ab78aca6 detail in extra trace code: total bytes is given by 'gettotalbytes',
not by 'totalbytes' counter.
2011-09-20 16:25:23 -03:00
Roberto Ierusalimschy
45c346645c avoid clearing ephemeron tables that have nothing to be cleaned
(no white elements)
2011-09-19 14:03:38 -03:00
Roberto Ierusalimschy
68ce878292 cannot compute 'mainposition' before checking whether key is nil 2011-09-15 14:09:02 -03:00
Roberto Ierusalimschy
500336efd0 small bug in if-goto optimization: block must be closed ('leaveblock')
*before* the jump out ('escapelist')
2011-09-14 14:40:26 -03:00
Roberto Ierusalimschy
5ea8f108e1 using 'long' versions of 'fseek'/'ftell' when available 2011-09-13 18:09:04 -03:00
Roberto Ierusalimschy
2275030b86 details (and missing 'break's) 2011-09-13 15:05:59 -03:00
Roberto Ierusalimschy
05de314701 upvalue names always can be NULL (if debug info was removed), so
always check for that case
2011-09-13 14:40:20 -03:00
Roberto Ierusalimschy
d281d23f8d detail (make 'lua_assert' a valid expression even when turned off) 2011-09-13 14:39:23 -03:00
Roberto Ierusalimschy
ec431ce5db comment 2011-09-12 17:33:03 -03:00
Roberto Ierusalimschy
c8f47c2934 optimization for |if cond then goto| 2011-08-30 13:38:58 -03:00
Roberto Ierusalimschy
ca458f1f52 'luaK_goiffalse' exported 2011-08-30 13:26:41 -03:00
Roberto Ierusalimschy
121dc8af66 cleaner code for 'if' construct 2011-08-25 10:45:24 -03:00
Roberto Ierusalimschy
a8675966ec detail: centralize all tests for Windows on variable 'LUA_WIN' 2011-08-23 14:25:42 -03:00
Roberto Ierusalimschy
3dc5475e23 'nCcalls' should be local to each thread, as each thread may have its
own C stack (with LuaThreads or something similar)
2011-08-23 14:24:34 -03:00
Roberto Ierusalimschy
8a008a2057 bug: __newindex metamethod may not work if metatable is its own
metatable.
2011-08-17 17:38:51 -03:00
Roberto Ierusalimschy
89b59eee73 bug: __newindex metamethod may not work if metatable is its own
metatable + luaV_settable does not create entry when there is a
metamethod (and therefore entry is useless)
2011-08-17 17:26:47 -03:00
Roberto Ierusalimschy
166dd0261a new option '-E' to avoid environment variables 2011-08-17 17:19:52 -03:00
Roberto Ierusalimschy
51471ba748 comments about use of 'luaH_set' 2011-08-15 16:41:58 -03:00
Roberto Ierusalimschy
0b65cb74cd new implementation for 'getobjname': first search for relevant
instruction (new function 'findsetreg') and then try to build
a meaningful name
2011-08-12 17:01:44 -03:00
Roberto Ierusalimschy
ea46b750dc comment 2011-08-11 14:06:12 -03:00
Roberto Ierusalimschy
92afcf2823 no more 'luaH_setstr (used only once) + 'luaH_setint' receives value
to be set.
2011-08-09 17:58:29 -03:00
Roberto Ierusalimschy
b5bf7d9ef4 'string.format' checks whether values for integer formats are
actually integers
2011-08-09 17:58:29 -03:00
Roberto Ierusalimschy
6a5d89b39f detail (using array instead of several variables to keep track of
enabled command-line options)
2011-08-04 15:16:16 -03:00
Roberto Ierusalimschy
ae14adc272 better error message when trying to open files 2011-08-02 15:00:01 -03:00
Roberto Ierusalimschy
ff98f17d27 detail: factoring in common code for opening files and checking for
errors
2011-07-28 15:41:15 -03:00
Roberto Ierusalimschy
59bcd137ae reducing even more use of C stack by the parser: struct 'FuncState'
does not need field 'L' + number of labels/gotos in a chunk may be
limited to SHRT_MAX. (Also removed some non-needed 'unsigned's.)
2011-07-27 15:09:01 -03:00
Roberto Ierusalimschy
5ab6d36d99 no more field 'L' in 'FuncState' 2011-07-27 15:07:37 -03:00
Roberto Ierusalimschy
43c873895f tonumber: base 10 is not special, no base is 2011-07-27 09:14:06 -03:00
Roberto Ierusalimschy
03a078493e refuse things like 'inf' or 'Nan' as numerals 2011-07-27 09:13:08 -03:00
Roberto Ierusalimschy
bae57ea088 'M_IX86' -> '_M_IX86' 2011-07-25 14:20:47 -03:00
Roberto Ierusalimschy
2557107e91 removed unused variable 'found' (in 'findfield') + removed legacy
test for 'what' being "tail"
2011-07-25 14:18:49 -03:00
Roberto Ierusalimschy
32a12e2f3f detail (cleaned whitespaces at end of lines) 2011-07-15 09:50:29 -03:00
Roberto Ierusalimschy
559bb554c9 no more 'zungetc' (better not to read next char) 2011-07-15 09:48:03 -03:00
Roberto Ierusalimschy
fd5e810e08 macro 'char2int' replaced by 'cast_uchar' (used by other files) 2011-07-15 09:35:32 -03:00
Roberto Ierusalimschy
067f761739 better code for numerical escapes 2011-07-15 09:30:41 -03:00
Roberto Ierusalimschy
7978a8d8b2 added '_M_IX86' in NaN trick 2011-07-08 17:07:11 -03:00
Roberto Ierusalimschy
32e09c2a16 detail 2011-07-08 17:01:38 -03:00
Roberto Ierusalimschy
df19931ddc error on invalid escape sequences 2011-07-08 16:17:30 -03:00
Roberto Ierusalimschy
b5084fdafe detail (comment) 2011-07-06 13:45:14 -03:00
Roberto Ierusalimschy
d8200d5f3c '\*' -> '\z' + '\?' is not an official escape sequence 2011-07-05 16:13:45 -03:00
Roberto Ierusalimschy
79cbc3468c removed and deprecated functions really removed from the code base 2011-07-05 09:49:35 -03:00
Roberto Ierusalimschy
9e89a55a4f NILCONSTANT also depends no endianess (with NaN trick) 2011-07-04 17:29:02 -03:00
Roberto Ierusalimschy
b707e81c3d comments about some compiler options that should be tested once in a while 2011-07-04 13:10:15 -03:00
Roberto Ierusalimschy
ee37ee50d6 'table.pack' also returns 'n' + 'deprecated' changed to 'removed' 2011-07-02 13:01:44 -03:00
Roberto Ierusalimschy
ad1a54b5c0 reordering of some defines (more logical grouping) 2011-07-02 13:00:15 -03:00
Roberto Ierusalimschy
88c29c0cd5 compilation warning about integer size x pointer size 2011-07-02 12:59:17 -03:00
Roberto Ierusalimschy
d93df22bf6 small simplifications (and assert was wrongly written) 2011-07-02 12:58:14 -03:00
Roberto Ierusalimschy
5017cc6ba2 simpler 'luai_apicheck' (and avoids compilation error...) 2011-07-02 12:57:25 -03:00
Roberto Ierusalimschy
2f125ebc33 'deprecated' x 'removed' (they are not the same thing) 2011-07-02 12:56:43 -03:00
Roberto Ierusalimschy
49a01c0991 'package.loaders' -> 'package.searchers' 2011-06-28 14:14:12 -03:00
Roberto Ierusalimschy
17526ed2fe no more errors on accesses to 'string' and strings 2011-06-28 14:13:52 -03:00
Roberto Ierusalimschy
f180822fa6 back to internal table for 'ctype', no more locale manipulation 2011-06-28 12:42:04 -03:00
Roberto Ierusalimschy
594220c624 use standard "underscore + uppercases" for reserved keys in the registry 2011-06-27 16:42:31 -03:00
Roberto Ierusalimschy
3dd68624dc comments 2011-06-27 15:27:18 -03:00
Roberto Ierusalimschy
f9eea453b7 avoid "magic constant" 32 (the difference from 'A' to 'a') 2011-06-27 15:22:46 -03:00
Roberto Ierusalimschy
374773748b back to "one-label-per-block" 2011-06-27 15:18:59 -03:00
Roberto Ierusalimschy
29644366fc useless assignments removed (macros already do the assignment) 2011-06-24 11:36:21 -03:00
Roberto Ierusalimschy
6eadedbfa1 resort to standard C ctype for non-ASCII systems + 'ltoupper' replaced
by 'ltolower'
2011-06-24 09:25:33 -03:00
Roberto Ierusalimschy
1978094b3a resort to standard C ctype for non-ASCII systems 2011-06-24 09:25:33 -03:00
Roberto Ierusalimschy
5acc5b0c1e using 'tolower' instead of 'toupper' (slightly simpler to implement) 2011-06-24 09:25:02 -03:00
Roberto Ierusalimschy
59547c6cda macro 'ltoupper' instead of 'lisupper' (more usefull for Lua) 2011-06-23 13:01:06 -03:00
Roberto Ierusalimschy
3d3355b4f3 label syntax changed to '::label::' 2011-06-23 11:54:48 -03:00
Roberto Ierusalimschy
801f43f09a change in the representation of file handles 2011-06-21 10:43:48 -03:00
Roberto Ierusalimschy
719c01359f label syntax changed to '::label::' 2011-06-20 13:52:48 -03:00
Roberto Ierusalimschy
43f13729a2 comment 2011-06-20 13:50:59 -03:00
Roberto Ierusalimschy
136f8e148d added cast to void to calls to 'setlocale' (to easy redefining it as
a constant)
2011-06-20 13:36:03 -03:00
Roberto Ierusalimschy
f90a130b07 typo in message 2011-06-20 13:35:23 -03:00
Roberto Ierusalimschy
cb4950a6d8 parser must work with C locale, but external locale must be preserved 2011-06-18 14:08:58 -03:00
Roberto Ierusalimschy
fdede85419 label names must be unique inside a function 2011-06-16 13:36:39 -03:00
Roberto Ierusalimschy
beab626061 correct length for LUA_COPYRIGHT (without trailing '\0') 2011-06-16 11:30:58 -03:00
Roberto Ierusalimschy
817f8674af avoid warning about -unsigned value 2011-06-16 11:14:31 -03:00
Roberto Ierusalimschy
cf0562e1e7 detail (missing cast to unsigned char when converting char to int) 2011-06-16 11:13:22 -03:00
Roberto Ierusalimschy
22e1c5ebad avoid conversion from 'const char*' to 'void *' (warning about 'const') 2011-06-16 11:12:24 -03:00
Roberto Ierusalimschy
470dd56a89 'os.execute' (and similars) should return 'exit' and code in case
of success, too.
2011-06-16 11:11:04 -03:00
Roberto Ierusalimschy
20d30bcd33 declarations should be present only when implementations are 2011-06-16 11:10:12 -03:00
Roberto Ierusalimschy
44b6f496b5 just in case, avoid side effects in 'ctype' macros 2011-06-15 11:35:55 -03:00
Roberto Ierusalimschy
fd80e63468 configuration for NaN trick big-endian + macro 'luai_checknum' to
ensure numbers comming from C are not "improper" (some kinds of
signaling NaNs)
2011-06-13 11:13:06 -03:00
Roberto Ierusalimschy
f62565abea avoid warnings with -Wstrict-overflow 2011-06-09 15:24:22 -03:00
Roberto Ierusalimschy
c9d1d9f9c6 better way to test overflows with string indices 2011-06-09 15:22:47 -03:00
Roberto Ierusalimschy
35391d9b1a macro 'NNMARK' (mark for non-number values using the NaN trick) 2011-06-09 15:21:25 -03:00
Roberto Ierusalimschy
99b1b8e918 first version with 'NANTRICK' (packing all Lua values inside a 'double') 2011-06-07 16:02:33 -03:00
Roberto Ierusalimschy
3b44821334 stricter control (using tag variants) over closure kinds (Lua x C) 2011-06-02 16:31:40 -03:00
Roberto Ierusalimschy
0214dab989 yet another macro ('num_') 2011-05-31 16:15:01 -03:00
Roberto Ierusalimschy
821bd7025e more uniform names for 'equalobj'-related functions 2011-05-31 15:27:56 -03:00
Roberto Ierusalimschy
9b7dddad7d no need for two different implementations for equality (one raw and
one with metamethods)
2011-05-31 15:24:36 -03:00
Roberto Ierusalimschy
3f04a9f2c0 code is simpler without 'goto' here 2011-05-30 13:36:38 -03:00
Roberto Ierusalimschy
2a59a999d4 yet another macro abstracting TValue representation 2011-05-26 14:12:31 -03:00
Roberto Ierusalimschy
ee7d0c2649 new macro 'luai_writeline' to print newlines (and flush 'stdout') 2011-05-26 13:09:40 -03:00
Roberto Ierusalimschy
aa13c591f5 avoid use of 'ifdef/ifndef'; use 'defined' instead (simpler and
more powerful)
2011-05-25 11:12:28 -03:00
Roberto Ierusalimschy
6c8a32217a changes by lhf (better control of chars x bytes) 2011-05-17 09:42:43 -03:00
Roberto Ierusalimschy
cb09f4fef4 details 2011-05-06 13:00:23 -03:00
Roberto Ierusalimschy
3cf1729a02 new macro 'lua_longassert' that is equivalent to an assertion without
a stringfication of the condition, to avoid too long string literals
(limited by C90 to ~510 characters)
2011-05-05 16:43:14 -03:00
Roberto Ierusalimschy
74b0bb3a45 macro 'checkconsistency' moved to this file, as it is used only
here
2011-05-05 16:42:25 -03:00
Roberto Ierusalimschy
e4076fe6d9 break long assertion in two shorter ones 2011-05-05 13:18:53 -03:00
Roberto Ierusalimschy
81952e6884 avoid using expression as argument to unsafe macro 'l_isfalse' 2011-05-05 13:16:33 -03:00
Roberto Ierusalimschy
25b4e35ee8 new macros abstracting TValue representation (to easy change to
other representations)
2011-05-05 12:53:23 -03:00
Roberto Ierusalimschy
7e1facaa4e detail in assertion 2011-05-04 14:04:06 -03:00
Roberto Ierusalimschy
ad2531a0ee more complete (and hopefuly more correct) handling of 'sizeof(char)' 2011-05-03 13:01:57 -03:00
Roberto Ierusalimschy
bc1c718cc0 removed TOKEN_LEN (useless) 2011-05-03 12:51:16 -03:00
Roberto Ierusalimschy
c9ce754e38 comment 2011-05-02 14:33:01 -03:00
Roberto Ierusalimschy
d34271fe42 MacOS 'strtod' handles hexa formats too 2011-04-29 10:56:28 -03:00
Roberto Ierusalimschy
d120ec29ca bug in OP_SELF when method name goes to a register 2011-04-28 11:00:11 -03:00
Roberto Ierusalimschy
2aff901c93 Mac OS defines LUA_USE_AFORMAT and LUA_USE_LONGLONG by default 2011-04-20 15:25:54 -03:00
Roberto Ierusalimschy
bad231c481 'LUA_USELONGLONG' -> 'LUA_USE_LONGLONG' 2011-04-20 13:36:28 -03:00
Roberto Ierusalimschy
a2b1c279f1 'LUA_USELONGLONG' on by default on Linux + LUA_USE_HEXAFLOAT renamed
to LUA_USE_STRTODHEX (as Lua 5.2 always *uses*  hexa floats)
2011-04-19 15:31:30 -03:00
Roberto Ierusalimschy
2f128c5130 'luaL_setfuncs' does not need to accept a NULL list. (If there is
no list, there is no reason to call this function.)
2011-04-19 15:29:41 -03:00
Roberto Ierusalimschy
4758113043 change in opcode OP_LOADNIL: B is used as a counter instead of a
register. (Avoids an assignment to R(B), not present in any other
instruction.)
2011-04-19 13:22:13 -03:00
Roberto Ierusalimschy
a4e644add2 small bug (masked by wrong entry for OP_TEST in opcodes.c) 2011-04-18 16:49:13 -03:00
Roberto Ierusalimschy
05ca63642b added macro for code checking 2011-04-18 16:48:53 -03:00
Roberto Ierusalimschy
f17e3624ef local function name only visible to debug info after being initialized 2011-04-18 16:48:24 -03:00
Roberto Ierusalimschy
2e9b8476ca detail ('luai_apicheck' should be used always through macro 'api_check') 2011-04-18 12:02:37 -03:00
Roberto Ierusalimschy
c31f4946e9 copyright updated to 2011 2011-04-18 11:15:48 -03:00
Roberto Ierusalimschy
c86586e866 small corrections in description of OP_TEST and OP_LOADKX 2011-04-12 14:27:35 -03:00
Roberto Ierusalimschy
19fbdf6cae 'luaL_findtable' -> 'luaL_getsubtable' 2011-04-08 16:17:36 -03:00
Roberto Ierusalimschy
427ee519db new instruction OP_LOADKX (to replace OP_LOADK with extra argument) 2011-04-07 15:14:12 -03:00
Roberto Ierusalimschy
a958b711f5 cleaner scheme of bits for variant types (light C functions) and
collectable types
2011-04-07 13:11:57 -03:00
Roberto Ierusalimschy
1ffdd0bc7a detail (should use macro 'ttisdeadkey') 2011-04-05 15:32:28 -03:00
Roberto Ierusalimschy
5286650894 new macro 'ttisequal' 2011-04-05 15:32:06 -03:00
Roberto Ierusalimschy
0fb1644c60 2nd operand for unary tag methods does not need to be 'nil' 2011-04-05 11:26:23 -03:00
Roberto Ierusalimschy
119d5e46d5 lua_arith gets no fake operand for unary minus 2011-04-05 11:26:23 -03:00
Roberto Ierusalimschy
83abbac946 all names used internally by macros end with '_' 2011-04-05 11:24:07 -03:00
Roberto Ierusalimschy
a25416a8d5 use of 'luaL_tolstring' for option '%s' in 'string.format' 2011-03-18 16:02:33 -03:00
Roberto Ierusalimschy
682cce3813 macro 'mark' renamed 'EOFMARK' ('mark' is too easy to confict, e.g.
in alllua.c)
2011-03-14 12:39:42 -03:00
Roberto Ierusalimschy
d806710ab5 returns for file-related functions and process-related functions
unified in 'auxlib'
2011-03-03 13:34:46 -03:00
Roberto Ierusalimschy
e049abb69a loaders receive an extra argument returned by the searcher
(typically the file name)
2011-03-01 14:01:53 -03:00
Roberto Ierusalimschy
98816d0ce5 small problems with 'luaone.c' 2011-02-28 14:32:10 -03:00
Roberto Ierusalimschy
7482e8f914 no need of lookahead in Zio 2011-02-23 10:13:10 -03:00
Roberto Ierusalimschy
03b769053a correct interpretation of return value from pclose 2011-02-21 16:12:54 -03:00
Roberto Ierusalimschy
3c710f056b small bug: may call reader function again after it returned end
of input
2011-02-17 15:34:16 -02:00
Roberto Ierusalimschy
c0a865fa54 error for repeated label + jumps allowed to labels followed by
'no-op' statements
2011-02-14 14:36:34 -02:00
Roberto Ierusalimschy
0009ac1f3a 'break' does not need to be last statement in a block +
'explist1' -> 'explist' + moving a few functions around
2011-02-14 12:59:28 -02:00
Roberto Ierusalimschy
7b968bb514 p-close returns "correct" status plus type of termination 2011-02-10 13:35:50 -02:00
Roberto Ierusalimschy
bf8b08295a 'break' coded as 'goto' + small bug when closing multiple gotos
to the same label
2011-02-10 12:50:41 -02:00
Roberto Ierusalimschy
3f5b56c48b simpler code for repeat-until 2011-02-09 15:03:18 -02:00
Roberto Ierusalimschy
e7192dfdbb corrected 'follow' for checking whether label is last statement
in a block
2011-02-09 14:51:28 -02:00
Roberto Ierusalimschy
0539f48661 small changes in goto-related error messages 2011-02-09 12:45:19 -02:00
Roberto Ierusalimschy
e7a9c45a48 trying to avoid assumption that sizeof(char)==1 2011-02-07 17:15:24 -02:00
Roberto Ierusalimschy
fd6c1f4898 ensures that all local variables are declared inside some block,
opening a new block at 'open_func'
2011-02-07 17:00:30 -02:00
Roberto Ierusalimschy
f079749287 some reorganization of dynamic data structures used by the parser 2011-02-07 15:14:50 -02:00
Roberto Ierusalimschy
f8d677f94c no more 'OP_CLOSE' instructions (use jumps to close upvalues) 2011-02-07 10:28:27 -02:00
Roberto Ierusalimschy
094a7d0290 detail in 'print_usage' 2011-02-07 10:27:13 -02:00
Roberto Ierusalimschy
7cc0e63d8a first implementation of 'goto' 2011-02-04 15:34:43 -02:00
Roberto Ierusalimschy
a4a8914c20 new reserved word 'goto' 2011-02-02 12:55:17 -02:00
Roberto Ierusalimschy
06c7efb4a9 avoid extra increment to 'savedpc' when jumping 2011-02-01 16:32:55 -02:00
Roberto Ierusalimschy
dd547c55c8 new scheme to close upvalues in 'break'; jump instructions may
do the close, avoiding the need for a OP_CLOSE instruction
2011-02-01 16:03:10 -02:00
Roberto Ierusalimschy
f6bd8b1147 better control for GC running or stopped 2011-02-01 14:52:38 -02:00
Roberto Ierusalimschy
a7faa557fa bug: problem with optimizations of short-circuit logic 2011-01-31 12:52:32 -02:00
Roberto Ierusalimschy
026a7e92be bug in some short-circuit optimizations 2011-01-31 12:28:41 -02:00
Roberto Ierusalimschy
c4ea0c3b29 detail (cleaning trailing spaces) 2011-01-26 14:30:02 -02:00
Roberto Ierusalimschy
7106c491dd 'sep' argument to 'string.rep' + 'string.rep' preallocates entire
buffer before creating resulting string
2011-01-12 18:36:01 -02:00
Roberto Ierusalimschy
a10d495b18 'luaL_findtable' returns boolean about whether it created a new
table (to easy initializing table)
2011-01-10 13:51:42 -02:00
Roberto Ierusalimschy
c2e3cc4c89 using 'luaL_findtable' to manage hook table 2011-01-10 13:51:19 -02:00
Roberto Ierusalimschy
67feed49f1 optional argument 'sep' to 'searchpath' 2011-01-07 16:54:49 -02:00
Roberto Ierusalimschy
b63b0928cf prototype for 'luaO_ceillog2' was different from definition 2011-01-07 13:46:27 -02:00
Roberto Ierusalimschy
511679313f new function 'rawlen' 2011-01-07 10:41:48 -02:00
Roberto Ierusalimschy
868ff40339 full collection does not restart collector + avoid changing GC
state if an error happens in a step
2010-12-29 16:00:23 -02:00
Roberto Ierusalimschy
aa6faa6331 own implementation of 'tunumber', so that it works correctly with
numbers outside the 'int' range
2010-12-27 16:00:38 -02:00
Roberto Ierusalimschy
0b3f4e254e more efficient hash for numbers in IEEE754 machines 2010-12-23 13:38:28 -02:00
Roberto Ierusalimschy
551b076f1c change in the relationship between totalbytes and GCdebt - luaM_realloc_
is too critical to update two counters
2010-12-20 17:40:07 -02:00
Roberto Ierusalimschy
737f119187 better control for GC running or stopped 2010-12-20 16:17:46 -02:00
Roberto Ierusalimschy
8980c630bf error when indexing strings with invalid keys 2010-12-20 15:25:36 -02:00
Roberto Ierusalimschy
8d579c5bc5 'debug.setmetatable' returns object (like 'setmetatable') 2010-12-20 15:24:15 -02:00
Roberto Ierusalimschy
d51743b0c7 removed 'newproxy' 2010-12-17 13:14:58 -02:00
Roberto Ierusalimschy
1a92c2b354 allows number of bits used by the library to be changed from outside 2010-12-17 11:26:38 -02:00
Roberto Ierusalimschy
fe0d54d37e table library respects '#' metamethods 2010-12-17 10:15:34 -02:00
Roberto Ierusalimschy
c9af0768fc GC does not mark dead registers inside activation record 2010-12-17 10:05:37 -02:00
Roberto Ierusalimschy
7e0caa7d61 new closures are always created on "next" register (so that GC knows
stack limit)
2010-12-17 10:03:41 -02:00
Roberto Ierusalimschy
a40768e5ea new macro 'luaC_condGC' to allow extra code to be run in case
of GC steps
2010-12-17 10:02:29 -02:00
Roberto Ierusalimschy
4a83fe569c comment 2010-12-15 17:13:29 -02:00
Roberto Ierusalimschy
b83b6ba015 'loadin' -> 'load' 2010-12-13 14:38:00 -02:00
Roberto Ierusalimschy
af119c8b55 official support for floating hexa numerals 2010-12-10 17:03:46 -02:00
Roberto Ierusalimschy
1aead7f553 'hexafloat' moved to 'lobject.c' (hexa conversion needs it too) 2010-12-10 12:53:15 -02:00
Roberto Ierusalimschy
75d8470f0f new macro 'cast_uchar' 2010-12-10 11:40:22 -02:00
Roberto Ierusalimschy
81646af13b 'loadstring' deprecated; use 'load' instead 2010-12-08 10:58:04 -02:00
Roberto Ierusalimschy
233b71c092 comment 2010-12-07 09:40:42 -02:00
Roberto Ierusalimschy
ccc4fc9cf0 detection of erroneous numeric strings with \0 (such as "1\0") 2010-12-06 19:08:36 -02:00
Roberto Ierusalimschy
c79b4a97aa using 'strspn' to skip spaces in 'tonumber' 2010-12-06 14:25:48 -02:00
Roberto Ierusalimschy
ac3afc7cd4 'printf' replaced by 'luai_writestring' 2010-12-03 15:20:50 -02:00
Roberto Ierusalimschy
350cc4bcb6 'micro' bug: when closing state, old objects are finalized (breaking
assertion)
2010-12-03 09:48:25 -02:00
Roberto Ierusalimschy
35931bbed4 comments 2010-12-02 17:51:15 -02:00
Roberto Ierusalimschy
12779b2b71 getlocal/setlocal can access vararg parameters 2010-11-30 15:17:51 -02:00
Roberto Ierusalimschy
7ca1bd639f new functions 'extract' and 'replace' 2010-11-29 13:19:28 -02:00
Roberto Ierusalimschy
9b7a12c46d finalizers (__gc) for tables 2010-11-26 12:32:31 -02:00
56 changed files with 3045 additions and 1915 deletions

95
bugs
View File

@@ -1880,8 +1880,8 @@ patch = [[
+++ lundump.c 2008/04/04 19:51:41 2.7.1.4 +++ lundump.c 2008/04/04 19:51:41 2.7.1.4
@@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/* /*
-** $Id: bugs,v 1.107 2010/04/19 18:04:58 roberto Exp roberto $ -** $Id: bugs,v 1.110 2011/08/17 20:38:51 roberto Exp roberto $
+** $Id: bugs,v 1.107 2010/04/19 18:04:58 roberto Exp roberto $ +** $Id: bugs,v 1.110 2011/08/17 20:38:51 roberto Exp roberto $
** load precompiled Lua chunks ** load precompiled Lua chunks
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -2316,3 +2316,94 @@ patch = [[
]] ]]
} }
Bug{
what = [[wrong code generation for some particular boolean expressions]],
report = [[Thierry Van Elsuwe, 2011/01/20]],
since = [[5.0]],
example = [[
print((('hi' or true) and true) or true)
--> hi (should be true)
print(((nil and nil) or false) and true)
--> nil (should be false)
]],
patch = [[
--- lcode.c 2009/06/15 14:12:25 2.25.1.4
+++ lcode.c 2011/01/31 14:44:25
@@ -549,13 +549,6 @@
pc = e->u.s.info;
break;
}
- case VFALSE: {
- if (!hasjumps(e)) {
- pc = luaK_jump(fs); /* always jump */
- break;
- }
- /* else go through */
- }
default: {
pc = jumponcond(fs, e, 0);
break;
@@ -579,13 +572,6 @@
pc = e->u.s.info;
break;
}
- case VTRUE: {
- if (!hasjumps(e)) {
- pc = luaK_jump(fs); /* always jump */
- break;
- }
- /* else go through */
- }
default: {
pc = jumponcond(fs, e, 1);
break;
]]
}
Bug{
what = [[__newindex metamethod may not work if metatable is its own
metatable]],
report = [[Cuero Bugot, 2011/08/09]],
since = [[5.1]],
example = [[
meta={}
setmetatable(meta, meta)
meta.__newindex = function(t, key, value) print("set") end
o = setmetatable({}, meta)
o.x = 10 -- should print 'set'
]],
patch = [[
--- lvm.c 2009/07/01 21:10:33 2.63.1.4
+++ lvm.c 2011/08/17 20:36:28
@@ -142,6 +142,7 @@
if (!ttisnil(oldval) || /* result is no nil? */
(tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */
setobj2t(L, oldval, val);
+ h->flags = 0;
luaC_barriert(L, h, val);
return;
}
]]
}
Bug{
what = [[parser may collect a prototype while building it]],
report = [[Ingo van Lil, 2011/10/13]],
since = [[5.1.4 (caused by patch 5.1.4-6)]],
example = nil,
patch = [[
--- lparser.c 2007/12/28 15:32:23 2.42.1.3
+++ lparser.c 2011/10/17 13:10:43
@@ -374,9 +374,9 @@
lua_assert(luaG_checkcode(f));
lua_assert(fs->bl == NULL);
ls->fs = fs->prev;
- L->top -= 2; /* remove table and prototype from the stack */
/* last token read was anchored in defunct function; must reanchor it */
if (fs) anchor_token(ls);
+ L->top -= 2; /* remove table and prototype from the stack */
}
]]
}

273
lapi.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lapi.c,v 2.139 2010/10/25 20:31:11 roberto Exp roberto $ ** $Id: lapi.c,v 2.158 2011/11/29 15:55:08 roberto Exp roberto $
** Lua API ** Lua API
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -34,9 +34,13 @@ const char lua_ident[] =
"$LuaAuthors: " LUA_AUTHORS " $"; "$LuaAuthors: " LUA_AUTHORS " $";
/* value at a non-valid index */
#define NONVALIDVALUE cast(TValue *, luaO_nilobject)
#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject, \ /* corresponding test */
"invalid index") #define isvalid(o) ((o) != luaO_nilobject)
#define api_checkvalidindex(L, i) api_check(L, isvalid(i), "invalid index")
static TValue *index2addr (lua_State *L, int idx) { static TValue *index2addr (lua_State *L, int idx) {
@@ -44,7 +48,7 @@ static TValue *index2addr (lua_State *L, int idx) {
if (idx > 0) { if (idx > 0) {
TValue *o = ci->func + idx; TValue *o = ci->func + idx;
api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");
if (o >= L->top) return cast(TValue *, luaO_nilobject); if (o >= L->top) return NONVALIDVALUE;
else return o; else return o;
} }
else if (idx > LUA_REGISTRYINDEX) { else if (idx > LUA_REGISTRYINDEX) {
@@ -57,12 +61,10 @@ static TValue *index2addr (lua_State *L, int idx) {
idx = LUA_REGISTRYINDEX - idx; idx = LUA_REGISTRYINDEX - idx;
api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
if (ttislcf(ci->func)) /* light C function? */ if (ttislcf(ci->func)) /* light C function? */
return cast(TValue *, luaO_nilobject); /* it has no upvalues */ return NONVALIDVALUE; /* it has no upvalues */
else { else {
Closure *func = clvalue(ci->func); CClosure *func = clCvalue(ci->func);
return (idx <= func->c.nupvalues) return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE;
? &func->c.upvalue[idx-1]
: cast(TValue *, luaO_nilobject);
} }
} }
} }
@@ -195,10 +197,8 @@ static void moveto (lua_State *L, TValue *fr, int idx) {
TValue *to = index2addr(L, idx); TValue *to = index2addr(L, idx);
api_checkvalidindex(L, to); api_checkvalidindex(L, to);
setobj(L, to, fr); setobj(L, to, fr);
if (idx < LUA_REGISTRYINDEX) { /* function upvalue? */ if (idx < LUA_REGISTRYINDEX) /* function upvalue? */
lua_assert(ttisclosure(L->ci->func)); luaC_barrier(L, clCvalue(L->ci->func), fr);
luaC_barrier(L, clvalue(L->ci->func), fr);
}
/* LUA_REGISTRYINDEX does not need gc barrier /* LUA_REGISTRYINDEX does not need gc barrier
(collector revisits it before finishing collection) */ (collector revisits it before finishing collection) */
} }
@@ -239,7 +239,7 @@ LUA_API void lua_pushvalue (lua_State *L, int idx) {
LUA_API int lua_type (lua_State *L, int idx) { LUA_API int lua_type (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
return (o == luaO_nilobject) ? LUA_TNONE : ttypenv(o); return (isvalid(o) ? ttypenv(o) : LUA_TNONE);
} }
@@ -251,7 +251,7 @@ LUA_API const char *lua_typename (lua_State *L, int t) {
LUA_API int lua_iscfunction (lua_State *L, int idx) { LUA_API int lua_iscfunction (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
return (ttislcf(o) || (ttisclosure(o) && clvalue(o)->c.isC)); return (ttislcf(o) || (ttisCclosure(o)));
} }
@@ -277,21 +277,28 @@ LUA_API int lua_isuserdata (lua_State *L, int idx) {
LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
StkId o1 = index2addr(L, index1); StkId o1 = index2addr(L, index1);
StkId o2 = index2addr(L, index2); StkId o2 = index2addr(L, index2);
return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0;
: luaO_rawequalObj(o1, o2);
} }
LUA_API void lua_arith (lua_State *L, int op) { LUA_API void lua_arith (lua_State *L, int op) {
StkId o1; /* 1st operand */
StkId o2; /* 2nd operand */
lua_lock(L); lua_lock(L);
api_checknelems(L, 2); if (op != LUA_OPUNM) /* all other operations expect two operands */
if (ttisnumber(L->top - 2) && ttisnumber(L->top - 1)) { api_checknelems(L, 2);
changenvalue(L->top - 2, else { /* for unary minus, add fake 2nd operand */
luaO_arith(op, nvalue(L->top - 2), nvalue(L->top - 1))); api_checknelems(L, 1);
setobjs2s(L, L->top, L->top - 1);
L->top++;
}
o1 = L->top - 2;
o2 = L->top - 1;
if (ttisnumber(o1) && ttisnumber(o2)) {
changenvalue(o1, luaO_arith(op, nvalue(o1), nvalue(o2)));
} }
else else
luaV_arith(L, L->top - 2, L->top - 2, L->top - 1, luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD));
cast(TMS, op - LUA_OPADD + TM_ADD));
L->top--; L->top--;
lua_unlock(L); lua_unlock(L);
} }
@@ -299,17 +306,17 @@ LUA_API void lua_arith (lua_State *L, int op) {
LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
StkId o1, o2; StkId o1, o2;
int i; int i = 0;
lua_lock(L); /* may call tag method */ lua_lock(L); /* may call tag method */
o1 = index2addr(L, index1); o1 = index2addr(L, index1);
o2 = index2addr(L, index2); o2 = index2addr(L, index2);
if (o1 == luaO_nilobject || o2 == luaO_nilobject) if (isvalid(o1) && isvalid(o2)) {
i = 0; switch (op) {
else switch (op) { case LUA_OPEQ: i = equalobj(L, o1, o2); break;
case LUA_OPEQ: i = equalobj(L, o1, o2); break; case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; default: api_check(L, 0, "invalid option");
default: api_check(L, 0, "invalid option"); i = 0; }
} }
lua_unlock(L); lua_unlock(L);
return i; return i;
@@ -390,7 +397,7 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
LUA_API size_t lua_rawlen (lua_State *L, int idx) { LUA_API size_t lua_rawlen (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
switch (ttype(o)) { switch (ttypenv(o)) {
case LUA_TSTRING: return tsvalue(o)->len; case LUA_TSTRING: return tsvalue(o)->len;
case LUA_TUSERDATA: return uvalue(o)->len; case LUA_TUSERDATA: return uvalue(o)->len;
case LUA_TTABLE: return luaH_getn(hvalue(o)); case LUA_TTABLE: return luaH_getn(hvalue(o));
@@ -402,15 +409,15 @@ LUA_API size_t lua_rawlen (lua_State *L, int idx) {
LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
if (ttislcf(o)) return fvalue(o); if (ttislcf(o)) return fvalue(o);
else if (ttisclosure(o) && clvalue(o)->c.isC) else if (ttisCclosure(o))
return clvalue(o)->c.f; return clCvalue(o)->f;
else return NULL; /* not a C function */ else return NULL; /* not a C function */
} }
LUA_API void *lua_touserdata (lua_State *L, int idx) { LUA_API void *lua_touserdata (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
switch (ttype(o)) { switch (ttypenv(o)) {
case LUA_TUSERDATA: return (rawuvalue(o) + 1); case LUA_TUSERDATA: return (rawuvalue(o) + 1);
case LUA_TLIGHTUSERDATA: return pvalue(o); case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL; default: return NULL;
@@ -428,7 +435,8 @@ LUA_API const void *lua_topointer (lua_State *L, int idx) {
StkId o = index2addr(L, idx); StkId o = index2addr(L, idx);
switch (ttype(o)) { switch (ttype(o)) {
case LUA_TTABLE: return hvalue(o); case LUA_TTABLE: return hvalue(o);
case LUA_TFUNCTION: return clvalue(o); case LUA_TLCL: return clLvalue(o);
case LUA_TCCL: return clCvalue(o);
case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));
case LUA_TTHREAD: return thvalue(o); case LUA_TTHREAD: return thvalue(o);
case LUA_TUSERDATA: case LUA_TUSERDATA:
@@ -456,6 +464,8 @@ LUA_API void lua_pushnil (lua_State *L) {
LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
lua_lock(L); lua_lock(L);
setnvalue(L->top, n); setnvalue(L->top, n);
luai_checknum(L, L->top,
luaG_runerror(L, "C API - attempt to push a signaling NaN"));
api_incr_top(L); api_incr_top(L);
lua_unlock(L); lua_unlock(L);
} }
@@ -548,7 +558,7 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
L->top -= n; L->top -= n;
while (n--) while (n--)
setobj2n(L, &cl->c.upvalue[n], L->top + n); setobj2n(L, &cl->c.upvalue[n], L->top + n);
setclvalue(L, L->top, cl); setclCvalue(L, L->top, cl);
} }
api_incr_top(L); api_incr_top(L);
lua_unlock(L); lua_unlock(L);
@@ -586,6 +596,17 @@ LUA_API int lua_pushthread (lua_State *L) {
*/ */
LUA_API void lua_getglobal (lua_State *L, const char *var) {
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt; /* global table */
lua_lock(L);
gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
setsvalue2s(L, L->top++, luaS_new(L, var));
luaV_gettable(L, gt, L->top - 1, L->top - 1);
lua_unlock(L);
}
LUA_API void lua_gettable (lua_State *L, int idx) { LUA_API void lua_gettable (lua_State *L, int idx) {
StkId t; StkId t;
lua_lock(L); lua_lock(L);
@@ -619,11 +640,24 @@ LUA_API void lua_rawget (lua_State *L, int idx) {
LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
StkId o; StkId t;
lua_lock(L); lua_lock(L);
o = index2addr(L, idx); t = index2addr(L, idx);
api_check(L, ttistable(o), "table expected"); api_check(L, ttistable(t), "table expected");
setobj2s(L, L->top, luaH_getint(hvalue(o), n)); setobj2s(L, L->top, luaH_getint(hvalue(t), n));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) {
StkId t;
TValue k;
lua_lock(L);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
setpvalue(&k, cast(void *, p));
setobj2s(L, L->top, luaH_get(hvalue(t), &k));
api_incr_top(L); api_incr_top(L);
lua_unlock(L); lua_unlock(L);
} }
@@ -648,7 +682,7 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) {
int res; int res;
lua_lock(L); lua_lock(L);
obj = index2addr(L, objindex); obj = index2addr(L, objindex);
switch (ttype(obj)) { switch (ttypenv(obj)) {
case LUA_TTABLE: case LUA_TTABLE:
mt = hvalue(obj)->metatable; mt = hvalue(obj)->metatable;
break; break;
@@ -691,6 +725,19 @@ LUA_API void lua_getuservalue (lua_State *L, int idx) {
*/ */
LUA_API void lua_setglobal (lua_State *L, const char *var) {
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt; /* global table */
lua_lock(L);
api_checknelems(L, 1);
gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
setsvalue2s(L, L->top++, luaS_new(L, var));
luaV_settable(L, gt, L->top - 1, L->top - 2);
L->top -= 2; /* pop value and key */
lua_unlock(L);
}
LUA_API void lua_settable (lua_State *L, int idx) { LUA_API void lua_settable (lua_State *L, int idx) {
StkId t; StkId t;
lua_lock(L); lua_lock(L);
@@ -723,6 +770,7 @@ LUA_API void lua_rawset (lua_State *L, int idx) {
t = index2addr(L, idx); t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected"); api_check(L, ttistable(t), "table expected");
setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
invalidateTMcache(hvalue(t));
luaC_barrierback(L, gcvalue(t), L->top-1); luaC_barrierback(L, gcvalue(t), L->top-1);
L->top -= 2; L->top -= 2;
lua_unlock(L); lua_unlock(L);
@@ -730,13 +778,28 @@ LUA_API void lua_rawset (lua_State *L, int idx) {
LUA_API void lua_rawseti (lua_State *L, int idx, int n) { LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
StkId o; StkId t;
lua_lock(L); lua_lock(L);
api_checknelems(L, 1); api_checknelems(L, 1);
o = index2addr(L, idx); t = index2addr(L, idx);
api_check(L, ttistable(o), "table expected"); api_check(L, ttistable(t), "table expected");
setobj2t(L, luaH_setint(L, hvalue(o), n), L->top-1); luaH_setint(L, hvalue(t), n, L->top - 1);
luaC_barrierback(L, gcvalue(o), L->top-1); luaC_barrierback(L, gcvalue(t), L->top-1);
L->top--;
lua_unlock(L);
}
LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
StkId t;
TValue k;
lua_lock(L);
api_checknelems(L, 1);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
setpvalue(&k, cast(void *, p));
setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1);
luaC_barrierback(L, gcvalue(t), L->top - 1);
L->top--; L->top--;
lua_unlock(L); lua_unlock(L);
} }
@@ -755,18 +818,19 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) {
api_check(L, ttistable(L->top - 1), "table expected"); api_check(L, ttistable(L->top - 1), "table expected");
mt = hvalue(L->top - 1); mt = hvalue(L->top - 1);
} }
switch (ttype(obj)) { switch (ttypenv(obj)) {
case LUA_TTABLE: { case LUA_TTABLE: {
hvalue(obj)->metatable = mt; hvalue(obj)->metatable = mt;
if (mt) if (mt)
luaC_objbarrierback(L, gcvalue(obj), mt); luaC_objbarrierback(L, gcvalue(obj), mt);
luaC_checkfinalizer(L, gcvalue(obj), mt);
break; break;
} }
case LUA_TUSERDATA: { case LUA_TUSERDATA: {
uvalue(obj)->metatable = mt; uvalue(obj)->metatable = mt;
if (mt) { if (mt) {
luaC_objbarrier(L, rawuvalue(obj), mt); luaC_objbarrier(L, rawuvalue(obj), mt);
luaC_checkfinalizer(L, rawuvalue(obj)); luaC_checkfinalizer(L, gcvalue(obj), mt);
} }
break; break;
} }
@@ -904,23 +968,22 @@ LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
const char *chunkname) { const char *chunkname, const char *mode) {
ZIO z; ZIO z;
int status; int status;
lua_lock(L); lua_lock(L);
if (!chunkname) chunkname = "?"; if (!chunkname) chunkname = "?";
luaZ_init(L, &z, reader, data); luaZ_init(L, &z, reader, data);
status = luaD_protectedparser(L, &z, chunkname); status = luaD_protectedparser(L, &z, chunkname, mode);
if (status == LUA_OK) { /* no errors? */ if (status == LUA_OK) { /* no errors? */
Closure *f = clvalue(L->top - 1); /* get newly created function */ LClosure *f = clLvalue(L->top - 1); /* get newly created function */
lua_assert(!f->c.isC); if (f->nupvalues == 1) { /* does it have one upvalue? */
if (f->l.nupvalues == 1) { /* does it have one upvalue? */
/* get global table from registry */ /* get global table from registry */
Table *reg = hvalue(&G(L)->l_registry); Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
/* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
setobj(L, f->l.upvals[0]->v, gt); setobj(L, f->upvals[0]->v, gt);
luaC_barrier(L, f->l.upvals[0], gt); luaC_barrier(L, f->upvals[0], gt);
} }
} }
lua_unlock(L); lua_unlock(L);
@@ -959,11 +1022,12 @@ LUA_API int lua_gc (lua_State *L, int what, int data) {
g = G(L); g = G(L);
switch (what) { switch (what) {
case LUA_GCSTOP: { case LUA_GCSTOP: {
stopgc(g); g->gcrunning = 0;
break; break;
} }
case LUA_GCRESTART: { case LUA_GCRESTART: {
g->GCdebt = 0; luaE_setdebt(g, 0);
g->gcrunning = 1;
break; break;
} }
case LUA_GCCOLLECT: { case LUA_GCCOLLECT: {
@@ -972,30 +1036,27 @@ LUA_API int lua_gc (lua_State *L, int what, int data) {
} }
case LUA_GCCOUNT: { case LUA_GCCOUNT: {
/* GC values are expressed in Kbytes: #bytes/2^10 */ /* GC values are expressed in Kbytes: #bytes/2^10 */
res = cast_int(g->totalbytes >> 10); res = cast_int(gettotalbytes(g) >> 10);
break; break;
} }
case LUA_GCCOUNTB: { case LUA_GCCOUNTB: {
res = cast_int(g->totalbytes & 0x3ff); res = cast_int(gettotalbytes(g) & 0x3ff);
break; break;
} }
case LUA_GCSTEP: { case LUA_GCSTEP: {
int stopped = gcstopped(g);
if (g->gckind == KGC_GEN) { /* generational mode? */ if (g->gckind == KGC_GEN) { /* generational mode? */
res = (g->lastmajormem == 0); /* 1 if will do major collection */ res = (g->lastmajormem == 0); /* 1 if will do major collection */
luaC_step(L); /* do a single step */ luaC_forcestep(L); /* do a single step */
} }
else { else {
while (data-- >= 0) { while (data-- >= 0) {
luaC_step(L); luaC_forcestep(L);
if (g->gcstate == GCSpause) { /* end of cycle? */ if (g->gcstate == GCSpause) { /* end of cycle? */
res = 1; /* signal it */ res = 1; /* signal it */
break; break;
} }
} }
} }
if (stopped) /* collector was stopped? */
stopgc(g); /* keep it that way */
break; break;
} }
case LUA_GCSETPAUSE: { case LUA_GCSETPAUSE: {
@@ -1014,7 +1075,7 @@ LUA_API int lua_gc (lua_State *L, int what, int data) {
break; break;
} }
case LUA_GCISRUNNING: { case LUA_GCISRUNNING: {
res = !gcstopped(g); res = g->gcrunning;
break; break;
} }
case LUA_GCGEN: { /* change collector to generational mode */ case LUA_GCGEN: { /* change collector to generational mode */
@@ -1121,35 +1182,34 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
static const char *aux_upvalue (StkId fi, int n, TValue **val, static const char *aux_upvalue (StkId fi, int n, TValue **val,
GCObject **owner) { GCObject **owner) {
Closure *f; switch (ttype(fi)) {
if (!ttisclosure(fi)) return NULL; case LUA_TCCL: { /* C closure */
f = clvalue(fi); CClosure *f = clCvalue(fi);
if (f->c.isC) { if (!(1 <= n && n <= f->nupvalues)) return NULL;
if (!(1 <= n && n <= f->c.nupvalues)) return NULL; *val = &f->upvalue[n-1];
*val = &f->c.upvalue[n-1]; if (owner) *owner = obj2gco(f);
if (owner) *owner = obj2gco(f); return "";
return ""; }
} case LUA_TLCL: { /* Lua closure */
else { LClosure *f = clLvalue(fi);
const char *name; TString *name;
Proto *p = f->l.p; Proto *p = f->p;
if (!(1 <= n && n <= p->sizeupvalues)) return NULL; if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
*val = f->l.upvals[n-1]->v; *val = f->upvals[n-1]->v;
if (owner) *owner = obj2gco(f->l.upvals[n - 1]); if (owner) *owner = obj2gco(f->upvals[n - 1]);
name = getstr(p->upvalues[n-1].name); name = p->upvalues[n-1].name;
if (name == NULL) /* no debug information? */ return (name == NULL) ? "" : getstr(name);
name = ""; }
return name; default: return NULL; /* not a closure */
} }
} }
LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
const char *name; const char *name;
TValue *val; TValue *val = NULL; /* to avoid warnings */
lua_lock(L); lua_lock(L);
name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL); name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);
if (name) { if (name) {
@@ -1163,8 +1223,8 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
const char *name; const char *name;
TValue *val; TValue *val = NULL; /* to avoid warnings */
GCObject *owner; GCObject *owner = NULL; /* to avoid warnings */
StkId fi; StkId fi;
lua_lock(L); lua_lock(L);
fi = index2addr(L, funcindex); fi = index2addr(L, funcindex);
@@ -1180,34 +1240,39 @@ LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
} }
static UpVal **getupvalref (lua_State *L, int fidx, int n, Closure **pf) { static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
Closure *f; LClosure *f;
StkId fi = index2addr(L, fidx); StkId fi = index2addr(L, fidx);
api_check(L, ttisclosure(fi), "Lua function expected"); api_check(L, ttisLclosure(fi), "Lua function expected");
f = clvalue(fi); f = clLvalue(fi);
api_check(L, !f->c.isC, "Lua function expected"); api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
api_check(L, (1 <= n && n <= f->l.p->sizeupvalues), "invalid upvalue index");
if (pf) *pf = f; if (pf) *pf = f;
return &f->l.upvals[n - 1]; /* get its upvalue pointer */ return &f->upvals[n - 1]; /* get its upvalue pointer */
} }
LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
Closure *f;
StkId fi = index2addr(L, fidx); StkId fi = index2addr(L, fidx);
api_check(L, ttisclosure(fi), "function expected"); switch (ttype(fi)) {
f = clvalue(fi); case LUA_TLCL: { /* lua closure */
if (f->c.isC) { return *getupvalref(L, fidx, n, NULL);
api_check(L, 1 <= n && n <= f->c.nupvalues, "invalid upvalue index"); }
return &f->c.upvalue[n - 1]; case LUA_TCCL: { /* C closure */
CClosure *f = clCvalue(fi);
api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
return &f->upvalue[n - 1];
}
default: {
api_check(L, 0, "closure expected");
return NULL;
}
} }
else return *getupvalref(L, fidx, n, NULL);
} }
LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
int fidx2, int n2) { int fidx2, int n2) {
Closure *f1; LClosure *f1;
UpVal **up1 = getupvalref(L, fidx1, n1, &f1); UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
UpVal **up2 = getupvalref(L, fidx2, n2, NULL); UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
*up1 = *up2; *up1 = *up2;

122
lauxlib.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lauxlib.c,v 1.226 2010/11/10 17:38:10 roberto Exp roberto $ ** $Id: lauxlib.c,v 1.239 2011/12/02 13:25:57 roberto Exp roberto $
** Auxiliary functions for building Lua libraries ** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -41,11 +41,10 @@
** return 1 + string at top if find a good name. ** return 1 + string at top if find a good name.
*/ */
static int findfield (lua_State *L, int objidx, int level) { static int findfield (lua_State *L, int objidx, int level) {
int found = 0;
if (level == 0 || !lua_istable(L, -1)) if (level == 0 || !lua_istable(L, -1))
return 0; /* not found */ return 0; /* not found */
lua_pushnil(L); /* start 'next' loop */ lua_pushnil(L); /* start 'next' loop */
while (!found && lua_next(L, -2)) { /* for each pair in table */ while (lua_next(L, -2)) { /* for each pair in table */
if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
if (lua_rawequal(L, objidx, -1)) { /* found object? */ if (lua_rawequal(L, objidx, -1)) { /* found object? */
lua_pop(L, 1); /* remove value (but keep name) */ lua_pop(L, 1); /* remove value (but keep name) */
@@ -86,7 +85,7 @@ static void pushfuncname (lua_State *L, lua_Debug *ar) {
lua_pushfstring(L, "function " LUA_QS, ar->name); lua_pushfstring(L, "function " LUA_QS, ar->name);
else if (*ar->what == 'm') /* main? */ else if (*ar->what == 'm') /* main? */
lua_pushfstring(L, "main chunk"); lua_pushfstring(L, "main chunk");
else if (*ar->what == 'C' || *ar->what == 't') { else if (*ar->what == 'C') {
if (pushglobalfuncname(L, ar)) { if (pushglobalfuncname(L, ar)) {
lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */ lua_remove(L, -2); /* remove name */
@@ -203,6 +202,63 @@ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
return lua_error(L); return lua_error(L);
} }
LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
int en = errno; /* calls to Lua API may change this value */
if (stat) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
if (fname)
lua_pushfstring(L, "%s: %s", fname, strerror(en));
else
lua_pushfstring(L, "%s", strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
#if !defined(inspectstat) /* { */
#if defined(LUA_USE_POSIX)
#include <sys/wait.h>
/*
** use appropriate macros to interpret 'pclose' return status
*/
#define inspectstat(stat,what) \
if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
#else
#define inspectstat(stat,what) /* no op */
#endif
#endif /* } */
LUALIB_API int luaL_execresult (lua_State *L, int stat) {
const char *what = "exit"; /* type of termination */
if (stat == -1) /* error? */
return luaL_fileresult(L, 0, NULL);
else {
inspectstat(stat, what); /* interpret result */
if (*what == 'e' && stat == 0) /* successful termination? */
lua_pushboolean(L, 1);
else
lua_pushnil(L);
lua_pushstring(L, what);
lua_pushinteger(L, stat);
return 3; /* return true/nil,what,code */
}
}
/* }====================================================== */ /* }====================================================== */
@@ -213,7 +269,7 @@ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
*/ */
LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ luaL_getmetatable(L, tname); /* try to get metatable */
if (!lua_isnil(L, -1)) /* name already in use? */ if (!lua_isnil(L, -1)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */ return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1); lua_pop(L, 1);
@@ -234,7 +290,7 @@ LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
void *p = lua_touserdata(L, ud); void *p = lua_touserdata(L, ud);
if (p != NULL) { /* value is a userdata? */ if (p != NULL) { /* value is a userdata? */
if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ luaL_getmetatable(L, tname); /* get correct metatable */
if (!lua_rawequal(L, -1, -2)) /* not the same? */ if (!lua_rawequal(L, -1, -2)) /* not the same? */
p = NULL; /* value is a userdata with wrong metatable */ p = NULL; /* value is a userdata with wrong metatable */
lua_pop(L, 2); /* remove both metatables */ lua_pop(L, 2); /* remove both metatables */
@@ -274,7 +330,9 @@ LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
if (!lua_checkstack(L, space)) { /* keep some extra space to run error routines, if needed */
const int extra = LUA_MINSTACK;
if (!lua_checkstack(L, space + extra)) {
if (msg) if (msg)
luaL_error(L, "stack overflow (%s)", msg); luaL_error(L, "stack overflow (%s)", msg);
else else
@@ -384,8 +442,10 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
newsize = B->n + sz; newsize = B->n + sz;
if (newsize < B->n || newsize - B->n < sz) if (newsize < B->n || newsize - B->n < sz)
luaL_error(L, "buffer too large"); luaL_error(L, "buffer too large");
newbuff = (char *)lua_newuserdata(L, newsize); /* create larger buffer */ /* create larger buffer */
memcpy(newbuff, B->b, B->n); /* move content to new buffer */ newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
/* move content to new buffer */
memcpy(newbuff, B->b, B->n * sizeof(char));
if (buffonstack(B)) if (buffonstack(B))
lua_remove(L, -2); /* remove old buffer */ lua_remove(L, -2); /* remove old buffer */
B->b = newbuff; B->b = newbuff;
@@ -397,7 +457,7 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
char *b = luaL_prepbuffsize(B, l); char *b = luaL_prepbuffsize(B, l);
memcpy(b, s, l); memcpy(b, s, l * sizeof(char));
luaL_addsize(B, l); luaL_addsize(B, l);
} }
@@ -507,7 +567,7 @@ typedef struct LoadF {
static const char *getF (lua_State *L, void *ud, size_t *size) { static const char *getF (lua_State *L, void *ud, size_t *size) {
LoadF *lf = (LoadF *)ud; LoadF *lf = (LoadF *)ud;
(void)L; (void)L; /* not used */
if (lf->n > 0) { /* are there pre-read characters to be read? */ if (lf->n > 0) { /* are there pre-read characters to be read? */
*size = lf->n; /* return them (chars already in buffer) */ *size = lf->n; /* return them (chars already in buffer) */
lf->n = 0; /* no more pre-read characters */ lf->n = 0; /* no more pre-read characters */
@@ -564,7 +624,8 @@ static int skipcomment (LoadF *lf, int *cp) {
} }
LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
const char *mode) {
LoadF lf; LoadF lf;
int status, readstatus; int status, readstatus;
int c; int c;
@@ -587,7 +648,7 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
} }
if (c != EOF) if (c != EOF)
lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
status = lua_load(L, getF, &lf, lua_tostring(L, -1)); status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
readstatus = ferror(lf.f); readstatus = ferror(lf.f);
if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (filename) fclose(lf.f); /* close file (even in case of errors) */
if (readstatus) { if (readstatus) {
@@ -607,7 +668,7 @@ typedef struct LoadS {
static const char *getS (lua_State *L, void *ud, size_t *size) { static const char *getS (lua_State *L, void *ud, size_t *size) {
LoadS *ls = (LoadS *)ud; LoadS *ls = (LoadS *)ud;
(void)L; (void)L; /* not used */
if (ls->size == 0) return NULL; if (ls->size == 0) return NULL;
*size = ls->size; *size = ls->size;
ls->size = 0; ls->size = 0;
@@ -615,12 +676,12 @@ static const char *getS (lua_State *L, void *ud, size_t *size) {
} }
LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size, LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
const char *name) { const char *name, const char *mode) {
LoadS ls; LoadS ls;
ls.s = buff; ls.s = buff;
ls.size = size; ls.size = size;
return lua_load(L, getS, &ls, name); return lua_load(L, getS, &ls, name, mode);
} }
@@ -700,8 +761,8 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
*/ */
#if defined(LUA_COMPAT_MODULE) #if defined(LUA_COMPAT_MODULE)
static const char *luaL_findtablex (lua_State *L, int idx, static const char *luaL_findtable (lua_State *L, int idx,
const char *fname, int szhint) { const char *fname, int szhint) {
const char *e; const char *e;
if (idx) lua_pushvalue(L, idx); if (idx) lua_pushvalue(L, idx);
do { do {
@@ -745,13 +806,13 @@ static int libsize (const luaL_Reg *l) {
*/ */
LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname, LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
int sizehint) { int sizehint) {
luaL_findtablex(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */ luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
lua_getfield(L, -1, modname); /* get _LOADED[modname] */ lua_getfield(L, -1, modname); /* get _LOADED[modname] */
if (!lua_istable(L, -1)) { /* not found? */ if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */ lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */ /* try global variable (and create one if it does not exist) */
lua_pushglobaltable(L); lua_pushglobaltable(L);
if (luaL_findtablex(L, 0, modname, sizehint) != NULL) if (luaL_findtable(L, 0, modname, sizehint) != NULL)
luaL_error(L, "name conflict for module " LUA_QS, modname); luaL_error(L, "name conflict for module " LUA_QS, modname);
lua_pushvalue(L, -1); lua_pushvalue(L, -1);
lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */ lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
@@ -767,7 +828,10 @@ LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
} }
luaL_setfuncs(L, l, nup); if (l)
luaL_setfuncs(L, l, nup);
else
lua_pop(L, nup); /* remove upvalues */
} }
#endif #endif
@@ -780,7 +844,7 @@ LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
*/ */
LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
luaL_checkstack(L, nup, "too many upvalues"); luaL_checkstack(L, nup, "too many upvalues");
for (; l && l->name; l++) { /* fill the table with given functions */ for (; l->name != NULL; l++) { /* fill the table with given functions */
int i; int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */ for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup); lua_pushvalue(L, -nup);
@@ -795,15 +859,16 @@ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
** ensure that stack[idx][fname] has a table and push that table ** ensure that stack[idx][fname] has a table and push that table
** into the stack ** into the stack
*/ */
LUALIB_API void luaL_findtable (lua_State *L, int idx, const char *fname) { LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
lua_getfield(L, idx, fname); lua_getfield(L, idx, fname);
if (lua_istable(L, -1)) return; /* table already there */ if (lua_istable(L, -1)) return 1; /* table already there */
else { else {
idx = lua_absindex(L, idx); idx = lua_absindex(L, idx);
lua_pop(L, 1); /* remove previous result */ lua_pop(L, 1); /* remove previous result */
lua_newtable(L); lua_newtable(L);
lua_pushvalue(L, -1); /* copy to be left at top */ lua_pushvalue(L, -1); /* copy to be left at top */
lua_setfield(L, idx, fname); /* assign new table to field */ lua_setfield(L, idx, fname); /* assign new table to field */
return 0; /* false, because did not find table there */
} }
} }
@@ -819,7 +884,7 @@ LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
lua_pushcfunction(L, openf); lua_pushcfunction(L, openf);
lua_pushstring(L, modname); /* argument to open function */ lua_pushstring(L, modname); /* argument to open function */
lua_call(L, 1, 1); /* open module */ lua_call(L, 1, 1); /* open module */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED"); luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_pushvalue(L, -2); /* make copy of module (call result) */ lua_pushvalue(L, -2); /* make copy of module (call result) */
lua_setfield(L, -2, modname); /* _LOADED[modname] = module */ lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
lua_pop(L, 1); /* remove _LOADED table */ lua_pop(L, 1); /* remove _LOADED table */
@@ -850,8 +915,7 @@ LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud; (void)ud; (void)osize; /* not used */
(void)osize;
if (nsize == 0) { if (nsize == 0) {
free(ptr); free(ptr);
return NULL; return NULL;
@@ -880,7 +944,7 @@ LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
if (v != lua_version(NULL)) if (v != lua_version(NULL))
luaL_error(L, "multiple Lua VMs detected"); luaL_error(L, "multiple Lua VMs detected");
else if (*v != ver) else if (*v != ver)
luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f", luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
ver, *v); ver, *v);
/* check conversions number -> integer types */ /* check conversions number -> integer types */
lua_pushnumber(L, -(lua_Number)0x1234); lua_pushnumber(L, -(lua_Number)0x1234);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lauxlib.h,v 1.112 2010/11/16 17:43:29 roberto Exp roberto $ ** $Id: lauxlib.h,v 1.119 2011/11/14 17:10:24 roberto Exp roberto $
** Auxiliary functions for building Lua libraries ** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -62,6 +62,9 @@ LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
const char *const lst[]); const char *const lst[]);
LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
/* pre-defined references */ /* pre-defined references */
#define LUA_NOREF (-2) #define LUA_NOREF (-2)
#define LUA_REFNIL (-1) #define LUA_REFNIL (-1)
@@ -69,9 +72,13 @@ LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
LUALIB_API int (luaL_ref) (lua_State *L, int t); LUALIB_API int (luaL_ref) (lua_State *L, int t);
LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,
LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, const char *mode);
const char *name);
#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)
LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
const char *name, const char *mode);
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void); LUALIB_API lua_State *(luaL_newstate) (void);
@@ -83,7 +90,7 @@ LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
LUALIB_API void (luaL_findtable) (lua_State *L, int idx, const char *fname); LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
const char *msg, int level); const char *msg, int level);
@@ -124,6 +131,8 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
/* /*
** {====================================================== ** {======================================================
@@ -160,7 +169,33 @@ LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
/* }====================================================== */ /* }====================================================== */
/*
** {======================================================
** File handles for IO library
** =======================================================
*/
/*
** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and
** initial structure 'luaL_Stream' (it may contain other fields
** after that initial structure).
*/
#define LUA_FILEHANDLE "FILE*"
typedef struct luaL_Stream {
FILE *f; /* stream (NULL for incompletely created streams) */
lua_CFunction closef; /* to close stream (NULL for closed streams) */
} luaL_Stream;
/* }====================================================== */
/* compatibility with old module system */ /* compatibility with old module system */
#if defined(LUA_COMPAT_MODULE)
LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,
int sizehint); int sizehint);
@@ -169,6 +204,8 @@ LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0)) #define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))
#endif
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lbaselib.c,v 1.250 2010/09/07 19:38:36 roberto Exp roberto $ ** $Id: lbaselib.c,v 1.272 2011/11/30 12:42:21 roberto Exp roberto $
** Basic library ** Basic library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -32,44 +32,56 @@ static int luaB_print (lua_State *L) {
lua_call(L, 1, 1); lua_call(L, 1, 1);
s = lua_tolstring(L, -1, &l); /* get result */ s = lua_tolstring(L, -1, &l); /* get result */
if (s == NULL) if (s == NULL)
return luaL_error(L, LUA_QL("tostring") " must return a string to " return luaL_error(L,
LUA_QL("print")); LUA_QL("tostring") " must return a string to " LUA_QL("print"));
if (i>1) luai_writestring("\t", 1); if (i>1) luai_writestring("\t", 1);
luai_writestring(s, l); luai_writestring(s, l);
lua_pop(L, 1); /* pop result */ lua_pop(L, 1); /* pop result */
} }
luai_writestring("\n", 1); luai_writeline();
return 0; return 0;
} }
#define SPACECHARS " \f\n\r\t\v"
static int luaB_tonumber (lua_State *L) { static int luaB_tonumber (lua_State *L) {
int base = luaL_optint(L, 2, 10); if (lua_isnoneornil(L, 2)) { /* standard conversion */
if (base == 10) { /* standard conversion */ int isnum;
luaL_checkany(L, 1); lua_Number n = lua_tonumberx(L, 1, &isnum);
if (lua_isnumber(L, 1)) { if (isnum) {
lua_pushnumber(L, lua_tonumber(L, 1)); lua_pushnumber(L, n);
return 1; return 1;
} } /* else not a number; must be something */
luaL_checkany(L, 1);
} }
else { else {
const char *s1 = luaL_checkstring(L, 1); size_t l;
char *s2; const char *s = luaL_checklstring(L, 1, &l);
unsigned long n; const char *e = s + l; /* end point for 's' */
int base = luaL_checkint(L, 2);
int neg = 0; int neg = 0;
luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
while (isspace((unsigned char)(*s1))) s1++; /* skip initial spaces */ s += strspn(s, SPACECHARS); /* skip initial spaces */
if (*s1 == '-') { s1++; neg = 1; } if (*s == '-') { s++; neg = 1; } /* handle signal */
n = strtoul(s1, &s2, base); else if (*s == '+') s++;
if (s1 != s2) { /* at least one valid digit? */ if (isalnum((unsigned char)*s)) {
while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */ lua_Number n = 0;
if (*s2 == '\0') { /* no invalid trailing characters? */ do {
lua_pushnumber(L, (neg) ? -(lua_Number)n : (lua_Number)n); int digit = (isdigit((unsigned char)*s)) ? *s - '0'
: toupper((unsigned char)*s) - 'A' + 10;
if (digit >= base) break; /* invalid numeral; force a fail */
n = n * (lua_Number)base + (lua_Number)digit;
s++;
} while (isalnum((unsigned char)*s));
s += strspn(s, SPACECHARS); /* skip trailing spaces */
if (s == e) { /* no invalid trailing characters? */
lua_pushnumber(L, (neg) ? -n : n);
return 1; return 1;
} } /* else not a number */
} } /* else not a number */
} }
lua_pushnil(L); /* else not a number */ lua_pushnil(L); /* not a number */
return 1; return 1;
} }
@@ -110,13 +122,6 @@ static int luaB_setmetatable (lua_State *L) {
} }
static int luaB_getfenv (lua_State *L) {
return luaL_error(L, "getfenv/setfenv deprecated");
}
#define luaB_setfenv luaB_getfenv
static int luaB_rawequal (lua_State *L) { static int luaB_rawequal (lua_State *L) {
luaL_checkany(L, 1); luaL_checkany(L, 1);
luaL_checkany(L, 2); luaL_checkany(L, 2);
@@ -125,6 +130,15 @@ static int luaB_rawequal (lua_State *L) {
} }
static int luaB_rawlen (lua_State *L) {
int t = lua_type(L, 1);
luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
"table or string expected");
lua_pushinteger(L, lua_rawlen(L, 1));
return 1;
}
static int luaB_rawget (lua_State *L) { static int luaB_rawget (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE); luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2); luaL_checkany(L, 2);
@@ -146,7 +160,7 @@ static int luaB_rawset (lua_State *L) {
static int luaB_collectgarbage (lua_State *L) { static int luaB_collectgarbage (lua_State *L) {
static const char *const opts[] = {"stop", "restart", "collect", static const char *const opts[] = {"stop", "restart", "collect",
"count", "step", "setpause", "setstepmul", "count", "step", "setpause", "setstepmul",
"setmajorinc", "isrunning", "gen", "inc", NULL}; "setmajorinc", "isrunning", "generational", "incremental", NULL};
static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
@@ -241,7 +255,14 @@ static int load_aux (lua_State *L, int status) {
static int luaB_loadfile (lua_State *L) { static int luaB_loadfile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL); const char *fname = luaL_optstring(L, 1, NULL);
return load_aux(L, luaL_loadfile(L, fname)); const char *mode = luaL_optstring(L, 2, NULL);
int env = !lua_isnone(L, 3); /* 'env' parameter? */
int status = luaL_loadfilex(L, fname, mode);
if (status == LUA_OK && env) { /* 'env' parameter? */
lua_pushvalue(L, 3);
lua_setupvalue(L, -2, 1); /* set it as 1st upvalue of loaded chunk */
}
return load_aux(L, status);
} }
@@ -251,20 +272,13 @@ static int luaB_loadfile (lua_State *L) {
** ======================================================= ** =======================================================
*/ */
static const char *checkrights (lua_State *L, const char *mode, const char *s) {
if (strchr(mode, 'b') == NULL && *s == LUA_SIGNATURE[0])
return lua_pushstring(L, "attempt to load a binary chunk");
if (strchr(mode, 't') == NULL && *s != LUA_SIGNATURE[0])
return lua_pushstring(L, "attempt to load a text chunk");
return NULL; /* chunk in allowed format */
}
/* /*
** reserves a slot, above all arguments, to hold a copy of the returned ** reserved slot, above all arguments, to hold a copy of the returned
** string to avoid it being collected while parsed ** string to avoid it being collected while parsed. 'load' has four
** optional arguments (chunk, source name, mode, and environment).
*/ */
#define RESERVEDSLOT 4 #define RESERVEDSLOT 5
/* /*
@@ -273,83 +287,45 @@ static const char *checkrights (lua_State *L, const char *mode, const char *s) {
** stack top. Instead, it keeps its resulting string in a ** stack top. Instead, it keeps its resulting string in a
** reserved slot inside the stack. ** reserved slot inside the stack.
*/ */
typedef struct { /* reader state */
int f; /* position of reader function on stack */
const char *mode; /* allowed modes (binary/text) */
} Readstat;
static const char *generic_reader (lua_State *L, void *ud, size_t *size) { static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
const char *s; (void)(ud); /* not used */
Readstat *stat = (Readstat *)ud;
luaL_checkstack(L, 2, "too many nested functions"); luaL_checkstack(L, 2, "too many nested functions");
lua_pushvalue(L, stat->f); /* get function */ lua_pushvalue(L, 1); /* get function */
lua_call(L, 0, 1); /* call it */ lua_call(L, 0, 1); /* call it */
if (lua_isnil(L, -1)) { if (lua_isnil(L, -1)) {
*size = 0; *size = 0;
return NULL; return NULL;
} }
else if ((s = lua_tostring(L, -1)) != NULL) { else if (!lua_isstring(L, -1))
if (stat->mode != NULL) { /* first time? */
s = checkrights(L, stat->mode, s); /* check mode */
stat->mode = NULL; /* to avoid further checks */
if (s) luaL_error(L, s);
}
lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
return lua_tolstring(L, RESERVEDSLOT, size);
}
else {
luaL_error(L, "reader function must return a string"); luaL_error(L, "reader function must return a string");
return NULL; /* to avoid warnings */ lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
} return lua_tolstring(L, RESERVEDSLOT, size);
}
static int luaB_load_aux (lua_State *L, int farg) {
int status;
Readstat stat;
size_t l;
const char *s = lua_tolstring(L, farg, &l);
stat.mode = luaL_optstring(L, farg + 2, "bt");
if (s != NULL) { /* loading a string? */
const char *chunkname = luaL_optstring(L, farg + 1, s);
status = (checkrights(L, stat.mode, s) != NULL)
|| luaL_loadbuffer(L, s, l, chunkname);
}
else { /* loading from a reader function */
const char *chunkname = luaL_optstring(L, farg + 1, "=(load)");
luaL_checktype(L, farg, LUA_TFUNCTION);
stat.f = farg;
lua_settop(L, RESERVEDSLOT); /* create reserved slot */
status = lua_load(L, generic_reader, &stat, chunkname);
}
return load_aux(L, status);
} }
static int luaB_load (lua_State *L) { static int luaB_load (lua_State *L) {
return luaB_load_aux(L, 1); int status;
} size_t l;
int top = lua_gettop(L);
const char *s = lua_tolstring(L, 1, &l);
static int luaB_loadin (lua_State *L) { const char *mode = luaL_optstring(L, 3, "bt");
int n; if (s != NULL) { /* loading a string? */
luaL_checkany(L, 1); const char *chunkname = luaL_optstring(L, 2, s);
n = luaB_load_aux(L, 2); status = luaL_loadbufferx(L, s, l, chunkname, mode);
if (n == 1) { /* success? */
lua_pushvalue(L, 1); /* environment for loaded function */
if (lua_setupvalue(L, -2, 1) == NULL)
luaL_error(L, "loaded chunk does not have an upvalue");
} }
return n; else { /* loading from a reader function */
const char *chunkname = luaL_optstring(L, 2, "=(load)");
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, RESERVEDSLOT); /* create reserved slot */
status = lua_load(L, generic_reader, NULL, chunkname, mode);
}
if (status == LUA_OK && top >= 4) { /* is there an 'env' argument */
lua_pushvalue(L, 4); /* environment for loaded function */
lua_setupvalue(L, -2, 1); /* set it as 1st upvalue */
}
return load_aux(L, status);
} }
static int luaB_loadstring (lua_State *L) {
lua_settop(L, 2);
lua_pushliteral(L, "tb");
return luaB_load(L); /* dostring(s, n) == load(s, n, "tb") */
}
/* }====================================================== */ /* }====================================================== */
@@ -390,27 +366,32 @@ static int luaB_select (lua_State *L) {
} }
static int pcallcont (lua_State *L) { static int finishpcall (lua_State *L, int status) {
int errfunc; /* call has an error function in bottom of the stack */ if (!lua_checkstack(L, 1)) { /* no space for extra boolean? */
int status = lua_getctx(L, &errfunc); lua_settop(L, 0); /* create space for return values */
lua_assert(status != LUA_OK); lua_pushboolean(L, 0);
lua_pushboolean(L, (status == LUA_YIELD)); /* first result (status) */ lua_pushstring(L, "stack overflow");
if (errfunc) /* came from xpcall? */ return 2; /* return false, msg */
lua_replace(L, 1); /* put first result in place of error function */ }
else /* came from pcall */ lua_pushboolean(L, status); /* first result (status) */
lua_insert(L, 1); /* open space for first result */ lua_replace(L, 1); /* put first result in first slot */
return lua_gettop(L); return lua_gettop(L);
} }
static int pcallcont (lua_State *L) {
int status = lua_getctx(L, NULL);
return finishpcall(L, (status == LUA_YIELD));
}
static int luaB_pcall (lua_State *L) { static int luaB_pcall (lua_State *L) {
int status; int status;
luaL_checkany(L, 1); luaL_checkany(L, 1);
status = lua_pcallk(L, lua_gettop(L) - 1, LUA_MULTRET, 0, 0, pcallcont); lua_pushnil(L);
luaL_checkstack(L, 1, NULL); lua_insert(L, 1); /* create space for status result */
lua_pushboolean(L, (status == LUA_OK)); status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont);
lua_insert(L, 1); return finishpcall(L, (status == LUA_OK));
return lua_gettop(L); /* return status + all results */
} }
@@ -421,11 +402,8 @@ static int luaB_xpcall (lua_State *L) {
lua_pushvalue(L, 1); /* exchange function... */ lua_pushvalue(L, 1); /* exchange function... */
lua_copy(L, 2, 1); /* ...and error handler */ lua_copy(L, 2, 1); /* ...and error handler */
lua_replace(L, 2); lua_replace(L, 2);
status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 1, pcallcont); status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont);
luaL_checkstack(L, 1, NULL); return finishpcall(L, (status == LUA_OK));
lua_pushboolean(L, (status == LUA_OK));
lua_replace(L, 1);
return lua_gettop(L); /* return status + all results */
} }
@@ -436,55 +414,27 @@ static int luaB_tostring (lua_State *L) {
} }
static int luaB_newproxy (lua_State *L) {
lua_settop(L, 1);
lua_newuserdata(L, 0); /* create proxy */
if (lua_toboolean(L, 1) == 0)
return 1; /* no metatable */
else if (lua_isboolean(L, 1)) {
lua_createtable(L, 0, 1); /* create a new metatable `m' ... */
lua_pushboolean(L, 1);
lua_setfield(L, -2, "__gc"); /* ... m.__gc = false (HACK!!)... */
lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
lua_pushboolean(L, 1);
lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
}
else {
int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
if (lua_getmetatable(L, 1)) {
lua_rawget(L, lua_upvalueindex(1));
validproxy = lua_toboolean(L, -1);
lua_pop(L, 1); /* remove value */
}
luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
lua_getmetatable(L, 1); /* metatable is valid; get it */
}
lua_setmetatable(L, 2);
return 1;
}
static const luaL_Reg base_funcs[] = { static const luaL_Reg base_funcs[] = {
{"assert", luaB_assert}, {"assert", luaB_assert},
{"collectgarbage", luaB_collectgarbage}, {"collectgarbage", luaB_collectgarbage},
{"dofile", luaB_dofile}, {"dofile", luaB_dofile},
{"error", luaB_error}, {"error", luaB_error},
{"getfenv", luaB_getfenv},
{"getmetatable", luaB_getmetatable}, {"getmetatable", luaB_getmetatable},
{"ipairs", luaB_ipairs}, {"ipairs", luaB_ipairs},
{"loadfile", luaB_loadfile}, {"loadfile", luaB_loadfile},
{"load", luaB_load}, {"load", luaB_load},
{"loadin", luaB_loadin}, #if defined(LUA_COMPAT_LOADSTRING)
{"loadstring", luaB_loadstring}, {"loadstring", luaB_load},
#endif
{"next", luaB_next}, {"next", luaB_next},
{"pairs", luaB_pairs}, {"pairs", luaB_pairs},
{"pcall", luaB_pcall}, {"pcall", luaB_pcall},
{"print", luaB_print}, {"print", luaB_print},
{"rawequal", luaB_rawequal}, {"rawequal", luaB_rawequal},
{"rawlen", luaB_rawlen},
{"rawget", luaB_rawget}, {"rawget", luaB_rawget},
{"rawset", luaB_rawset}, {"rawset", luaB_rawset},
{"select", luaB_select}, {"select", luaB_select},
{"setfenv", luaB_setfenv},
{"setmetatable", luaB_setmetatable}, {"setmetatable", luaB_setmetatable},
{"tonumber", luaB_tonumber}, {"tonumber", luaB_tonumber},
{"tostring", luaB_tostring}, {"tostring", luaB_tostring},
@@ -503,14 +453,6 @@ LUAMOD_API int luaopen_base (lua_State *L) {
luaL_setfuncs(L, base_funcs, 0); luaL_setfuncs(L, base_funcs, 0);
lua_pushliteral(L, LUA_VERSION); lua_pushliteral(L, LUA_VERSION);
lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */ lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
/* `newproxy' needs a weaktable as upvalue */
lua_createtable(L, 0, 1); /* new table `w' */
lua_pushvalue(L, -1); /* `w' will be its own metatable */
lua_setmetatable(L, -2);
lua_pushliteral(L, "kv");
lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
lua_pushcclosure(L, luaB_newproxy, 1);
lua_setfield(L, -2, "newproxy"); /* set global `newproxy' */
return 1; return 1;
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lbitlib.c,v 1.12 2010/11/22 16:39:20 roberto Exp roberto $ ** $Id: lbitlib.c,v 1.15 2010/12/17 13:26:38 roberto Exp roberto $
** Standard library for bitwise operations ** Standard library for bitwise operations
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -14,25 +14,30 @@
/* number of bits to consider in a number */ /* number of bits to consider in a number */
#define NBITS 32 #if !defined(LUA_NBITS)
#define LUA_NBITS 32
#endif
#define ALLONES (~(((~(lua_Unsigned)0) << (NBITS - 1)) << 1))
/* mask to trim extra bits */ #define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
/* macro to trim extra bits */
#define trim(x) ((x) & ALLONES) #define trim(x) ((x) & ALLONES)
/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */
#define mask(n) (~((ALLONES << 1) << ((n) - 1)))
typedef lua_Unsigned b_uint; typedef lua_Unsigned b_uint;
#define getuintarg(L,arg) luaL_checkunsigned(L,arg)
static b_uint andaux (lua_State *L) { static b_uint andaux (lua_State *L) {
int i, n = lua_gettop(L); int i, n = lua_gettop(L);
b_uint r = ~(b_uint)0; b_uint r = ~(b_uint)0;
for (i = 1; i <= n; i++) for (i = 1; i <= n; i++)
r &= getuintarg(L, i); r &= luaL_checkunsigned(L, i);
return trim(r); return trim(r);
} }
@@ -55,7 +60,7 @@ static int b_or (lua_State *L) {
int i, n = lua_gettop(L); int i, n = lua_gettop(L);
b_uint r = 0; b_uint r = 0;
for (i = 1; i <= n; i++) for (i = 1; i <= n; i++)
r |= getuintarg(L, i); r |= luaL_checkunsigned(L, i);
lua_pushunsigned(L, trim(r)); lua_pushunsigned(L, trim(r));
return 1; return 1;
} }
@@ -65,14 +70,14 @@ static int b_xor (lua_State *L) {
int i, n = lua_gettop(L); int i, n = lua_gettop(L);
b_uint r = 0; b_uint r = 0;
for (i = 1; i <= n; i++) for (i = 1; i <= n; i++)
r ^= getuintarg(L, i); r ^= luaL_checkunsigned(L, i);
lua_pushunsigned(L, trim(r)); lua_pushunsigned(L, trim(r));
return 1; return 1;
} }
static int b_not (lua_State *L) { static int b_not (lua_State *L) {
b_uint r = ~getuintarg(L, 1); b_uint r = ~luaL_checkunsigned(L, 1);
lua_pushunsigned(L, trim(r)); lua_pushunsigned(L, trim(r));
return 1; return 1;
} }
@@ -82,11 +87,11 @@ static int b_shift (lua_State *L, b_uint r, int i) {
if (i < 0) { /* shift right? */ if (i < 0) { /* shift right? */
i = -i; i = -i;
r = trim(r); r = trim(r);
if (i >= NBITS) r = 0; if (i >= LUA_NBITS) r = 0;
else r >>= i; else r >>= i;
} }
else { /* shift left */ else { /* shift left */
if (i >= NBITS) r = 0; if (i >= LUA_NBITS) r = 0;
else r <<= i; else r <<= i;
r = trim(r); r = trim(r);
} }
@@ -96,22 +101,22 @@ static int b_shift (lua_State *L, b_uint r, int i) {
static int b_lshift (lua_State *L) { static int b_lshift (lua_State *L) {
return b_shift(L, getuintarg(L, 1), luaL_checkint(L, 2)); return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkint(L, 2));
} }
static int b_rshift (lua_State *L) { static int b_rshift (lua_State *L) {
return b_shift(L, getuintarg(L, 1), -luaL_checkint(L, 2)); return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkint(L, 2));
} }
static int b_arshift (lua_State *L) { static int b_arshift (lua_State *L) {
b_uint r = getuintarg(L, 1); b_uint r = luaL_checkunsigned(L, 1);
int i = luaL_checkint(L, 2); int i = luaL_checkint(L, 2);
if (i < 0 || !(r & ((b_uint)1 << (NBITS - 1)))) if (i < 0 || !(r & ((b_uint)1 << (LUA_NBITS - 1))))
return b_shift(L, r, -i); return b_shift(L, r, -i);
else { /* arithmetic shift for 'negative' number */ else { /* arithmetic shift for 'negative' number */
if (i >= NBITS) r = ALLONES; if (i >= LUA_NBITS) r = ALLONES;
else else
r = trim((r >> i) | ~(~(b_uint)0 >> i)); /* add signal bit */ r = trim((r >> i) | ~(~(b_uint)0 >> i)); /* add signal bit */
lua_pushunsigned(L, r); lua_pushunsigned(L, r);
@@ -121,10 +126,10 @@ static int b_arshift (lua_State *L) {
static int b_rot (lua_State *L, int i) { static int b_rot (lua_State *L, int i) {
b_uint r = getuintarg(L, 1); b_uint r = luaL_checkunsigned(L, 1);
i &= (NBITS - 1); /* i = i % NBITS */ i &= (LUA_NBITS - 1); /* i = i % NBITS */
r = trim(r); r = trim(r);
r = (r << i) | (r >> (NBITS - i)); r = (r << i) | (r >> (LUA_NBITS - i));
lua_pushunsigned(L, trim(r)); lua_pushunsigned(L, trim(r));
return 1; return 1;
} }
@@ -140,17 +145,58 @@ static int b_rrot (lua_State *L) {
} }
/*
** get field and width arguments for field-manipulation functions,
** checking whether they are valid
*/
static int fieldargs (lua_State *L, int farg, int *width) {
int f = luaL_checkint(L, farg);
int w = luaL_optint(L, farg + 1, 1);
luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
if (f + w > LUA_NBITS)
luaL_error(L, "trying to access non-existent bits");
*width = w;
return f;
}
static int b_extract (lua_State *L) {
int w;
b_uint r = luaL_checkunsigned(L, 1);
int f = fieldargs(L, 2, &w);
r = (r >> f) & mask(w);
lua_pushunsigned(L, r);
return 1;
}
static int b_replace (lua_State *L) {
int w;
b_uint r = luaL_checkunsigned(L, 1);
b_uint v = luaL_checkunsigned(L, 2);
int f = fieldargs(L, 3, &w);
int m = mask(w);
v &= m; /* erase bits outside given width */
r = (r & ~(m << f)) | (v << f);
lua_pushunsigned(L, r);
return 1;
}
static const luaL_Reg bitlib[] = { static const luaL_Reg bitlib[] = {
{"arshift", b_arshift}, {"arshift", b_arshift},
{"band", b_and}, {"band", b_and},
{"bnot", b_not}, {"bnot", b_not},
{"bor", b_or}, {"bor", b_or},
{"bxor", b_xor}, {"bxor", b_xor},
{"btest", b_test},
{"extract", b_extract},
{"lrotate", b_lrot}, {"lrotate", b_lrot},
{"lshift", b_lshift}, {"lshift", b_lshift},
{"replace", b_replace},
{"rrotate", b_rrot}, {"rrotate", b_rrot},
{"rshift", b_rshift}, {"rshift", b_rshift},
{"btest", b_test},
{NULL, NULL} {NULL, NULL}
}; };

96
lcode.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lcode.c,v 2.48 2010/07/02 20:42:40 roberto Exp roberto $ ** $Id: lcode.c,v 2.59 2011/08/15 19:41:58 roberto Exp roberto $
** Code generator for Lua ** Code generator for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -23,6 +23,7 @@
#include "lparser.h" #include "lparser.h"
#include "lstring.h" #include "lstring.h"
#include "ltable.h" #include "ltable.h"
#include "lvm.h"
#define hasjumps(e) ((e)->t != (e)->f) #define hasjumps(e) ((e)->t != (e)->f)
@@ -35,19 +36,23 @@ static int isnumeral(expdesc *e) {
void luaK_nil (FuncState *fs, int from, int n) { void luaK_nil (FuncState *fs, int from, int n) {
Instruction *previous; Instruction *previous;
int l = from + n - 1; /* last register to set nil */
if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ if (fs->pc > fs->lasttarget) { /* no jumps to current position? */
previous = &fs->f->code[fs->pc-1]; previous = &fs->f->code[fs->pc-1];
if (GET_OPCODE(*previous) == OP_LOADNIL) { if (GET_OPCODE(*previous) == OP_LOADNIL) {
int pfrom = GETARG_A(*previous); int pfrom = GETARG_A(*previous);
int pto = GETARG_B(*previous); int pl = pfrom + GETARG_B(*previous);
if (pfrom <= from && from <= pto+1) { /* can connect both? */ if ((pfrom <= from && from <= pl + 1) ||
if (from+n-1 > pto) (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
SETARG_B(*previous, from+n-1); if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
if (pl > l) l = pl; /* l = max(l, pl) */
SETARG_A(*previous, from);
SETARG_B(*previous, l - from);
return; return;
} }
} } /* else go through */
} }
luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */ luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
} }
@@ -171,6 +176,19 @@ void luaK_patchlist (FuncState *fs, int list, int target) {
} }
LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) {
level++; /* argument is +1 to reserve 0 as non-op */
while (list != NO_JUMP) {
int next = getjump(fs, list);
lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&
(GETARG_A(fs->f->code[list]) == 0 ||
GETARG_A(fs->f->code[list]) >= level));
SETARG_A(fs->f->code[list], level);
list = next;
}
}
void luaK_patchtohere (FuncState *fs, int list) { void luaK_patchtohere (FuncState *fs, int list) {
luaK_getlabel(fs); luaK_getlabel(fs);
luaK_concat(fs, &fs->jpc, list); luaK_concat(fs, &fs->jpc, list);
@@ -195,11 +213,11 @@ static int luaK_code (FuncState *fs, Instruction i) {
Proto *f = fs->f; Proto *f = fs->f;
dischargejpc(fs); /* `pc' will change */ dischargejpc(fs); /* `pc' will change */
/* put new instruction in code array */ /* put new instruction in code array */
luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction, luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
MAX_INT, "opcodes"); MAX_INT, "opcodes");
f->code[fs->pc] = i; f->code[fs->pc] = i;
/* save corresponding line information */ /* save corresponding line information */
luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int, luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
MAX_INT, "opcodes"); MAX_INT, "opcodes");
f->lineinfo[fs->pc] = fs->ls->lastline; f->lineinfo[fs->pc] = fs->ls->lastline;
return fs->pc++; return fs->pc++;
@@ -229,11 +247,11 @@ static int codeextraarg (FuncState *fs, int a) {
} }
int luaK_codeABxX (FuncState *fs, OpCode o, int reg, int k) { int luaK_codek (FuncState *fs, int reg, int k) {
if (k < MAXARG_Bx) if (k <= MAXARG_Bx)
return luaK_codeABx(fs, o, reg, k + 1); return luaK_codeABx(fs, OP_LOADK, reg, k);
else { else {
int p = luaK_codeABx(fs, o, reg, 0); int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
codeextraarg(fs, k); codeextraarg(fs, k);
return p; return p;
} }
@@ -271,14 +289,14 @@ static void freeexp (FuncState *fs, expdesc *e) {
static int addk (FuncState *fs, TValue *key, TValue *v) { static int addk (FuncState *fs, TValue *key, TValue *v) {
lua_State *L = fs->L; lua_State *L = fs->ls->L;
TValue *idx = luaH_set(L, fs->h, key); TValue *idx = luaH_set(L, fs->h, key);
Proto *f = fs->f; Proto *f = fs->f;
int k, oldsize; int k, oldsize;
if (ttisnumber(idx)) { if (ttisnumber(idx)) {
lua_Number n = nvalue(idx); lua_Number n = nvalue(idx);
lua_number2int(k, n); lua_number2int(k, n);
if (luaO_rawequalObj(&f->k[k], v)) if (luaV_rawequalobj(&f->k[k], v))
return k; return k;
/* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0"); /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");
go through and create a new entry for this value */ go through and create a new entry for this value */
@@ -286,6 +304,8 @@ static int addk (FuncState *fs, TValue *key, TValue *v) {
/* constant not found; create a new entry */ /* constant not found; create a new entry */
oldsize = f->sizek; oldsize = f->sizek;
k = fs->nk; k = fs->nk;
/* numerical value does not need GC barrier;
table has no metatable, so it does not need to invalidate cache */
setnvalue(idx, cast_num(k)); setnvalue(idx, cast_num(k));
luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
@@ -298,14 +318,14 @@ static int addk (FuncState *fs, TValue *key, TValue *v) {
int luaK_stringK (FuncState *fs, TString *s) { int luaK_stringK (FuncState *fs, TString *s) {
TValue o; TValue o;
setsvalue(fs->L, &o, s); setsvalue(fs->ls->L, &o, s);
return addk(fs, &o, &o); return addk(fs, &o, &o);
} }
int luaK_numberK (FuncState *fs, lua_Number r) { int luaK_numberK (FuncState *fs, lua_Number r) {
int n; int n;
lua_State *L = fs->L; lua_State *L = fs->ls->L;
TValue o; TValue o;
setnvalue(&o, r); setnvalue(&o, r);
if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */ if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */
@@ -332,7 +352,7 @@ static int nilK (FuncState *fs) {
TValue k, v; TValue k, v;
setnilvalue(&v); setnilvalue(&v);
/* cannot use nil as key; instead use table itself to represent nil */ /* cannot use nil as key; instead use table itself to represent nil */
sethvalue(fs->L, &k, fs->h); sethvalue(fs->ls->L, &k, fs->h);
return addk(fs, &k, &v); return addk(fs, &k, &v);
} }
@@ -564,15 +584,15 @@ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
int func; int ereg;
luaK_exp2anyreg(fs, e); luaK_exp2anyreg(fs, e);
ereg = e->u.info; /* register where 'e' was placed */
freeexp(fs, e); freeexp(fs, e);
func = fs->freereg; e->u.info = fs->freereg; /* base register for op_self */
luaK_codeABC(fs, OP_SELF, func, e->u.info, luaK_exp2RK(fs, key));
freeexp(fs, key);
luaK_reserveregs(fs, 2);
e->u.info = func;
e->k = VNONRELOC; e->k = VNONRELOC;
luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));
freeexp(fs, key);
} }
@@ -603,21 +623,14 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) {
int pc; /* pc of last jump */ int pc; /* pc of last jump */
luaK_dischargevars(fs, e); luaK_dischargevars(fs, e);
switch (e->k) { switch (e->k) {
case VK: case VKNUM: case VTRUE: {
pc = NO_JUMP; /* always true; do nothing */
break;
}
case VJMP: { case VJMP: {
invertjump(fs, e); invertjump(fs, e);
pc = e->u.info; pc = e->u.info;
break; break;
} }
case VFALSE: { case VK: case VKNUM: case VTRUE: {
if (!hasjumps(e)) { pc = NO_JUMP; /* always true; do nothing */
pc = luaK_jump(fs); /* always jump */ break;
break;
}
/* else go through */
} }
default: { default: {
pc = jumponcond(fs, e, 0); pc = jumponcond(fs, e, 0);
@@ -630,24 +643,17 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) {
} }
static void luaK_goiffalse (FuncState *fs, expdesc *e) { void luaK_goiffalse (FuncState *fs, expdesc *e) {
int pc; /* pc of last jump */ int pc; /* pc of last jump */
luaK_dischargevars(fs, e); luaK_dischargevars(fs, e);
switch (e->k) { switch (e->k) {
case VNIL: case VFALSE: {
pc = NO_JUMP; /* always false; do nothing */
break;
}
case VJMP: { case VJMP: {
pc = e->u.info; pc = e->u.info;
break; break;
} }
case VTRUE: { case VNIL: case VFALSE: {
if (!hasjumps(e)) { pc = NO_JUMP; /* always false; do nothing */
pc = luaK_jump(fs); /* always jump */ break;
break;
}
/* else go through */
} }
default: { default: {
pc = jumponcond(fs, e, 1); pc = jumponcond(fs, e, 1);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lcode.h,v 1.54 2010/04/17 12:46:32 roberto Exp roberto $ ** $Id: lcode.h,v 1.57 2011/04/07 18:14:12 roberto Exp roberto $
** Code generator for Lua ** Code generator for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -44,11 +44,9 @@ typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) #define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)
#define luaK_codek(fs,reg,k) luaK_codeABxX(fs, OP_LOADK, reg, k)
LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
LUAI_FUNC int luaK_codeABxX (FuncState *fs, OpCode o, int reg, int k); LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k);
LUAI_FUNC void luaK_fixline (FuncState *fs, int line); LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
@@ -64,6 +62,7 @@ LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);
LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);
@@ -71,6 +70,7 @@ LUAI_FUNC int luaK_jump (FuncState *fs);
LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level);
LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
LUAI_FUNC int luaK_getlabel (FuncState *fs); LUAI_FUNC int luaK_getlabel (FuncState *fs);
LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lcorolib.c,v 1.1 2010/06/10 21:30:26 roberto Exp roberto $ ** $Id: lcorolib.c,v 1.2 2010/07/02 11:38:13 roberto Exp roberto $
** Coroutine Library ** Coroutine Library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -28,7 +28,7 @@ static int auxresume (lua_State *L, lua_State *co, int narg) {
return -1; /* error flag */ return -1; /* error flag */
} }
lua_xmove(L, co, narg); lua_xmove(L, co, narg);
status = lua_resume(co, narg); status = lua_resume(co, L, narg);
if (status == LUA_OK || status == LUA_YIELD) { if (status == LUA_OK || status == LUA_YIELD) {
int nres = lua_gettop(co); int nres = lua_gettop(co);
if (!lua_checkstack(L, nres + 1)) { if (!lua_checkstack(L, nres + 1)) {

View File

@@ -1,45 +1,52 @@
/* /*
** $Id: lctype.c,v 1.7 2009/05/27 16:51:15 roberto Exp roberto $ ** $Id: lctype.c,v 1.10 2011/06/24 12:25:33 roberto Exp roberto $
** 'ctype' functions for Lua ** 'ctype' functions for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include <limits.h> #define lctype_c
#define LUA_CORE
#include "lctype.h" #include "lctype.h"
#if !LUA_USE_CTYPE /* { */
#include <limits.h>
LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
0x00, /* EOZ */ 0x00, /* EOZ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */
0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */
0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x25, 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */
0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25,
0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25,
0x25, 0x25, 0x25, 0x04, 0x04, 0x04, 0x04, 0x05,
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}; };
#endif /* } */

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lctype.h,v 1.7 2009/05/27 16:51:15 roberto Exp roberto $ ** $Id: lctype.h,v 1.11 2011/06/27 18:22:46 roberto Exp roberto $
** 'ctype' functions for Lua ** 'ctype' functions for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -7,11 +7,32 @@
#ifndef lctype_h #ifndef lctype_h
#define lctype_h #define lctype_h
#include "lua.h"
/*
** WARNING: the functions defined here do not necessarily correspond
** to the similar functions in the standard C ctype.h. They are
** optimized for the specific needs of Lua
*/
#if !defined(LUA_USE_CTYPE)
#if 'A' == 65 && '0' == 48
/* ASCII case: can use its own tables; faster and fixed */
#define LUA_USE_CTYPE 0
#else
/* must use standard C ctype */
#define LUA_USE_CTYPE 1
#endif
#endif
#if !LUA_USE_CTYPE /* { */
#include <limits.h> #include <limits.h>
#include "lua.h"
#include "llimits.h" #include "llimits.h"
@@ -20,7 +41,6 @@
#define PRINTBIT 2 #define PRINTBIT 2
#define SPACEBIT 3 #define SPACEBIT 3
#define XDIGITBIT 4 #define XDIGITBIT 4
#define UPPERBIT 5
#define MASK(B) (1 << (B)) #define MASK(B) (1 << (B))
@@ -36,15 +56,40 @@
*/ */
#define lislalpha(c) testprop(c, MASK(ALPHABIT)) #define lislalpha(c) testprop(c, MASK(ALPHABIT))
#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) #define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT)))
#define lisupper(c) testprop(c, MASK(UPPERBIT))
#define lisdigit(c) testprop(c, MASK(DIGITBIT)) #define lisdigit(c) testprop(c, MASK(DIGITBIT))
#define lisspace(c) testprop(c, MASK(SPACEBIT)) #define lisspace(c) testprop(c, MASK(SPACEBIT))
#define lisprint(c) testprop(c, MASK(PRINTBIT)) #define lisprint(c) testprop(c, MASK(PRINTBIT))
#define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) #define lisxdigit(c) testprop(c, MASK(XDIGITBIT))
/*
** this 'ltolower' only works for alphabetic characters
*/
#define ltolower(c) ((c) | ('A' ^ 'a'))
/* one more entry for 0 and one more for -1 (EOZ) */
/* two more entries for 0 and -1 (EOZ) */
LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2]; LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2];
#else /* }{ */
/*
** use standard C ctypes
*/
#include <ctype.h>
#define lislalpha(c) (isalpha(c) || (c) == '_')
#define lislalnum(c) (isalnum(c) || (c) == '_')
#define lisdigit(c) (isdigit(c))
#define lisspace(c) (isspace(c))
#define lisprint(c) (isprint(c))
#define lisxdigit(c) (isxdigit(c))
#define ltolower(c) (tolower(c))
#endif /* } */
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldblib.c,v 1.125 2010/11/10 18:06:10 roberto Exp roberto $ ** $Id: ldblib.c,v 1.130 2011/04/08 19:17:36 roberto Exp roberto $
** Interface from Lua to its debug API ** Interface from Lua to its debug API
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -18,6 +18,9 @@
#include "lualib.h" #include "lualib.h"
#define HOOKKEY "_HKEY"
static int db_getregistry (lua_State *L) { static int db_getregistry (lua_State *L) {
lua_pushvalue(L, LUA_REGISTRYINDEX); lua_pushvalue(L, LUA_REGISTRYINDEX);
@@ -39,8 +42,8 @@ static int db_setmetatable (lua_State *L) {
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected"); "nil or table expected");
lua_settop(L, 2); lua_settop(L, 2);
lua_pushboolean(L, lua_setmetatable(L, 1)); lua_setmetatable(L, 1);
return 1; return 1; /* return 1st argument */
} }
@@ -250,16 +253,14 @@ static int db_upvaluejoin (lua_State *L) {
} }
static const char KEY_HOOK = 'h'; #define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY);
static void hookf (lua_State *L, lua_Debug *ar) { static void hookf (lua_State *L, lua_Debug *ar) {
static const char *const hooknames[] = static const char *const hooknames[] =
{"call", "return", "line", "count", "tail call"}; {"call", "return", "line", "count", "tail call"};
lua_pushlightuserdata(L, (void *)&KEY_HOOK); gethooktable(L);
lua_rawget(L, LUA_REGISTRYINDEX); lua_rawgetp(L, -1, L);
lua_pushlightuserdata(L, L);
lua_rawget(L, -2);
if (lua_isfunction(L, -1)) { if (lua_isfunction(L, -1)) {
lua_pushstring(L, hooknames[(int)ar->event]); lua_pushstring(L, hooknames[(int)ar->event]);
if (ar->currentline >= 0) if (ar->currentline >= 0)
@@ -291,19 +292,6 @@ static char *unmakemask (int mask, char *smask) {
} }
static void gethooktable (lua_State *L) {
lua_pushlightuserdata(L, (void *)&KEY_HOOK);
lua_rawget(L, LUA_REGISTRYINDEX);
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_createtable(L, 0, 1);
lua_pushlightuserdata(L, (void *)&KEY_HOOK);
lua_pushvalue(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
}
}
static int db_sethook (lua_State *L) { static int db_sethook (lua_State *L) {
int arg, mask, count; int arg, mask, count;
lua_Hook func; lua_Hook func;
@@ -319,9 +307,8 @@ static int db_sethook (lua_State *L) {
func = hookf; mask = makemask(smask, count); func = hookf; mask = makemask(smask, count);
} }
gethooktable(L); gethooktable(L);
lua_pushlightuserdata(L, L1);
lua_pushvalue(L, arg+1); lua_pushvalue(L, arg+1);
lua_rawset(L, -3); /* set new hook */ lua_rawsetp(L, -2, L1); /* set new hook */
lua_pop(L, 1); /* remove hook table */ lua_pop(L, 1); /* remove hook table */
lua_sethook(L1, func, mask, count); /* set hooks */ lua_sethook(L1, func, mask, count); /* set hooks */
return 0; return 0;
@@ -338,8 +325,7 @@ static int db_gethook (lua_State *L) {
lua_pushliteral(L, "external hook"); lua_pushliteral(L, "external hook");
else { else {
gethooktable(L); gethooktable(L);
lua_pushlightuserdata(L, L1); lua_rawgetp(L, -1, L1); /* get hook */
lua_rawget(L, -2); /* get hook */
lua_remove(L, -2); /* remove hook table */ lua_remove(L, -2); /* remove hook table */
} }
lua_pushstring(L, unmakemask(mask, buff)); lua_pushstring(L, unmakemask(mask, buff));

278
ldebug.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldebug.c,v 2.73 2010/09/07 19:21:39 roberto Exp roberto $ ** $Id: ldebug.c,v 2.87 2011/10/07 20:45:19 roberto Exp roberto $
** Debug Interface ** Debug Interface
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -35,12 +35,12 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
static int currentpc (CallInfo *ci) { static int currentpc (CallInfo *ci) {
lua_assert(isLua(ci)); lua_assert(isLua(ci));
return pcRel(ci->u.l.savedpc, ci_func(ci)->l.p); return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
} }
static int currentline (CallInfo *ci) { static int currentline (CallInfo *ci) {
return getfuncline(ci_func(ci)->l.p, currentpc(ci)); return getfuncline(ci_func(ci)->p, currentpc(ci));
} }
@@ -94,13 +94,35 @@ LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
} }
static const char *upvalname (Proto *p, int uv) {
TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
if (s == NULL) return "?";
else return getstr(s);
}
static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
int nparams = clLvalue(ci->func)->p->numparams;
if (n >= ci->u.l.base - ci->func - nparams)
return NULL; /* no such vararg */
else {
*pos = ci->func + nparams + n;
return "(*vararg)"; /* generic name for any vararg */
}
}
static const char *findlocal (lua_State *L, CallInfo *ci, int n, static const char *findlocal (lua_State *L, CallInfo *ci, int n,
StkId *pos) { StkId *pos) {
const char *name = NULL; const char *name = NULL;
StkId base; StkId base;
if (isLua(ci)) { if (isLua(ci)) {
base = ci->u.l.base; if (n < 0) /* access to vararg values? */
name = luaF_getlocalname(ci_func(ci)->l.p, n, currentpc(ci)); return findvararg(ci, -n, pos);
else {
base = ci->u.l.base;
name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
}
} }
else else
base = ci->func + 1; base = ci->func + 1;
@@ -108,10 +130,8 @@ static const char *findlocal (lua_State *L, CallInfo *ci, int n,
StkId limit = (ci == L->ci) ? L->top : ci->next->func; StkId limit = (ci == L->ci) ? L->top : ci->next->func;
if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */
name = "(*temporary)"; /* generic name for any valid slot */ name = "(*temporary)"; /* generic name for any valid slot */
else { else
*pos = base; /* to avoid warnings */
return NULL; /* no name */ return NULL; /* no name */
}
} }
*pos = base + (n - 1); *pos = base + (n - 1);
return name; return name;
@@ -125,10 +145,10 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
if (!isLfunction(L->top - 1)) /* not a Lua function? */ if (!isLfunction(L->top - 1)) /* not a Lua function? */
name = NULL; name = NULL;
else /* consider live variables at function start (parameters) */ else /* consider live variables at function start (parameters) */
name = luaF_getlocalname(clvalue(L->top - 1)->l.p, n, 0); name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);
} }
else { /* active function; get information through 'ar' */ else { /* active function; get information through 'ar' */
StkId pos; StkId pos = 0; /* to avoid warnings */
name = findlocal(L, ar->i_ci, n, &pos); name = findlocal(L, ar->i_ci, n, &pos);
if (name) { if (name) {
setobj2s(L, L->top, pos); setobj2s(L, L->top, pos);
@@ -141,11 +161,11 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
StkId pos; StkId pos = 0; /* to avoid warnings */
const char *name = findlocal(L, ar->i_ci, n, &pos); const char *name = findlocal(L, ar->i_ci, n, &pos);
lua_lock(L); lua_lock(L);
if (name) if (name)
setobjs2s(L, pos, L->top - 1); setobjs2s(L, pos, L->top - 1);
L->top--; /* pop value */ L->top--; /* pop value */
lua_unlock(L); lua_unlock(L);
return name; return name;
@@ -177,12 +197,14 @@ static void collectvalidlines (lua_State *L, Closure *f) {
} }
else { else {
int i; int i;
TValue v;
int *lineinfo = f->l.p->lineinfo; int *lineinfo = f->l.p->lineinfo;
Table *t = luaH_new(L); Table *t = luaH_new(L); /* new table to store active lines */
sethvalue(L, L->top, t); sethvalue(L, L->top, t); /* push it on stack */
incr_top(L); incr_top(L);
for (i=0; i<f->l.p->sizelineinfo; i++) setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */
setbvalue(luaH_setint(L, t, lineinfo[i]), 1); for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */
luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */
} }
} }
@@ -217,7 +239,11 @@ static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
break; break;
} }
case 'n': { case 'n': {
ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL; /* calling function is a known Lua function? */
if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous))
ar->namewhat = getfuncname(L, ci->previous, &ar->name);
else
ar->namewhat = NULL;
if (ar->namewhat == NULL) { if (ar->namewhat == NULL) {
ar->namewhat = ""; /* not found */ ar->namewhat = ""; /* not found */
ar->name = NULL; ar->name = NULL;
@@ -243,7 +269,7 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
if (*what == '>') { if (*what == '>') {
ci = NULL; ci = NULL;
func = L->top - 1; func = L->top - 1;
luai_apicheck(L, ttisfunction(func)); api_check(L, ttisfunction(func), "function expected");
what++; /* skip the '>' */ what++; /* skip the '>' */
L->top--; /* pop function */ L->top--; /* pop function */
} }
@@ -271,96 +297,57 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
** ======================================================= ** =======================================================
*/ */
static const char *getobjname (Proto *p, int lastpc, int reg,
const char **name);
static void kname (Proto *p, int c, int reg, const char *what,
const char **name) { /*
if (c == reg && what && *what == 'c') ** find a "name" for the RK value 'c'
return; /* index is a constant; name already correct */ */
else if (ISK(c) && ttisstring(&p->k[INDEXK(c)])) static void kname (Proto *p, int pc, int c, const char **name) {
*name = svalue(&p->k[INDEXK(c)]); if (ISK(c)) { /* is 'c' a constant? */
else TValue *kvalue = &p->k[INDEXK(c)];
*name = "?"; if (ttisstring(kvalue)) { /* literal constant? */
*name = svalue(kvalue); /* it is its own name */
return;
}
/* else no reasonable name found */
}
else { /* 'c' is a register */
const char *what = getobjname(p, pc, c, name); /* search for 'c' */
if (what && *what == 'c') { /* found a constant name? */
return; /* 'name' already filled */
}
/* else no reasonable name found */
}
*name = "?"; /* no reasonable name found */
} }
static const char *getobjname (lua_State *L, CallInfo *ci, int reg, /*
const char **name) { ** try to find last instruction before 'lastpc' that modified register 'reg'
Proto *p = ci_func(ci)->l.p; */
const char *what = NULL; static int findsetreg (Proto *p, int lastpc, int reg) {
int lastpc = currentpc(ci);
int pc; int pc;
*name = luaF_getlocalname(p, reg + 1, lastpc); int setreg = -1; /* keep last instruction that changed 'reg' */
if (*name) /* is a local? */
return "local";
/* else try symbolic execution */
for (pc = 0; pc < lastpc; pc++) { for (pc = 0; pc < lastpc; pc++) {
Instruction i = p->code[pc]; Instruction i = p->code[pc];
OpCode op = GET_OPCODE(i); OpCode op = GET_OPCODE(i);
int a = GETARG_A(i); int a = GETARG_A(i);
switch (op) { switch (op) {
case OP_MOVE: {
if (reg == a) {
int b = GETARG_B(i); /* move from 'b' to 'a' */
if (b < a)
what = getobjname(L, ci, b, name); /* get name for 'b' */
else what = NULL;
}
break;
}
case OP_GETTABUP:
case OP_GETTABLE: {
if (reg == a) {
int k = GETARG_C(i); /* key index */
int t = GETARG_B(i);
const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
? luaF_getlocalname(p, t + 1, pc)
: getstr(p->upvalues[t].name);
kname(p, k, a, what, name);
what = (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
}
break;
}
case OP_GETUPVAL: {
if (reg == a) {
int u = GETARG_B(i); /* upvalue index */
TString *tn = p->upvalues[u].name;
*name = tn ? getstr(tn) : "?";
what = "upvalue";
}
break;
}
case OP_LOADK: {
if (reg == a) {
int b = GETARG_Bx(i);
b = (b > 0) ? b - 1 : GETARG_Ax(p->code[pc + 1]);
if (ttisstring(&p->k[b])) {
what = "constant";
*name = svalue(&p->k[b]);
}
}
break;
}
case OP_LOADNIL: { case OP_LOADNIL: {
int b = GETARG_B(i); /* move from 'b' to 'a' */ int b = GETARG_B(i);
if (a <= reg && reg <= b) /* set registers from 'a' to 'b' */ if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
what = NULL; setreg = pc;
break;
}
case OP_SELF: {
if (reg == a) {
int k = GETARG_C(i); /* key index */
kname(p, k, a, what, name);
what = "method";
}
break; break;
} }
case OP_TFORCALL: { case OP_TFORCALL: {
if (reg >= a + 2) what = NULL; /* affect all regs above its base */ if (reg >= a + 2) setreg = pc; /* affect all regs above its base */
break; break;
} }
case OP_CALL: case OP_CALL:
case OP_TAILCALL: { case OP_TAILCALL: {
if (reg >= a) what = NULL; /* affect all registers above base */ if (reg >= a) setreg = pc; /* affect all registers above base */
break; break;
} }
case OP_JMP: { case OP_JMP: {
@@ -371,32 +358,88 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg,
pc += b; /* do the jump */ pc += b; /* do the jump */
break; break;
} }
case OP_TEST: {
if (reg == a) setreg = pc; /* jumped code can change 'a' */
break;
}
default: default:
if (testAMode(op) && reg == a) what = NULL; if (testAMode(op) && reg == a) /* any instruction that set A */
setreg = pc;
break; break;
} }
} }
return what; return setreg;
}
static const char *getobjname (Proto *p, int lastpc, int reg,
const char **name) {
int pc;
*name = luaF_getlocalname(p, reg + 1, lastpc);
if (*name) /* is a local? */
return "local";
/* else try symbolic execution */
pc = findsetreg(p, lastpc, reg);
if (pc != -1) { /* could find instruction? */
Instruction i = p->code[pc];
OpCode op = GET_OPCODE(i);
switch (op) {
case OP_MOVE: {
int b = GETARG_B(i); /* move from 'b' to 'a' */
if (b < GETARG_A(i))
return getobjname(p, pc, b, name); /* get name for 'b' */
break;
}
case OP_GETTABUP:
case OP_GETTABLE: {
int k = GETARG_C(i); /* key index */
int t = GETARG_B(i); /* table index */
const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
? luaF_getlocalname(p, t + 1, pc)
: upvalname(p, t);
kname(p, pc, k, name);
return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
}
case OP_GETUPVAL: {
*name = upvalname(p, GETARG_B(i));
return "upvalue";
}
case OP_LOADK:
case OP_LOADKX: {
int b = (op == OP_LOADK) ? GETARG_Bx(i)
: GETARG_Ax(p->code[pc + 1]);
if (ttisstring(&p->k[b])) {
*name = svalue(&p->k[b]);
return "constant";
}
break;
}
case OP_SELF: {
int k = GETARG_C(i); /* key index */
kname(p, pc, k, name);
return "method";
}
default: break; /* go through to return NULL */
}
}
return NULL; /* could not find reasonable name */
} }
static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
TMS tm; TMS tm;
Instruction i; Proto *p = ci_func(ci)->p; /* calling function */
if ((ci->callstatus & CIST_TAIL) || !isLua(ci->previous)) int pc = currentpc(ci); /* calling instruction index */
return NULL; /* calling function is not Lua (or is unknown) */ Instruction i = p->code[pc]; /* calling instruction */
ci = ci->previous; /* calling function */
i = ci_func(ci)->l.p->code[currentpc(ci)];
if (GET_OPCODE(i) == OP_EXTRAARG) /* extra argument? */
i = ci_func(ci)->l.p->code[currentpc(ci) - 1]; /* get 'real' instruction */
switch (GET_OPCODE(i)) { switch (GET_OPCODE(i)) {
case OP_CALL: case OP_CALL:
case OP_TAILCALL: case OP_TAILCALL: /* get function name */
return getobjname(L, ci, GETARG_A(i), name); return getobjname(p, pc, GETARG_A(i), name);
case OP_TFORCALL: { case OP_TFORCALL: { /* for iterator */
*name = "for iterator"; *name = "for iterator";
return "for iterator"; return "for iterator";
} }
/* all other instructions can call only through metamethods */
case OP_SELF: case OP_SELF:
case OP_GETTABUP: case OP_GETTABUP:
case OP_GETTABLE: tm = TM_INDEX; break; case OP_GETTABLE: tm = TM_INDEX; break;
@@ -425,7 +468,10 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
/* only ANSI way to check whether a pointer points to an array */ /*
** only ANSI way to check whether a pointer points to an array
** (used only for error messages, so efficiency is not a big concern)
*/
static int isinstack (CallInfo *ci, const TValue *o) { static int isinstack (CallInfo *ci, const TValue *o) {
StkId p; StkId p;
for (p = ci->u.l.base; p < ci->top; p++) for (p = ci->u.l.base; p < ci->top; p++)
@@ -435,12 +481,12 @@ static int isinstack (CallInfo *ci, const TValue *o) {
static const char *getupvalname (CallInfo *ci, const TValue *o, static const char *getupvalname (CallInfo *ci, const TValue *o,
const char **name) { const char **name) {
LClosure *c = &ci_func(ci)->l; LClosure *c = ci_func(ci);
int i; int i;
for (i = 0; i < c->nupvalues; i++) { for (i = 0; i < c->nupvalues; i++) {
if (c->upvals[i]->v == o) { if (c->upvals[i]->v == o) {
*name = getstr(c->p->upvalues[i].name); *name = upvalname(c->p, i);
return "upvalue"; return "upvalue";
} }
} }
@@ -448,15 +494,16 @@ static const char *getupvalname (CallInfo *ci, const TValue *o,
} }
void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
CallInfo *ci = L->ci; CallInfo *ci = L->ci;
const char *name = NULL; const char *name = NULL;
const char *t = objtypename(o); const char *t = objtypename(o);
const char *kind = NULL; const char *kind = NULL;
if (isLua(ci)) { if (isLua(ci)) {
kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
if (!kind && isinstack(ci, o)) /* no? try a register */ if (!kind && isinstack(ci, o)) /* no? try a register */
kind = getobjname(L, ci, cast_int(o - ci->u.l.base), &name); kind = getobjname(ci_func(ci)->p, currentpc(ci),
cast_int(o - ci->u.l.base), &name);
} }
if (kind) if (kind)
luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
@@ -466,14 +513,14 @@ void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
} }
void luaG_concaterror (lua_State *L, StkId p1, StkId p2) { l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
lua_assert(!ttisstring(p1) && !ttisnumber(p2)); lua_assert(!ttisstring(p1) && !ttisnumber(p2));
luaG_typeerror(L, p1, "concatenate"); luaG_typeerror(L, p1, "concatenate");
} }
void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
TValue temp; TValue temp;
if (luaV_tonumber(p1, &temp) == NULL) if (luaV_tonumber(p1, &temp) == NULL)
p2 = p1; /* first operand is wrong */ p2 = p1; /* first operand is wrong */
@@ -481,14 +528,13 @@ void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
} }
int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
const char *t1 = objtypename(p1); const char *t1 = objtypename(p1);
const char *t2 = objtypename(p2); const char *t2 = objtypename(p2);
if (t1 == t2) if (t1 == t2)
luaG_runerror(L, "attempt to compare two %s values", t1); luaG_runerror(L, "attempt to compare two %s values", t1);
else else
luaG_runerror(L, "attempt to compare %s with %s", t1, t2); luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
return 0;
} }
@@ -497,7 +543,7 @@ static void addinfo (lua_State *L, const char *msg) {
if (isLua(ci)) { /* is Lua code? */ if (isLua(ci)) { /* is Lua code? */
char buff[LUA_IDSIZE]; /* add file:line information */ char buff[LUA_IDSIZE]; /* add file:line information */
int line = currentline(ci); int line = currentline(ci);
TString *src = ci_func(ci)->l.p->source; TString *src = ci_func(ci)->p->source;
if (src) if (src)
luaO_chunkid(buff, getstr(src), LUA_IDSIZE); luaO_chunkid(buff, getstr(src), LUA_IDSIZE);
else { /* no source available; use "?" instead */ else { /* no source available; use "?" instead */
@@ -508,7 +554,7 @@ static void addinfo (lua_State *L, const char *msg) {
} }
void luaG_errormsg (lua_State *L) { l_noret luaG_errormsg (lua_State *L) {
if (L->errfunc != 0) { /* is there an error handling function? */ if (L->errfunc != 0) { /* is there an error handling function? */
StkId errfunc = restorestack(L, L->errfunc); StkId errfunc = restorestack(L, L->errfunc);
if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
@@ -521,7 +567,7 @@ void luaG_errormsg (lua_State *L) {
} }
void luaG_runerror (lua_State *L, const char *fmt, ...) { l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
va_list argp; va_list argp;
va_start(argp, fmt); va_start(argp, fmt);
addinfo(L, luaO_pushvfstring(L, fmt, argp)); addinfo(L, luaO_pushvfstring(L, fmt, argp));

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldebug.h,v 2.4 2009/04/30 17:42:21 roberto Exp roberto $ ** $Id: ldebug.h,v 2.6 2011/06/02 19:31:40 roberto Exp roberto $
** Auxiliary functions from Debug Interface module ** Auxiliary functions from Debug Interface module
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -17,15 +17,18 @@
#define resethookcount(L) (L->hookcount = L->basehookcount) #define resethookcount(L) (L->hookcount = L->basehookcount)
/* Active Lua function (given call info) */
#define ci_func(ci) (clLvalue((ci)->func))
LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,
const char *opname); LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2); const char *opname);
LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1, LUAI_FUNC l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2);
const TValue *p2); LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1,
LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2);
const TValue *p2); LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); const TValue *p2);
LUAI_FUNC void luaG_errormsg (lua_State *L); LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
#endif #endif

185
ldo.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldo.c,v 2.89 2010/09/30 17:21:31 roberto Exp roberto $ ** $Id: ldo.c,v 2.101 2011/10/07 20:45:19 roberto Exp roberto $
** Stack and Call structure of Lua ** Stack and Call structure of Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -100,7 +100,7 @@ static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
} }
void luaD_throw (lua_State *L, int errcode) { l_noret luaD_throw (lua_State *L, int errcode) {
if (L->errorJmp) { /* thread has an error handler? */ if (L->errorJmp) { /* thread has an error handler? */
L->errorJmp->status = errcode; /* set status */ L->errorJmp->status = errcode; /* set status */
LUAI_THROW(L, L->errorJmp); /* jump to it */ LUAI_THROW(L, L->errorJmp); /* jump to it */
@@ -123,7 +123,7 @@ void luaD_throw (lua_State *L, int errcode) {
int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
unsigned short oldnCcalls = G(L)->nCcalls; unsigned short oldnCcalls = L->nCcalls;
struct lua_longjmp lj; struct lua_longjmp lj;
lj.status = LUA_OK; lj.status = LUA_OK;
lj.previous = L->errorJmp; /* chain new error handler */ lj.previous = L->errorJmp; /* chain new error handler */
@@ -132,7 +132,7 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
(*f)(L, ud); (*f)(L, ud);
); );
L->errorJmp = lj.previous; /* restore old error handler */ L->errorJmp = lj.previous; /* restore old error handler */
G(L)->nCcalls = oldnCcalls; L->nCcalls = oldnCcalls;
return lj.status; return lj.status;
} }
@@ -293,65 +293,59 @@ static StkId tryfuncTM (lua_State *L, StkId func) {
** returns true if function has been executed (C function) ** returns true if function has been executed (C function)
*/ */
int luaD_precall (lua_State *L, StkId func, int nresults) { int luaD_precall (lua_State *L, StkId func, int nresults) {
Closure *cl;
lua_CFunction f; lua_CFunction f;
ptrdiff_t funcr; CallInfo *ci;
if (!ttisfunction(func)) /* `func' is not a function? */ int n; /* number of arguments (Lua) or returns (C) */
func = tryfuncTM(L, func); /* check the `function' tag method */ ptrdiff_t funcr = savestack(L, func);
funcr = savestack(L, func); switch (ttype(func)) {
if (ttislcf(func)) { /* light C function? */ case LUA_TLCF: /* light C function */
f = fvalue(func); /* get it */ f = fvalue(func);
goto isCfunc; /* go to call it */ goto Cfunc;
} case LUA_TCCL: { /* C closure */
cl = clvalue(func); f = clCvalue(func)->f;
if (cl->c.isC) { /* C closure? */ Cfunc:
CallInfo *ci; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
int n; ci = next_ci(L); /* now 'enter' new function */
f = cl->c.f; ci->nresults = nresults;
isCfunc: /* call C function 'f' */ ci->func = restorestack(L, funcr);
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ ci->top = L->top + LUA_MINSTACK;
ci = next_ci(L); /* now 'enter' new function */ lua_assert(ci->top <= L->stack_last);
ci->nresults = nresults; ci->callstatus = 0;
ci->func = restorestack(L, funcr); if (L->hookmask & LUA_MASKCALL)
ci->top = L->top + LUA_MINSTACK; luaD_hook(L, LUA_HOOKCALL, -1);
lua_assert(ci->top <= L->stack_last); lua_unlock(L);
ci->callstatus = 0; n = (*f)(L); /* do the actual call */
if (L->hookmask & LUA_MASKCALL) lua_lock(L);
luaD_hook(L, LUA_HOOKCALL, -1); api_checknelems(L, n);
lua_unlock(L); luaD_poscall(L, L->top - n);
n = (*f)(L); /* do the actual call */ return 1;
lua_lock(L); }
api_checknelems(L, n); case LUA_TLCL: { /* Lua function: prepare its call */
luaD_poscall(L, L->top - n); StkId base;
return 1; Proto *p = clLvalue(func)->p;
} luaD_checkstack(L, p->maxstacksize);
else { /* Lua function: prepare its call */ func = restorestack(L, funcr);
CallInfo *ci; n = cast_int(L->top - func) - 1; /* number of real arguments */
int nparams, nargs; for (; n < p->numparams; n++)
StkId base; setnilvalue(L->top++); /* complete missing arguments */
Proto *p = cl->l.p; base = (!p->is_vararg) ? func + 1 : adjust_varargs(L, p, n);
luaD_checkstack(L, p->maxstacksize); ci = next_ci(L); /* now 'enter' new function */
func = restorestack(L, funcr); ci->nresults = nresults;
nargs = cast_int(L->top - func) - 1; /* number of real arguments */ ci->func = func;
nparams = p->numparams; /* number of expected parameters */ ci->u.l.base = base;
for (; nargs < nparams; nargs++) ci->top = base + p->maxstacksize;
setnilvalue(L->top++); /* complete missing arguments */ lua_assert(ci->top <= L->stack_last);
if (!p->is_vararg) /* no varargs? */ ci->u.l.savedpc = p->code; /* starting point */
base = func + 1; ci->callstatus = CIST_LUA;
else /* vararg function */ L->top = ci->top;
base = adjust_varargs(L, p, nargs); if (L->hookmask & LUA_MASKCALL)
ci = next_ci(L); /* now 'enter' new function */ callhook(L, ci);
ci->nresults = nresults; return 0;
ci->func = func; }
ci->u.l.base = base; default: { /* not a function */
ci->top = base + p->maxstacksize; func = tryfuncTM(L, func); /* retry with 'function' tag method */
lua_assert(ci->top <= L->stack_last); return luaD_precall(L, func, nresults); /* now it must be a function */
ci->u.l.savedpc = p->code; /* starting point */ }
ci->callstatus = CIST_LUA;
L->top = ci->top;
if (L->hookmask & LUA_MASKCALL)
callhook(L, ci);
return 0;
} }
} }
@@ -388,18 +382,17 @@ int luaD_poscall (lua_State *L, StkId firstResult) {
** function position. ** function position.
*/ */
void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) { void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {
global_State *g = G(L); if (++L->nCcalls >= LUAI_MAXCCALLS) {
if (++g->nCcalls >= LUAI_MAXCCALLS) { if (L->nCcalls == LUAI_MAXCCALLS)
if (g->nCcalls == LUAI_MAXCCALLS)
luaG_runerror(L, "C stack overflow"); luaG_runerror(L, "C stack overflow");
else if (g->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
} }
if (!allowyield) L->nny++; if (!allowyield) L->nny++;
if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ if (!luaD_precall(L, func, nResults)) /* is a Lua function? */
luaV_execute(L); /* call it */ luaV_execute(L); /* call it */
if (!allowyield) L->nny--; if (!allowyield) L->nny--;
g->nCcalls--; L->nCcalls--;
luaC_checkGC(L); luaC_checkGC(L);
} }
@@ -410,7 +403,7 @@ static void finishCcall (lua_State *L) {
lua_assert(ci->u.c.k != NULL); /* must have a continuation */ lua_assert(ci->u.c.k != NULL); /* must have a continuation */
lua_assert(L->nny == 0); lua_assert(L->nny == 0);
/* finish 'luaD_call' */ /* finish 'luaD_call' */
G(L)->nCcalls--; L->nCcalls--;
/* finish 'lua_callk' */ /* finish 'lua_callk' */
adjustresults(L, ci->nresults); adjustresults(L, ci->nresults);
/* call continuation function */ /* call continuation function */
@@ -479,7 +472,7 @@ static int recover (lua_State *L, int status) {
** coroutine itself. (Such errors should not be handled by any coroutine ** coroutine itself. (Such errors should not be handled by any coroutine
** error handler and should not kill the coroutine.) ** error handler and should not kill the coroutine.)
*/ */
static void resume_error (lua_State *L, const char *msg, StkId firstArg) { static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
L->top = firstArg; /* remove args from the stack */ L->top = firstArg; /* remove args from the stack */
setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
incr_top(L); incr_top(L);
@@ -493,7 +486,7 @@ static void resume_error (lua_State *L, const char *msg, StkId firstArg) {
static void resume (lua_State *L, void *ud) { static void resume (lua_State *L, void *ud) {
StkId firstArg = cast(StkId, ud); StkId firstArg = cast(StkId, ud);
CallInfo *ci = L->ci; CallInfo *ci = L->ci;
if (G(L)->nCcalls >= LUAI_MAXCCALLS) if (L->nCcalls >= LUAI_MAXCCALLS)
resume_error(L, "C stack overflow", firstArg); resume_error(L, "C stack overflow", firstArg);
if (L->status == LUA_OK) { /* may be starting a coroutine */ if (L->status == LUA_OK) { /* may be starting a coroutine */
if (ci != &L->base_ci) /* not in base level? */ if (ci != &L->base_ci) /* not in base level? */
@@ -520,7 +513,7 @@ static void resume (lua_State *L, void *ud) {
api_checknelems(L, n); api_checknelems(L, n);
firstArg = L->top - n; /* yield results come from continuation */ firstArg = L->top - n; /* yield results come from continuation */
} }
G(L)->nCcalls--; /* finish 'luaD_call' */ L->nCcalls--; /* finish 'luaD_call' */
luaD_poscall(L, firstArg); /* finish 'luaD_precall' */ luaD_poscall(L, firstArg); /* finish 'luaD_precall' */
} }
unroll(L, NULL); unroll(L, NULL);
@@ -528,11 +521,11 @@ static void resume (lua_State *L, void *ud) {
} }
LUA_API int lua_resume (lua_State *L, int nargs) { LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
int status; int status;
lua_lock(L); lua_lock(L);
luai_userstateresume(L, nargs); luai_userstateresume(L, nargs);
++G(L)->nCcalls; /* count resume */ L->nCcalls = (from) ? from->nCcalls + 1 : 1;
L->nny = 0; /* allow yields */ L->nny = 0; /* allow yields */
api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
status = luaD_rawrunprotected(L, resume, L->top - nargs); status = luaD_rawrunprotected(L, resume, L->top - nargs);
@@ -552,7 +545,8 @@ LUA_API int lua_resume (lua_State *L, int nargs) {
lua_assert(status == L->status); lua_assert(status == L->status);
} }
L->nny = 1; /* do not allow yields */ L->nny = 1; /* do not allow yields */
--G(L)->nCcalls; L->nCcalls--;
lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
lua_unlock(L); lua_unlock(L);
return status; return status;
} }
@@ -615,39 +609,60 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u,
*/ */
struct SParser { /* data to `f_parser' */ struct SParser { /* data to `f_parser' */
ZIO *z; ZIO *z;
Mbuffer buff; /* buffer to be used by the scanner */ Mbuffer buff; /* dynamic structure used by the scanner */
Varlist varl; /* list of local variables (to be used by the parser) */ Dyndata dyd; /* dynamic structures used by the parser */
const char *mode;
const char *name; const char *name;
}; };
static void checkmode (lua_State *L, const char *mode, const char *x) {
if (mode && strchr(mode, x[0]) == NULL) {
luaO_pushfstring(L,
"attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
luaD_throw(L, LUA_ERRSYNTAX);
}
}
static void f_parser (lua_State *L, void *ud) { static void f_parser (lua_State *L, void *ud) {
int i; int i;
Proto *tf; Proto *tf;
Closure *cl; Closure *cl;
struct SParser *p = cast(struct SParser *, ud); struct SParser *p = cast(struct SParser *, ud);
int c = luaZ_lookahead(p->z); int c = zgetc(p->z); /* read first character */
tf = (c == LUA_SIGNATURE[0]) if (c == LUA_SIGNATURE[0]) {
? luaU_undump(L, p->z, &p->buff, p->name) checkmode(L, p->mode, "binary");
: luaY_parser(L, p->z, &p->buff, &p->varl, p->name); tf = luaU_undump(L, p->z, &p->buff, p->name);
}
else {
checkmode(L, p->mode, "text");
tf = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
}
setptvalue2s(L, L->top, tf); setptvalue2s(L, L->top, tf);
incr_top(L); incr_top(L);
cl = luaF_newLclosure(L, tf); cl = luaF_newLclosure(L, tf);
setclvalue(L, L->top - 1, cl); setclLvalue(L, L->top - 1, cl);
for (i = 0; i < tf->sizeupvalues; i++) /* initialize upvalues */ for (i = 0; i < tf->sizeupvalues; i++) /* initialize upvalues */
cl->l.upvals[i] = luaF_newupval(L); cl->l.upvals[i] = luaF_newupval(L);
} }
int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
const char *mode) {
struct SParser p; struct SParser p;
int status; int status;
L->nny++; /* cannot yield during parsing */ L->nny++; /* cannot yield during parsing */
p.z = z; p.name = name; p.z = z; p.name = name; p.mode = mode;
p.varl.actvar = NULL; p.varl.nactvar = p.varl.actvarsize = 0; p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
p.dyd.label.arr = NULL; p.dyd.label.size = 0;
luaZ_initbuffer(L, &p.buff); luaZ_initbuffer(L, &p.buff);
status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
luaZ_freebuffer(L, &p.buff); luaZ_freebuffer(L, &p.buff);
luaM_freearray(L, p.varl.actvar, p.varl.actvarsize); luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
L->nny--; L->nny--;
return status; return status;
} }

7
ldo.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldo.h,v 2.17 2009/11/25 15:27:51 roberto Exp roberto $ ** $Id: ldo.h,v 2.19 2011/10/07 20:45:19 roberto Exp roberto $
** Stack and Call structure of Lua ** Stack and Call structure of Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -26,7 +26,8 @@
/* type of protected functions, to be ran by `runprotected' */ /* type of protected functions, to be ran by `runprotected' */
typedef void (*Pfunc) (lua_State *L, void *ud); typedef void (*Pfunc) (lua_State *L, void *ud);
LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name); LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
const char *mode);
LUAI_FUNC void luaD_hook (lua_State *L, int event, int line); LUAI_FUNC void luaD_hook (lua_State *L, int event, int line);
LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults, LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults,
@@ -38,7 +39,7 @@ LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
LUAI_FUNC void luaD_growstack (lua_State *L, int n); LUAI_FUNC void luaD_growstack (lua_State *L, int n);
LUAI_FUNC void luaD_shrinkstack (lua_State *L); LUAI_FUNC void luaD_shrinkstack (lua_State *L);
LUAI_FUNC void luaD_throw (lua_State *L, int errcode); LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);
LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
#endif #endif

10
ldump.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldump.c,v 1.17 2010/10/13 21:04:52 lhf Exp $ ** $Id: ldump.c,v 1.19 2011/11/23 17:48:18 lhf Exp $
** save precompiled Lua chunks ** save precompiled Lua chunks
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -69,7 +69,7 @@ static void DumpString(const TString* s, DumpState* D)
{ {
size_t size=s->tsv.len+1; /* include trailing '\0' */ size_t size=s->tsv.len+1; /* include trailing '\0' */
DumpVar(size,D); DumpVar(size,D);
DumpBlock(getstr(s),size,D); DumpBlock(getstr(s),size*sizeof(char),D);
} }
} }
@@ -111,8 +111,8 @@ static void DumpUpvalues(const Proto* f, DumpState* D)
DumpInt(n,D); DumpInt(n,D);
for (i=0; i<n; i++) for (i=0; i<n; i++)
{ {
DumpChar(f->upvalues[i].instack, D); DumpChar(f->upvalues[i].instack,D);
DumpChar(f->upvalues[i].idx, D); DumpChar(f->upvalues[i].idx,D);
} }
} }
@@ -150,7 +150,7 @@ static void DumpFunction(const Proto* f, DumpState* D)
static void DumpHeader(DumpState* D) static void DumpHeader(DumpState* D)
{ {
char h[LUAC_HEADERSIZE]; lu_byte h[LUAC_HEADERSIZE];
luaU_header(h); luaU_header(h);
DumpBlock(h,LUAC_HEADERSIZE,D); DumpBlock(h,LUAC_HEADERSIZE,D);
} }

287
lgc.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lgc.c,v 2.102 2010/09/03 14:14:01 roberto Exp roberto $ ** $Id: lgc.c,v 2.115 2011/11/28 17:25:48 roberto Exp roberto $
** Garbage Collector ** Garbage Collector
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -51,7 +51,7 @@
** standard negative debt for GC; a reasonable "time" to wait before ** standard negative debt for GC; a reasonable "time" to wait before
** starting a new cycle ** starting a new cycle
*/ */
#define stddebt(g) (-cast(l_mem, g->totalbytes/100) * g->gcpause) #define stddebt(g) (-cast(l_mem, gettotalbytes(g)/100) * g->gcpause)
/* /*
@@ -68,11 +68,15 @@
#define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS))) #define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS)))
#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT) #define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT)
#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n))) #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
#define checkconsistency(obj) \
lua_longassert(!iscollectable(obj) || righttt(obj))
#define markvalue(g,o) { checkconsistency(o); \ #define markvalue(g,o) { checkconsistency(o); \
if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
@@ -89,6 +93,12 @@ static void reallymarkobject (global_State *g, GCObject *o);
*/ */
/*
** one after last element in a hash array
*/
#define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
/* /*
** link table 'h' into list pointed by 'p' ** link table 'h' into list pointed by 'p'
*/ */
@@ -96,12 +106,13 @@ static void reallymarkobject (global_State *g, GCObject *o);
/* /*
** mark a table entry as dead (therefore removing it from the table) ** if key is not marked, mark its entry as dead (therefore removing it
** from the table)
*/ */
static void removeentry (Node *n) { static void removeentry (Node *n) {
lua_assert(ttisnil(gval(n))); lua_assert(ttisnil(gval(n)));
if (iscollectable(gkey(n))) if (valiswhite(gkey(n)))
setdeadvalue(gkey(n)); /* dead key; remove it */ setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */
} }
@@ -112,14 +123,13 @@ static void removeentry (Node *n) {
** other objects: if really collected, cannot keep them; for objects ** other objects: if really collected, cannot keep them; for objects
** being finalized, keep them in keys, but not in values ** being finalized, keep them in keys, but not in values
*/ */
static int iscleared (const TValue *o, int iskey) { static int iscleared (const TValue *o) {
if (!iscollectable(o)) return 0; if (!iscollectable(o)) return 0;
if (ttisstring(o)) { else if (ttisstring(o)) {
stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */ stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */
return 0; return 0;
} }
return iswhite(gcvalue(o)) || else return iswhite(gcvalue(o));
(ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
} }
@@ -149,7 +159,7 @@ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
*/ */
void luaC_barrierback_ (lua_State *L, GCObject *o) { void luaC_barrierback_ (lua_State *L, GCObject *o) {
global_State *g = G(L); global_State *g = G(L);
lua_assert(isblack(o) && !isdead(g, o)); lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE);
black2gray(o); /* make object gray (again) */ black2gray(o); /* make object gray (again) */
gco2t(o)->gclist = g->grayagain; gco2t(o)->gclist = g->grayagain;
g->grayagain = o; g->grayagain = o;
@@ -281,7 +291,7 @@ static void reallymarkobject (global_State *g, GCObject *o) {
/* /*
** mark tag methods for basic types ** mark metamethods for basic types
*/ */
static void markmt (global_State *g) { static void markmt (global_State *g) {
int i; int i;
@@ -319,8 +329,7 @@ static void remarkupvals (global_State *g) {
** mark root set and reset all gray lists, to start a new ** mark root set and reset all gray lists, to start a new
** incremental (or full) collection ** incremental (or full) collection
*/ */
static void markroot (lua_State *L) { static void markroot (global_State *g) {
global_State *g = G(L);
g->gray = g->grayagain = NULL; g->gray = g->grayagain = NULL;
g->weak = g->allweak = g->ephemeron = NULL; g->weak = g->allweak = g->ephemeron = NULL;
markobject(g, g->mainthread); markobject(g, g->mainthread);
@@ -339,7 +348,10 @@ static void markroot (lua_State *L) {
*/ */
static void traverseweakvalue (global_State *g, Table *h) { static void traverseweakvalue (global_State *g, Table *h) {
Node *n, *limit = gnode(h, sizenode(h)); Node *n, *limit = gnodelast(h);
/* if there is array part, assume it may have white values (do not
traverse it just to check) */
int hasclears = (h->sizearray > 0);
for (n = gnode(h, 0); n < limit; n++) { for (n = gnode(h, 0); n < limit; n++) {
checkdeadkey(n); checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */ if (ttisnil(gval(n))) /* entry is empty? */
@@ -347,16 +359,22 @@ static void traverseweakvalue (global_State *g, Table *h) {
else { else {
lua_assert(!ttisnil(gkey(n))); lua_assert(!ttisnil(gkey(n)));
markvalue(g, gkey(n)); /* mark key */ markvalue(g, gkey(n)); /* mark key */
if (!hasclears && iscleared(gval(n))) /* is there a white value? */
hasclears = 1; /* table will have to be cleared */
} }
} }
linktable(h, &g->weak); /* link into appropriate list */ if (hasclears)
linktable(h, &g->weak); /* has to be cleared later */
else /* no white values */
linktable(h, &g->grayagain); /* no need to clean */
} }
static int traverseephemeron (global_State *g, Table *h) { static int traverseephemeron (global_State *g, Table *h) {
int marked = 0; /* true if an object is marked in this traversal */ int marked = 0; /* true if an object is marked in this traversal */
int hasclears = 0; /* true if table has unmarked pairs */ int hasclears = 0; /* true if table has white keys */
Node *n, *limit = gnode(h, sizenode(h)); int prop = 0; /* true if table has entry "white-key -> white-value" */
Node *n, *limit = gnodelast(h);
int i; int i;
/* traverse array part (numeric keys are 'strong') */ /* traverse array part (numeric keys are 'strong') */
for (i = 0; i < h->sizearray; i++) { for (i = 0; i < h->sizearray; i++) {
@@ -370,25 +388,28 @@ static int traverseephemeron (global_State *g, Table *h) {
checkdeadkey(n); checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */ if (ttisnil(gval(n))) /* entry is empty? */
removeentry(n); /* remove it */ removeentry(n); /* remove it */
else if (iscleared(gkey(n))) { /* key is not marked (yet)? */
hasclears = 1; /* table must be cleared */
if (valiswhite(gval(n))) /* value not marked yet? */
prop = 1; /* must propagate again */
}
else if (valiswhite(gval(n))) { /* value not marked yet? */ else if (valiswhite(gval(n))) { /* value not marked yet? */
if (iscleared(gkey(n), 1)) /* key is not marked (yet)? */ marked = 1;
hasclears = 1; /* may have to propagate mark from key to value */ reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
else { /* key is marked, so mark value */
marked = 1; /* value was not marked */
reallymarkobject(g, gcvalue(gval(n)));
}
} }
} }
if (hasclears) /* does table have unmarked pairs? */ if (prop)
linktable(h, &g->ephemeron); /* will have to propagate again */ linktable(h, &g->ephemeron); /* have to propagate again */
else /* nothing to propagate */ else if (hasclears) /* does table have white keys? */
linktable(h, &g->weak); /* avoid convergence phase */ linktable(h, &g->allweak); /* may have to clean white keys */
else /* no white keys */
linktable(h, &g->grayagain); /* no need to clean */
return marked; return marked;
} }
static void traversestrongtable (global_State *g, Table *h) { static void traversestrongtable (global_State *g, Table *h) {
Node *n, *limit = gnode(h, sizenode(h)); Node *n, *limit = gnodelast(h);
int i; int i;
for (i = 0; i < h->sizearray; i++) /* traverse array part */ for (i = 0; i < h->sizearray; i++) /* traverse array part */
markvalue(g, &h->array[i]); markvalue(g, &h->array[i]);
@@ -524,11 +545,26 @@ static void propagateall (global_State *g) {
} }
static void traverselistofgrays (global_State *g, GCObject **l) { static void propagatelist (global_State *g, GCObject *l) {
lua_assert(g->gray == NULL); /* no grays left */ lua_assert(g->gray == NULL); /* no grays left */
g->gray = *l; /* now 'l' is new gray list */ g->gray = l;
*l = NULL; propagateall(g); /* traverse all elements from 'l' */
propagateall(g); }
/*
** retraverse all gray lists. Because tables may be reinserted in other
** lists when traversed, traverse the original lists to avoid traversing
** twice the same table (which is not wrong, but inefficient)
*/
static void retraversegrays (global_State *g) {
GCObject *weak = g->weak; /* save original lists */
GCObject *grayagain = g->grayagain;
GCObject *ephemeron = g->ephemeron;
g->weak = g->grayagain = g->ephemeron = NULL;
propagateall(g); /* traverse main gray list */
propagatelist(g, grayagain);
propagatelist(g, weak);
propagatelist(g, ephemeron);
} }
@@ -560,21 +596,39 @@ static void convergeephemerons (global_State *g) {
/* /*
** clear collected entries from all weaktables in list 'l' ** clear entries with unmarked keys from all weaktables in list 'l' up
** to element 'f'
*/ */
static void cleartable (GCObject *l) { static void clearkeys (GCObject *l, GCObject *f) {
for (; l != NULL; l = gco2t(l)->gclist) { for (; l != f; l = gco2t(l)->gclist) {
Table *h = gco2t(l); Table *h = gco2t(l);
Node *n, *limit = gnode(h, sizenode(h)); Node *n, *limit = gnodelast(h);
for (n = gnode(h, 0); n < limit; n++) {
if (!ttisnil(gval(n)) && (iscleared(gkey(n)))) {
setnilvalue(gval(n)); /* remove value ... */
removeentry(n); /* and remove entry from table */
}
}
}
}
/*
** clear entries with unmarked values from all weaktables in list 'l' up
** to element 'f'
*/
static void clearvalues (GCObject *l, GCObject *f) {
for (; l != f; l = gco2t(l)->gclist) {
Table *h = gco2t(l);
Node *n, *limit = gnodelast(h);
int i; int i;
for (i = 0; i < h->sizearray; i++) { for (i = 0; i < h->sizearray; i++) {
TValue *o = &h->array[i]; TValue *o = &h->array[i];
if (iscleared(o, 0)) /* value was collected? */ if (iscleared(o)) /* value was collected? */
setnilvalue(o); /* remove value */ setnilvalue(o); /* remove value */
} }
for (n = gnode(h, 0); n < limit; n++) { for (n = gnode(h, 0); n < limit; n++) {
if (!ttisnil(gval(n)) && /* non-empty entry? */ if (!ttisnil(gval(n)) && iscleared(gval(n))) {
(iscleared(gkey(n), 1) || iscleared(gval(n), 0))) {
setnilvalue(gval(n)); /* remove value ... */ setnilvalue(gval(n)); /* remove value ... */
removeentry(n); /* and remove entry from table */ removeentry(n); /* and remove entry from table */
} }
@@ -635,6 +689,7 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
int ow = otherwhite(g); int ow = otherwhite(g);
int toclear, toset; /* bits to clear and to set in all live objects */ int toclear, toset; /* bits to clear and to set in all live objects */
int tostop; /* stop sweep when this is true */ int tostop; /* stop sweep when this is true */
l_mem debt = g->GCdebt; /* current debt */
if (isgenerational(g)) { /* generational mode? */ if (isgenerational(g)) { /* generational mode? */
toclear = ~0; /* clear nothing */ toclear = ~0; /* clear nothing */
toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */ toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */
@@ -657,13 +712,15 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */ sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */
if (testbits(marked, tostop)) { if (testbits(marked, tostop)) {
static GCObject *nullp = NULL; static GCObject *nullp = NULL;
return &nullp; /* stop sweeping this list */ p = &nullp; /* stop sweeping this list */
break;
} }
/* update marks */ /* update marks */
gch(curr)->marked = cast_byte((marked & toclear) | toset); gch(curr)->marked = cast_byte((marked & toclear) | toset);
p = &gch(curr)->next; /* go to next element */ p = &gch(curr)->next; /* go to next element */
} }
} }
luaE_setdebt(g, debt); /* sweeping should not change debt */
return p; return p;
} }
@@ -687,19 +744,17 @@ static void checkSizes (lua_State *L) {
} }
static Udata *udata2finalize (global_State *g) { static GCObject *udata2finalize (global_State *g) {
GCObject *o = g->tobefnz; /* get first element */ GCObject *o = g->tobefnz; /* get first element */
Udata *u = rawgco2u(o); lua_assert(isfinalized(o));
lua_assert(isfinalized(&u->uv)); g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
lua_assert(!isold(o)); gch(o)->next = g->allgc; /* return it to 'allgc' list */
g->tobefnz = u->uv.next; /* remove it from 'tobefnz' list */
u->uv.next = g->allgc; /* return it to 'allgc' list */
g->allgc = o; g->allgc = o;
resetbit(u->uv.marked, SEPARATED); /* mark that it is not in 'tobefnz' */ resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */
resetoldbit(o); /* see MOVE OLD rule */ lua_assert(!isold(o)); /* see MOVE OLD rule */
if (!keepinvariant(g)) /* not keeping invariant? */ if (!keepinvariant(g)) /* not keeping invariant? */
makewhite(g, o); /* "sweep" object */ makewhite(g, o); /* "sweep" object */
return u; return o;
} }
@@ -711,23 +766,25 @@ static void dothecall (lua_State *L, void *ud) {
static void GCTM (lua_State *L, int propagateerrors) { static void GCTM (lua_State *L, int propagateerrors) {
global_State *g = G(L); global_State *g = G(L);
Udata *udata = udata2finalize(g); const TValue *tm;
const TValue *tm = gfasttm(g, udata->uv.metatable, TM_GC); TValue v;
setgcovalue(L, &v, udata2finalize(g));
tm = luaT_gettmbyobj(L, &v, TM_GC);
if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */ if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
int status; int status;
lu_byte oldah = L->allowhook; lu_byte oldah = L->allowhook;
lu_mem oldd = g->GCdebt; int running = g->gcrunning;
L->allowhook = 0; /* stop debug hooks during GC tag method */ L->allowhook = 0; /* stop debug hooks during GC metamethod */
stopgc(g); /* avoid GC steps */ g->gcrunning = 0; /* avoid GC steps */
setobj2s(L, L->top, tm); /* push finalizer... */ setobj2s(L, L->top, tm); /* push finalizer... */
setuvalue(L, L->top+1, udata); /* ... and its argument */ setobj2s(L, L->top + 1, &v); /* ... and its argument */
L->top += 2; /* and (next line) call the finalizer */ L->top += 2; /* and (next line) call the finalizer */
status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
L->allowhook = oldah; /* restore hooks */ L->allowhook = oldah; /* restore hooks */
g->GCdebt = oldd; /* restore threshold */ g->gcrunning = running; /* restore state */
if (status != LUA_OK && propagateerrors) { /* error while running __gc? */ if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
if (status == LUA_ERRRUN) { /* is there an error msg.? */ if (status == LUA_ERRRUN) { /* is there an error msg.? */
luaO_pushfstring(L, "error in __gc tag method (%s)", luaO_pushfstring(L, "error in __gc metamethod (%s)",
lua_tostring(L, -1)); lua_tostring(L, -1));
status = LUA_ERRGCMM; /* error in __gc metamethod */ status = LUA_ERRGCMM; /* error in __gc metamethod */
} }
@@ -738,25 +795,25 @@ static void GCTM (lua_State *L, int propagateerrors) {
/* /*
** move all unreachable udata that need finalization from list 'udgc' to ** move all unreachable objects (or 'all' objects) that need
** list 'tobefnz' ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
*/ */
void luaC_separateudata (lua_State *L, int all) { static void separatetobefnz (lua_State *L, int all) {
global_State *g = G(L); global_State *g = G(L);
GCObject **p = &g->udgc; GCObject **p = &g->finobj;
GCObject *curr; GCObject *curr;
GCObject **lastnext = &g->tobefnz; GCObject **lastnext = &g->tobefnz;
/* find last 'next' field in 'tobefnz' list (to add elements in its end) */ /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
while (*lastnext != NULL) while (*lastnext != NULL)
lastnext = &gch(*lastnext)->next; lastnext = &gch(*lastnext)->next;
while ((curr = *p) != NULL) { /* traverse all finalizable objects */ while ((curr = *p) != NULL) { /* traverse all finalizable objects */
lua_assert(gch(curr)->tt == LUA_TUSERDATA && !isfinalized(gco2u(curr))); lua_assert(!isfinalized(curr));
lua_assert(testbit(gch(curr)->marked, SEPARATED)); lua_assert(testbit(gch(curr)->marked, SEPARATED));
if (!(all || iswhite(curr))) /* not being collected? */ if (!(all || iswhite(curr))) /* not being collected? */
p = &gch(curr)->next; /* don't bother with it */ p = &gch(curr)->next; /* don't bother with it */
else { else {
l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */ l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
*p = gch(curr)->next; /* remove 'curr' from 'udgc' list */ *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */
gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */ gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
*lastnext = curr; *lastnext = curr;
lastnext = &gch(curr)->next; lastnext = &gch(curr)->next;
@@ -766,23 +823,23 @@ void luaC_separateudata (lua_State *L, int all) {
/* /*
** if userdata 'u' has a finalizer, remove it from 'allgc' list (must ** if object 'o' has a finalizer, remove it from 'allgc' list (must
** search the list to find it) and link it in 'udgc' list. ** search the list to find it) and link it in 'finobj' list.
*/ */
void luaC_checkfinalizer (lua_State *L, Udata *u) { void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
global_State *g = G(L); global_State *g = G(L);
if (testbit(u->uv.marked, SEPARATED) || /* udata is already separated... */ if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
isfinalized(&u->uv) || /* ... or is finalized... */ isfinalized(o) || /* ... or is finalized... */
gfasttm(g, u->uv.metatable, TM_GC) == NULL) /* or has no finalizer? */ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
return; /* nothing to be done */ return; /* nothing to be done */
else { /* move 'u' to 'udgc' list */ else { /* move 'o' to 'finobj' list */
GCObject **p; GCObject **p;
for (p = &g->allgc; *p != obj2gco(u); p = &gch(*p)->next) ; for (p = &g->allgc; *p != o; p = &gch(*p)->next) ;
*p = u->uv.next; /* remove 'u' from root list */ *p = gch(o)->next; /* remove 'o' from root list */
u->uv.next = g->udgc; /* link it in list 'udgc' */ gch(o)->next = g->finobj; /* link it in list 'finobj' */
g->udgc = obj2gco(u); g->finobj = o;
l_setbit(u->uv.marked, SEPARATED); /* mark it as such */ l_setbit(gch(o)->marked, SEPARATED); /* mark it as such */
resetoldbit(obj2gco(u)); /* see MOVE OLD rule */ resetoldbit(o); /* see MOVE OLD rule */
} }
} }
@@ -808,7 +865,7 @@ void luaC_changemode (lua_State *L, int mode) {
if (mode == KGC_GEN) { /* change to generational mode */ if (mode == KGC_GEN) { /* change to generational mode */
/* make sure gray lists are consistent */ /* make sure gray lists are consistent */
luaC_runtilstate(L, bitmask(GCSpropagate)); luaC_runtilstate(L, bitmask(GCSpropagate));
g->lastmajormem = g->totalbytes; g->lastmajormem = gettotalbytes(g);
g->gckind = KGC_GEN; g->gckind = KGC_GEN;
} }
else { /* change to incremental mode */ else { /* change to incremental mode */
@@ -823,24 +880,27 @@ void luaC_changemode (lua_State *L, int mode) {
/* /*
** call all pending finalizers */ ** call all pending finalizers
*/
static void callallpendingfinalizers (lua_State *L, int propagateerrors) { static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
global_State *g = G(L); global_State *g = G(L);
while (g->tobefnz) GCTM(L, propagateerrors); while (g->tobefnz) {
resetoldbit(g->tobefnz);
GCTM(L, propagateerrors);
}
} }
void luaC_freeallobjects (lua_State *L) { void luaC_freeallobjects (lua_State *L) {
global_State *g = G(L); global_State *g = G(L);
int i; int i;
separatetobefnz(L, 1); /* separate all objects with finalizers */
lua_assert(g->finobj == NULL);
callallpendingfinalizers(L, 0); callallpendingfinalizers(L, 0);
/* following "white" makes all objects look dead */ g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
g->currentwhite = WHITEBITS;
g->gckind = KGC_NORMAL; g->gckind = KGC_NORMAL;
sweepwholelist(L, &g->udgc); sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */
lua_assert(g->udgc == NULL);
sweepwholelist(L, &g->allgc); sweepwholelist(L, &g->allgc);
lua_assert(g->allgc == NULL);
for (i = 0; i < g->strt.size; i++) /* free all string lists */ for (i = 0; i < g->strt.size; i++) /* free all string lists */
sweepwholelist(L, &g->strt.hash[i]); sweepwholelist(L, &g->strt.hash[i]);
lua_assert(g->strt.nuse == 0); lua_assert(g->strt.nuse == 0);
@@ -849,6 +909,7 @@ void luaC_freeallobjects (lua_State *L) {
static void atomic (lua_State *L) { static void atomic (lua_State *L) {
global_State *g = G(L); global_State *g = G(L);
GCObject *origweak, *origall;
lua_assert(!iswhite(obj2gco(g->mainthread))); lua_assert(!iswhite(obj2gco(g->mainthread)));
markobject(g, L); /* mark running thread */ markobject(g, L); /* mark running thread */
/* registry and global metatables may be changed by API */ /* registry and global metatables may be changed by API */
@@ -857,20 +918,24 @@ static void atomic (lua_State *L) {
/* remark occasional upvalues of (maybe) dead threads */ /* remark occasional upvalues of (maybe) dead threads */
remarkupvals(g); remarkupvals(g);
/* traverse objects caught by write barrier and by 'remarkupvals' */ /* traverse objects caught by write barrier and by 'remarkupvals' */
propagateall(g); retraversegrays(g);
traverselistofgrays(g, &g->weak); /* remark weak tables */
traverselistofgrays(g, &g->ephemeron); /* remark ephemeron tables */
traverselistofgrays(g, &g->grayagain); /* remark gray again */
convergeephemerons(g); convergeephemerons(g);
/* at this point, all strongly accessible objects are marked. */ /* at this point, all strongly accessible objects are marked. */
luaC_separateudata(L, 0); /* separate userdata to be finalized */ /* clear values from weak tables, before checking finalizers */
clearvalues(g->weak, NULL);
clearvalues(g->allweak, NULL);
origweak = g->weak; origall = g->allweak;
separatetobefnz(L, 0); /* separate objects to be finalized */
markbeingfnz(g); /* mark userdata that will be finalized */ markbeingfnz(g); /* mark userdata that will be finalized */
propagateall(g); /* remark, to propagate `preserveness' */ propagateall(g); /* remark, to propagate `preserveness' */
convergeephemerons(g); convergeephemerons(g);
/* remove collected objects from weak tables */ /* at this point, all resurrected objects are marked. */
cleartable(g->weak); /* remove dead objects from weak tables */
cleartable(g->ephemeron); clearkeys(g->ephemeron, NULL); /* clear keys from all ephemeron tables */
cleartable(g->allweak); clearkeys(g->allweak, NULL); /* clear keys from all allweak tables */
/* clear values from resurrected weak tables */
clearvalues(g->weak, origweak);
clearvalues(g->allweak, origall);
g->sweepstrgc = 0; /* prepare to sweep strings */ g->sweepstrgc = 0; /* prepare to sweep strings */
g->gcstate = GCSsweepstring; g->gcstate = GCSsweepstring;
g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
@@ -883,7 +948,7 @@ static l_mem singlestep (lua_State *L) {
switch (g->gcstate) { switch (g->gcstate) {
case GCSpause: { case GCSpause: {
if (!isgenerational(g)) if (!isgenerational(g))
markroot(L); /* start a new collection */ markroot(g); /* start a new collection */
/* in any case, root must be marked */ /* in any case, root must be marked */
lua_assert(!iswhite(obj2gco(g->mainthread)) lua_assert(!iswhite(obj2gco(g->mainthread))
&& !iswhite(gcvalue(&g->l_registry))); && !iswhite(gcvalue(&g->l_registry)));
@@ -905,7 +970,7 @@ static l_mem singlestep (lua_State *L) {
return GCSWEEPCOST; return GCSWEEPCOST;
} }
else { /* no more strings to sweep */ else { /* no more strings to sweep */
g->sweepgc = &g->udgc; /* prepare to sweep userdata */ g->sweepgc = &g->finobj; /* prepare to sweep finalizable objects */
g->gcstate = GCSsweepudata; g->gcstate = GCSsweepudata;
return 0; return 0;
} }
@@ -955,15 +1020,15 @@ static void generationalcollection (lua_State *L) {
global_State *g = G(L); global_State *g = G(L);
if (g->lastmajormem == 0) { /* signal for another major collection? */ if (g->lastmajormem == 0) { /* signal for another major collection? */
luaC_fullgc(L, 0); /* perform a full regular collection */ luaC_fullgc(L, 0); /* perform a full regular collection */
g->lastmajormem = g->totalbytes; /* update control */ g->lastmajormem = gettotalbytes(g); /* update control */
} }
else { else {
luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */ luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */
luaC_runtilstate(L, bitmask(GCSpause)); luaC_runtilstate(L, bitmask(GCSpause));
if (g->totalbytes > g->lastmajormem/100 * g->gcmajorinc) if (gettotalbytes(g) > g->lastmajormem/100 * g->gcmajorinc)
g->lastmajormem = 0; /* signal for a major collection */ g->lastmajormem = 0; /* signal for a major collection */
} }
g->GCdebt = stddebt(g); luaE_setdebt(g, stddebt(g));
} }
@@ -974,21 +1039,33 @@ static void step (lua_State *L) {
lim -= singlestep(L); lim -= singlestep(L);
} while (lim > 0 && g->gcstate != GCSpause); } while (lim > 0 && g->gcstate != GCSpause);
if (g->gcstate != GCSpause) if (g->gcstate != GCSpause)
g->GCdebt -= GCSTEPSIZE; luaE_setdebt(g, g->GCdebt - GCSTEPSIZE);
else else
g->GCdebt = stddebt(g); luaE_setdebt(g, stddebt(g));
} }
void luaC_step (lua_State *L) { /*
** performs a basic GC step even if the collector is stopped
*/
void luaC_forcestep (lua_State *L) {
global_State *g = G(L);
int i; int i;
if (isgenerational(G(L))) generationalcollection(L); if (isgenerational(g)) generationalcollection(L);
else step(L); else step(L);
for (i = 0; i < GCFINALIZENUM && G(L)->tobefnz; i++) for (i = 0; i < GCFINALIZENUM && g->tobefnz; i++)
GCTM(L, 1); /* Call a few pending finalizers */ GCTM(L, 1); /* Call a few pending finalizers */
} }
/*
** performs a basic GC step only if collector is running
*/
void luaC_step (lua_State *L) {
if (G(L)->gcrunning) luaC_forcestep(L);
}
/* /*
** performs a full GC cycle; if "isemergency", does not call ** performs a full GC cycle; if "isemergency", does not call
** finalizers (which could change stack positions) ** finalizers (which could change stack positions)
@@ -1016,7 +1093,7 @@ void luaC_fullgc (lua_State *L, int isemergency) {
luaC_runtilstate(L, bitmask(GCSpropagate)); luaC_runtilstate(L, bitmask(GCSpropagate));
} }
g->gckind = origkind; g->gckind = origkind;
g->GCdebt = stddebt(g); luaE_setdebt(g, stddebt(g));
if (!isemergency) /* do not run finalizers during emergency GC */ if (!isemergency) /* do not run finalizers during emergency GC */
callallpendingfinalizers(L, 1); callallpendingfinalizers(L, 1);
} }

21
lgc.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lgc.h,v 2.43 2010/06/07 16:55:34 roberto Exp roberto $ ** $Id: lgc.h,v 2.51 2011/09/30 12:44:19 roberto Exp roberto $
** Garbage Collector ** Garbage Collector
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -52,10 +52,6 @@
#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic) #define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)
#define gcstopped(g) ((g)->GCdebt == MIN_LMEM)
#define stopgc(g) ((g)->GCdebt = MIN_LMEM)
/* /*
** some useful bit tricks ** some useful bit tricks
*/ */
@@ -67,17 +63,14 @@
#define l_setbit(x,b) setbits(x, bitmask(b)) #define l_setbit(x,b) setbits(x, bitmask(b))
#define resetbit(x,b) resetbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b))
#define testbit(x,b) testbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b))
#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2)))
#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2)))
/* Layout for bit use in `marked' field: */ /* Layout for bit use in `marked' field: */
#define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE0BIT 0 /* object is white (type 0) */
#define WHITE1BIT 1 /* object is white (type 1) */ #define WHITE1BIT 1 /* object is white (type 1) */
#define BLACKBIT 2 /* object is black */ #define BLACKBIT 2 /* object is black */
#define FINALIZEDBIT 3 /* for userdata: has been finalized */ #define FINALIZEDBIT 3 /* object has been separated for finalization */
#define SEPARATED 4 /* " ": it's in 'udgc' list or in 'tobefnz' */ #define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */
#define FIXEDBIT 5 /* object is fixed (should not be collected) */ #define FIXEDBIT 5 /* object is fixed (should not be collected) */
#define OLDBIT 6 /* object is old (only in generational mode) */ #define OLDBIT 6 /* object is old (only in generational mode) */
/* bit 7 is currently used by tests (luaL_checkmemory) */ /* bit 7 is currently used by tests (luaL_checkmemory) */
@@ -108,7 +101,9 @@
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
#define luaC_checkGC(L) {condchangemem(L); if (G(L)->GCdebt > 0) luaC_step(L);} #define luaC_condGC(L,c) \
{if (G(L)->GCdebt > 0) {c;}; condchangemem(L);}
#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);)
#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
@@ -127,9 +122,9 @@
#define luaC_barrierproto(L,p,c) \ #define luaC_barrierproto(L,p,c) \
{ if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); } { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); }
LUAI_FUNC void luaC_separateudata (lua_State *L, int all);
LUAI_FUNC void luaC_freeallobjects (lua_State *L); LUAI_FUNC void luaC_freeallobjects (lua_State *L);
LUAI_FUNC void luaC_step (lua_State *L); LUAI_FUNC void luaC_step (lua_State *L);
LUAI_FUNC void luaC_forcestep (lua_State *L);
LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
@@ -137,7 +132,7 @@ LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c); LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);
LUAI_FUNC void luaC_checkfinalizer (lua_State *L, Udata *u); LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv); LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
LUAI_FUNC void luaC_changemode (lua_State *L, int mode); LUAI_FUNC void luaC_changemode (lua_State *L, int mode);

10
linit.c
View File

@@ -1,16 +1,16 @@
/* /*
** $Id: linit.c,v 1.29 2010/10/25 14:32:36 roberto Exp roberto $ ** $Id: linit.c,v 1.31 2011/01/26 16:30:02 roberto Exp roberto $
** Initialization of libraries for lua.c and other clients ** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
/* /*
** If you embed Lua in your program and need to open the standard ** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a ** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit ** different set of libraries, copy this file to your project and edit
** it to suit your needs. ** it to suit your needs.
*/ */
#define linit_c #define linit_c
@@ -57,7 +57,7 @@ LUALIB_API void luaL_openlibs (lua_State *L) {
lua_pop(L, 1); /* remove lib */ lua_pop(L, 1); /* remove lib */
} }
/* add open functions from 'preloadedlibs' into 'package.preload' table */ /* add open functions from 'preloadedlibs' into 'package.preload' table */
luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
for (lib = preloadedlibs; lib->func; lib++) { for (lib = preloadedlibs; lib->func; lib++) {
lua_pushcfunction(L, lib->func); lua_pushcfunction(L, lib->func);
lua_setfield(L, -2, lib->name); lua_setfield(L, -2, lib->name);

408
liolib.c
View File

@@ -1,10 +1,20 @@
/* /*
** $Id: liolib.c,v 2.94 2010/11/09 16:57:49 roberto Exp roberto $ ** $Id: liolib.c,v 2.107 2011/11/14 16:55:35 roberto Exp roberto $
** Standard I/O (and system) library ** Standard I/O (and system) library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
/*
** POSIX idiosyncrasy!
** This definition must come before the inclusion of 'stdio.h'; it
** should not affect non-POSIX systems
*/
#if !defined(_FILE_OFFSET_BITS)
#define _FILE_OFFSET_BITS 64
#endif
#include <errno.h> #include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@@ -19,78 +29,96 @@
#include "lualib.h" #include "lualib.h"
#define MAX_SIZE_T (~(size_t)0)
/*
** {======================================================
** lua_popen spawns a new process connected to the current
** one through the file streams.
** =======================================================
*/
#if !defined(lua_popen) /* { */
#if defined(LUA_USE_POPEN) /* { */
#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
#define lua_pclose(L,file) ((void)L, pclose(file))
#elif defined(LUA_WIN) /* }{ */
#define lua_popen(L,c,m) ((void)L, _popen(c,m))
#define lua_pclose(L,file) ((void)L, _pclose(file))
#else /* }{ */
#define lua_popen(L,c,m) ((void)((void)c, m), \
luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
#define lua_pclose(L,file) ((void)((void)L, file), -1)
#endif /* } */
#endif /* } */
/* }====================================================== */
/* /*
** lua_popen spawns a new process connected to the current one through ** {======================================================
** the file streams. ** lua_fseek/lua_ftell: configuration for longer offsets
** =======================================================
*/ */
#if !defined(lua_popen)
#if defined(LUA_USE_POPEN) #if !defined(lua_fseek) /* { */
#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) #if defined(LUA_USE_POSIX)
#define lua_pclose(L,file) ((void)L, pclose(file))
#elif defined(LUA_WIN) #define l_fseek(f,o,w) fseeko(f,o,w)
#define l_ftell(f) ftello(f)
#define l_seeknum off_t
#define lua_popen(L,c,m) ((void)L, _popen(c,m)) #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
#define lua_pclose(L,file) ((void)L, _pclose(file)) && defined(_MSC_VER) && (_MSC_VER >= 1400)
/* Windows (but not DDK) and Visual C++ 2005 or higher */
#define l_fseek(f,o,w) _fseeki64(f,o,w)
#define l_ftell(f) _ftelli64(f)
#define l_seeknum __int64
#else #else
#define lua_popen(L,c,m) ((void)((void)c, m), \ #define l_fseek(f,o,w) fseek(f,o,w)
luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) #define l_ftell(f) ftell(f)
#define lua_pclose(L,file) ((void)((void)L, file), -1) #define l_seeknum long
#endif #endif
#endif #endif /* } */
/* }====================================================== */
#define IO_PREFIX "_IO_"
#define IO_INPUT 1 #define IO_INPUT (IO_PREFIX "input")
#define IO_OUTPUT 2 #define IO_OUTPUT (IO_PREFIX "output")
static const char *const fnames[] = {"input", "output"}; typedef luaL_Stream LStream;
static int pushresult (lua_State *L, int i, const char *filename) { #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
int en = errno; /* calls to Lua API may change this value */
if (i) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
if (filename)
lua_pushfstring(L, "%s: %s", filename, strerror(en));
else
lua_pushfstring(L, "%s", strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
#define isclosed(p) ((p)->closef == NULL)
static void fileerror (lua_State *L, int arg, const char *filename) {
lua_pushfstring(L, "%s: %s", filename, strerror(errno));
luaL_argerror(L, arg, lua_tostring(L, -1));
}
#define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
static int io_type (lua_State *L) { static int io_type (lua_State *L) {
void *ud; LStream *p;
luaL_checkany(L, 1); luaL_checkany(L, 1);
ud = luaL_testudata(L, 1, LUA_FILEHANDLE); p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
if (ud == NULL) if (p == NULL)
lua_pushnil(L); /* not a file */ lua_pushnil(L); /* not a file */
else if (*((FILE **)ud) == NULL) else if (isclosed(p))
lua_pushliteral(L, "closed file"); lua_pushliteral(L, "closed file");
else else
lua_pushliteral(L, "file"); lua_pushliteral(L, "file");
@@ -98,11 +126,22 @@ static int io_type (lua_State *L) {
} }
static int f_tostring (lua_State *L) {
LStream *p = tolstream(L);
if (isclosed(p))
lua_pushliteral(L, "file (closed)");
else
lua_pushfstring(L, "file (%p)", p->f);
return 1;
}
static FILE *tofile (lua_State *L) { static FILE *tofile (lua_State *L) {
FILE **f = tofilep(L); LStream *p = tolstream(L);
if (*f == NULL) if (isclosed(p))
luaL_error(L, "attempt to use a closed file"); luaL_error(L, "attempt to use a closed file");
return *f; lua_assert(p->f);
return p->f;
} }
@@ -111,45 +150,35 @@ static FILE *tofile (lua_State *L) {
** before opening the actual file; so, if there is a memory error, the ** before opening the actual file; so, if there is a memory error, the
** file is not left opened. ** file is not left opened.
*/ */
static FILE **newprefile (lua_State *L) { static LStream *newprefile (lua_State *L) {
FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
*pf = NULL; /* file handle is currently `closed' */ p->closef = NULL; /* mark file handle as 'closed' */
luaL_setmetatable(L, LUA_FILEHANDLE); luaL_setmetatable(L, LUA_FILEHANDLE);
return pf; return p;
} }
static FILE **newfile (lua_State *L) { static int aux_close (lua_State *L) {
FILE **pf = newprefile(L); LStream *p = tolstream(L);
lua_pushvalue(L, lua_upvalueindex(1)); /* set upvalue... */ lua_CFunction cf = p->closef;
lua_setuservalue(L, -2); /* ... as environment for new file */ p->closef = NULL; /* mark stream as closed */
return pf; return (*cf)(L); /* close it */
} }
/* static int io_close (lua_State *L) {
** function to (not) close the standard files stdin, stdout, and stderr if (lua_isnone(L, 1)) /* no argument? */
*/ lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
static int io_noclose (lua_State *L) { tofile(L); /* make sure argument is an open stream */
lua_pushnil(L); return aux_close(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
} }
/* static int f_gc (lua_State *L) {
** function to close 'popen' files LStream *p = tolstream(L);
*/ if (!isclosed(p) && p->f != NULL)
static int io_pclose (lua_State *L) { aux_close(L); /* ignore closed and incompletely open files */
FILE **p = tofilep(L); return 0;
int stat = lua_pclose(L, *p);
*p = NULL;
if (stat == -1) /* error? */
return pushresult(L, 0, NULL);
else {
lua_pushinteger(L, stat);
return 1; /* return status */
}
} }
@@ -157,112 +186,94 @@ static int io_pclose (lua_State *L) {
** function to close regular files ** function to close regular files
*/ */
static int io_fclose (lua_State *L) { static int io_fclose (lua_State *L) {
FILE **p = tofilep(L); LStream *p = tolstream(L);
int ok = (fclose(*p) == 0); int res = fclose(p->f);
*p = NULL; return luaL_fileresult(L, (res == 0), NULL);
return pushresult(L, ok, NULL);
} }
static int aux_close (lua_State *L) { static LStream *newfile (lua_State *L) {
lua_getuservalue(L, 1); LStream *p = newprefile(L);
lua_getfield(L, -1, "__close"); p->f = NULL;
return (lua_tocfunction(L, -1))(L); p->closef = &io_fclose;
return p;
} }
static int io_close (lua_State *L) { static void opencheck (lua_State *L, const char *fname, const char *mode) {
if (lua_isnone(L, 1)) LStream *p = newfile(L);
lua_rawgeti(L, lua_upvalueindex(1), IO_OUTPUT); p->f = fopen(fname, mode);
tofile(L); /* make sure argument is a file */ if (p->f == NULL)
return aux_close(L); luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
}
static int io_gc (lua_State *L) {
FILE *f = *tofilep(L);
/* ignore closed files */
if (f != NULL)
aux_close(L);
return 0;
}
static int io_tostring (lua_State *L) {
FILE *f = *tofilep(L);
if (f == NULL)
lua_pushliteral(L, "file (closed)");
else
lua_pushfstring(L, "file (%p)", f);
return 1;
} }
static int io_open (lua_State *L) { static int io_open (lua_State *L) {
const char *filename = luaL_checkstring(L, 1); const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r"); const char *mode = luaL_optstring(L, 2, "r");
FILE **pf; LStream *p = newfile(L);
int i = 0; int i = 0;
/* check whether 'mode' matches '[rwa]%+?b?' */ /* check whether 'mode' matches '[rwa]%+?b?' */
if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL && if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL &&
(mode[i] != '+' || ++i) && /* skip if char is '+' */ (mode[i] != '+' || ++i) && /* skip if char is '+' */
(mode[i] != 'b' || ++i) && /* skip if char is 'b' */ (mode[i] != 'b' || ++i) && /* skip if char is 'b' */
(mode[i] == '\0'))) (mode[i] == '\0')))
luaL_error(L, "invalid mode " LUA_QL("%s") return luaL_error(L, "invalid mode " LUA_QS
" (should match " LUA_QL("[rwa]%%+?b?") ")", mode); " (should match " LUA_QL("[rwa]%%+?b?") ")", mode);
pf = newfile(L); p->f = fopen(filename, mode);
*pf = fopen(filename, mode); return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
} }
/* /*
** this function has a separated environment, which defines the ** function to close 'popen' files
** correct __close for 'popen' files
*/ */
static int io_pclose (lua_State *L) {
LStream *p = tolstream(L);
return luaL_execresult(L, lua_pclose(L, p->f));
}
static int io_popen (lua_State *L) { static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1); const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r"); const char *mode = luaL_optstring(L, 2, "r");
FILE **pf = newfile(L); LStream *p = newprefile(L);
*pf = lua_popen(L, filename, mode); p->f = lua_popen(L, filename, mode);
return (*pf == NULL) ? pushresult(L, 0, filename) : 1; p->closef = &io_pclose;
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
} }
static int io_tmpfile (lua_State *L) { static int io_tmpfile (lua_State *L) {
FILE **pf = newfile(L); LStream *p = newfile(L);
*pf = tmpfile(); p->f = tmpfile();
return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
} }
static FILE *getiofile (lua_State *L, int findex) { static FILE *getiofile (lua_State *L, const char *findex) {
FILE *f; LStream *p;
lua_rawgeti(L, lua_upvalueindex(1), findex); lua_getfield(L, LUA_REGISTRYINDEX, findex);
f = *(FILE **)lua_touserdata(L, -1); p = (LStream *)lua_touserdata(L, -1);
if (f == NULL) if (isclosed(p))
luaL_error(L, "standard %s file is closed", fnames[findex - 1]); luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
return f; return p->f;
} }
static int g_iofile (lua_State *L, int f, const char *mode) { static int g_iofile (lua_State *L, const char *f, const char *mode) {
if (!lua_isnoneornil(L, 1)) { if (!lua_isnoneornil(L, 1)) {
const char *filename = lua_tostring(L, 1); const char *filename = lua_tostring(L, 1);
if (filename) { if (filename)
FILE **pf = newfile(L); opencheck(L, filename, mode);
*pf = fopen(filename, mode);
if (*pf == NULL)
fileerror(L, 1, filename);
}
else { else {
tofile(L); /* check that it's a valid file handle */ tofile(L); /* check that it's a valid file handle */
lua_pushvalue(L, 1); lua_pushvalue(L, 1);
} }
lua_rawseti(L, lua_upvalueindex(1), f); lua_setfield(L, LUA_REGISTRYINDEX, f);
} }
/* return current value */ /* return current value */
lua_rawgeti(L, lua_upvalueindex(1), f); lua_getfield(L, LUA_REGISTRYINDEX, f);
return 1; return 1;
} }
@@ -304,18 +315,15 @@ static int io_lines (lua_State *L) {
int toclose; int toclose;
if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
if (lua_isnil(L, 1)) { /* no file name? */ if (lua_isnil(L, 1)) { /* no file name? */
lua_rawgeti(L, lua_upvalueindex(1), IO_INPUT); /* get default input */ lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
lua_replace(L, 1); /* put it at index 1 */ lua_replace(L, 1); /* put it at index 1 */
tofile(L); /* check that it's a valid file handle */ tofile(L); /* check that it's a valid file handle */
toclose = 0; /* do not close it after iteration */ toclose = 0; /* do not close it after iteration */
} }
else { /* open a new file */ else { /* open a new file */
const char *filename = luaL_checkstring(L, 1); const char *filename = luaL_checkstring(L, 1);
FILE **pf = newfile(L); opencheck(L, filename, "r");
*pf = fopen(filename, "r"); lua_replace(L, 1); /* put file at index 1 */
if (*pf == NULL)
fileerror(L, 1, filename);
lua_replace(L, 1); /* put file at index 1 */
toclose = 1; /* close it after iteration */ toclose = 1; /* close it after iteration */
} }
aux_lines(L, toclose); aux_lines(L, toclose);
@@ -373,6 +381,8 @@ static int read_line (lua_State *L, FILE *f, int chop) {
} }
#define MAX_SIZE_T (~(size_t)0)
static void read_all (lua_State *L, FILE *f) { static void read_all (lua_State *L, FILE *f) {
size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */ size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
luaL_Buffer b; luaL_Buffer b;
@@ -443,7 +453,7 @@ static int g_read (lua_State *L, FILE *f, int first) {
} }
} }
if (ferror(f)) if (ferror(f))
return pushresult(L, 0, NULL); return luaL_fileresult(L, 0, NULL);
if (!success) { if (!success) {
lua_pop(L, 1); /* remove last result */ lua_pop(L, 1); /* remove last result */
lua_pushnil(L); /* push nil instead */ lua_pushnil(L); /* push nil instead */
@@ -463,22 +473,23 @@ static int f_read (lua_State *L) {
static int io_readline (lua_State *L) { static int io_readline (lua_State *L) {
FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
int i; int i;
int n = (int)lua_tointeger(L, lua_upvalueindex(2)); int n = (int)lua_tointeger(L, lua_upvalueindex(2));
if (f == NULL) /* file is already closed? */ if (isclosed(p)) /* file is already closed? */
luaL_error(L, "file is already closed"); return luaL_error(L, "file is already closed");
lua_settop(L , 1); lua_settop(L , 1);
for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
lua_pushvalue(L, lua_upvalueindex(3 + i)); lua_pushvalue(L, lua_upvalueindex(3 + i));
n = g_read(L, f, 2); /* 'n' is number of results */ n = g_read(L, p->f, 2); /* 'n' is number of results */
lua_assert(n > 0); /* should return at least a nil */ lua_assert(n > 0); /* should return at least a nil */
if (!lua_isnil(L, -n)) /* read at least one value? */ if (!lua_isnil(L, -n)) /* read at least one value? */
return n; /* return them */ return n; /* return them */
else { /* first result is nil: EOF or error */ else { /* first result is nil: EOF or error */
if (!lua_isnil(L, -1)) /* is there error information? */ if (n > 1) { /* is there error information? */
return luaL_error(L, "%s", lua_tostring(L, -1)); /* error */ /* 2nd result is error message */
/* else EOF */ return luaL_error(L, "%s", lua_tostring(L, -n + 1));
}
if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
lua_settop(L, 0); lua_settop(L, 0);
lua_pushvalue(L, lua_upvalueindex(1)); lua_pushvalue(L, lua_upvalueindex(1));
@@ -507,7 +518,7 @@ static int g_write (lua_State *L, FILE *f, int arg) {
} }
} }
if (status) return 1; /* file handle already on stack top */ if (status) return 1; /* file handle already on stack top */
else return pushresult(L, status, NULL); else return luaL_fileresult(L, status, NULL);
} }
@@ -517,7 +528,7 @@ static int io_write (lua_State *L) {
static int f_write (lua_State *L) { static int f_write (lua_State *L) {
FILE * f = tofile(L); FILE *f = tofile(L);
lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
return g_write(L, f, 2); return g_write(L, f, 2);
} }
@@ -528,12 +539,15 @@ static int f_seek (lua_State *L) {
static const char *const modenames[] = {"set", "cur", "end", NULL}; static const char *const modenames[] = {"set", "cur", "end", NULL};
FILE *f = tofile(L); FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, "cur", modenames); int op = luaL_checkoption(L, 2, "cur", modenames);
long offset = luaL_optlong(L, 3, 0); lua_Number p3 = luaL_optnumber(L, 3, 0);
op = fseek(f, offset, mode[op]); l_seeknum offset = (l_seeknum)p3;
luaL_argcheck(L, (lua_Number)offset == p3, 3,
"not an integer in proper range");
op = l_fseek(f, offset, mode[op]);
if (op) if (op)
return pushresult(L, 0, NULL); /* error */ return luaL_fileresult(L, 0, NULL); /* error */
else { else {
lua_pushinteger(L, ftell(f)); lua_pushnumber(L, (lua_Number)l_ftell(f));
return 1; return 1;
} }
} }
@@ -546,21 +560,24 @@ static int f_setvbuf (lua_State *L) {
int op = luaL_checkoption(L, 2, NULL, modenames); int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
int res = setvbuf(f, NULL, mode[op], sz); int res = setvbuf(f, NULL, mode[op], sz);
return pushresult(L, res == 0, NULL); return luaL_fileresult(L, res == 0, NULL);
} }
static int io_flush (lua_State *L) { static int io_flush (lua_State *L) {
return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
} }
static int f_flush (lua_State *L) { static int f_flush (lua_State *L) {
return pushresult(L, fflush(tofile(L)) == 0, NULL); return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
} }
/*
** functions for 'io' library
*/
static const luaL_Reg iolib[] = { static const luaL_Reg iolib[] = {
{"close", io_close}, {"close", io_close},
{"flush", io_flush}, {"flush", io_flush},
@@ -577,6 +594,9 @@ static const luaL_Reg iolib[] = {
}; };
/*
** methods for file handles
*/
static const luaL_Reg flib[] = { static const luaL_Reg flib[] = {
{"close", io_close}, {"close", io_close},
{"flush", f_flush}, {"flush", f_flush},
@@ -585,8 +605,8 @@ static const luaL_Reg flib[] = {
{"seek", f_seek}, {"seek", f_seek},
{"setvbuf", f_setvbuf}, {"setvbuf", f_setvbuf},
{"write", f_write}, {"write", f_write},
{"__gc", io_gc}, {"__gc", f_gc},
{"__tostring", io_tostring}, {"__tostring", f_tostring},
{NULL, NULL} {NULL, NULL}
}; };
@@ -600,46 +620,38 @@ static void createmeta (lua_State *L) {
} }
static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) { /*
*newprefile(L) = f; ** function to (not) close the standard files stdin, stdout, and stderr
if (k > 0) { */
lua_pushvalue(L, -1); /* copy new file */ static int io_noclose (lua_State *L) {
lua_rawseti(L, 1, k); /* add it to common upvalue */ LStream *p = tolstream(L);
} p->closef = &io_noclose; /* keep file opened */
lua_pushvalue(L, 3); /* get environment for default files */ lua_pushnil(L);
lua_setuservalue(L, -2); /* set it as environment for file */ lua_pushliteral(L, "cannot close standard file");
lua_setfield(L, 2, fname); /* add file to module */ return 2;
} }
/* static void createstdfile (lua_State *L, FILE *f, const char *k,
** pushes a new table with {__close = cls} const char *fname) {
*/ LStream *p = newprefile(L);
static void newenv (lua_State *L, lua_CFunction cls) { p->f = f;
lua_createtable(L, 0, 1); p->closef = &io_noclose;
lua_pushcfunction(L, cls); if (k != NULL) {
lua_setfield(L, -2, "__close"); lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
}
lua_setfield(L, -2, fname); /* add file to module */
} }
LUAMOD_API int luaopen_io (lua_State *L) { LUAMOD_API int luaopen_io (lua_State *L) {
lua_settop(L, 0); luaL_newlib(L, iolib); /* new module */
createmeta(L); createmeta(L);
/* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
newenv(L, io_fclose); /* upvalue for all io functions at index 1 */
luaL_newlibtable(L, iolib); /* new module at index 2 */
lua_pushvalue(L, 1); /* copy of env to be consumed by 'setfuncs' */
luaL_setfuncs(L, iolib, 1);
/* create (and set) default files */ /* create (and set) default files */
newenv(L, io_noclose); /* environment for default files at index 3 */
createstdfile(L, stdin, IO_INPUT, "stdin"); createstdfile(L, stdin, IO_INPUT, "stdin");
createstdfile(L, stdout, IO_OUTPUT, "stdout"); createstdfile(L, stdout, IO_OUTPUT, "stdout");
createstdfile(L, stderr, 0, "stderr"); createstdfile(L, stderr, NULL, "stderr");
lua_pop(L, 1); /* pop environment for default files */
lua_getfield(L, 2, "popen");
newenv(L, io_pclose); /* create environment for 'popen' streams */
lua_setupvalue(L, -2, 1); /* set it as upvalue for 'popen' */
lua_pop(L, 1); /* pop 'popen' */
return 1; return 1;
} }

136
llex.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: llex.c,v 2.40 2010/10/25 12:24:36 roberto Exp roberto $ ** $Id: llex.c,v 2.58 2011/08/15 19:41:58 roberto Exp roberto $
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -35,10 +35,10 @@
/* ORDER RESERVED */ /* ORDER RESERVED */
static const char *const luaX_tokens [] = { static const char *const luaX_tokens [] = {
"and", "break", "do", "else", "elseif", "and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "if", "end", "false", "for", "function", "goto", "if",
"in", "local", "nil", "not", "or", "repeat", "in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while", "return", "then", "true", "until", "while",
"..", "...", "==", ">=", "<=", "~=", "<eof>", "..", "...", "==", ">=", "<=", "~=", "::", "<eof>",
"<number>", "<name>", "<string>" "<number>", "<name>", "<string>"
}; };
@@ -46,7 +46,7 @@ static const char *const luaX_tokens [] = {
#define save_and_next(ls) (save(ls, ls->current), next(ls)) #define save_and_next(ls) (save(ls, ls->current), next(ls))
static void lexerror (LexState *ls, const char *msg, int token); static l_noret lexerror (LexState *ls, const char *msg, int token);
static void save (LexState *ls, int c) { static void save (LexState *ls, int c) {
@@ -67,7 +67,6 @@ void luaX_init (lua_State *L) {
for (i=0; i<NUM_RESERVED; i++) { for (i=0; i<NUM_RESERVED; i++) {
TString *ts = luaS_new(L, luaX_tokens[i]); TString *ts = luaS_new(L, luaX_tokens[i]);
luaS_fix(ts); /* reserved words are never collected */ luaS_fix(ts); /* reserved words are never collected */
lua_assert(strlen(luaX_tokens[i])+1 <= TOKEN_LEN);
ts->tsv.reserved = cast_byte(i+1); /* reserved word */ ts->tsv.reserved = cast_byte(i+1); /* reserved word */
} }
} }
@@ -102,7 +101,7 @@ static const char *txtToken (LexState *ls, int token) {
} }
static void lexerror (LexState *ls, const char *msg, int token) { static l_noret lexerror (LexState *ls, const char *msg, int token) {
char buff[LUA_IDSIZE]; char buff[LUA_IDSIZE];
luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE); luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);
msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
@@ -112,7 +111,7 @@ static void lexerror (LexState *ls, const char *msg, int token) {
} }
void luaX_syntaxerror (LexState *ls, const char *msg) { l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
lexerror(ls, msg, ls->t.token); lexerror(ls, msg, ls->t.token);
} }
@@ -127,8 +126,10 @@ TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
TValue *o; /* entry for `str' */ TValue *o; /* entry for `str' */
TString *ts = luaS_newlstr(L, str, l); /* create new string */ TString *ts = luaS_newlstr(L, str, l); /* create new string */
setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
o = luaH_setstr(L, ls->fs->h, ts); o = luaH_set(L, ls->fs->h, L->top - 1);
if (ttisnil(o)) { if (ttisnil(o)) { /* not in use yet? (see 'addK') */
/* boolean value does not need GC barrier;
table has no metatable, so it does not need to invalidate cache */
setbvalue(o, 1); /* t[string] = true */ setbvalue(o, 1); /* t[string] = true */
luaC_checkGC(L); luaC_checkGC(L);
} }
@@ -152,9 +153,11 @@ static void inclinenumber (LexState *ls) {
} }
void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
int firstchar) {
ls->decpoint = '.'; ls->decpoint = '.';
ls->L = L; ls->L = L;
ls->current = firstchar;
ls->lookahead.token = TK_EOS; /* no look-ahead token */ ls->lookahead.token = TK_EOS; /* no look-ahead token */
ls->z = z; ls->z = z;
ls->fs = NULL; ls->fs = NULL;
@@ -164,7 +167,6 @@ void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) {
ls->envn = luaS_new(L, LUA_ENV); /* create env name */ ls->envn = luaS_new(L, LUA_ENV); /* create env name */
luaS_fix(ls->envn); /* never collect this name */ luaS_fix(ls->envn); /* never collect this name */
luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
next(ls); /* read first char */
} }
@@ -185,7 +187,7 @@ static int check_next (LexState *ls, const char *set) {
} }
/* /*
** change all characters 'from' in buffer to 'to' ** change all characters 'from' in buffer to 'to'
*/ */
static void buffreplace (LexState *ls, char from, char to) { static void buffreplace (LexState *ls, char from, char to) {
@@ -200,6 +202,9 @@ static void buffreplace (LexState *ls, char from, char to) {
#define getlocaledecpoint() (localeconv()->decimal_point[0]) #define getlocaledecpoint() (localeconv()->decimal_point[0])
#endif #endif
#define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)
/* /*
** in case of format error, try to change decimal point separator to ** in case of format error, try to change decimal point separator to
** the one defined in the current locale and check again ** the one defined in the current locale and check again
@@ -208,7 +213,7 @@ static void trydecpoint (LexState *ls, SemInfo *seminfo) {
char old = ls->decpoint; char old = ls->decpoint;
ls->decpoint = getlocaledecpoint(); ls->decpoint = getlocaledecpoint();
buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) { if (!buff2d(ls->buff, &seminfo->r)) {
/* format error with correct decimal point: no more options */ /* format error with correct decimal point: no more options */
buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
lexerror(ls, "malformed number", TK_NUMBER); lexerror(ls, "malformed number", TK_NUMBER);
@@ -226,7 +231,7 @@ static void read_numeral (LexState *ls, SemInfo *seminfo) {
} while (lislalnum(ls->current) || ls->current == '.'); } while (lislalnum(ls->current) || ls->current == '.');
save(ls, '\0'); save(ls, '\0');
buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */ if (!buff2d(ls->buff, &seminfo->r)) /* format error? */
trydecpoint(ls, seminfo); /* try to update decimal point separator */ trydecpoint(ls, seminfo); /* try to update decimal point separator */
} }
@@ -283,45 +288,41 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
} }
static int hexavalue (int c) { static void escerror (LexState *ls, int *c, int n, const char *msg) {
if (lisdigit(c)) return c - '0'; int i;
else if (lisupper(c)) return c - 'A' + 10; luaZ_resetbuffer(ls->buff); /* prepare error message */
else return c - 'a' + 10; save(ls, '\\');
for (i = 0; i < n && c[i] != EOZ; i++)
save(ls, c[i]);
lexerror(ls, msg, TK_STRING);
} }
static int readhexaesc (LexState *ls) { static int readhexaesc (LexState *ls) {
int c1, c2 = EOZ; int c[3], i; /* keep input for error message */
if (!lisxdigit(c1 = next(ls)) || !lisxdigit(c2 = next(ls))) { int r = 0; /* result accumulator */
luaZ_resetbuffer(ls->buff); /* prepare error message */ c[0] = 'x'; /* for error message */
save(ls, '\\'); save(ls, 'x'); for (i = 1; i < 3; i++) { /* read two hexa digits */
if (c1 != EOZ) save(ls, c1); c[i] = next(ls);
if (c2 != EOZ) save(ls, c2); if (!lisxdigit(c[i]))
lexerror(ls, "hexadecimal digit expected", TK_STRING); escerror(ls, c, i + 1, "hexadecimal digit expected");
r = (r << 4) + luaO_hexavalue(c[i]);
} }
return (hexavalue(c1) << 4) + hexavalue(c2); return r;
} }
static int readdecesc (LexState *ls) { static int readdecesc (LexState *ls) {
int c1 = ls->current, c2, c3; int c[3], i;
int c = c1 - '0'; int r = 0; /* result accumulator */
if (lisdigit(c2 = next(ls))) { for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
c = 10*c + c2 - '0'; c[i] = ls->current;
if (lisdigit(c3 = next(ls))) { r = 10*r + c[i] - '0';
c = 10*c + c3 - '0'; next(ls);
if (c > UCHAR_MAX) {
luaZ_resetbuffer(ls->buff); /* prepare error message */
save(ls, '\\');
save(ls, c1); save(ls, c2); save(ls, c3);
lexerror(ls, "decimal escape too large", TK_STRING);
}
return c;
}
} }
/* else, has read one character that was not a digit */ if (r > UCHAR_MAX)
zungetc(ls->z); /* return it to input stream */ escerror(ls, c, i, "decimal escape too large");
return c; return r;
} }
@@ -340,36 +341,38 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) {
int c; /* final character to be saved */ int c; /* final character to be saved */
next(ls); /* do not save the `\' */ next(ls); /* do not save the `\' */
switch (ls->current) { switch (ls->current) {
case 'a': c = '\a'; break; case 'a': c = '\a'; goto read_save;
case 'b': c = '\b'; break; case 'b': c = '\b'; goto read_save;
case 'f': c = '\f'; break; case 'f': c = '\f'; goto read_save;
case 'n': c = '\n'; break; case 'n': c = '\n'; goto read_save;
case 'r': c = '\r'; break; case 'r': c = '\r'; goto read_save;
case 't': c = '\t'; break; case 't': c = '\t'; goto read_save;
case 'v': c = '\v'; break; case 'v': c = '\v'; goto read_save;
case 'x': c = readhexaesc(ls); break; case 'x': c = readhexaesc(ls); goto read_save;
case '\n': case '\n': case '\r':
case '\r': save(ls, '\n'); inclinenumber(ls); continue; inclinenumber(ls); c = '\n'; goto only_save;
case EOZ: continue; /* will raise an error next loop */ case '\\': case '\"': case '\'':
case '*': { /* skip following span of spaces */ c = ls->current; goto read_save;
next(ls); /* skip the '*' */ case EOZ: goto no_save; /* will raise an error next loop */
case 'z': { /* zap following span of spaces */
next(ls); /* skip the 'z' */
while (lisspace(ls->current)) { while (lisspace(ls->current)) {
if (currIsNewline(ls)) inclinenumber(ls); if (currIsNewline(ls)) inclinenumber(ls);
else next(ls); else next(ls);
} }
continue; /* do not save 'c' */ goto no_save;
} }
default: { default: {
if (!lisdigit(ls->current)) if (!lisdigit(ls->current))
c = ls->current; /* handles \\, \", \', and \? */ escerror(ls, &ls->current, 1, "invalid escape sequence");
else /* digital escape \ddd */ /* digital escape \ddd */
c = readdecesc(ls); c = readdecesc(ls);
break; goto only_save;
} }
} }
next(ls); read_save: next(ls); /* read next character */
save(ls, c); only_save: save(ls, c); /* save 'c' */
break; no_save: break;
} }
default: default:
save_and_next(ls); save_and_next(ls);
@@ -441,6 +444,11 @@ static int llex (LexState *ls, SemInfo *seminfo) {
if (ls->current != '=') return '~'; if (ls->current != '=') return '~';
else { next(ls); return TK_NE; } else { next(ls); return TK_NE; }
} }
case ':': {
next(ls);
if (ls->current != ':') return ':';
else { next(ls); return TK_DBCOLON; }
}
case '"': case '\'': { /* short literal strings */ case '"': case '\'': { /* short literal strings */
read_string(ls, ls->current, seminfo); read_string(ls, ls->current, seminfo);
return TK_STRING; return TK_STRING;

18
llex.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: llex.h,v 1.64 2010/03/13 15:55:42 roberto Exp roberto $ ** $Id: llex.h,v 1.71 2011/06/20 16:52:48 roberto Exp roberto $
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -13,8 +13,6 @@
#define FIRST_RESERVED 257 #define FIRST_RESERVED 257
/* maximum length of a reserved word */
#define TOKEN_LEN (sizeof("function")/sizeof(char))
/* /*
@@ -25,10 +23,10 @@ enum RESERVED {
/* terminal symbols denoted by reserved words */ /* terminal symbols denoted by reserved words */
TK_AND = FIRST_RESERVED, TK_BREAK, TK_AND = FIRST_RESERVED, TK_BREAK,
TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
/* other terminal symbols */ /* other terminal symbols */
TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_EOS, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_DBCOLON, TK_EOS,
TK_NUMBER, TK_NAME, TK_STRING TK_NUMBER, TK_NAME, TK_STRING
}; };
@@ -48,17 +46,19 @@ typedef struct Token {
} Token; } Token;
/* state of the lexer plus state of the parser when shared by all
functions */
typedef struct LexState { typedef struct LexState {
int current; /* current character (charint) */ int current; /* current character (charint) */
int linenumber; /* input line counter */ int linenumber; /* input line counter */
int lastline; /* line of last token `consumed' */ int lastline; /* line of last token `consumed' */
Token t; /* current token */ Token t; /* current token */
Token lookahead; /* look ahead token */ Token lookahead; /* look ahead token */
struct FuncState *fs; /* `FuncState' is private to the parser */ struct FuncState *fs; /* current function (parser) */
struct lua_State *L; struct lua_State *L;
ZIO *z; /* input stream */ ZIO *z; /* input stream */
Mbuffer *buff; /* buffer for tokens */ Mbuffer *buff; /* buffer for tokens */
struct Varlist *varl; /* list of all active local variables */ struct Dyndata *dyd; /* dynamic structures used by the parser */
TString *source; /* current source name */ TString *source; /* current source name */
TString *envn; /* environment variable name */ TString *envn; /* environment variable name */
char decpoint; /* locale decimal point */ char decpoint; /* locale decimal point */
@@ -67,11 +67,11 @@ typedef struct LexState {
LUAI_FUNC void luaX_init (lua_State *L); LUAI_FUNC void luaX_init (lua_State *L);
LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
TString *source); TString *source, int firstchar);
LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
LUAI_FUNC void luaX_next (LexState *ls); LUAI_FUNC void luaX_next (LexState *ls);
LUAI_FUNC int luaX_lookahead (LexState *ls); LUAI_FUNC int luaX_lookahead (LexState *ls);
LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s); LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s);
LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: llimits.h,v 1.83 2010/11/03 15:16:17 roberto Exp roberto $ ** $Id: llimits.h,v 1.94 2011/11/29 15:39:48 roberto Exp roberto $
** Limits, basic types, and some other `installation-dependent' definitions ** Limits, basic types, and some other `installation-dependent' definitions
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -30,7 +30,6 @@ typedef unsigned char lu_byte;
#define MAX_SIZET ((size_t)(~(size_t)0)-2) #define MAX_SIZET ((size_t)(~(size_t)0)-2)
#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) #define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)
#define MIN_LMEM ((l_mem)~((~(lu_mem)0)>>1))
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ #define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
@@ -59,21 +58,28 @@ typedef LUAI_UACNUMBER l_uacNumber;
/* internal assertions for in-house debugging */ /* internal assertions for in-house debugging */
#if defined(lua_assert) #if defined(lua_assert)
#define check_exp(c,e) (lua_assert(c), (e)) #define check_exp(c,e) (lua_assert(c), (e))
/* to avoid problems with conditions too long */
#define lua_longassert(c) { if (!(c)) lua_assert(0); }
#else #else
#define lua_assert(c) /* empty */ #define lua_assert(c) ((void)0)
#define check_exp(c,e) (e) #define check_exp(c,e) (e)
#define lua_longassert(c) ((void)0)
#endif #endif
/* /*
** assertion for checking API calls ** assertion for checking API calls
*/ */
#if !defined(luai_apicheck)
#if defined(LUA_USE_APICHECK) #if defined(LUA_USE_APICHECK)
#include <assert.h> #include <assert.h>
#define luai_apicheck(L,e) { (void)L; assert(e); } #define luai_apicheck(L,e) assert(e)
#elif !defined(luai_apicheck) #else
#define luai_apicheck(L,e) lua_assert(e) #define luai_apicheck(L,e) lua_assert(e)
#endif #endif
#endif
#define api_check(l,e,msg) luai_apicheck(l,(e) && msg) #define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
@@ -87,6 +93,20 @@ typedef LUAI_UACNUMBER l_uacNumber;
#define cast_byte(i) cast(lu_byte, (i)) #define cast_byte(i) cast(lu_byte, (i))
#define cast_num(i) cast(lua_Number, (i)) #define cast_num(i) cast(lua_Number, (i))
#define cast_int(i) cast(int, (i)) #define cast_int(i) cast(int, (i))
#define cast_uchar(i) cast(unsigned char, (i))
/*
** non-return type
*/
#if defined(__GNUC__)
#define l_noret void __attribute__((noreturn))
#elif defined(_MSC_VER)
#define l_noret void __declspec(noreturn)
#else
#define l_noret void
#endif
/* /*
@@ -173,6 +193,9 @@ typedef lu_int32 Instruction;
** lua_number2integer is a macro to convert lua_Number to lua_Integer. ** lua_number2integer is a macro to convert lua_Number to lua_Integer.
** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned. ** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned.
** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number. ** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number.
** luai_hashnum is a macro to hash a lua_Number value into an integer.
** The hash must be deterministic and give reasonable values for
** both small and large values (outside the range of integers).
*/ */
#if defined(MS_ASMTRICK) /* { */ #if defined(MS_ASMTRICK) /* { */
@@ -203,6 +226,10 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; };
volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; \ volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; \
(i) = (t)u.l_p[LUA_IEEEENDIAN]; } (i) = (t)u.l_p[LUA_IEEEENDIAN]; }
#define luai_hashnum(i,n) \
{ volatile union luai_Cast u; u.l_d = (n) + 1.0; /* avoid -0 */ \
(i) = u.l_p[0]; (i) += u.l_p[1]; } /* add double bits for his hash */
#define lua_number2int(i,n) lua_number2int32(i, n, int) #define lua_number2int(i,n) lua_number2int32(i, n, int)
#define lua_number2integer(i,n) lua_number2int32(i, n, lua_Integer) #define lua_number2integer(i,n) lua_number2int32(i, n, lua_Integer)
#define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned) #define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned)
@@ -241,14 +268,8 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; };
#endif #endif
/*
** luai_hashnum is a macro do hash a lua_Number value into an integer.
** The hash must be deterministic and give reasonable values for
** both small and large values (outside the range of integers).
** It is used only in ltable.c.
*/
#if !defined(luai_hashnum) /* { */ #if defined(ltable_c) && !defined(luai_hashnum)
#include <float.h> #include <float.h>
#include <math.h> #include <math.h>
@@ -257,7 +278,7 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; };
n = frexp(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \ n = frexp(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \
lua_number2int(i, n); i += e; } lua_number2int(i, n); i += e; }
#endif /* } */ #endif
@@ -275,7 +296,7 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; };
#define condchangemem(L) condmovestack(L) #define condchangemem(L) condmovestack(L)
#else #else
#define condchangemem(L) \ #define condchangemem(L) \
((void)(gcstopped(G(L)) || (luaC_fullgc(L, 0), 1))) ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1)))
#endif #endif
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lmathlib.c,v 1.78 2010/11/12 15:47:34 roberto Exp roberto $ ** $Id: lmathlib.c,v 1.79 2010/11/18 18:38:27 roberto Exp roberto $
** Standard mathematical library ** Standard mathematical library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -134,15 +134,12 @@ static int math_log (lua_State *L) {
return 1; return 1;
} }
#if defined(LUA_COMPAT_LOG10)
static int math_log10 (lua_State *L) { static int math_log10 (lua_State *L) {
#if !defined(LUA_COMPAT_LOG10)
return luaL_error(L, "function " LUA_QL("log10")
" is deprecated; use log(x, 10) instead");
#else
lua_pushnumber(L, l_tg(log10)(luaL_checknumber(L, 1))); lua_pushnumber(L, l_tg(log10)(luaL_checknumber(L, 1)));
return 1; return 1;
#endif
} }
#endif
static int math_exp (lua_State *L) { static int math_exp (lua_State *L) {
lua_pushnumber(L, l_tg(exp)(luaL_checknumber(L, 1))); lua_pushnumber(L, l_tg(exp)(luaL_checknumber(L, 1)));
@@ -252,7 +249,9 @@ static const luaL_Reg mathlib[] = {
{"fmod", math_fmod}, {"fmod", math_fmod},
{"frexp", math_frexp}, {"frexp", math_frexp},
{"ldexp", math_ldexp}, {"ldexp", math_ldexp},
#if defined(LUA_COMPAT_LOG10)
{"log10", math_log10}, {"log10", math_log10},
#endif
{"log", math_log}, {"log", math_log},
{"max", math_max}, {"max", math_max},
{"min", math_min}, {"min", math_min},

17
lmem.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lmem.c,v 1.78 2010/05/04 18:10:02 roberto Exp roberto $ ** $Id: lmem.c,v 1.82 2011/09/20 19:25:23 roberto Exp roberto $
** Interface to Memory Manager ** Interface to Memory Manager
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -63,9 +63,8 @@ void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
} }
void *luaM_toobig (lua_State *L) { l_noret luaM_toobig (lua_State *L) {
luaG_runerror(L, "memory allocation error: block too big"); luaG_runerror(L, "memory allocation error: block too big");
return NULL; /* to avoid warnings */
} }
@@ -79,14 +78,14 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
size_t realosize = (block) ? osize : 0; size_t realosize = (block) ? osize : 0;
lua_assert((realosize == 0) == (block == NULL)); lua_assert((realosize == 0) == (block == NULL));
#if defined(HARDMEMTESTS) #if defined(HARDMEMTESTS)
if (nsize > realosize && !gcstopped(g)) if (nsize > realosize && g->gcrunning)
luaC_fullgc(L, 1); /* force a GC whenever possible */ luaC_fullgc(L, 1); /* force a GC whenever possible */
#endif #endif
newblock = (*g->frealloc)(g->ud, block, osize, nsize); newblock = (*g->frealloc)(g->ud, block, osize, nsize);
if (newblock == NULL && nsize > 0) { if (newblock == NULL && nsize > 0) {
api_check(L, nsize > realosize, api_check(L, nsize > realosize,
"realloc cannot fail when shrinking a block"); "realloc cannot fail when shrinking a block");
if (!gcstopped(g)) { if (g->gcrunning) {
luaC_fullgc(L, 1); /* try to free some memory... */ luaC_fullgc(L, 1); /* try to free some memory... */
newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
} }
@@ -94,9 +93,7 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
luaD_throw(L, LUA_ERRMEM); luaD_throw(L, LUA_ERRMEM);
} }
lua_assert((nsize == 0) == (newblock == NULL)); lua_assert((nsize == 0) == (newblock == NULL));
g->totalbytes = (g->totalbytes - realosize) + nsize; g->GCdebt = (g->GCdebt + nsize) - realosize;
if (!gcstopped(g))
g->GCdebt += nsize; /* give some credit to garbage collector */
#if defined(TRACEMEM) #if defined(TRACEMEM)
{ /* auxiliary patch to monitor garbage collection. { /* auxiliary patch to monitor garbage collection.
** To plot, gnuplot with following command: ** To plot, gnuplot with following command:
@@ -108,9 +105,7 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
if ((total % 200) == 0) { if ((total % 200) == 0) {
if (f == NULL) f = fopen(TRACEMEM, "w"); if (f == NULL) f = fopen(TRACEMEM, "w");
fprintf(f, "%lu %u %d %d\n", total, fprintf(f, "%lu %u %d %d\n", total,
g->totalbytes, gettotalbytes(g), g->GCdebt, g->gcstate * 10000);
gcstopped(g) ? 0 : g->GCdebt,
g->gcstate * 1000);
} }
} }
#endif #endif

10
lmem.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lmem.h,v 1.35 2009/12/16 16:42:58 roberto Exp roberto $ ** $Id: lmem.h,v 1.37 2011/11/30 12:42:49 roberto Exp roberto $
** Interface to Memory Manager ** Interface to Memory Manager
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -15,9 +15,9 @@
#define luaM_reallocv(L,b,on,n,e) \ #define luaM_reallocv(L,b,on,n,e) \
((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \ ((cast(size_t, (n)+1) > MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \
luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \ (luaM_toobig(L), (void *)0) : \
luaM_toobig(L)) luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) #define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) #define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
@@ -37,7 +37,7 @@
#define luaM_reallocvector(L, v,oldn,n,t) \ #define luaM_reallocvector(L, v,oldn,n,t) \
((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
LUAI_FUNC void *luaM_toobig (lua_State *L); LUAI_FUNC l_noret luaM_toobig (lua_State *L);
/* not to be called directly */ /* not to be called directly */
LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,

237
loadlib.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: loadlib.c,v 1.93 2010/11/10 18:05:36 roberto Exp roberto $ ** $Id: loadlib.c,v 1.107 2011/11/30 12:58:57 roberto Exp roberto $
** Dynamic library loader for Lua ** Dynamic library loader for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
** **
@@ -9,6 +9,14 @@
*/ */
/*
** if needed, includes windows header before everything else
*/
#if defined(_WIN32)
#include <windows.h>
#endif
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -62,6 +70,20 @@
#endif #endif
/*
** LUA_CSUBSEP is the character that replaces dots in submodule names
** when searching for a C loader.
** LUA_LSUBSEP is the character that replaces dots in submodule names
** when searching for a Lua loader.
*/
#if !defined(LUA_CSUBSEP)
#define LUA_CSUBSEP LUA_DIRSEP
#endif
#if !defined(LUA_LSUBSEP)
#define LUA_LSUBSEP LUA_DIRSEP
#endif
/* prefix for open functions in C libraries */ /* prefix for open functions in C libraries */
#define LUA_POF "luaopen_" #define LUA_POF "luaopen_"
@@ -110,7 +132,7 @@ static void ll_unloadlib (void *lib) {
static void *ll_load (lua_State *L, const char *path, int seeglb) { static void *ll_load (lua_State *L, const char *path, int seeglb) {
void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : 0)); void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
if (lib == NULL) lua_pushstring(L, dlerror()); if (lib == NULL) lua_pushstring(L, dlerror());
return lib; return lib;
} }
@@ -133,8 +155,6 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
** ======================================================================= ** =======================================================================
*/ */
#include <windows.h>
#undef setprogdir #undef setprogdir
/* /*
@@ -164,7 +184,7 @@ static void pusherror (lua_State *L) {
int error = GetLastError(); int error = GetLastError();
char buffer[128]; char buffer[128];
if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error, 0, buffer, sizeof(buffer), NULL)) NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
lua_pushstring(L, buffer); lua_pushstring(L, buffer);
else else
lua_pushfstring(L, "system error %d\n", error); lua_pushfstring(L, "system error %d\n", error);
@@ -177,7 +197,7 @@ static void ll_unloadlib (void *lib) {
static void *ll_load (lua_State *L, const char *path, int seeglb) { static void *ll_load (lua_State *L, const char *path, int seeglb) {
HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
(void)(seeglb); /* symbols are 'global' by default */ (void)(seeglb); /* not used: symbols are 'global' by default */
if (lib == NULL) pusherror(L); if (lib == NULL) pusherror(L);
return lib; return lib;
} }
@@ -207,19 +227,19 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
static void ll_unloadlib (void *lib) { static void ll_unloadlib (void *lib) {
(void)(lib); /* to avoid warnings */ (void)(lib); /* not used */
} }
static void *ll_load (lua_State *L, const char *path, int seeglb) { static void *ll_load (lua_State *L, const char *path, int seeglb) {
(void)(path); (void)(seeglb); /* to avoid warnings */ (void)(path); (void)(seeglb); /* not used */
lua_pushliteral(L, DLMSG); lua_pushliteral(L, DLMSG);
return NULL; return NULL;
} }
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
(void)(lib); (void)(sym); /* to avoid warnings */ (void)(lib); (void)(sym); /* not used */
lua_pushliteral(L, DLMSG); lua_pushliteral(L, DLMSG);
return NULL; return NULL;
} }
@@ -321,9 +341,13 @@ static const char *pushnexttemplate (lua_State *L, const char *path) {
static const char *searchpath (lua_State *L, const char *name, static const char *searchpath (lua_State *L, const char *name,
const char *path) { const char *path,
name = luaL_gsub(L, name, ".", LUA_DIRSEP); const char *sep,
lua_pushliteral(L, ""); /* error accumulator */ const char *dirsep) {
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
if (*sep != '\0') /* non-empty separator? */
name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
while ((path = pushnexttemplate(L, path)) != NULL) { while ((path = pushnexttemplate(L, path)) != NULL) {
const char *filename = luaL_gsub(L, lua_tostring(L, -1), const char *filename = luaL_gsub(L, lua_tostring(L, -1),
LUA_PATH_MARK, name); LUA_PATH_MARK, name);
@@ -332,14 +356,18 @@ static const char *searchpath (lua_State *L, const char *name,
return filename; /* return that file name */ return filename; /* return that file name */
lua_pushfstring(L, "\n\tno file " LUA_QS, filename); lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
lua_remove(L, -2); /* remove file name */ lua_remove(L, -2); /* remove file name */
lua_concat(L, 2); /* add entry to possible error message */ luaL_addvalue(&msg); /* concatenate error msg. entry */
} }
luaL_pushresult(&msg); /* create error message */
return NULL; /* not found */ return NULL; /* not found */
} }
static int ll_searchpath (lua_State *L) { static int ll_searchpath (lua_State *L) {
const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2)); const char *f = searchpath(L, luaL_checkstring(L, 1),
luaL_checkstring(L, 2),
luaL_optstring(L, 3, "."),
luaL_optstring(L, 4, LUA_DIRSEP));
if (f != NULL) return 1; if (f != NULL) return 1;
else { /* error message is on top of the stack */ else { /* error message is on top of the stack */
lua_pushnil(L); lua_pushnil(L);
@@ -350,30 +378,35 @@ static int ll_searchpath (lua_State *L) {
static const char *findfile (lua_State *L, const char *name, static const char *findfile (lua_State *L, const char *name,
const char *pname) { const char *pname,
const char *dirsep) {
const char *path; const char *path;
lua_getfield(L, lua_upvalueindex(1), pname); lua_getfield(L, lua_upvalueindex(1), pname);
path = lua_tostring(L, -1); path = lua_tostring(L, -1);
if (path == NULL) if (path == NULL)
luaL_error(L, LUA_QL("package.%s") " must be a string", pname); luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
return searchpath(L, name, path); return searchpath(L, name, path, ".", dirsep);
} }
static void loaderror (lua_State *L, const char *filename) { static int checkload (lua_State *L, int stat, const char *filename) {
luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", if (stat) { /* module loaded successfully? */
lua_tostring(L, 1), filename, lua_tostring(L, -1)); lua_pushstring(L, filename); /* will be 2nd argument to module */
return 2; /* return open function and file name */
}
else
return luaL_error(L, "error loading module " LUA_QS
" from file " LUA_QS ":\n\t%s",
lua_tostring(L, 1), filename, lua_tostring(L, -1));
} }
static int loader_Lua (lua_State *L) { static int searcher_Lua (lua_State *L) {
const char *filename; const char *filename;
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
filename = findfile(L, name, "path"); filename = findfile(L, name, "path", LUA_LSUBSEP);
if (filename == NULL) return 1; /* library not found in this path */ if (filename == NULL) return 1; /* module not found in this path */
if (luaL_loadfile(L, filename) != LUA_OK) return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
loaderror(L, filename);
return 1; /* library loaded successfully */
} }
@@ -395,36 +428,38 @@ static int loadfunc (lua_State *L, const char *filename, const char *modname) {
} }
static int loader_C (lua_State *L) { static int searcher_C (lua_State *L) {
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
const char *filename = findfile(L, name, "cpath"); const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
if (filename == NULL) return 1; /* library not found in this path */ if (filename == NULL) return 1; /* module not found in this path */
if (loadfunc(L, filename, name) != 0) return checkload(L, (loadfunc(L, filename, name) == 0), filename);
loaderror(L, filename);
return 1; /* library loaded successfully */
} }
static int loader_Croot (lua_State *L) { static int searcher_Croot (lua_State *L) {
const char *filename; const char *filename;
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
const char *p = strchr(name, '.'); const char *p = strchr(name, '.');
int stat; int stat;
if (p == NULL) return 0; /* is root */ if (p == NULL) return 0; /* is root */
lua_pushlstring(L, name, p - name); lua_pushlstring(L, name, p - name);
filename = findfile(L, lua_tostring(L, -1), "cpath"); filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
if (filename == NULL) return 1; /* root not found */ if (filename == NULL) return 1; /* root not found */
if ((stat = loadfunc(L, filename, name)) != 0) { if ((stat = loadfunc(L, filename, name)) != 0) {
if (stat != ERRFUNC) loaderror(L, filename); /* real error */ if (stat != ERRFUNC)
lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, return checkload(L, 0, filename); /* real error */
name, filename); else { /* open function not found */
return 1; /* function not found */ lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
name, filename);
return 1;
}
} }
return 1; lua_pushstring(L, filename); /* will be 2nd argument to module */
return 2;
} }
static int loader_preload (lua_State *L) { static int searcher_preload (lua_State *L) {
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD"); lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_getfield(L, -1, name); lua_getfield(L, -1, name);
@@ -434,35 +469,49 @@ static int loader_preload (lua_State *L) {
} }
static void findloader (lua_State *L, const char *name) {
int i;
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */
if (!lua_istable(L, 3))
luaL_error(L, LUA_QL("package.searchers") " must be a table");
/* iterate over available seachers to find a loader */
for (i = 1; ; i++) {
lua_rawgeti(L, 3, i); /* get a seacher */
if (lua_isnil(L, -1)) { /* no more searchers? */
lua_pop(L, 1); /* remove nil */
luaL_pushresult(&msg); /* create error message */
luaL_error(L, "module " LUA_QS " not found:%s",
name, lua_tostring(L, -1));
}
lua_pushstring(L, name);
lua_call(L, 1, 2); /* call it */
if (lua_isfunction(L, -2)) /* did it find a loader? */
return; /* module loader found */
else if (lua_isstring(L, -2)) { /* searcher returned error message? */
lua_pop(L, 1); /* remove extra return */
luaL_addvalue(&msg); /* concatenate error message */
}
else
lua_pop(L, 2); /* remove both returns */
}
}
static int ll_require (lua_State *L) { static int ll_require (lua_State *L) {
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
int i;
lua_settop(L, 1); /* _LOADED table will be at index 2 */ lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, name); lua_getfield(L, 2, name); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */ if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */ return 1; /* package is already loaded */
/* else must load it; iterate over available loaders */ /* else must load package */
lua_getfield(L, lua_upvalueindex(1), "loaders"); lua_pop(L, 1); /* remove 'getfield' result */
if (!lua_istable(L, -1)) findloader(L, name);
luaL_error(L, LUA_QL("package.loaders") " must be a table"); lua_pushstring(L, name); /* pass name as argument to module loader */
lua_pushliteral(L, ""); /* error message accumulator */ lua_insert(L, -2); /* name is 1st argument (before search data) */
for (i=1; ; i++) { lua_call(L, 2, 1); /* run loader to load module */
lua_rawgeti(L, -2, i); /* get a loader */
if (lua_isnil(L, -1))
luaL_error(L, "module " LUA_QS " not found:%s",
name, lua_tostring(L, -2));
lua_pushstring(L, name);
lua_call(L, 1, 1); /* call it */
if (lua_isfunction(L, -1)) /* did it find module? */
break; /* module loaded successfully */
else if (lua_isstring(L, -1)) /* loader returned error message? */
lua_concat(L, 2); /* accumulate it */
else
lua_pop(L, 1);
}
lua_pushstring(L, name); /* pass name as argument to module */
lua_call(L, 1, 1); /* run loaded module */
if (!lua_isnil(L, -1)) /* non-nil return? */ if (!lua_isnil(L, -1)) /* non-nil return? */
lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
lua_getfield(L, 2, name); lua_getfield(L, 2, name);
@@ -503,9 +552,11 @@ static void set_env (lua_State *L) {
static void dooptions (lua_State *L, int n) { static void dooptions (lua_State *L, int n) {
int i; int i;
for (i = 2; i <= n; i++) { for (i = 2; i <= n; i++) {
lua_pushvalue(L, i); /* get option (a function) */ if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */
lua_pushvalue(L, -2); /* module */ lua_pushvalue(L, i); /* get option (a function) */
lua_call(L, 1, 0); lua_pushvalue(L, -2); /* module */
lua_call(L, 1, 0);
}
} }
} }
@@ -556,17 +607,6 @@ static int ll_seeall (lua_State *L) {
return 0; return 0;
} }
#else
static int ll_seeall (lua_State *L) {
return luaL_error(L, "deprecated function");
}
static int ll_module (lua_State *L) {
return luaL_error(L, "deprecated function");
}
#endif #endif
/* }====================================================== */ /* }====================================================== */
@@ -575,12 +615,25 @@ static int ll_module (lua_State *L) {
/* auxiliary mark (for internal use) */ /* auxiliary mark (for internal use) */
#define AUXMARK "\1" #define AUXMARK "\1"
/*
** return registry.LUA_NOENV as a boolean
*/
static int noenv (lua_State *L) {
int b;
lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
b = lua_toboolean(L, -1);
lua_pop(L, 1); /* remove value */
return b;
}
static void setpath (lua_State *L, const char *fieldname, const char *envname1, static void setpath (lua_State *L, const char *fieldname, const char *envname1,
const char *envname2, const char *def) { const char *envname2, const char *def) {
const char *path = getenv(envname1); const char *path = getenv(envname1);
if (path == NULL) /* no environment variable? */ if (path == NULL) /* no environment variable? */
path = getenv(envname2); /* try alternative name */ path = getenv(envname2); /* try alternative name */
if (path == NULL) /* no environment variable? */ if (path == NULL || noenv(L)) /* no environment variable? */
lua_pushstring(L, def); /* use default */ lua_pushstring(L, def); /* use default */
else { else {
/* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
@@ -597,20 +650,24 @@ static void setpath (lua_State *L, const char *fieldname, const char *envname1,
static const luaL_Reg pk_funcs[] = { static const luaL_Reg pk_funcs[] = {
{"loadlib", ll_loadlib}, {"loadlib", ll_loadlib},
{"searchpath", ll_searchpath}, {"searchpath", ll_searchpath},
#if defined(LUA_COMPAT_MODULE)
{"seeall", ll_seeall}, {"seeall", ll_seeall},
#endif
{NULL, NULL} {NULL, NULL}
}; };
static const luaL_Reg ll_funcs[] = { static const luaL_Reg ll_funcs[] = {
#if defined(LUA_COMPAT_MODULE)
{"module", ll_module}, {"module", ll_module},
#endif
{"require", ll_require}, {"require", ll_require},
{NULL, NULL} {NULL, NULL}
}; };
static const lua_CFunction loaders[] = static const lua_CFunction searchers[] =
{loader_preload, loader_Lua, loader_C, loader_Croot, NULL}; {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL};
LUAMOD_API int luaopen_package (lua_State *L) { LUAMOD_API int luaopen_package (lua_State *L) {
@@ -621,15 +678,19 @@ LUAMOD_API int luaopen_package (lua_State *L) {
lua_setfield(L, -2, "__gc"); lua_setfield(L, -2, "__gc");
/* create `package' table */ /* create `package' table */
luaL_newlib(L, pk_funcs); luaL_newlib(L, pk_funcs);
/* create `loaders' table */ /* create 'searchers' table */
lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0); lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
/* fill it with pre-defined loaders */ /* fill it with pre-defined searchers */
for (i=0; loaders[i] != NULL; i++) { for (i=0; searchers[i] != NULL; i++) {
lua_pushvalue(L, -2); /* set 'package' as upvalue for all loaders */ lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
lua_pushcclosure(L, loaders[i], 1); lua_pushcclosure(L, searchers[i], 1);
lua_rawseti(L, -2, i+1); lua_rawseti(L, -2, i+1);
} }
lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */ #if defined(LUA_COMPAT_LOADERS)
lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */
#endif
lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
/* set field 'path' */ /* set field 'path' */
setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT); setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT);
/* set field 'cpath' */ /* set field 'cpath' */
@@ -639,10 +700,10 @@ LUAMOD_API int luaopen_package (lua_State *L) {
LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
lua_setfield(L, -2, "config"); lua_setfield(L, -2, "config");
/* set field `loaded' */ /* set field `loaded' */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED"); luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_setfield(L, -2, "loaded"); lua_setfield(L, -2, "loaded");
/* set field `preload' */ /* set field `preload' */
luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_setfield(L, -2, "preload"); lua_setfield(L, -2, "preload");
lua_pushglobaltable(L); lua_pushglobaltable(L);
lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */

128
lobject.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lobject.c,v 2.42 2010/10/29 11:13:14 roberto Exp roberto $ ** $Id: lobject.c,v 2.54 2011/11/30 12:44:26 roberto Exp roberto $
** Some generic functions over Lua objects ** Some generic functions over Lua objects
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -33,7 +33,7 @@ LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
** eeeee != 0 and (xxx) otherwise. ** eeeee != 0 and (xxx) otherwise.
*/ */
int luaO_int2fb (lu_int32 x) { int luaO_int2fb (unsigned int x) {
int e = 0; /* exponent */ int e = 0; /* exponent */
if (x < 8) return x; if (x < 8) return x;
while (x >= 0x10) { while (x >= 0x10) {
@@ -70,28 +70,6 @@ int luaO_ceillog2 (unsigned int x) {
} }
int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
if (ttype(t1) != ttype(t2)) return 0;
else switch (ttype(t1)) {
case LUA_TNIL:
return 1;
case LUA_TNUMBER:
return luai_numeq(nvalue(t1), nvalue(t2));
case LUA_TBOOLEAN:
return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
case LUA_TLIGHTUSERDATA:
return pvalue(t1) == pvalue(t2);
case LUA_TSTRING:
return rawtsvalue(t1) == rawtsvalue(t2);
case LUA_TLCF:
return fvalue(t1) == fvalue(t2);
default:
lua_assert(iscollectable(t1));
return gcvalue(t1) == gcvalue(t2);
}
}
lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) { lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
switch (op) { switch (op) {
case LUA_OPADD: return luai_numadd(NULL, v1, v2); case LUA_OPADD: return luai_numadd(NULL, v1, v2);
@@ -106,19 +84,88 @@ lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
} }
static int checkend (const char *s, const char *endptr) { int luaO_hexavalue (int c) {
if (endptr == s) return 0; /* no characters converted */ if (lisdigit(c)) return c - '0';
while (lisspace(cast(unsigned char, *endptr))) endptr++; else return ltolower(c) - 'a' + 10;
return (*endptr == '\0'); /* OK if no trailing characters */
} }
int luaO_str2d (const char *s, lua_Number *result) { #if !defined(lua_strx2number)
#include <math.h>
static int isneg (const char **s) {
if (**s == '-') { (*s)++; return 1; }
else if (**s == '+') (*s)++;
return 0;
}
static lua_Number readhexa (const char **s, lua_Number r, int *count) {
for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */
r = (r * 16.0) + cast_num(luaO_hexavalue(cast_uchar(**s)));
(*count)++;
}
return r;
}
/*
** convert an hexadecimal numeric string to a number, following
** C99 specification for 'strtod'
*/
static lua_Number lua_strx2number (const char *s, char **endptr) {
lua_Number r = 0.0;
int e = 0, i = 0;
int neg = 0; /* 1 if number is negative */
*endptr = cast(char *, s); /* nothing is valid yet */
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
neg = isneg(&s); /* check signal */
if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
return 0.0; /* invalid format (no '0x') */
s += 2; /* skip '0x' */
r = readhexa(&s, r, &i); /* read integer part */
if (*s == '.') {
s++; /* skip dot */
r = readhexa(&s, r, &e); /* read fractional part */
}
if (i == 0 && e == 0)
return 0.0; /* invalid format (no digit) */
e *= -4; /* each fractional digit divides value by 2^-4 */
*endptr = cast(char *, s); /* valid up to here */
if (*s == 'p' || *s == 'P') { /* exponent part? */
int exp1 = 0;
int neg1;
s++; /* skip 'p' */
neg1 = isneg(&s); /* signal */
if (!lisdigit(cast_uchar(*s)))
goto ret; /* must have at least one digit */
while (lisdigit(cast_uchar(*s))) /* read exponent */
exp1 = exp1 * 10 + *(s++) - '0';
if (neg1) exp1 = -exp1;
e += exp1;
}
*endptr = cast(char *, s); /* valid up to here */
ret:
if (neg) r = -r;
return ldexp(r, e);
}
#endif
int luaO_str2d (const char *s, size_t len, lua_Number *result) {
char *endptr; char *endptr;
*result = lua_str2number(s, &endptr); if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */
if (checkend(s, endptr)) return 1; /* conversion OK? */ return 0;
*result = cast_num(strtoul(s, &endptr, 0)); /* try hexadecimal */ else if (strpbrk(s, "xX")) /* hexa? */
return checkend(s, endptr); *result = lua_strx2number(s, &endptr);
else
*result = lua_str2number(s, &endptr);
if (endptr == s) return 0; /* nothing recognized */
while (lisspace(cast_uchar(*endptr))) endptr++;
return (endptr == s + len); /* OK if no trailing characters */
} }
@@ -174,7 +221,6 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
luaG_runerror(L, luaG_runerror(L,
"invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"), "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
*(e + 1)); *(e + 1));
break;
} }
} }
n += 2; n += 2;
@@ -196,19 +242,20 @@ const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
} }
/* number of chars of a literal string without the ending \0 */
#define LL(x) (sizeof(x)/sizeof(char) - 1)
#define LL(x) (sizeof(x) - 1)
#define RETS "..." #define RETS "..."
#define PRE "[string \"" #define PRE "[string \""
#define POS "\"]" #define POS "\"]"
#define addstr(a,b,l) ( memcpy(a,b,l), a += (l) ) #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
void luaO_chunkid (char *out, const char *source, size_t bufflen) { void luaO_chunkid (char *out, const char *source, size_t bufflen) {
size_t l = strlen(source); size_t l = strlen(source);
if (*source == '=') { /* 'literal' source */ if (*source == '=') { /* 'literal' source */
if (l <= bufflen) /* small enough? */ if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l); memcpy(out, source + 1, l * sizeof(char));
else { /* truncate it */ else { /* truncate it */
addstr(out, source + 1, bufflen - 1); addstr(out, source + 1, bufflen - 1);
*out = '\0'; *out = '\0';
@@ -216,11 +263,11 @@ void luaO_chunkid (char *out, const char *source, size_t bufflen) {
} }
else if (*source == '@') { /* file name */ else if (*source == '@') { /* file name */
if (l <= bufflen) /* small enough? */ if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l); memcpy(out, source + 1, l * sizeof(char));
else { /* add '...' before rest of name */ else { /* add '...' before rest of name */
addstr(out, RETS, LL(RETS)); addstr(out, RETS, LL(RETS));
bufflen -= LL(RETS); bufflen -= LL(RETS);
memcpy(out, source + 1 + l - bufflen, bufflen); memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
} }
} }
else { /* string; format as [string "source"] */ else { /* string; format as [string "source"] */
@@ -236,6 +283,7 @@ void luaO_chunkid (char *out, const char *source, size_t bufflen) {
addstr(out, source, l); addstr(out, source, l);
addstr(out, RETS, LL(RETS)); addstr(out, RETS, LL(RETS));
} }
memcpy(out, POS, LL(POS) + 1); memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
} }
} }

358
lobject.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lobject.h,v 2.41 2010/06/04 13:25:10 roberto Exp roberto $ ** $Id: lobject.h,v 2.63 2011/10/17 14:46:13 roberto Exp roberto $
** Type definitions for Lua objects ** Type definitions for Lua objects
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -23,12 +23,38 @@
#define LUA_TUPVAL (LUA_NUMTAGS+1) #define LUA_TUPVAL (LUA_NUMTAGS+1)
#define LUA_TDEADKEY (LUA_NUMTAGS+2) #define LUA_TDEADKEY (LUA_NUMTAGS+2)
/*
** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
*/
#define LUA_TOTALTAGS (LUA_TUPVAL+2)
/* /*
** Variant tag for light C functions (negative to be considered ** tags for Tagged Values have the following use of bits:
** non collectable by 'iscollectable') ** bits 0-3: actual tag (a LUA_T* value)
** bits 4-5: variant bits
** bit 6: whether value is collectable
*/ */
#define LUA_TLCF (~0x0F | LUA_TFUNCTION)
/*
** LUA_TFUNCTION variants:
** 0 - Lua function
** 1 - light C function
** 2 - regular C function (closure)
*/
/* Variant tags for functions */
#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */
#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */
#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */
/* Bit mark for collectable types */
#define BIT_ISCOLLECTABLE (1 << 6)
/* mark a tag as collectable */
#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
/* /*
** Union of all collectable objects ** Union of all collectable objects
@@ -55,13 +81,10 @@ typedef struct GCheader {
/* /*
** Union of all Lua values ** Union of all Lua values
*/ */
typedef union { typedef union Value Value;
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
lua_Number n; /* numbers */ #define numfield lua_Number n; /* numbers */
int b; /* booleans */
lua_CFunction f; /* light C functions */
} Value;
@@ -72,125 +95,145 @@ typedef union {
#define TValuefields Value value_; int tt_ #define TValuefields Value value_; int tt_
typedef struct lua_TValue { typedef struct lua_TValue TValue;
TValuefields;
} TValue;
/* macro defining a nil value */ /* macro defining a nil value */
#define NILCONSTANT {NULL}, LUA_TNIL #define NILCONSTANT {NULL}, LUA_TNIL
/* #define val_(o) ((o)->value_)
** type tag of a TValue #define num_(o) (val_(o).n)
*/
#define ttype(o) ((o)->tt_)
/* /* raw type tag of a TValue */
** type tag of a TValue with no variants #define rttype(o) ((o)->tt_)
*/
#define ttypenv(o) (ttype(o) & 0x0F) /* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
#define ttype(o) (rttype(o) & 0x3F)
/* type tag of a TValue with no variants (bits 0-3) */
#define ttypenv(o) (rttype(o) & 0x0F)
/* Macros to test type */ /* Macros to test type */
#define ttisnil(o) (ttype(o) == LUA_TNIL) #define checktag(o,t) (rttype(o) == (t))
#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) #define ttisnumber(o) checktag((o), LUA_TNUMBER)
#define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttisnil(o) checktag((o), LUA_TNIL)
#define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttisboolean(o) checktag((o), LUA_TBOOLEAN)
#define ttisfunction(o) (ttypenv(o) == LUA_TFUNCTION) #define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)
#define ttisclosure(o) (ttype(o) == LUA_TFUNCTION) #define ttisstring(o) checktag((o), ctb(LUA_TSTRING))
#define ttislcf(o) (ttype(o) == LUA_TLCF) #define ttistable(o) checktag((o), ctb(LUA_TTABLE))
#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) #define ttisfunction(o) (ttypenv(o) == LUA_TFUNCTION)
#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) #define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION)
#define ttisthread(o) (ttype(o) == LUA_TTHREAD) #define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) #define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
#define ttisdeadkey(o) (ttype(o) == LUA_TDEADKEY) #define ttislcf(o) checktag((o), LUA_TLCF)
#define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA))
#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY)
#define ttisequal(o1,o2) (rttype(o1) == rttype(o2))
/* Macros to access values */ /* Macros to access values */
#define gcvalue(o) check_exp(iscollectable(o), (o)->value_.gc) #define nvalue(o) check_exp(ttisnumber(o), num_(o))
#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value_.p) #define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
#define nvalue(o) check_exp(ttisnumber(o), (o)->value_.n) #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value_.gc->ts) #define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts)
#define tsvalue(o) (&rawtsvalue(o)->tsv) #define tsvalue(o) (&rawtsvalue(o)->tsv)
#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value_.gc->u) #define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u)
#define uvalue(o) (&rawuvalue(o)->uv) #define uvalue(o) (&rawuvalue(o)->uv)
#define clvalue(o) check_exp(ttisclosure(o), &(o)->value_.gc->cl) #define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl)
#define fvalue(o) check_exp(ttislcf(o), (o)->value_.f) #define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l)
#define hvalue(o) check_exp(ttistable(o), &(o)->value_.gc->h) #define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c)
#define bvalue(o) check_exp(ttisboolean(o), (o)->value_.b) #define fvalue(o) check_exp(ttislcf(o), val_(o).f)
#define thvalue(o) check_exp(ttisthread(o), &(o)->value_.gc->th) #define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h)
#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)
#define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th)
/* a dead value may get the 'gc' field, but cannot access its contents */
#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))
#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
#define iscollectable(o) (ttype(o) >= LUA_TSTRING) #define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)
/* Macros for internal tests */ /* Macros for internal tests */
#define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt) #define righttt(obj) (ttypenv(obj) == gcvalue(obj)->gch.tt)
#define checkconsistency(obj) lua_assert(!iscollectable(obj) || righttt(obj))
#define checkliveness(g,obj) \ #define checkliveness(g,obj) \
lua_assert(!iscollectable(obj) || (righttt(obj) && !isdead(g,gcvalue(obj)))) lua_longassert(!iscollectable(obj) || \
(righttt(obj) && !isdead(g,gcvalue(obj))))
/* Macros to set values */ /* Macros to set values */
#define setnilvalue(obj) ((obj)->tt_=LUA_TNIL) #define settt_(o,t) ((o)->tt_=(t))
#define setnvalue(obj,x) \ #define setnvalue(obj,x) \
{ TValue *i_o=(obj); i_o->value_.n=(x); i_o->tt_=LUA_TNUMBER; } { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); }
#define changenvalue(o,x) check_exp(ttisnumber(o), num_(o)=(x))
#define setnilvalue(obj) settt_(obj, LUA_TNIL)
#define setfvalue(obj,x) \ #define setfvalue(obj,x) \
{ TValue *i_o=(obj); i_o->value_.f=(x); i_o->tt_=LUA_TLCF; } { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }
#define changenvalue(o,x) check_exp((o)->tt_==LUA_TNUMBER, (o)->value_.n=(x))
#define setpvalue(obj,x) \ #define setpvalue(obj,x) \
{ TValue *i_o=(obj); i_o->value_.p=(x); i_o->tt_=LUA_TLIGHTUSERDATA; } { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }
#define setbvalue(obj,x) \ #define setbvalue(obj,x) \
{ TValue *i_o=(obj); i_o->value_.b=(x); i_o->tt_=LUA_TBOOLEAN; } { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
#define setgcovalue(L,obj,x) \
{ TValue *io=(obj); GCObject *i_g=(x); \
val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); }
#define setsvalue(L,obj,x) \ #define setsvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TSTRING; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TSTRING)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setuvalue(L,obj,x) \ #define setuvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TUSERDATA; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setthvalue(L,obj,x) \ #define setthvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TTHREAD; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setclvalue(L,obj,x) \ #define setclLvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TFUNCTION; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setclCvalue(L,obj,x) \
{ TValue *io=(obj); \
val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \
checkliveness(G(L),io); }
#define sethvalue(L,obj,x) \ #define sethvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TTABLE; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setptvalue(L,obj,x) \ #define setptvalue(L,obj,x) \
{ TValue *i_o=(obj); \ { TValue *io=(obj); \
i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TPROTO; \ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TPROTO)); \
checkliveness(G(L),i_o); } checkliveness(G(L),io); }
#define setdeadvalue(obj) ((obj)->tt_=LUA_TDEADKEY) #define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY)
#define setobj(L,obj1,obj2) \ #define setobj(L,obj1,obj2) \
{ const TValue *o2=(obj2); TValue *o1=(obj1); \ { const TValue *io2=(obj2); TValue *io1=(obj1); \
o1->value_ = o2->value_; o1->tt_=o2->tt_; \ io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
checkliveness(G(L),o1); } checkliveness(G(L),io1); }
/* /*
@@ -214,9 +257,143 @@ typedef struct lua_TValue {
/*
** {======================================================
** NaN Trick
** =======================================================
*/
#if defined(LUA_NANTRICK) \
|| defined(LUA_NANTRICK_LE) \
|| defined(LUA_NANTRICK_BE)
/*
** numbers are represented in the 'd_' field. All other values have the
** value (NNMARK | tag) in 'tt__'. A number with such pattern would be
** a "signaled NaN", which is never generated by regular operations by
** the CPU (nor by 'strtod')
*/
#if !defined(NNMARK)
#define NNMARK 0x7FF7A500
#define NNMASK 0x7FFFFF00
#endif
#undef TValuefields
#undef NILCONSTANT
#if defined(LUA_NANTRICK_LE)
/* little endian */
#define TValuefields \
union { struct { Value v__; int tt__; } i; double d__; } u
#define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}}
/* field-access macros */
#define v_(o) ((o)->u.i.v__)
#define d_(o) ((o)->u.d__)
#define tt_(o) ((o)->u.i.tt__)
#elif defined(LUA_NANTRICK_BE)
/* big endian */
#define TValuefields \
union { struct { int tt__; Value v__; } i; double d__; } u
#define NILCONSTANT {{tag2tt(LUA_TNIL), {NULL}}}
/* field-access macros */
#define v_(o) ((o)->u.i.v__)
#define d_(o) ((o)->u.d__)
#define tt_(o) ((o)->u.i.tt__)
#elif !defined(TValuefields)
#error option 'LUA_NANTRICK' needs declaration for 'TValuefields'
#endif
/* correspondence with standard representation */
#undef val_
#define val_(o) v_(o)
#undef num_
#define num_(o) d_(o)
#undef numfield
#define numfield /* no such field; numbers are the entire struct */
/* basic check to distinguish numbers from non-numbers */
#undef ttisnumber
#define ttisnumber(o) ((tt_(o) & NNMASK) != NNMARK)
#define tag2tt(t) (NNMARK | (t))
#undef rttype
#define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff)
#undef settt_
#define settt_(o,t) (tt_(o) = tag2tt(t))
#undef setnvalue
#define setnvalue(obj,x) \
{ TValue *io_=(obj); num_(io_)=(x); lua_assert(ttisnumber(io_)); }
#undef setobj
#define setobj(L,obj1,obj2) \
{ const TValue *o2_=(obj2); TValue *o1_=(obj1); \
o1_->u = o2_->u; \
checkliveness(G(L),o1_); }
/*
** these redefinitions are not mandatory, but these forms are more efficient
*/
#undef checktag
#define checktag(o,t) (tt_(o) == tag2tt(t))
#undef ttisequal
#define ttisequal(o1,o2) \
(ttisnumber(o1) ? ttisnumber(o2) : (tt_(o1) == tt_(o2)))
#define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; }
#else
#define luai_checknum(L,o,c) { /* empty */ }
#endif
/* }====================================================== */
/*
** {======================================================
** types and prototypes
** =======================================================
*/
union Value {
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
int b; /* booleans */
lua_CFunction f; /* light C functions */
numfield /* numbers */
};
struct lua_TValue {
TValuefields;
};
typedef TValue *StkId; /* index to stack elements */ typedef TValue *StkId; /* index to stack elements */
/* /*
** Header for string value; string bytes follow the end of this structure ** Header for string value; string bytes follow the end of this structure
*/ */
@@ -226,7 +403,7 @@ typedef union TString {
CommonHeader; CommonHeader;
lu_byte reserved; lu_byte reserved;
unsigned int hash; unsigned int hash;
size_t len; size_t len; /* number of characters in string */
} tsv; } tsv;
} TString; } TString;
@@ -247,7 +424,7 @@ typedef union Udata {
CommonHeader; CommonHeader;
struct Table *metatable; struct Table *metatable;
struct Table *env; struct Table *env;
size_t len; size_t len; /* number of bytes */
} uv; } uv;
} Udata; } Udata;
@@ -282,11 +459,11 @@ typedef struct Proto {
TValue *k; /* constants used by the function */ TValue *k; /* constants used by the function */
Instruction *code; Instruction *code;
struct Proto **p; /* functions defined inside the function */ struct Proto **p; /* functions defined inside the function */
int *lineinfo; /* map from opcodes to source lines */ int *lineinfo; /* map from opcodes to source lines (debug information) */
LocVar *locvars; /* information about local variables */ LocVar *locvars; /* information about local variables (debug information) */
Upvaldesc *upvalues; /* upvalue information */ Upvaldesc *upvalues; /* upvalue information */
union Closure *cache; /* last created closure with this prototype */ union Closure *cache; /* last created closure with this prototype */
TString *source; TString *source; /* used for debug information */
int sizeupvalues; /* size of 'upvalues' */ int sizeupvalues; /* size of 'upvalues' */
int sizek; /* size of `k' */ int sizek; /* size of `k' */
int sizecode; int sizecode;
@@ -346,9 +523,9 @@ typedef union Closure {
} Closure; } Closure;
#define isLfunction(o) (ttisclosure(o) && !clvalue(o)->c.isC) #define isLfunction(o) ttisLclosure(o)
#define getproto(o) (clvalue(o)->l.p) #define getproto(o) (clLvalue(o)->p)
/* /*
@@ -403,12 +580,13 @@ typedef struct Table {
LUAI_DDEC const TValue luaO_nilobject_; LUAI_DDEC const TValue luaO_nilobject_;
LUAI_FUNC int luaO_int2fb (unsigned int x); LUAI_FUNC int luaO_int2fb (unsigned int x);
LUAI_FUNC int luaO_fb2int (int x); LUAI_FUNC int luaO_fb2int (int x);
LUAI_FUNC int luaO_ceillog2 (lu_int32 x); LUAI_FUNC int luaO_ceillog2 (unsigned int x);
LUAI_FUNC lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2); LUAI_FUNC lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2);
LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result);
LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); LUAI_FUNC int luaO_hexavalue (int c);
LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
va_list argp); va_list argp);
LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lopcodes.c,v 1.43 2010/03/12 19:14:06 roberto Exp roberto $ ** $Id: lopcodes.c,v 1.47 2011/04/12 17:27:35 roberto Exp roberto $
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -16,6 +16,7 @@
LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {
"MOVE", "MOVE",
"LOADK", "LOADK",
"LOADKX",
"LOADBOOL", "LOADBOOL",
"LOADNIL", "LOADNIL",
"GETUPVAL", "GETUPVAL",
@@ -50,7 +51,6 @@ LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {
"TFORCALL", "TFORCALL",
"TFORLOOP", "TFORLOOP",
"SETLIST", "SETLIST",
"CLOSE",
"CLOSURE", "CLOSURE",
"VARARG", "VARARG",
"EXTRAARG", "EXTRAARG",
@@ -64,8 +64,9 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
/* T A B C mode opcode */ /* T A B C mode opcode */
opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */
,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */
,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */
,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */
,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */ ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */
,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */
@@ -88,7 +89,7 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */
,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */ ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */
,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */
@@ -98,7 +99,6 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */ ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */
,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */ ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */
,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */
,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */
,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */
,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */
,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */ ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lopcodes.h,v 1.136 2010/10/13 16:45:54 roberto Exp roberto $ ** $Id: lopcodes.h,v 1.141 2011/04/19 16:22:13 roberto Exp roberto $
** Opcodes for Lua virtual machine ** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -167,9 +167,10 @@ typedef enum {
name args description name args description
------------------------------------------------------------------------*/ ------------------------------------------------------------------------*/
OP_MOVE,/* A B R(A) := R(B) */ OP_MOVE,/* A B R(A) := R(B) */
OP_LOADK,/* A Bx R(A) := Kst(Bx - 1) */ OP_LOADK,/* A Bx R(A) := Kst(Bx) */
OP_LOADKX,/* A R(A) := Kst(extra arg) */
OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */ OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */
OP_GETUPVAL,/* A B R(A) := UpValue[B] */ OP_GETUPVAL,/* A B R(A) := UpValue[B] */
OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */ OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */
@@ -195,8 +196,7 @@ OP_LEN,/* A B R(A) := length of R(B) */
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
OP_JMP,/* sBx pc+=sBx */ OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A) + 1 */
OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
@@ -217,7 +217,6 @@ OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/
OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */ OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/
OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */ OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */
OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */ OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */
@@ -244,7 +243,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
(*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
'instruction' is EXTRAARG(real C). 'instruction' is EXTRAARG(real C).
(*) In OP_LOADK, if (Bx == 0) then next 'instruction' is EXTRAARG(real Bx). (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
(*) For comparisons, A specifies what condition the test should accept (*) For comparisons, A specifies what condition the test should accept
(true or false). (true or false).

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: loslib.c,v 1.31 2010/07/02 12:01:53 roberto Exp roberto $ ** $Id: loslib.c,v 1.37 2011/11/29 17:15:42 roberto Exp roberto $
** Standard Operating System library ** Standard Operating System library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -21,7 +21,7 @@
/* /*
** list of valid conversion specifiers @* for the 'strftime' function ** list of valid conversion specifiers for the 'strftime' function
*/ */
#if !defined(LUA_STRFTIMEOPTIONS) #if !defined(LUA_STRFTIMEOPTIONS)
@@ -58,38 +58,46 @@
#endif #endif
/*
** By default, Lua uses gmtime/localtime, except when POSIX is available,
** where it uses gmtime_r/localtime_r
*/
#if defined(LUA_USE_GMTIME_R)
#define l_gmtime(t,r) gmtime_r(t,r)
#define l_localtime(t,r) localtime_r(t,r)
#elif !defined(l_gmtime)
#define l_gmtime(t,r) ((void)r, gmtime(t))
#define l_localtime(t,r) ((void)r, localtime(t))
#endif
static int os_pushresult (lua_State *L, int i, const char *filename) {
int en = errno; /* calls to Lua API may change this value */
if (i) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
lua_pushfstring(L, "%s: %s", filename, strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
static int os_execute (lua_State *L) { static int os_execute (lua_State *L) {
lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); const char *cmd = luaL_optstring(L, 1, NULL);
return 1; int stat = system(cmd);
if (cmd != NULL)
return luaL_execresult(L, stat);
else {
lua_pushboolean(L, stat); /* true if there is a shell */
return 1;
}
} }
static int os_remove (lua_State *L) { static int os_remove (lua_State *L) {
const char *filename = luaL_checkstring(L, 1); const char *filename = luaL_checkstring(L, 1);
return os_pushresult(L, remove(filename) == 0, filename); return luaL_fileresult(L, remove(filename) == 0, filename);
} }
static int os_rename (lua_State *L) { static int os_rename (lua_State *L) {
const char *fromname = luaL_checkstring(L, 1); const char *fromname = luaL_checkstring(L, 1);
const char *toname = luaL_checkstring(L, 2); const char *toname = luaL_checkstring(L, 2);
return os_pushresult(L, rename(fromname, toname) == 0, fromname); return luaL_fileresult(L, rename(fromname, toname) == 0, fromname);
} }
@@ -182,17 +190,17 @@ static const char *checkoption (lua_State *L, const char *conv, char *buff) {
return conv; /* to avoid warnings */ return conv; /* to avoid warnings */
} }
static int os_date (lua_State *L) { static int os_date (lua_State *L) {
const char *s = luaL_optstring(L, 1, "%c"); const char *s = luaL_optstring(L, 1, "%c");
time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL)); time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL));
struct tm *stm; struct tm tmr, *stm;
if (*s == '!') { /* UTC? */ if (*s == '!') { /* UTC? */
stm = gmtime(&t); stm = l_gmtime(&t, &tmr);
s++; /* skip `!' */ s++; /* skip `!' */
} }
else else
stm = localtime(&t); stm = l_localtime(&t, &tmr);
if (stm == NULL) /* invalid date? */ if (stm == NULL) /* invalid date? */
lua_pushnil(L); lua_pushnil(L);
else if (strcmp(s, "*t") == 0) { else if (strcmp(s, "*t") == 0) {
@@ -283,7 +291,8 @@ static int os_exit (lua_State *L) {
status = luaL_optint(L, 1, EXIT_SUCCESS); status = luaL_optint(L, 1, EXIT_SUCCESS);
if (lua_toboolean(L, 2)) if (lua_toboolean(L, 2))
lua_close(L); lua_close(L);
exit(status); if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
return 0;
} }

605
lparser.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lparser.c,v 2.91 2010/08/23 17:32:34 roberto Exp roberto $ ** $Id: lparser.c,v 2.123 2011/11/30 12:43:51 roberto Exp roberto $
** Lua Parser ** Lua Parser
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -41,10 +41,11 @@
*/ */
typedef struct BlockCnt { typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */ struct BlockCnt *previous; /* chain */
int breaklist; /* list of jumps out of this loop */ short firstlabel; /* index of first label in this block */
lu_byte nactvar; /* # active locals outside the breakable structure */ short firstgoto; /* index of first pending goto in this block */
lu_byte nactvar; /* # active locals outside the block */
lu_byte upval; /* true if some variable in the block is an upvalue */ lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isbreakable; /* true if `block' is a loop */ lu_byte isloop; /* true if `block' is a loop */
} BlockCnt; } BlockCnt;
@@ -52,7 +53,7 @@ typedef struct BlockCnt {
/* /*
** prototypes for recursive non-terminal functions ** prototypes for recursive non-terminal functions
*/ */
static void chunk (LexState *ls); static void statement (LexState *ls);
static void expr (LexState *ls, expdesc *v); static void expr (LexState *ls, expdesc *v);
@@ -66,20 +67,28 @@ static void anchor_token (LexState *ls) {
} }
static void error_expected (LexState *ls, int token) { /* semantic error */
static l_noret semerror (LexState *ls, const char *msg) {
ls->t.token = 0; /* remove 'near to' from final message */
luaX_syntaxerror(ls, msg);
}
static l_noret error_expected (LexState *ls, int token) {
luaX_syntaxerror(ls, luaX_syntaxerror(ls,
luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
} }
static void errorlimit (FuncState *fs, int limit, const char *what) { static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
lua_State *L = fs->ls->L;
const char *msg; const char *msg;
int line = fs->f->linedefined; int line = fs->f->linedefined;
const char *where = (line == 0) const char *where = (line == 0)
? "main function" ? "main function"
: luaO_pushfstring(fs->L, "function at line %d", line); : luaO_pushfstring(L, "function at line %d", line);
msg = luaO_pushfstring(fs->L, "too many %s (limit is %d) in %s", msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
what, limit, where); what, limit, where);
luaX_syntaxerror(fs->ls, msg); luaX_syntaxerror(fs->ls, msg);
} }
@@ -103,6 +112,7 @@ static void check (LexState *ls, int c) {
error_expected(ls, c); error_expected(ls, c);
} }
static void checknext (LexState *ls, int c) { static void checknext (LexState *ls, int c) {
check(ls, c); check(ls, c);
luaX_next(ls); luaX_next(ls);
@@ -167,13 +177,13 @@ static int registerlocalvar (LexState *ls, TString *varname) {
static void new_localvar (LexState *ls, TString *name) { static void new_localvar (LexState *ls, TString *name) {
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
Varlist *vl = ls->varl; Dyndata *dyd = ls->dyd;
int reg = registerlocalvar(ls, name); int reg = registerlocalvar(ls, name);
checklimit(fs, vl->nactvar + 1 - fs->firstlocal, checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
MAXVARS, "local variables"); MAXVARS, "local variables");
luaM_growvector(ls->L, vl->actvar, vl->nactvar + 1, luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
vl->actvarsize, vardesc, MAX_INT, "local variables"); dyd->actvar.size, Vardesc, MAX_INT, "local variables");
vl->actvar[vl->nactvar++].idx = cast(unsigned short, reg); dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
} }
@@ -186,7 +196,7 @@ static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
static LocVar *getlocvar (FuncState *fs, int i) { static LocVar *getlocvar (FuncState *fs, int i) {
int idx = fs->ls->varl->actvar[fs->firstlocal + i].idx; int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
lua_assert(idx < fs->nlocvars); lua_assert(idx < fs->nlocvars);
return &fs->f->locvars[idx]; return &fs->f->locvars[idx];
} }
@@ -202,7 +212,7 @@ static void adjustlocalvars (LexState *ls, int nvars) {
static void removevars (FuncState *fs, int tolevel) { static void removevars (FuncState *fs, int tolevel) {
fs->ls->varl->nactvar -= (fs->nactvar - tolevel); fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
while (fs->nactvar > tolevel) while (fs->nactvar > tolevel)
getlocvar(fs, --fs->nactvar)->endpc = fs->pc; getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
} }
@@ -222,13 +232,13 @@ static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
Proto *f = fs->f; Proto *f = fs->f;
int oldsize = f->sizeupvalues; int oldsize = f->sizeupvalues;
checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
luaM_growvector(fs->L, f->upvalues, fs->nups, f->sizeupvalues, luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
Upvaldesc, MAXUPVAL, "upvalues"); Upvaldesc, MAXUPVAL, "upvalues");
while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
f->upvalues[fs->nups].instack = (v->k == VLOCAL); f->upvalues[fs->nups].instack = (v->k == VLOCAL);
f->upvalues[fs->nups].idx = cast_byte(v->u.info); f->upvalues[fs->nups].idx = cast_byte(v->u.info);
f->upvalues[fs->nups].name = name; f->upvalues[fs->nups].name = name;
luaC_objbarrier(fs->L, f, name); luaC_objbarrier(fs->ls->L, f, name);
return fs->nups++; return fs->nups++;
} }
@@ -245,12 +255,12 @@ static int searchvar (FuncState *fs, TString *n) {
/* /*
Mark block where variable at given level was defined Mark block where variable at given level was defined
(to emit OP_CLOSE later). (to emit close instructions later).
*/ */
static void markupval (FuncState *fs, int level) { static void markupval (FuncState *fs, int level) {
BlockCnt *bl = fs->bl; BlockCnt *bl = fs->bl;
while (bl && bl->nactvar > level) bl = bl->previous; while (bl->nactvar > level) bl = bl->previous;
if (bl) bl->upval = 1; bl->upval = 1;
} }
@@ -318,19 +328,118 @@ static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
static void enterlevel (LexState *ls) { static void enterlevel (LexState *ls) {
global_State *g = G(ls->L); lua_State *L = ls->L;
++g->nCcalls; ++L->nCcalls;
checklimit(ls->fs, g->nCcalls, LUAI_MAXCCALLS, "syntax levels"); checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
} }
#define leavelevel(ls) (G((ls)->L)->nCcalls--) #define leavelevel(ls) ((ls)->L->nCcalls--)
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) { static void closegoto (LexState *ls, int g, Labeldesc *label) {
bl->breaklist = NO_JUMP; int i;
bl->isbreakable = isbreakable; FuncState *fs = ls->fs;
Labellist *gl = &ls->dyd->gt;
Labeldesc *gt = &gl->arr[g];
lua_assert(eqstr(gt->name, label->name));
if (gt->nactvar < label->nactvar) {
TString *vname = getlocvar(fs, gt->nactvar)->varname;
const char *msg = luaO_pushfstring(ls->L,
"<goto %s> at line %d jumps into the scope of local " LUA_QS,
getstr(gt->name), gt->line, getstr(vname));
semerror(ls, msg);
}
luaK_patchlist(fs, gt->pc, label->pc);
/* remove goto from pending list */
for (i = g; i < gl->n - 1; i++)
gl->arr[i] = gl->arr[i + 1];
gl->n--;
}
/*
** try to close a goto with existing labels; this solves backward jumps
*/
static int findlabel (LexState *ls, int g) {
int i;
BlockCnt *bl = ls->fs->bl;
Dyndata *dyd = ls->dyd;
Labeldesc *gt = &dyd->gt.arr[g];
/* check labels in current block for a match */
for (i = bl->firstlabel; i < dyd->label.n; i++) {
Labeldesc *lb = &dyd->label.arr[i];
if (eqstr(lb->name, gt->name)) { /* correct label? */
if (gt->nactvar > lb->nactvar &&
(bl->upval || dyd->label.n > bl->firstlabel))
luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
closegoto(ls, g, lb); /* close it */
return 1;
}
}
return 0; /* label not found; cannot close goto */
}
static int newlabelentry (LexState *ls, Labellist *l, TString *name,
int line, int pc) {
int n = l->n;
luaM_growvector(ls->L, l->arr, n, l->size,
Labeldesc, SHRT_MAX, "labels/gotos");
l->arr[n].name = name;
l->arr[n].line = line;
l->arr[n].nactvar = ls->fs->nactvar;
l->arr[n].pc = pc;
l->n++;
return n;
}
/*
** check whether new label 'lb' matches any pending gotos in current
** block; solves forward jumps
*/
static void findgotos (LexState *ls, Labeldesc *lb) {
Labellist *gl = &ls->dyd->gt;
int i = ls->fs->bl->firstgoto;
while (i < gl->n) {
if (eqstr(gl->arr[i].name, lb->name))
closegoto(ls, i, lb);
else
i++;
}
}
/*
** "export" pending gotos to outer level, to check them against
** outer labels; if the block being exited has upvalues, and
** the goto exits the scope of any variable (which can be the
** upvalue), close those variables being exited.
*/
static void movegotosout (FuncState *fs, BlockCnt *bl) {
int i = bl->firstgoto;
Labellist *gl = &fs->ls->dyd->gt;
/* correct pending gotos to current block and try to close it
with visible labels */
while (i < gl->n) {
Labeldesc *gt = &gl->arr[i];
if (gt->nactvar > bl->nactvar) {
if (bl->upval)
luaK_patchclose(fs, gt->pc, bl->nactvar);
gt->nactvar = bl->nactvar;
}
if (!findlabel(fs->ls, i))
i++; /* move to next one */
}
}
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
bl->isloop = isloop;
bl->nactvar = fs->nactvar; bl->nactvar = fs->nactvar;
bl->firstlabel = fs->ls->dyd->label.n;
bl->firstgoto = fs->ls->dyd->gt.n;
bl->upval = 0; bl->upval = 0;
bl->previous = fs->bl; bl->previous = fs->bl;
fs->bl = bl; fs->bl = bl;
@@ -338,17 +447,48 @@ static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
} }
/*
** create a label named "break" to resolve break statements
*/
static void breaklabel (LexState *ls) {
TString *n = luaS_new(ls->L, "break");
int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
findgotos(ls, &ls->dyd->label.arr[l]);
}
/*
** generates an error for an undefined 'goto'; choose appropriate
** message when label name is a reserved word (which can only be 'break')
*/
static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
const char *msg = (gt->name->tsv.reserved > 0)
? "<%s> at line %d not inside a loop"
: "no visible label " LUA_QS " for <goto> at line %d";
msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
semerror(ls, msg);
}
static void leaveblock (FuncState *fs) { static void leaveblock (FuncState *fs) {
BlockCnt *bl = fs->bl; BlockCnt *bl = fs->bl;
LexState *ls = fs->ls;
if (bl->previous && bl->upval) {
/* create a 'jump to here' to close upvalues */
int j = luaK_jump(fs);
luaK_patchclose(fs, j, bl->nactvar);
luaK_patchtohere(fs, j);
}
if (bl->isloop)
breaklabel(ls); /* close pending breaks */
fs->bl = bl->previous; fs->bl = bl->previous;
removevars(fs, bl->nactvar); removevars(fs, bl->nactvar);
if (bl->upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
/* a block either controls scope or breaks (never both) */
lua_assert(!bl->isbreakable || !bl->upval);
lua_assert(bl->nactvar == fs->nactvar); lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */ fs->freereg = fs->nactvar; /* free registers */
luaK_patchtohere(fs, bl->breaklist); ls->dyd->label.n = bl->firstlabel; /* remove local labels */
if (bl->previous) /* inner block? */
movegotosout(fs, bl); /* update pending gotos to outer block */
else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
} }
@@ -368,15 +508,15 @@ static void codeclosure (LexState *ls, Proto *clp, expdesc *v) {
f->p[fs->np++] = clp; f->p[fs->np++] = clp;
luaC_objbarrier(ls->L, f, clp); luaC_objbarrier(ls->L, f, clp);
init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1)); init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
luaK_exp2nextreg(fs, v); /* fix it at stack top (for GC) */
} }
static void open_func (LexState *ls, FuncState *fs) { static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
lua_State *L = ls->L; lua_State *L = ls->L;
Proto *f; Proto *f;
fs->prev = ls->fs; /* linked list of funcstates */ fs->prev = ls->fs; /* linked list of funcstates */
fs->ls = ls; fs->ls = ls;
fs->L = L;
ls->fs = fs; ls->fs = fs;
fs->pc = 0; fs->pc = 0;
fs->lasttarget = 0; fs->lasttarget = 0;
@@ -387,7 +527,7 @@ static void open_func (LexState *ls, FuncState *fs) {
fs->nups = 0; fs->nups = 0;
fs->nlocvars = 0; fs->nlocvars = 0;
fs->nactvar = 0; fs->nactvar = 0;
fs->firstlocal = ls->varl->nactvar; fs->firstlocal = ls->dyd->actvar.n;
fs->bl = NULL; fs->bl = NULL;
f = luaF_newproto(L); f = luaF_newproto(L);
fs->f = f; fs->f = f;
@@ -400,6 +540,7 @@ static void open_func (LexState *ls, FuncState *fs) {
/* anchor table of constants (to avoid being collected) */ /* anchor table of constants (to avoid being collected) */
sethvalue2s(L, L->top, fs->h); sethvalue2s(L, L->top, fs->h);
incr_top(L); incr_top(L);
enterblock(fs, bl, 0);
} }
@@ -408,7 +549,7 @@ static void close_func (LexState *ls) {
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
Proto *f = fs->f; Proto *f = fs->f;
luaK_ret(fs, 0, 0); /* final return */ luaK_ret(fs, 0, 0); /* final return */
removevars(fs, 0); leaveblock(fs);
luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
f->sizecode = fs->pc; f->sizecode = fs->pc;
luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
@@ -435,42 +576,49 @@ static void close_func (LexState *ls) {
** opens the main function, which is a regular vararg function with an ** opens the main function, which is a regular vararg function with an
** upvalue named LUA_ENV ** upvalue named LUA_ENV
*/ */
static void open_mainfunc (LexState *ls, FuncState *fs) { static void open_mainfunc (LexState *ls, FuncState *fs, BlockCnt *bl) {
expdesc v; expdesc v;
open_func(ls, fs); open_func(ls, fs, bl);
fs->f->is_vararg = 1; /* main function is always vararg */ fs->f->is_vararg = 1; /* main function is always vararg */
init_exp(&v, VLOCAL, 0); init_exp(&v, VLOCAL, 0);
newupvalue(fs, ls->envn, &v); /* create environment upvalue */ newupvalue(fs, ls->envn, &v); /* create environment upvalue */
} }
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Varlist *varl,
const char *name) {
LexState lexstate;
FuncState funcstate;
TString *tname = luaS_new(L, name);
setsvalue2s(L, L->top, tname); /* push name to protect it */
incr_top(L);
lexstate.buff = buff;
lexstate.varl = varl;
luaX_setinput(L, &lexstate, z, tname);
open_mainfunc(&lexstate, &funcstate);
luaX_next(&lexstate); /* read first token */
chunk(&lexstate); /* read main chunk */
check(&lexstate, TK_EOS);
close_func(&lexstate);
L->top--; /* pop name */
lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
return funcstate.f;
}
/*============================================================*/ /*============================================================*/
/* GRAMMAR RULES */ /* GRAMMAR RULES */
/*============================================================*/ /*============================================================*/
/*
** check whether current token is in the follow set of a block.
** 'until' closes syntactical blocks, but do not close scope,
** so it handled in separate.
*/
static int block_follow (LexState *ls, int withuntil) {
switch (ls->t.token) {
case TK_ELSE: case TK_ELSEIF:
case TK_END: case TK_EOS:
return 1;
case TK_UNTIL: return withuntil;
default: return 0;
}
}
static void statlist (LexState *ls) {
/* statlist -> { stat [`;'] } */
while (!block_follow(ls, 1)) {
if (ls->t.token == TK_RETURN) {
statement(ls);
return; /* 'return' must be last statement */
}
statement(ls);
}
}
static void fieldsel (LexState *ls, expdesc *v) { static void fieldsel (LexState *ls, expdesc *v) {
/* fieldsel -> ['.' | ':'] NAME */ /* fieldsel -> ['.' | ':'] NAME */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
@@ -586,7 +734,7 @@ static void field (LexState *ls, struct ConsControl *cc) {
static void constructor (LexState *ls, expdesc *t) { static void constructor (LexState *ls, expdesc *t) {
/* constructor -> '{' [ field { sep field } [sep] ] '}' /* constructor -> '{' [ field { sep field } [sep] ] '}'
sep -> ',' | ';' */ sep -> ',' | ';' */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
int line = ls->linenumber; int line = ls->linenumber;
@@ -596,7 +744,7 @@ static void constructor (LexState *ls, expdesc *t) {
cc.t = t; cc.t = t;
init_exp(t, VRELOCABLE, pc); init_exp(t, VRELOCABLE, pc);
init_exp(&cc.v, VVOID, 0); /* no value (yet) */ init_exp(&cc.v, VVOID, 0); /* no value (yet) */
luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */ luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
checknext(ls, '{'); checknext(ls, '{');
do { do {
lua_assert(cc.v.k == VVOID || cc.tostore > 0); lua_assert(cc.v.k == VVOID || cc.tostore > 0);
@@ -643,19 +791,20 @@ static void parlist (LexState *ls) {
} }
static void body (LexState *ls, expdesc *e, int needself, int line) { static void body (LexState *ls, expdesc *e, int ismethod, int line) {
/* body -> `(' parlist `)' chunk END */ /* body -> `(' parlist `)' block END */
FuncState new_fs; FuncState new_fs;
open_func(ls, &new_fs); BlockCnt bl;
open_func(ls, &new_fs, &bl);
new_fs.f->linedefined = line; new_fs.f->linedefined = line;
checknext(ls, '('); checknext(ls, '(');
if (needself) { if (ismethod) {
new_localvarliteral(ls, "self"); new_localvarliteral(ls, "self"); /* create 'self' parameter */
adjustlocalvars(ls, 1); adjustlocalvars(ls, 1);
} }
parlist(ls); parlist(ls);
checknext(ls, ')'); checknext(ls, ')');
chunk(ls); statlist(ls);
new_fs.f->lastlinedefined = ls->linenumber; new_fs.f->lastlinedefined = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line); check_match(ls, TK_END, TK_FUNCTION, line);
codeclosure(ls, new_fs.f, e); codeclosure(ls, new_fs.f, e);
@@ -663,8 +812,8 @@ static void body (LexState *ls, expdesc *e, int needself, int line) {
} }
static int explist1 (LexState *ls, expdesc *v) { static int explist (LexState *ls, expdesc *v) {
/* explist1 -> expr { `,' expr } */ /* explist -> expr { `,' expr } */
int n = 1; /* at least one expression */ int n = 1; /* at least one expression */
expr(ls, v); expr(ls, v);
while (testnext(ls, ',')) { while (testnext(ls, ',')) {
@@ -681,12 +830,12 @@ static void funcargs (LexState *ls, expdesc *f, int line) {
expdesc args; expdesc args;
int base, nparams; int base, nparams;
switch (ls->t.token) { switch (ls->t.token) {
case '(': { /* funcargs -> `(' [ explist1 ] `)' */ case '(': { /* funcargs -> `(' [ explist ] `)' */
luaX_next(ls); luaX_next(ls);
if (ls->t.token == ')') /* arg list is empty? */ if (ls->t.token == ')') /* arg list is empty? */
args.k = VVOID; args.k = VVOID;
else { else {
explist1(ls, &args); explist(ls, &args);
luaK_setmultret(fs, &args); luaK_setmultret(fs, &args);
} }
check_match(ls, ')', '(', line); check_match(ls, ')', '(', line);
@@ -703,7 +852,6 @@ static void funcargs (LexState *ls, expdesc *f, int line) {
} }
default: { default: {
luaX_syntaxerror(ls, "function arguments expected"); luaX_syntaxerror(ls, "function arguments expected");
return;
} }
} }
lua_assert(f->k == VNONRELOC); lua_assert(f->k == VNONRELOC);
@@ -748,7 +896,6 @@ static void prefixexp (LexState *ls, expdesc *v) {
} }
default: { default: {
luaX_syntaxerror(ls, "unexpected symbol"); luaX_syntaxerror(ls, "unexpected symbol");
return;
} }
} }
} }
@@ -892,7 +1039,7 @@ static const struct {
** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where `binop' is any binary operator with a priority higher than `limit' ** where `binop' is any binary operator with a priority higher than `limit'
*/ */
static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) { static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
BinOpr op; BinOpr op;
UnOpr uop; UnOpr uop;
enterlevel(ls); enterlevel(ls);
@@ -937,23 +1084,12 @@ static void expr (LexState *ls, expdesc *v) {
*/ */
static int block_follow (int token) {
switch (token) {
case TK_ELSE: case TK_ELSEIF: case TK_END:
case TK_UNTIL: case TK_EOS:
return 1;
default: return 0;
}
}
static void block (LexState *ls) { static void block (LexState *ls) {
/* block -> chunk */ /* block -> statlist */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
BlockCnt bl; BlockCnt bl;
enterblock(fs, &bl, 0); enterblock(fs, &bl, 0);
chunk(ls); statlist(ls);
lua_assert(bl.breaklist == NO_JUMP);
leaveblock(fs); leaveblock(fs);
} }
@@ -969,31 +1105,34 @@ struct LHS_assign {
/* /*
** check whether, in an assignment to a local variable, the local variable ** check whether, in an assignment to an upvalue/local variable, the
** is needed in a previous assignment (to a table). If so, save original ** upvalue/local variable is begin used in a previous assignment to a
** local value in a safe place and use this safe copy in the previous ** table. If so, save original upvalue/local value in a safe place and
** assignment. ** use this safe copy in the previous assignment.
*/ */
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
int extra = fs->freereg; /* eventual position to save local variable */ int extra = fs->freereg; /* eventual position to save local variable */
int conflict = 0; int conflict = 0;
for (; lh; lh = lh->prev) { for (; lh; lh = lh->prev) { /* check all previous assignments */
/* conflict in table 't'? */ if (lh->v.k == VINDEXED) { /* assigning to a table? */
if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { /* table is the upvalue/local being assigned now? */
conflict = 1; if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
lh->v.u.ind.vt = VLOCAL; conflict = 1;
lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ lh->v.u.ind.vt = VLOCAL;
} lh->v.u.ind.t = extra; /* previous assignment will use safe copy */
/* conflict in index 'idx'? */ }
if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { /* index is the local being assigned? (index cannot be upvalue) */
conflict = 1; if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ conflict = 1;
lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
}
} }
} }
if (conflict) { if (conflict) {
/* copy upvalue/local value to a temporary (in position 'extra') */
OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
luaK_codeABC(fs, op, fs->freereg, v->u.info, 0); /* make copy */ luaK_codeABC(fs, op, extra, v->u.info, 0);
luaK_reserveregs(fs, 1); luaK_reserveregs(fs, 1);
} }
} }
@@ -1008,14 +1147,14 @@ static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
primaryexp(ls, &nv.v); primaryexp(ls, &nv.v);
if (nv.v.k != VINDEXED) if (nv.v.k != VINDEXED)
check_conflict(ls, lh, &nv.v); check_conflict(ls, lh, &nv.v);
checklimit(ls->fs, nvars, LUAI_MAXCCALLS - G(ls->L)->nCcalls, checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
"variable names"); "C levels");
assignment(ls, &nv, nvars+1); assignment(ls, &nv, nvars+1);
} }
else { /* assignment -> `=' explist1 */ else { /* assignment -> `=' explist */
int nexps; int nexps;
checknext(ls, '='); checknext(ls, '=');
nexps = explist1(ls, &e); nexps = explist(ls, &e);
if (nexps != nvars) { if (nexps != nvars) {
adjust_assign(ls, nvars, nexps, &e); adjust_assign(ls, nvars, nexps, &e);
if (nexps > nvars) if (nexps > nvars)
@@ -1042,19 +1181,52 @@ static int cond (LexState *ls) {
} }
static void breakstat (LexState *ls) { static void gotostat (LexState *ls, int pc) {
FuncState *fs = ls->fs; int line = ls->linenumber;
BlockCnt *bl = fs->bl; TString *label;
int upval = 0; int g;
while (bl && !bl->isbreakable) { if (testnext(ls, TK_GOTO))
upval |= bl->upval; label = str_checkname(ls);
bl = bl->previous; else {
luaX_next(ls); /* skip break */
label = luaS_new(ls->L, "break");
} }
if (!bl) g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
luaX_syntaxerror(ls, "no loop to break"); findlabel(ls, g); /* close it if label already defined */
if (upval) }
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
/* check for repeated labels on the same block */
static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
int i;
for (i = fs->bl->firstlabel; i < ll->n; i++) {
if (eqstr(label, ll->arr[i].name)) {
const char *msg = luaO_pushfstring(fs->ls->L,
"label " LUA_QS " already defined on line %d",
getstr(label), ll->arr[i].line);
semerror(fs->ls, msg);
}
}
}
static void labelstat (LexState *ls, TString *label, int line) {
/* label -> '::' NAME '::' */
FuncState *fs = ls->fs;
Labellist *ll = &ls->dyd->label;
int l; /* index of new label being created */
checkrepeated(fs, ll, label); /* check for repeated labels */
checknext(ls, TK_DBCOLON); /* skip double colon */
/* create new entry for this label */
l = newlabelentry(ls, ll, label, line, fs->pc);
/* skip other no-op statements */
while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
statement(ls);
if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
/* assume that locals are already out of scope */
ll->arr[l].nactvar = fs->bl->nactvar;
}
findgotos(ls, &ll->arr[l]);
} }
@@ -1086,19 +1258,13 @@ static void repeatstat (LexState *ls, int line) {
enterblock(fs, &bl1, 1); /* loop block */ enterblock(fs, &bl1, 1); /* loop block */
enterblock(fs, &bl2, 0); /* scope block */ enterblock(fs, &bl2, 0); /* scope block */
luaX_next(ls); /* skip REPEAT */ luaX_next(ls); /* skip REPEAT */
chunk(ls); statlist(ls);
check_match(ls, TK_UNTIL, TK_REPEAT, line); check_match(ls, TK_UNTIL, TK_REPEAT, line);
condexit = cond(ls); /* read condition (inside scope block) */ condexit = cond(ls); /* read condition (inside scope block) */
if (!bl2.upval) { /* no upvalues? */ if (bl2.upval) /* upvalues? */
leaveblock(fs); /* finish scope */ luaK_patchclose(fs, condexit, bl2.nactvar);
luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ leaveblock(fs); /* finish scope */
} luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
else { /* complete semantics when there are upvalues */
breakstat(ls); /* if condition then break */
luaK_patchtohere(ls->fs, condexit); /* else... */
leaveblock(fs); /* finish scope... */
luaK_jumpto(fs, repeat_init); /* and repeat */
}
leaveblock(fs); /* finish loop */ leaveblock(fs); /* finish loop */
} }
@@ -1163,7 +1329,7 @@ static void fornum (LexState *ls, TString *varname, int line) {
static void forlist (LexState *ls, TString *indexname) { static void forlist (LexState *ls, TString *indexname) {
/* forlist -> NAME {,NAME} IN explist1 forbody */ /* forlist -> NAME {,NAME} IN explist forbody */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
expdesc e; expdesc e;
int nvars = 4; /* gen, state, control, plus at least one declared var */ int nvars = 4; /* gen, state, control, plus at least one declared var */
@@ -1181,7 +1347,7 @@ static void forlist (LexState *ls, TString *indexname) {
} }
checknext(ls, TK_IN); checknext(ls, TK_IN);
line = ls->linenumber; line = ls->linenumber;
adjust_assign(ls, 3, explist1(ls, &e), &e); adjust_assign(ls, 3, explist(ls, &e), &e);
luaK_checkstack(fs, 3); /* extra space to call generator */ luaK_checkstack(fs, 3); /* extra space to call generator */
forbody(ls, base, line, nvars - 3, 0); forbody(ls, base, line, nvars - 3, 0);
} }
@@ -1205,55 +1371,67 @@ static void forstat (LexState *ls, int line) {
} }
static int test_then_block (LexState *ls) { static void test_then_block (LexState *ls, int *escapelist) {
/* test_then_block -> [IF | ELSEIF] cond THEN block */ /* test_then_block -> [IF | ELSEIF] cond THEN block */
int condexit; BlockCnt bl;
FuncState *fs = ls->fs;
expdesc v;
int jf; /* instruction to skip 'then' code (if condition is false) */
luaX_next(ls); /* skip IF or ELSEIF */ luaX_next(ls); /* skip IF or ELSEIF */
condexit = cond(ls); expr(ls, &v); /* read condition */
checknext(ls, TK_THEN); checknext(ls, TK_THEN);
block(ls); /* `then' part */ if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
return condexit; luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
enterblock(fs, &bl, 0); /* must enter block before 'goto' */
gotostat(ls, v.t); /* handle goto/break */
if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
leaveblock(fs);
return; /* and that is it */
}
else /* must skip over 'then' part if condition is false */
jf = luaK_jump(fs);
}
else { /* regular case (not goto/break) */
luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
enterblock(fs, &bl, 0);
jf = v.f;
}
statlist(ls); /* `then' part */
leaveblock(fs);
if (ls->t.token == TK_ELSE ||
ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
luaK_patchtohere(fs, jf);
} }
static void ifstat (LexState *ls, int line) { static void ifstat (LexState *ls, int line) {
/* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
int flist; int escapelist = NO_JUMP; /* exit list for finished parts */
int escapelist = NO_JUMP; test_then_block(ls, &escapelist); /* IF cond THEN block */
flist = test_then_block(ls); /* IF cond THEN block */ while (ls->t.token == TK_ELSEIF)
while (ls->t.token == TK_ELSEIF) { test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
luaK_concat(fs, &escapelist, luaK_jump(fs)); if (testnext(ls, TK_ELSE))
luaK_patchtohere(fs, flist);
flist = test_then_block(ls); /* ELSEIF cond THEN block */
}
if (ls->t.token == TK_ELSE) {
luaK_concat(fs, &escapelist, luaK_jump(fs));
luaK_patchtohere(fs, flist);
luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
block(ls); /* `else' part */ block(ls); /* `else' part */
}
else
luaK_concat(fs, &escapelist, flist);
luaK_patchtohere(fs, escapelist);
check_match(ls, TK_END, TK_IF, line); check_match(ls, TK_END, TK_IF, line);
luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
} }
static void localfunc (LexState *ls) { static void localfunc (LexState *ls) {
expdesc v, b; expdesc b;
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
new_localvar(ls, str_checkname(ls)); new_localvar(ls, str_checkname(ls)); /* new local variable */
init_exp(&v, VLOCAL, fs->freereg); adjustlocalvars(ls, 1); /* enter its scope */
luaK_reserveregs(fs, 1); body(ls, &b, 0, ls->linenumber); /* function created in next register */
adjustlocalvars(ls, 1); /* debug information will only see the variable after this point! */
body(ls, &b, 0, ls->linenumber); getlocvar(fs, b.u.info)->startpc = fs->pc;
luaK_storevar(fs, &v, &b);
} }
static void localstat (LexState *ls) { static void localstat (LexState *ls) {
/* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
int nvars = 0; int nvars = 0;
int nexps; int nexps;
expdesc e; expdesc e;
@@ -1262,7 +1440,7 @@ static void localstat (LexState *ls) {
nvars++; nvars++;
} while (testnext(ls, ',')); } while (testnext(ls, ','));
if (testnext(ls, '=')) if (testnext(ls, '='))
nexps = explist1(ls, &e); nexps = explist(ls, &e);
else { else {
e.k = VVOID; e.k = VVOID;
nexps = 0; nexps = 0;
@@ -1274,25 +1452,25 @@ static void localstat (LexState *ls) {
static int funcname (LexState *ls, expdesc *v) { static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {fieldsel} [`:' NAME] */ /* funcname -> NAME {fieldsel} [`:' NAME] */
int needself = 0; int ismethod = 0;
singlevar(ls, v); singlevar(ls, v);
while (ls->t.token == '.') while (ls->t.token == '.')
fieldsel(ls, v); fieldsel(ls, v);
if (ls->t.token == ':') { if (ls->t.token == ':') {
needself = 1; ismethod = 1;
fieldsel(ls, v); fieldsel(ls, v);
} }
return needself; return ismethod;
} }
static void funcstat (LexState *ls, int line) { static void funcstat (LexState *ls, int line) {
/* funcstat -> FUNCTION funcname body */ /* funcstat -> FUNCTION funcname body */
int needself; int ismethod;
expdesc v, b; expdesc v, b;
luaX_next(ls); /* skip FUNCTION */ luaX_next(ls); /* skip FUNCTION */
needself = funcname(ls, &v); ismethod = funcname(ls, &v);
body(ls, &b, needself, line); body(ls, &b, ismethod, line);
luaK_storevar(ls->fs, &v, &b); luaK_storevar(ls->fs, &v, &b);
luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
} }
@@ -1313,14 +1491,14 @@ static void exprstat (LexState *ls) {
static void retstat (LexState *ls) { static void retstat (LexState *ls) {
/* stat -> RETURN explist */ /* stat -> RETURN [explist] [';'] */
FuncState *fs = ls->fs; FuncState *fs = ls->fs;
expdesc e; expdesc e;
int first, nret; /* registers with returned values */ int first, nret; /* registers with returned values */
if (block_follow(ls->t.token) || ls->t.token == ';') if (block_follow(ls, 1) || ls->t.token == ';')
first = nret = 0; /* return no values */ first = nret = 0; /* return no values */
else { else {
nret = explist1(ls, &e); /* optional return values */ nret = explist(ls, &e); /* optional return values */
if (hasmultret(e.k)) { if (hasmultret(e.k)) {
luaK_setmultret(fs, &e); luaK_setmultret(fs, &e);
if (e.k == VCALL && nret == 1) { /* tail call? */ if (e.k == VCALL && nret == 1) { /* tail call? */
@@ -1341,41 +1519,43 @@ static void retstat (LexState *ls) {
} }
} }
luaK_ret(fs, first, nret); luaK_ret(fs, first, nret);
testnext(ls, ';'); /* skip optional semicolon */
} }
static int statement (LexState *ls) { static void statement (LexState *ls) {
int line = ls->linenumber; /* may be needed for error messages */ int line = ls->linenumber; /* may be needed for error messages */
enterlevel(ls);
switch (ls->t.token) { switch (ls->t.token) {
case ';': { /* stat -> ';' (empty statement) */ case ';': { /* stat -> ';' (empty statement) */
luaX_next(ls); /* skip ';' */ luaX_next(ls); /* skip ';' */
return 0; break;
} }
case TK_IF: { /* stat -> ifstat */ case TK_IF: { /* stat -> ifstat */
ifstat(ls, line); ifstat(ls, line);
return 0; break;
} }
case TK_WHILE: { /* stat -> whilestat */ case TK_WHILE: { /* stat -> whilestat */
whilestat(ls, line); whilestat(ls, line);
return 0; break;
} }
case TK_DO: { /* stat -> DO block END */ case TK_DO: { /* stat -> DO block END */
luaX_next(ls); /* skip DO */ luaX_next(ls); /* skip DO */
block(ls); block(ls);
check_match(ls, TK_END, TK_DO, line); check_match(ls, TK_END, TK_DO, line);
return 0; break;
} }
case TK_FOR: { /* stat -> forstat */ case TK_FOR: { /* stat -> forstat */
forstat(ls, line); forstat(ls, line);
return 0; break;
} }
case TK_REPEAT: { /* stat -> repeatstat */ case TK_REPEAT: { /* stat -> repeatstat */
repeatstat(ls, line); repeatstat(ls, line);
return 0; break;
} }
case TK_FUNCTION: { /* stat -> funcstat */ case TK_FUNCTION: { /* stat -> funcstat */
funcstat(ls, line); funcstat(ls, line);
return 0; break;
} }
case TK_LOCAL: { /* stat -> localstat */ case TK_LOCAL: { /* stat -> localstat */
luaX_next(ls); /* skip LOCAL */ luaX_next(ls); /* skip LOCAL */
@@ -1383,39 +1563,58 @@ static int statement (LexState *ls) {
localfunc(ls); localfunc(ls);
else else
localstat(ls); localstat(ls);
return 0; break;
}
case TK_DBCOLON: { /* stat -> label */
luaX_next(ls); /* skip double colon */
labelstat(ls, str_checkname(ls), line);
break;
} }
case TK_RETURN: { /* stat -> retstat */ case TK_RETURN: { /* stat -> retstat */
luaX_next(ls); /* skip RETURN */ luaX_next(ls); /* skip RETURN */
retstat(ls); retstat(ls);
return 1; /* must be last statement */ break;
} }
case TK_BREAK: { /* stat -> breakstat */ case TK_BREAK: /* stat -> breakstat */
luaX_next(ls); /* skip BREAK */ case TK_GOTO: { /* stat -> 'goto' NAME */
breakstat(ls); gotostat(ls, luaK_jump(ls->fs));
return 1; /* must be last statement */ break;
} }
default: { /* stat -> func | assignment */ default: { /* stat -> func | assignment */
exprstat(ls); exprstat(ls);
return 0; break;
} }
} }
} lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
ls->fs->freereg >= ls->fs->nactvar);
ls->fs->freereg = ls->fs->nactvar; /* free registers */
static void chunk (LexState *ls) {
/* chunk -> { stat [`;'] } */
int islast = 0;
enterlevel(ls);
while (!islast && !block_follow(ls->t.token)) {
islast = statement(ls);
if (islast)
testnext(ls, ';');
lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
ls->fs->freereg >= ls->fs->nactvar);
ls->fs->freereg = ls->fs->nactvar; /* free registers */
}
leavelevel(ls); leavelevel(ls);
} }
/* }====================================================================== */ /* }====================================================================== */
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
Dyndata *dyd, const char *name, int firstchar) {
LexState lexstate;
FuncState funcstate;
BlockCnt bl;
TString *tname = luaS_new(L, name);
setsvalue2s(L, L->top, tname); /* push name to protect it */
incr_top(L);
lexstate.buff = buff;
lexstate.dyd = dyd;
dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
luaX_setinput(L, &lexstate, z, tname, firstchar);
open_mainfunc(&lexstate, &funcstate, &bl);
luaX_next(&lexstate); /* read first token */
statlist(&lexstate); /* main body */
check(&lexstate, TK_EOS);
close_func(&lexstate);
L->top--; /* pop name */
lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
/* all scopes should be correctly finished */
lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
return funcstate.f;
}

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lparser.h,v 1.64 2010/07/02 20:42:40 roberto Exp roberto $ ** $Id: lparser.h,v 1.68 2011/02/23 13:13:10 roberto Exp roberto $
** Lua Parser ** Lua Parser
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -53,19 +53,42 @@ typedef struct expdesc {
} expdesc; } expdesc;
typedef struct vardesc { /* description of active local variable */
unsigned short idx; typedef struct Vardesc {
} vardesc; short idx; /* variable index in stack */
} Vardesc;
/* list of all active local variables */ /* description of pending goto statements and label statements */
typedef struct Varlist { typedef struct Labeldesc {
vardesc *actvar; TString *name; /* label identifier */
int nactvar; int pc; /* position in code */
int actvarsize; int line; /* line where it appeared */
} Varlist; lu_byte nactvar; /* local level where it appears in current block */
} Labeldesc;
/* list of labels or gotos */
typedef struct Labellist {
Labeldesc *arr; /* array */
int n; /* number of entries in use */
int size; /* array size */
} Labellist;
/* dynamic structures used by the parser */
typedef struct Dyndata {
struct { /* list of active local variables */
Vardesc *arr;
int n;
int size;
} actvar;
Labellist gt; /* list of pending gotos */
Labellist label; /* list of active labels */
} Dyndata;
/* control of blocks */
struct BlockCnt; /* defined in lparser.c */ struct BlockCnt; /* defined in lparser.c */
@@ -75,23 +98,22 @@ typedef struct FuncState {
Table *h; /* table to find (and reuse) elements in `k' */ Table *h; /* table to find (and reuse) elements in `k' */
struct FuncState *prev; /* enclosing function */ struct FuncState *prev; /* enclosing function */
struct LexState *ls; /* lexical state */ struct LexState *ls; /* lexical state */
struct lua_State *L; /* copy of the Lua state */
struct BlockCnt *bl; /* chain of current blocks */ struct BlockCnt *bl; /* chain of current blocks */
int pc; /* next position to code (equivalent to `ncode') */ int pc; /* next position to code (equivalent to `ncode') */
int lasttarget; /* `pc' of last `jump target' */ int lasttarget; /* 'label' of last 'jump label' */
int jpc; /* list of pending jumps to `pc' */ int jpc; /* list of pending jumps to `pc' */
int freereg; /* first free register */
int nk; /* number of elements in `k' */ int nk; /* number of elements in `k' */
int np; /* number of elements in `p' */ int np; /* number of elements in `p' */
int firstlocal; /* index of first local var of this function */ int firstlocal; /* index of first local var (in Dyndata array) */
short nlocvars; /* number of elements in `locvars' */ short nlocvars; /* number of elements in 'f->locvars' */
lu_byte nactvar; /* number of active local variables */ lu_byte nactvar; /* number of active local variables */
lu_byte nups; /* number of upvalues */ lu_byte nups; /* number of upvalues */
lu_byte freereg; /* first free register */
} FuncState; } FuncState;
LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
Varlist *varl, const char *name); Dyndata *dyd, const char *name, int firstchar);
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstate.c,v 2.85 2010/04/30 18:36:22 roberto Exp roberto $ ** $Id: lstate.c,v 2.91 2011/08/23 17:24:34 roberto Exp roberto $
** Global State ** Global State
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -65,11 +65,14 @@ typedef struct LG {
#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) #define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
/* /*
** maximum number of nested calls made by error-handling function ** set GCdebt to a new value keeping the value (totalbytes + GCdebt)
** invariant
*/ */
#define LUAI_EXTRACALLS 10 void luaE_setdebt (global_State *g, l_mem debt) {
g->totalbytes -= (debt - g->GCdebt);
g->GCdebt = debt;
}
CallInfo *luaE_extendCI (lua_State *L) { CallInfo *luaE_extendCI (lua_State *L) {
@@ -133,10 +136,10 @@ static void init_registry (lua_State *L, global_State *g) {
luaH_resize(L, registry, LUA_RIDX_LAST, 0); luaH_resize(L, registry, LUA_RIDX_LAST, 0);
/* registry[LUA_RIDX_MAINTHREAD] = L */ /* registry[LUA_RIDX_MAINTHREAD] = L */
setthvalue(L, &mt, L); setthvalue(L, &mt, L);
setobj2t(L, luaH_setint(L, registry, LUA_RIDX_MAINTHREAD), &mt); luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt);
/* registry[LUA_RIDX_GLOBALS] = table of globals */ /* registry[LUA_RIDX_GLOBALS] = table of globals */
sethvalue(L, &mt, luaH_new(L)); sethvalue(L, &mt, luaH_new(L));
setobj2t(L, luaH_setint(L, registry, LUA_RIDX_GLOBALS), &mt); luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt);
} }
@@ -154,7 +157,7 @@ static void f_luaopen (lua_State *L, void *ud) {
/* pre-create memory-error message */ /* pre-create memory-error message */
g->memerrmsg = luaS_newliteral(L, MEMERRMSG); g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
luaS_fix(g->memerrmsg); /* it should never be collected */ luaS_fix(g->memerrmsg); /* it should never be collected */
g->GCdebt = 0; g->gcrunning = 1; /* allow gc */
} }
@@ -168,6 +171,7 @@ static void preinit_state (lua_State *L, global_State *g) {
L->ci = NULL; L->ci = NULL;
L->stacksize = 0; L->stacksize = 0;
L->errorJmp = NULL; L->errorJmp = NULL;
L->nCcalls = 0;
L->hook = NULL; L->hook = NULL;
L->hookmask = 0; L->hookmask = 0;
L->basehookcount = 0; L->basehookcount = 0;
@@ -187,8 +191,8 @@ static void close_state (lua_State *L) {
luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
luaZ_freebuffer(L, &g->buff); luaZ_freebuffer(L, &g->buff);
freestack(L); freestack(L);
lua_assert(g->totalbytes == sizeof(LG)); lua_assert(gettotalbytes(g) == sizeof(LG));
(*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */
} }
@@ -234,14 +238,13 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
L->marked = luaC_white(g); L->marked = luaC_white(g);
g->gckind = KGC_NORMAL; g->gckind = KGC_NORMAL;
g->nCcalls = 0;
preinit_state(L, g); preinit_state(L, g);
g->frealloc = f; g->frealloc = f;
g->ud = ud; g->ud = ud;
g->mainthread = L; g->mainthread = L;
g->uvhead.u.l.prev = &g->uvhead; g->uvhead.u.l.prev = &g->uvhead;
g->uvhead.u.l.next = &g->uvhead; g->uvhead.u.l.next = &g->uvhead;
stopgc(g); /* no GC while building state */ g->gcrunning = 0; /* no GC while building state */
g->lastmajormem = 0; g->lastmajormem = 0;
g->strt.size = 0; g->strt.size = 0;
g->strt.nuse = 0; g->strt.nuse = 0;
@@ -252,11 +255,12 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
g->version = lua_version(NULL); g->version = lua_version(NULL);
g->gcstate = GCSpause; g->gcstate = GCSpause;
g->allgc = NULL; g->allgc = NULL;
g->udgc = NULL; g->finobj = NULL;
g->tobefnz = NULL; g->tobefnz = NULL;
g->gray = g->grayagain = NULL; g->gray = g->grayagain = NULL;
g->weak = g->ephemeron = g->allweak = NULL; g->weak = g->ephemeron = g->allweak = NULL;
g->totalbytes = sizeof(LG); g->totalbytes = sizeof(LG);
g->GCdebt = 0;
g->gcpause = LUAI_GCPAUSE; g->gcpause = LUAI_GCPAUSE;
g->gcmajorinc = LUAI_GCMAJOR; g->gcmajorinc = LUAI_GCMAJOR;
g->gcstepmul = LUAI_GCMUL; g->gcstepmul = LUAI_GCMUL;
@@ -275,9 +279,6 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
LUA_API void lua_close (lua_State *L) { LUA_API void lua_close (lua_State *L) {
L = G(L)->mainthread; /* only the main thread can be closed */ L = G(L)->mainthread; /* only the main thread can be closed */
lua_lock(L); lua_lock(L);
luaF_close(L, L->stack); /* close all upvalues for this thread */
luaC_separateudata(L, 1); /* separate all udata with GC metamethods */
lua_assert(L->next == NULL);
luai_userstateclose(L); luai_userstateclose(L);
close_state(L); close_state(L);
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstate.h,v 2.67 2010/09/30 17:21:31 roberto Exp roberto $ ** $Id: lstate.h,v 2.73 2011/08/23 17:24:34 roberto Exp roberto $
** Global State ** Global State
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -32,9 +32,9 @@
** when traversing the respective threads, but the thread may already be ** when traversing the respective threads, but the thread may already be
** dead, while the upvalue is still accessible through closures.) ** dead, while the upvalue is still accessible through closures.)
** **
** Userdata with finalizers are kept in the list g->udgc. ** Objects with finalizers are kept in the list g->finobj.
** **
** The list g->tobefnz links all userdata being finalized. ** The list g->tobefnz links all objects being finalized.
*/ */
@@ -47,8 +47,6 @@ struct lua_longjmp; /* defined in ldo.c */
#define EXTRA_STACK 5 #define EXTRA_STACK 5
#define BASIC_CI_SIZE 8
#define BASIC_STACK_SIZE (2*LUA_MINSTACK) #define BASIC_STACK_SIZE (2*LUA_MINSTACK)
@@ -104,7 +102,6 @@ typedef struct CallInfo {
#define CIST_TAIL (1<<6) /* call was tail called */ #define CIST_TAIL (1<<6) /* call was tail called */
#define ci_func(ci) (clvalue((ci)->func))
#define isLua(ci) ((ci)->callstatus & CIST_LUA) #define isLua(ci) ((ci)->callstatus & CIST_LUA)
@@ -114,18 +111,18 @@ typedef struct CallInfo {
typedef struct global_State { typedef struct global_State {
lua_Alloc frealloc; /* function to reallocate memory */ lua_Alloc frealloc; /* function to reallocate memory */
void *ud; /* auxiliary data to `frealloc' */ void *ud; /* auxiliary data to `frealloc' */
lu_mem totalbytes; /* number of bytes currently allocated */ lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */
l_mem GCdebt; /* when positive, run a GC step */ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
lu_mem lastmajormem; /* memory in use after last major collection */ lu_mem lastmajormem; /* memory in use after last major collection */
stringtable strt; /* hash table for strings */ stringtable strt; /* hash table for strings */
TValue l_registry; TValue l_registry;
unsigned short nCcalls; /* number of nested C calls */
lu_byte currentwhite; lu_byte currentwhite;
lu_byte gcstate; /* state of garbage collector */ lu_byte gcstate; /* state of garbage collector */
lu_byte gckind; /* kind of GC running */ lu_byte gckind; /* kind of GC running */
lu_byte gcrunning; /* true if GC is running */
int sweepstrgc; /* position of sweep in `strt' */ int sweepstrgc; /* position of sweep in `strt' */
GCObject *allgc; /* list of all collectable objects */ GCObject *allgc; /* list of all collectable objects */
GCObject *udgc; /* list of collectable userdata with finalizers */ GCObject *finobj; /* list of collectable objects with finalizers */
GCObject **sweepgc; /* current position of sweep */ GCObject **sweepgc; /* current position of sweep */
GCObject *gray; /* list of gray objects */ GCObject *gray; /* list of gray objects */
GCObject *grayagain; /* list of objects to be traversed atomically */ GCObject *grayagain; /* list of objects to be traversed atomically */
@@ -161,6 +158,7 @@ struct lua_State {
StkId stack; /* stack base */ StkId stack; /* stack base */
int stacksize; int stacksize;
unsigned short nny; /* number of non-yieldable calls in stack */ unsigned short nny; /* number of non-yieldable calls in stack */
unsigned short nCcalls; /* number of nested C calls */
lu_byte hookmask; lu_byte hookmask;
lu_byte allowhook; lu_byte allowhook;
int basehookcount; int basehookcount;
@@ -209,6 +207,10 @@ union GCObject {
#define obj2gco(v) (cast(GCObject *, (v))) #define obj2gco(v) (cast(GCObject *, (v)))
/* actual number of total bytes allocated */
#define gettotalbytes(g) ((g)->totalbytes + (g)->GCdebt)
LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
LUAI_FUNC void luaE_freeCI (lua_State *L); LUAI_FUNC void luaE_freeCI (lua_State *L);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstring.c,v 2.17 2010/04/03 20:24:18 roberto Exp roberto $ ** $Id: lstring.c,v 2.18 2010/05/10 18:23:45 roberto Exp roberto $
** String table (keeps all strings handled by Lua) ** String table (keeps all strings handled by Lua)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -84,8 +84,9 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
o != NULL; o != NULL;
o = gch(o)->next) { o = gch(o)->next) {
TString *ts = rawgco2ts(o); TString *ts = rawgco2ts(o);
if (h == ts->tsv.hash && ts->tsv.len == l && if (h == ts->tsv.hash &&
(memcmp(str, getstr(ts), l) == 0)) { ts->tsv.len == l &&
(memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */ if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */
changewhite(o); /* resurrect it */ changewhite(o); /* resurrect it */
return ts; return ts;

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstrlib.c,v 1.158 2010/11/16 20:39:41 roberto Exp roberto $ ** $Id: lstrlib.c,v 1.172 2011/10/25 12:01:20 roberto Exp roberto $
** Standard library for string operations and pattern-matching ** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -45,7 +45,7 @@ static int str_len (lua_State *L) {
/* translate a relative string position: negative means back from end */ /* translate a relative string position: negative means back from end */
static size_t posrelat (ptrdiff_t pos, size_t len) { static size_t posrelat (ptrdiff_t pos, size_t len) {
if (pos >= 0) return (size_t)pos; if (pos >= 0) return (size_t)pos;
else if (pos == -pos || (size_t)-pos > len) return 0; else if (0u - (size_t)pos > len) return 0;
else return len - ((size_t)-pos) + 1; else return len - ((size_t)-pos) + 1;
} }
@@ -101,15 +101,29 @@ static int str_upper (lua_State *L) {
return 1; return 1;
} }
/* reasonable limit to avoid arithmetic overflow */
#define MAXSIZE ((~(size_t)0) >> 1)
static int str_rep (lua_State *L) { static int str_rep (lua_State *L) {
size_t l; size_t l, lsep;
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l); const char *s = luaL_checklstring(L, 1, &l);
int n = luaL_checkint(L, 2); int n = luaL_checkint(L, 2);
luaL_buffinit(L, &b); const char *sep = luaL_optlstring(L, 3, "", &lsep);
while (n-- > 0) if (n <= 0) lua_pushliteral(L, "");
luaL_addlstring(&b, s, l); else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
luaL_pushresult(&b); return luaL_error(L, "resulting string too large");
else {
size_t totallen = n * l + (n - 1) * lsep;
luaL_Buffer b;
char *p = luaL_buffinitsize(L, &b, totallen);
while (n-- > 1) { /* first n-1 copies (followed by separator) */
memcpy(p, s, l * sizeof(char)); p += l;
memcpy(p, sep, lsep * sizeof(char)); p += lsep;
}
memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
luaL_pushresultsize(&b, totallen);
}
return 1; return 1;
} }
@@ -124,8 +138,8 @@ static int str_byte (lua_State *L) {
if (pose > l) pose = l; if (pose > l) pose = l;
if (posi > pose) return 0; /* empty interval; return no values */ if (posi > pose) return 0; /* empty interval; return no values */
n = (int)(pose - posi + 1); n = (int)(pose - posi + 1);
if (posi + n <= pose) /* overflow? */ if (posi + n <= pose) /* (size_t -> int) overflow? */
luaL_error(L, "string slice too long"); return luaL_error(L, "string slice too long");
luaL_checkstack(L, n, "string slice too long"); luaL_checkstack(L, n, "string slice too long");
for (i=0; i<n; i++) for (i=0; i<n; i++)
lua_pushinteger(L, uchar(s[posi+i-1])); lua_pushinteger(L, uchar(s[posi+i-1]));
@@ -140,7 +154,7 @@ static int str_char (lua_State *L) {
char *p = luaL_buffinitsize(L, &b, n); char *p = luaL_buffinitsize(L, &b, n);
for (i=1; i<=n; i++) { for (i=1; i<=n; i++) {
int c = luaL_checkint(L, i); int c = luaL_checkint(L, i);
luaL_argcheck(L, uchar(c) == c, i, "invalid value"); luaL_argcheck(L, uchar(c) == c, i, "value out of range");
p[i - 1] = uchar(c); p[i - 1] = uchar(c);
} }
luaL_pushresultsize(&b, n); luaL_pushresultsize(&b, n);
@@ -161,7 +175,7 @@ static int str_dump (lua_State *L) {
lua_settop(L, 1); lua_settop(L, 1);
luaL_buffinit(L,&b); luaL_buffinit(L,&b);
if (lua_dump(L, writer, &b) != 0) if (lua_dump(L, writer, &b) != 0)
luaL_error(L, "unable to dump given function"); return luaL_error(L, "unable to dump given function");
luaL_pushresult(&b); luaL_pushresult(&b);
return 1; return 1;
} }
@@ -510,7 +524,7 @@ static int nospecials (const char *p, size_t l) {
size_t upto = 0; size_t upto = 0;
do { do {
if (strpbrk(p + upto, SPECIALS)) if (strpbrk(p + upto, SPECIALS))
return 0; /* pattern has a special character */ return 0; /* pattern has a special character */
upto += strlen(p + upto) + 1; /* may have more after \0 */ upto += strlen(p + upto) + 1; /* may have more after \0 */
} while (upto <= l); } while (upto <= l);
return 1; /* no special chars found */ return 1; /* no special chars found */
@@ -729,7 +743,7 @@ static int str_gsub (lua_State *L) {
** the previous length ** the previous length
*/ */
#if !defined(LUA_INTFRMLEN) /* { */ #if !defined(LUA_INTFRMLEN) /* { */
#if defined(LUA_USELONGLONG) #if defined(LUA_USE_LONGLONG)
#define LUA_INTFRMLEN "ll" #define LUA_INTFRMLEN "ll"
#define LUA_INTFRM_T long long #define LUA_INTFRM_T long long
@@ -742,6 +756,9 @@ static int str_gsub (lua_State *L) {
#endif #endif
#endif /* } */ #endif /* } */
#define MAX_UINTFRM ((lua_Number)(~(unsigned LUA_INTFRM_T)0))
#define MAX_INTFRM ((lua_Number)((~(unsigned LUA_INTFRM_T)0)/2))
#define MIN_INTFRM (-(lua_Number)((~(unsigned LUA_INTFRM_T)0)/2) - 1)
/* /*
** LUA_FLTFRMLEN is the length modifier for float conversions in ** LUA_FLTFRMLEN is the length modifier for float conversions in
@@ -794,7 +811,7 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
const char *p = strfrmt; const char *p = strfrmt;
while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
if ((size_t)(p - strfrmt) >= sizeof(FLAGS)) if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
luaL_error(L, "invalid format (repeated flags)"); luaL_error(L, "invalid format (repeated flags)");
if (isdigit(uchar(*p))) p++; /* skip width */ if (isdigit(uchar(*p))) p++; /* skip width */
if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
@@ -806,7 +823,7 @@ static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
if (isdigit(uchar(*p))) if (isdigit(uchar(*p)))
luaL_error(L, "invalid format (width or precision too long)"); luaL_error(L, "invalid format (width or precision too long)");
*(form++) = '%'; *(form++) = '%';
memcpy(form, strfrmt, p - strfrmt + 1); memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
form += p - strfrmt + 1; form += p - strfrmt + 1;
*form = '\0'; *form = '\0';
return p; return p;
@@ -851,16 +868,26 @@ static int str_format (lua_State *L) {
nb = sprintf(buff, form, luaL_checkint(L, arg)); nb = sprintf(buff, form, luaL_checkint(L, arg));
break; break;
} }
case 'd': case 'i': case 'd': case 'i': {
lua_Number n = luaL_checknumber(L, arg);
luaL_argcheck(L, (MIN_INTFRM - 1) < n && n < (MAX_INTFRM + 1), arg,
"not a number in proper range");
addlenmod(form, LUA_INTFRMLEN);
nb = sprintf(buff, form, (LUA_INTFRM_T)n);
break;
}
case 'o': case 'u': case 'x': case 'X': { case 'o': case 'u': case 'x': case 'X': {
lua_Number n = luaL_checknumber(L, arg); lua_Number n = luaL_checknumber(L, arg);
LUA_INTFRM_T r = (n < 0) ? (LUA_INTFRM_T)n : luaL_argcheck(L, 0 <= n && n < (MAX_UINTFRM + 1), arg,
(LUA_INTFRM_T)(unsigned LUA_INTFRM_T)n; "not a non-negative number in proper range");
addlenmod(form, LUA_INTFRMLEN); addlenmod(form, LUA_INTFRMLEN);
nb = sprintf(buff, form, r); nb = sprintf(buff, form, (unsigned LUA_INTFRM_T)n);
break; break;
} }
case 'e': case 'E': case 'f': case 'e': case 'E': case 'f':
#if defined(LUA_USE_AFORMAT)
case 'a': case 'A':
#endif
case 'g': case 'G': { case 'g': case 'G': {
addlenmod(form, LUA_FLTFRMLEN); addlenmod(form, LUA_FLTFRMLEN);
nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg)); nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
@@ -872,16 +899,16 @@ static int str_format (lua_State *L) {
} }
case 's': { case 's': {
size_t l; size_t l;
const char *s = luaL_checklstring(L, arg, &l); const char *s = luaL_tolstring(L, arg, &l);
if (!strchr(form, '.') && l >= 100) { if (!strchr(form, '.') && l >= 100) {
/* no precision and string is too long to be formatted; /* no precision and string is too long to be formatted;
keep original string */ keep original string */
lua_pushvalue(L, arg);
luaL_addvalue(&b); luaL_addvalue(&b);
break; break;
} }
else { else {
nb = sprintf(buff, form, s); nb = sprintf(buff, form, s);
lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
break; break;
} }
} }
@@ -920,13 +947,13 @@ static const luaL_Reg strlib[] = {
static void createmetatable (lua_State *L) { static void createmetatable (lua_State *L) {
lua_createtable(L, 0, 1); /* create metatable for strings */ lua_createtable(L, 0, 1); /* table to be metatable for strings */
lua_pushliteral(L, ""); /* dummy string */ lua_pushliteral(L, ""); /* dummy string */
lua_pushvalue(L, -2); lua_pushvalue(L, -2); /* copy table */
lua_setmetatable(L, -2); /* set string metatable */ lua_setmetatable(L, -2); /* set table as metatable for strings */
lua_pop(L, 1); /* pop dummy string */ lua_pop(L, 1); /* pop dummy string */
lua_pushvalue(L, -2); /* string library... */ lua_pushvalue(L, -2); /* get string library */
lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */ lua_setfield(L, -2, "__index"); /* metatable.__index = string */
lua_pop(L, 1); /* pop metatable */ lua_pop(L, 1); /* pop metatable */
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltable.c,v 2.52 2010/06/25 12:18:10 roberto Exp roberto $ ** $Id: ltable.c,v 2.66 2011/11/28 17:25:48 roberto Exp roberto $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -33,6 +33,7 @@
#include "lstate.h" #include "lstate.h"
#include "lstring.h" #include "lstring.h"
#include "ltable.h" #include "ltable.h"
#include "lvm.h"
/* /*
@@ -63,13 +64,6 @@
#define hashpointer(t,p) hashmod(t, IntPoint(p)) #define hashpointer(t,p) hashmod(t, IntPoint(p))
/*
** number of ints inside a lua_Number
*/
#define numints cast_int(sizeof(lua_Number)/sizeof(int))
#define dummynode (&dummynode_) #define dummynode (&dummynode_)
#define isdummy(n) ((n) == dummynode) #define isdummy(n) ((n) == dummynode)
@@ -87,8 +81,9 @@ static Node *hashnum (const Table *t, lua_Number n) {
int i; int i;
luai_hashnum(i, n); luai_hashnum(i, n);
if (i < 0) { if (i < 0) {
i = -i; /* must be a positive value */ if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */
if (i < 0) i = 0; /* handle INT_MIN */ i = 0; /* handle INT_MIN */
i = -i; /* must be a positive value */
} }
return hashmod(t, i); return hashmod(t, i);
} }
@@ -146,19 +141,19 @@ static int findindex (lua_State *L, Table *t, StkId key) {
return i-1; /* yes; that's the index (corrected to C) */ return i-1; /* yes; that's the index (corrected to C) */
else { else {
Node *n = mainposition(t, key); Node *n = mainposition(t, key);
do { /* check whether `key' is somewhere in the chain */ for (;;) { /* check whether `key' is somewhere in the chain */
/* key may be dead already, but it is ok to use it in `next' */ /* key may be dead already, but it is ok to use it in `next' */
if (luaO_rawequalObj(gkey(n), key) || if (luaV_rawequalobj(gkey(n), key) ||
(ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && (ttisdeadkey(gkey(n)) && iscollectable(key) &&
gcvalue(gkey(n)) == gcvalue(key))) { deadvalue(gkey(n)) == gcvalue(key))) {
i = cast_int(n - gnode(t, 0)); /* key index in hash table */ i = cast_int(n - gnode(t, 0)); /* key index in hash table */
/* hash elements are numbered after array ones */ /* hash elements are numbered after array ones */
return i + t->sizearray; return i + t->sizearray;
} }
else n = gnext(n); else n = gnext(n);
} while (n); if (n == NULL)
luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
return 0; /* to avoid warnings */ }
} }
} }
@@ -312,7 +307,7 @@ void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
/* re-insert elements from vanishing slice */ /* re-insert elements from vanishing slice */
for (i=nasize; i<oldasize; i++) { for (i=nasize; i<oldasize; i++) {
if (!ttisnil(&t->array[i])) if (!ttisnil(&t->array[i]))
setobjt2t(L, luaH_setint(L, t, i+1), &t->array[i]); luaH_setint(L, t, i + 1, &t->array[i]);
} }
/* shrink array */ /* shrink array */
luaM_reallocvector(L, t->array, oldasize, nasize, TValue); luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
@@ -320,11 +315,14 @@ void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
/* re-insert elements from hash part */ /* re-insert elements from hash part */
for (i = twoto(oldhsize) - 1; i >= 0; i--) { for (i = twoto(oldhsize) - 1; i >= 0; i--) {
Node *old = nold+i; Node *old = nold+i;
if (!ttisnil(gval(old))) if (!ttisnil(gval(old))) {
/* doesn't need barrier/invalidate cache, as entry was
already present in the table */
setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));
}
} }
if (!isdummy(nold)) if (!isdummy(nold))
luaM_freearray(L, nold, twoto(oldhsize)); /* free old array */ luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */
} }
@@ -336,7 +334,7 @@ void luaH_resizearray (lua_State *L, Table *t, int nasize) {
static void rehash (lua_State *L, Table *t, const TValue *ek) { static void rehash (lua_State *L, Table *t, const TValue *ek) {
int nasize, na; int nasize, na;
int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
int i; int i;
int totaluse; int totaluse;
for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
@@ -372,7 +370,7 @@ Table *luaH_new (lua_State *L) {
void luaH_free (lua_State *L, Table *t) { void luaH_free (lua_State *L, Table *t) {
if (!isdummy(t->node)) if (!isdummy(t->node))
luaM_freearray(L, t->node, sizenode(t)); luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
luaM_freearray(L, t->array, t->sizearray); luaM_freearray(L, t->array, t->sizearray);
luaM_free(L, t); luaM_free(L, t);
} }
@@ -396,14 +394,19 @@ static Node *getfreepos (Table *t) {
** put new key in its main position; otherwise (colliding node is in its main ** put new key in its main position; otherwise (colliding node is in its main
** position), new key goes to an empty position. ** position), new key goes to an empty position.
*/ */
static TValue *newkey (lua_State *L, Table *t, const TValue *key) { TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp = mainposition(t, key); Node *mp;
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
luaG_runerror(L, "table index is NaN");
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */ if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
Node *othern; Node *othern;
Node *n = getfreepos(t); /* get a free place */ Node *n = getfreepos(t); /* get a free place */
if (n == NULL) { /* cannot find a free place? */ if (n == NULL) { /* cannot find a free place? */
rehash(L, t, key); /* grow table */ rehash(L, t, key); /* grow table */
return luaH_set(L, t, key); /* re-insert key into grown table */ /* whatever called 'newkey' take care of TM cache and GC barrier */
return luaH_set(L, t, key); /* insert key into grown table */
} }
lua_assert(!isdummy(n)); lua_assert(!isdummy(n));
othern = mainposition(t, gkey(mp)); othern = mainposition(t, gkey(mp));
@@ -467,7 +470,7 @@ const TValue *luaH_getstr (Table *t, TString *key) {
** main search function ** main search function
*/ */
const TValue *luaH_get (Table *t, const TValue *key) { const TValue *luaH_get (Table *t, const TValue *key) {
switch (ttype(key)) { switch (ttypenv(key)) {
case LUA_TNIL: return luaO_nilobject; case LUA_TNIL: return luaO_nilobject;
case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
case LUA_TNUMBER: { case LUA_TNUMBER: {
@@ -481,7 +484,7 @@ const TValue *luaH_get (Table *t, const TValue *key) {
default: { default: {
Node *n = mainposition(t, key); Node *n = mainposition(t, key);
do { /* check whether `key' is somewhere in the chain */ do { /* check whether `key' is somewhere in the chain */
if (luaO_rawequalObj(gkey(n), key)) if (luaV_rawequalobj(gkey(n), key))
return gval(n); /* that's it */ return gval(n); /* that's it */
else n = gnext(n); else n = gnext(n);
} while (n); } while (n);
@@ -491,41 +494,29 @@ const TValue *luaH_get (Table *t, const TValue *key) {
} }
/*
** beware: when using this function you probably need to check a GC
** barrier and invalidate the TM cache.
*/
TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
const TValue *p = luaH_get(t, key); const TValue *p = luaH_get(t, key);
t->flags = 0;
if (p != luaO_nilobject) if (p != luaO_nilobject)
return cast(TValue *, p); return cast(TValue *, p);
else { else return luaH_newkey(L, t, key);
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
luaG_runerror(L, "table index is NaN");
return newkey(L, t, key);
}
} }
TValue *luaH_setint (lua_State *L, Table *t, int key) { void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {
const TValue *p = luaH_getint(t, key); const TValue *p = luaH_getint(t, key);
TValue *cell;
if (p != luaO_nilobject) if (p != luaO_nilobject)
return cast(TValue *, p); cell = cast(TValue *, p);
else { else {
TValue k; TValue k;
setnvalue(&k, cast_num(key)); setnvalue(&k, cast_num(key));
return newkey(L, t, &k); cell = luaH_newkey(L, t, &k);
}
}
TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
const TValue *p = luaH_getstr(t, key);
if (p != luaO_nilobject)
return cast(TValue *, p);
else {
TValue k;
setsvalue(L, &k, key);
return newkey(L, t, &k);
} }
setobj2t(L, cell, value);
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltable.h,v 2.13 2009/11/06 17:07:48 roberto Exp roberto $ ** $Id: ltable.h,v 2.15 2011/08/09 20:58:29 roberto Exp roberto $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -15,12 +15,14 @@
#define gval(n) (&(n)->i_val) #define gval(n) (&(n)->i_val)
#define gnext(n) ((n)->i_key.nk.next) #define gnext(n) ((n)->i_key.nk.next)
#define invalidateTMcache(t) ((t)->flags = 0)
LUAI_FUNC const TValue *luaH_getint (Table *t, int key); LUAI_FUNC const TValue *luaH_getint (Table *t, int key);
LUAI_FUNC TValue *luaH_setint (lua_State *L, Table *t, int key); LUAI_FUNC void luaH_setint (lua_State *L, Table *t, int key, TValue *value);
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key);
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
LUAI_FUNC Table *luaH_new (lua_State *L); LUAI_FUNC Table *luaH_new (lua_State *L);
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize); LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize);

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltablib.c,v 1.57 2010/10/25 19:01:37 roberto Exp roberto $ ** $Id: ltablib.c,v 1.62 2011/09/30 12:45:45 roberto Exp roberto $
** Library for Table Manipulation ** Library for Table Manipulation
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -17,12 +17,7 @@
#define aux_getn(L,n) \ #define aux_getn(L,n) \
(luaL_checktype(L, n, LUA_TTABLE), (int)lua_rawlen(L, n)) (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))
static int deprecatedfunc (lua_State *L) {
return luaL_error(L, "deprecated function");
}
#if defined(LUA_COMPAT_MAXN) #if defined(LUA_COMPAT_MAXN)
@@ -40,8 +35,6 @@ static int maxn (lua_State *L) {
lua_pushnumber(L, max); lua_pushnumber(L, max);
return 1; return 1;
} }
#else
#define maxn deprecatedfunc
#endif #endif
@@ -93,7 +86,7 @@ static void addfield (lua_State *L, luaL_Buffer *b, int i) {
if (!lua_isstring(L, -1)) if (!lua_isstring(L, -1))
luaL_error(L, "invalid value (%s) at index %d in table for " luaL_error(L, "invalid value (%s) at index %d in table for "
LUA_QL("concat"), luaL_typename(L, -1), i); LUA_QL("concat"), luaL_typename(L, -1), i);
luaL_addvalue(b); luaL_addvalue(b);
} }
@@ -104,7 +97,7 @@ static int tconcat (lua_State *L) {
const char *sep = luaL_optlstring(L, 2, "", &lsep); const char *sep = luaL_optlstring(L, 2, "", &lsep);
luaL_checktype(L, 1, LUA_TTABLE); luaL_checktype(L, 1, LUA_TTABLE);
i = luaL_optint(L, 3, 1); i = luaL_optint(L, 3, 1);
last = luaL_opt(L, luaL_checkint, 4, (int)lua_rawlen(L, 1)); last = luaL_opt(L, luaL_checkint, 4, luaL_len(L, 1));
luaL_buffinit(L, &b); luaL_buffinit(L, &b);
for (; i < last; i++) { for (; i < last; i++) {
addfield(L, &b, i); addfield(L, &b, i);
@@ -124,18 +117,19 @@ static int tconcat (lua_State *L) {
*/ */
static int pack (lua_State *L) { static int pack (lua_State *L) {
int top = lua_gettop(L); int n = lua_gettop(L); /* number of elements to pack */
lua_createtable(L, top, 1); /* create result table */ lua_createtable(L, n, 1); /* create result table */
lua_pushinteger(L, top); /* number of elements */ lua_pushinteger(L, n);
lua_setfield(L, -2, "n"); /* t.n = number of elements */ lua_setfield(L, -2, "n"); /* t.n = number of elements */
if (top > 0) { /* at least one element? */ if (n > 0) { /* at least one element? */
int i;
lua_pushvalue(L, 1); lua_pushvalue(L, 1);
lua_rawseti(L, -2, 1); /* insert first element */ lua_rawseti(L, -2, 1); /* insert first element */
lua_replace(L, 1); /* move table into its position (index 1) */ lua_replace(L, 1); /* move table into index 1 */
for (; top >= 2; top--) /* assign other elements */ for (i = n; i >= 2; i--) /* assign other elements */
lua_rawseti(L, 1, top); lua_rawseti(L, 1, i);
} }
return 1; return 1; /* return table */
} }
@@ -143,7 +137,7 @@ static int unpack (lua_State *L) {
int i, e, n; int i, e, n;
luaL_checktype(L, 1, LUA_TTABLE); luaL_checktype(L, 1, LUA_TTABLE);
i = luaL_optint(L, 2, 1); i = luaL_optint(L, 2, 1);
e = luaL_opt(L, luaL_checkint, 3, (int)lua_rawlen(L, 1)); e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1));
if (i > e) return 0; /* empty range */ if (i > e) return 0; /* empty range */
n = e - i + 1; /* number of elements */ n = e - i + 1; /* number of elements */
if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */ if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */
@@ -265,10 +259,9 @@ static int sort (lua_State *L) {
static const luaL_Reg tab_funcs[] = { static const luaL_Reg tab_funcs[] = {
{"concat", tconcat}, {"concat", tconcat},
{"foreach", deprecatedfunc}, #if defined(LUA_COMPAT_MAXN)
{"foreachi", deprecatedfunc},
{"getn", deprecatedfunc},
{"maxn", maxn}, {"maxn", maxn},
#endif
{"insert", tinsert}, {"insert", tinsert},
{"pack", pack}, {"pack", pack},
{"unpack", unpack}, {"unpack", unpack},

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltests.c,v 2.112 2010/07/28 15:51:59 roberto Exp roberto $ ** $Id: ltests.c,v 2.123 2011/09/24 21:11:29 roberto Exp roberto $
** Internal Module for Debugging of the Lua Implementation ** Internal Module for Debugging of the Lua Implementation
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -83,7 +83,7 @@ typedef union Header {
} Header; } Header;
#ifndef EXTERNMEMCHECK #if !defined(EXTERNMEMCHECK)
/* full memory check */ /* full memory check */
#define MARKSIZE 16 /* size of marks after each block */ #define MARKSIZE 16 /* size of marks after each block */
@@ -215,7 +215,8 @@ static int testobjref (global_State *g, GCObject *f, GCObject *t) {
static void checkvalref (global_State *g, GCObject *f, const TValue *t) { static void checkvalref (global_State *g, GCObject *f, const TValue *t) {
if (iscollectable(t)) { if (iscollectable(t)) {
lua_assert(righttt(t) && testobjref(g, f, gcvalue(t))); lua_assert(righttt(t));
lua_assert(testobjref(g, f, gcvalue(t)));
} }
} }
@@ -290,7 +291,7 @@ static void checkclosure (global_State *g, Closure *cl) {
static int lua_checkpc (pCallInfo ci) { static int lua_checkpc (pCallInfo ci) {
if (!isLua(ci)) return 1; if (!isLua(ci)) return 1;
else { else {
Proto *p = ci_func(ci)->l.p; Proto *p = ci_func(ci)->p;
return p->code <= ci->u.l.savedpc && return p->code <= ci->u.l.savedpc &&
ci->u.l.savedpc <= p->code + p->sizecode; ci->u.l.savedpc <= p->code + p->sizecode;
} }
@@ -367,7 +368,7 @@ static void checkgraylist (GCObject *l) {
while (l) { while (l) {
lua_assert(isgray(l)); lua_assert(isgray(l));
lua_assert(!testbit(l->gch.marked, TESTGRAYBIT)); lua_assert(!testbit(l->gch.marked, TESTGRAYBIT));
l->gch.marked = l_setbit(l->gch.marked, TESTGRAYBIT); l_setbit(l->gch.marked, TESTGRAYBIT);
switch (gch(l)->tt) { switch (gch(l)->tt) {
case LUA_TTABLE: l = gco2t(l)->gclist; break; case LUA_TTABLE: l = gco2t(l)->gclist; break;
case LUA_TFUNCTION: l = gco2cl(l)->c.gclist; break; case LUA_TFUNCTION: l = gco2cl(l)->c.gclist; break;
@@ -404,7 +405,7 @@ static void checkold (global_State *g, GCObject *o) {
else lua_assert(!isold); /* non-old object cannot be after an old one */ else lua_assert(!isold); /* non-old object cannot be after an old one */
if (isgray(o)) { if (isgray(o)) {
lua_assert(!keepinvariant(g) || testbit(o->gch.marked, TESTGRAYBIT)); lua_assert(!keepinvariant(g) || testbit(o->gch.marked, TESTGRAYBIT));
o->gch.marked = resetbit(o->gch.marked, TESTGRAYBIT); resetbit(o->gch.marked, TESTGRAYBIT);
} }
lua_assert(!testbit(o->gch.marked, TESTGRAYBIT)); lua_assert(!testbit(o->gch.marked, TESTGRAYBIT));
} }
@@ -421,7 +422,7 @@ int lua_checkmemory (lua_State *L) {
} }
lua_assert(!isdead(g, gcvalue(&g->l_registry))); lua_assert(!isdead(g, gcvalue(&g->l_registry)));
checkstack(g, g->mainthread); checkstack(g, g->mainthread);
g->mainthread->marked = resetbit(g->mainthread->marked, TESTGRAYBIT); resetbit(g->mainthread->marked, TESTGRAYBIT);
/* check 'allgc' list */ /* check 'allgc' list */
markgrays(g); markgrays(g);
checkold(g, g->allgc); checkold(g, g->allgc);
@@ -429,20 +430,21 @@ int lua_checkmemory (lua_State *L) {
checkobject(g, o); checkobject(g, o);
lua_assert(!testbit(o->gch.marked, SEPARATED)); lua_assert(!testbit(o->gch.marked, SEPARATED));
} }
/* check 'udgc' list */ /* check 'finobj' list */
checkold(g, g->udgc); checkold(g, g->finobj);
for (o = g->udgc; o != NULL; o = gch(o)->next) { for (o = g->finobj; o != NULL; o = gch(o)->next) {
lua_assert(gch(o)->tt == LUA_TUSERDATA && lua_assert(!isdead(g, o) && testbit(o->gch.marked, SEPARATED));
!isdead(g, o) && lua_assert(gch(o)->tt == LUA_TUSERDATA ||
testbit(o->gch.marked, SEPARATED)); gch(o)->tt == LUA_TTABLE);
checkobject(g, o); checkobject(g, o);
} }
/* check 'tobefnz' list */ /* check 'tobefnz' list */
checkold(g, g->tobefnz); checkold(g, g->tobefnz);
for (o = g->tobefnz; o != NULL; o = gch(o)->next) { for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
lua_assert(gch(o)->tt == LUA_TUSERDATA); lua_assert(!iswhite(o));
lua_assert(isblack(o)); lua_assert(!isdead(g, o) && testbit(o->gch.marked, SEPARATED));
lua_assert(testbit(o->gch.marked, SEPARATED)); lua_assert(gch(o)->tt == LUA_TUSERDATA ||
gch(o)->tt == LUA_TTABLE);
} }
/* check 'uvhead' list */ /* check 'uvhead' list */
for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
@@ -593,7 +595,10 @@ static int mem_query (lua_State *L) {
static int settrick (lua_State *L) { static int settrick (lua_State *L) {
l_Trick = gcvalue(obj_at(L, 1)); if (ttisnil(obj_at(L, 1)))
l_Trick = NULL;
else
l_Trick = gcvalue(obj_at(L, 1));
return 0; return 0;
} }
@@ -775,7 +780,7 @@ static int newuserdata (lua_State *L) {
static int pushuserdata (lua_State *L) { static int pushuserdata (lua_State *L) {
lua_pushlightuserdata(L, cast(void *, luaL_checkint(L, 1))); lua_pushlightuserdata(L, cast(void *, luaL_checkinteger(L, 1)));
return 1; return 1;
} }
@@ -852,7 +857,7 @@ static int loadlib (lua_State *L) {
lua_State *L1 = getstate(L); lua_State *L1 = getstate(L);
int i; int i;
luaL_requiref(L1, "package", luaopen_package, 1); luaL_requiref(L1, "package", luaopen_package, 1);
luaL_findtable(L1, LUA_REGISTRYINDEX, "_PRELOAD"); luaL_getsubtable(L1, LUA_REGISTRYINDEX, "_PRELOAD");
for (i = 0; libs[i].name; i++) { for (i = 0; libs[i].name; i++) {
lua_pushcfunction(L1, libs[i].func); lua_pushcfunction(L1, libs[i].func);
lua_setfield(L1, -2, libs[i].name); lua_setfield(L1, -2, libs[i].name);
@@ -936,9 +941,9 @@ static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {
sig = -1; sig = -1;
(*pc)++; (*pc)++;
} }
if (!lisdigit(cast(unsigned char, **pc))) if (!lisdigit(cast_uchar(**pc)))
luaL_error(L, "number expected (%s)", *pc); luaL_error(L, "number expected (%s)", *pc);
while (lisdigit(cast(unsigned char, **pc))) res = res*10 + (*(*pc)++) - '0'; while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';
return sig*res; return sig*res;
} }
@@ -1208,7 +1213,7 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
} }
else if EQ("resume") { else if EQ("resume") {
int i = getindex; int i = getindex;
status = lua_resume(lua_tothread(L1, i), getnum); status = lua_resume(lua_tothread(L1, i), L, getnum);
} }
else if EQ("pushstatus") { else if EQ("pushstatus") {
pushcode(L1, status); pushcode(L1, status);
@@ -1252,7 +1257,8 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
lua_pushinteger(L1, i); lua_pushinteger(L1, i);
} }
else if EQ("checkstack") { else if EQ("checkstack") {
luaL_checkstack(L1, getnum, NULL); int sz = getnum;
luaL_checkstack(L1, sz, getstring);
} }
else if EQ("newmetatable") { else if EQ("newmetatable") {
lua_pushboolean(L1, luaL_newmetatable(L1, getstring)); lua_pushboolean(L1, luaL_newmetatable(L1, getstring));
@@ -1395,7 +1401,7 @@ static int coresume (lua_State *L) {
int status; int status;
lua_State *co = lua_tothread(L, 1); lua_State *co = lua_tothread(L, 1);
luaL_argcheck(L, co, 1, "coroutine expected"); luaL_argcheck(L, co, 1, "coroutine expected");
status = lua_resume(co, 0); status = lua_resume(co, L, 0);
if (status != LUA_OK && status != LUA_YIELD) { if (status != LUA_OK && status != LUA_YIELD) {
lua_pushboolean(L, 0); lua_pushboolean(L, 0);
lua_insert(L, -2); lua_insert(L, -2);

8
ltm.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltm.c,v 2.11 2010/01/13 16:18:25 roberto Exp roberto $ ** $Id: ltm.c,v 2.13 2011/02/28 17:32:10 roberto Exp roberto $
** Tag methods ** Tag methods
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -21,11 +21,11 @@
static const char udatatypename[] = "userdata"; static const char udatatypename[] = "userdata";
LUAI_DDEF const char *const luaT_typenames_[] = { LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = {
"no value", "no value",
"nil", "boolean", udatatypename, "number", "nil", "boolean", udatatypename, "number",
"string", "table", "function", udatatypename, "thread", "string", "table", "function", udatatypename, "thread",
"proto", "upval" "proto", "upval" /* these last two cases are used for tests only */
}; };
@@ -62,7 +62,7 @@ const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) { const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
Table *mt; Table *mt;
switch (ttype(o)) { switch (ttypenv(o)) {
case LUA_TTABLE: case LUA_TTABLE:
mt = hvalue(o)->metatable; mt = hvalue(o)->metatable;
break; break;

4
ltm.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltm.h,v 2.9 2010/01/13 16:18:25 roberto Exp roberto $ ** $Id: ltm.h,v 2.10 2010/04/13 20:48:12 roberto Exp roberto $
** Tag methods ** Tag methods
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -46,7 +46,7 @@ typedef enum {
#define ttypename(x) luaT_typenames_[(x) + 1] #define ttypename(x) luaT_typenames_[(x) + 1]
#define objtypename(x) ttypename(ttypenv(x)) #define objtypename(x) ttypename(ttypenv(x))
LUAI_DDEC const char *const luaT_typenames_[]; LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];
LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);

61
lua.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lua.c,v 1.193 2010/10/18 16:06:33 roberto Exp roberto $ ** $Id: lua.c,v 1.202 2011/08/17 20:19:52 roberto Exp roberto $
** Lua stand-alone interpreter ** Lua stand-alone interpreter
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -106,13 +106,11 @@ static void laction (int i) {
static void print_usage (const char *badoption) { static void print_usage (const char *badoption) {
if (badoption[1] == 'e' || badoption[1] == 'l') { luai_writestringerror("%s: ", progname);
luai_writestringerror("%s: ", progname); if (badoption[1] == 'e' || badoption[1] == 'l')
luai_writestringerror("'%s' needs argument\n", badoption); luai_writestringerror("'%s' needs argument\n", badoption);
} else { else
luai_writestringerror("%s: ", progname);
luai_writestringerror("unrecognized option '%s'\n", badoption); luai_writestringerror("unrecognized option '%s'\n", badoption);
}
luai_writestringerror( luai_writestringerror(
"usage: %s [options] [script [args]]\n" "usage: %s [options] [script [args]]\n"
"Available options are:\n" "Available options are:\n"
@@ -120,6 +118,7 @@ static void print_usage (const char *badoption) {
" -i enter interactive mode after executing " LUA_QL("script") "\n" " -i enter interactive mode after executing " LUA_QL("script") "\n"
" -l name require library " LUA_QL("name") "\n" " -l name require library " LUA_QL("name") "\n"
" -v show version information\n" " -v show version information\n"
" -E ignore environment variables\n"
" -- stop handling options\n" " -- stop handling options\n"
" - stop handling options and execute stdin\n" " - stop handling options and execute stdin\n"
, ,
@@ -185,7 +184,8 @@ static int docall (lua_State *L, int narg, int nres) {
static void print_version (void) { static void print_version (void) {
printf("%s\n", LUA_COPYRIGHT); luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
luai_writeline();
} }
@@ -247,14 +247,14 @@ static const char *get_prompt (lua_State *L, int firstline) {
} }
/* mark in error messages for incomplete statements */ /* mark in error messages for incomplete statements */
#define mark "<eof>" #define EOFMARK "<eof>"
#define marklen (sizeof(mark) - 1) #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
static int incomplete (lua_State *L, int status) { static int incomplete (lua_State *L, int status) {
if (status == LUA_ERRSYNTAX) { if (status == LUA_ERRSYNTAX) {
size_t lmsg; size_t lmsg;
const char *msg = lua_tolstring(L, -1, &lmsg); const char *msg = lua_tolstring(L, -1, &lmsg);
if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) { if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
lua_pop(L, 1); lua_pop(L, 1);
return 1; return 1;
} }
@@ -322,7 +322,7 @@ static void dotty (lua_State *L) {
} }
} }
lua_settop(L, 0); /* clear stack */ lua_settop(L, 0); /* clear stack */
luai_writestring("\n", 1); luai_writeline();
progname = oldprogname; progname = oldprogname;
} }
@@ -349,7 +349,16 @@ static int handle_script (lua_State *L, char **argv, int n) {
#define noextrachars(x) {if ((x)[2] != '\0') return -1;} #define noextrachars(x) {if ((x)[2] != '\0') return -1;}
static int collectargs (char **argv, int *pi, int *pv, int *pe) { /* indices of various argument indicators in array args */
#define has_i 0 /* -i */
#define has_v 1 /* -v */
#define has_e 2 /* -e */
#define has_E 3 /* -E */
#define num_has 4 /* number of 'has_*' */
static int collectargs (char **argv, int *args) {
int i; int i;
for (i = 1; argv[i] != NULL; i++) { for (i = 1; argv[i] != NULL; i++) {
if (argv[i][0] != '-') /* not an option? */ if (argv[i][0] != '-') /* not an option? */
@@ -360,15 +369,18 @@ static int collectargs (char **argv, int *pi, int *pv, int *pe) {
return (argv[i+1] != NULL ? i+1 : 0); return (argv[i+1] != NULL ? i+1 : 0);
case '\0': case '\0':
return i; return i;
case 'E':
args[has_E] = 1;
break;
case 'i': case 'i':
noextrachars(argv[i]); noextrachars(argv[i]);
*pi = 1; /* go through */ args[has_i] = 1; /* go through */
case 'v': case 'v':
noextrachars(argv[i]); noextrachars(argv[i]);
*pv = 1; args[has_v] = 1;
break; break;
case 'e': case 'e':
*pe = 1; /* go through */ args[has_e] = 1; /* go through */
case 'l': /* both options need an argument */ case 'l': /* both options need an argument */
if (argv[i][2] == '\0') { /* no concatenated argument? */ if (argv[i][2] == '\0') { /* no concatenated argument? */
i++; /* try next 'argv' */ i++; /* try next 'argv' */
@@ -431,28 +443,33 @@ static int pmain (lua_State *L) {
int argc = (int)lua_tointeger(L, 1); int argc = (int)lua_tointeger(L, 1);
char **argv = (char **)lua_touserdata(L, 2); char **argv = (char **)lua_touserdata(L, 2);
int script; int script;
int has_i = 0, has_v = 0, has_e = 0; int args[num_has];
args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
if (argv[0] && argv[0][0]) progname = argv[0]; if (argv[0] && argv[0][0]) progname = argv[0];
script = collectargs(argv, &has_i, &has_v, &has_e); script = collectargs(argv, args);
if (script < 0) { /* invalid arg? */ if (script < 0) { /* invalid arg? */
print_usage(argv[-script]); print_usage(argv[-script]);
return 0; return 0;
} }
if (has_v) print_version(); if (args[has_v]) print_version();
if (args[has_E]) { /* option '-E'? */
lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
}
/* open standard libraries */ /* open standard libraries */
luaL_checkversion(L); luaL_checkversion(L);
lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
luaL_openlibs(L); /* open libraries */ luaL_openlibs(L); /* open libraries */
lua_gc(L, LUA_GCRESTART, 0); lua_gc(L, LUA_GCRESTART, 0);
/* run LUA_INIT */ if (!args[has_E] && handle_luainit(L) != LUA_OK)
if (handle_luainit(L) != LUA_OK) return 0; return 0; /* error running LUA_INIT */
/* execute arguments -e and -l */ /* execute arguments -e and -l */
if (!runargs(L, argv, (script > 0) ? script : argc)) return 0; if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
/* execute main script (if there is one) */ /* execute main script (if there is one) */
if (script && handle_script(L, argv, script) != LUA_OK) return 0; if (script && handle_script(L, argv, script) != LUA_OK) return 0;
if (has_i) /* -i option? */ if (args[has_i]) /* -i option? */
dotty(L); dotty(L);
else if (script == 0 && !has_e && !has_v) { /* no arguments? */ else if (script == 0 && !args[has_e] && !args[has_v]) { /* no arguments? */
if (lua_stdin_is_tty()) { if (lua_stdin_is_tty()) {
print_version(); print_version();
dotty(L); dotty(L);

24
lua.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lua.h,v 1.275 2010/10/25 20:31:11 roberto Exp roberto $ ** $Id: lua.h,v 1.281 2011/10/24 16:53:05 roberto Exp roberto $
** Lua - A Scripting Language ** Lua - A Scripting Language
** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
** See Copyright Notice at the end of this file ** See Copyright Notice at the end of this file
@@ -18,12 +18,12 @@
#define LUA_VERSION_MAJOR "5" #define LUA_VERSION_MAJOR "5"
#define LUA_VERSION_MINOR "2" #define LUA_VERSION_MINOR "2"
#define LUA_VERSION_NUM 502
#define LUA_VERSION_RELEASE "0" #define LUA_VERSION_RELEASE "0"
#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR #define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE #define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
#define LUA_VERSION_NUM 502 #define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2011 Lua.org, PUC-Rio"
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2010 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
@@ -215,10 +215,12 @@ LUA_API int (lua_pushthread) (lua_State *L);
/* /*
** get functions (Lua -> stack) ** get functions (Lua -> stack)
*/ */
LUA_API void (lua_getglobal) (lua_State *L, const char *var);
LUA_API void (lua_gettable) (lua_State *L, int idx); LUA_API void (lua_gettable) (lua_State *L, int idx);
LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k);
LUA_API void (lua_rawget) (lua_State *L, int idx); LUA_API void (lua_rawget) (lua_State *L, int idx);
LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n);
LUA_API void (lua_rawgetp) (lua_State *L, int idx, const void *p);
LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
LUA_API int (lua_getmetatable) (lua_State *L, int objindex); LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
@@ -228,10 +230,12 @@ LUA_API void (lua_getuservalue) (lua_State *L, int idx);
/* /*
** set functions (stack -> Lua) ** set functions (stack -> Lua)
*/ */
LUA_API void (lua_setglobal) (lua_State *L, const char *var);
LUA_API void (lua_settable) (lua_State *L, int idx); LUA_API void (lua_settable) (lua_State *L, int idx);
LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);
LUA_API void (lua_rawset) (lua_State *L, int idx); LUA_API void (lua_rawset) (lua_State *L, int idx);
LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); LUA_API void (lua_rawseti) (lua_State *L, int idx, int n);
LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);
LUA_API int (lua_setmetatable) (lua_State *L, int objindex); LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
LUA_API void (lua_setuservalue) (lua_State *L, int idx); LUA_API void (lua_setuservalue) (lua_State *L, int idx);
@@ -250,7 +254,8 @@ LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) #define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
const char *chunkname); const char *chunkname,
const char *mode);
LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
@@ -261,7 +266,7 @@ LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx, LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx,
lua_CFunction k); lua_CFunction k);
#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) #define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)
LUA_API int (lua_resume) (lua_State *L, int narg); LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);
LUA_API int (lua_status) (lua_State *L); LUA_API int (lua_status) (lua_State *L);
/* /*
@@ -314,13 +319,6 @@ LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
#define lua_newtable(L) lua_createtable(L, 0, 0) #define lua_newtable(L) lua_createtable(L, 0, 0)
#define lua_setglobal(L,s) \
(lua_pushglobaltable(L), lua_pushvalue(L, -2), \
lua_setfield(L, -2, (s)), lua_pop(L, 2))
#define lua_getglobal(L,s) \
(lua_pushglobaltable(L), lua_getfield(L, -1, (s)), lua_remove(L, -2))
#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) #define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) #define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
@@ -415,7 +413,7 @@ struct lua_Debug {
/****************************************************************************** /******************************************************************************
* Copyright (C) 1994-2010 Lua.org, PUC-Rio. All rights reserved. * Copyright (C) 1994-2011 Lua.org, PUC-Rio. All rights reserved.
* *
* Permission is hereby granted, free of charge, to any person obtaining * Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the * a copy of this software and associated documentation files (the

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: luaconf.h,v 1.150 2010/11/10 17:38:10 roberto Exp roberto $ ** $Id: luaconf.h,v 1.169 2011/11/30 12:35:05 roberto Exp roberto $
** Configuration file for Lua ** Configuration file for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -29,12 +29,13 @@
#endif #endif
#if !defined(LUA_ANSI) && defined(_WIN32) #if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE)
#define LUA_WIN #define LUA_WIN /* enable goodies for regular Windows platforms */
#endif #endif
#if defined(LUA_WIN) #if defined(LUA_WIN)
#define LUA_DL_DLL #define LUA_DL_DLL
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#endif #endif
@@ -43,12 +44,18 @@
#define LUA_USE_POSIX #define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ #define LUA_USE_DLOPEN /* needs an extra library: -ldl */
#define LUA_USE_READLINE /* needs some extra libraries */ #define LUA_USE_READLINE /* needs some extra libraries */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hexa formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */
#endif #endif
#if defined(LUA_USE_MACOSX) #if defined(LUA_USE_MACOSX)
#define LUA_USE_POSIX #define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* does not need -ldl */ #define LUA_USE_DLOPEN /* does not need -ldl */
#define LUA_USE_READLINE /* needs an extra library: -lreadline */ #define LUA_USE_READLINE /* needs an extra library: -lreadline */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hexa formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */
#endif #endif
@@ -63,6 +70,7 @@
#define LUA_USE_ISATTY #define LUA_USE_ISATTY
#define LUA_USE_POPEN #define LUA_USE_POPEN
#define LUA_USE_ULONGJMP #define LUA_USE_ULONGJMP
#define LUA_USE_GMTIME_R
#endif #endif
@@ -166,13 +174,8 @@
** give a warning about it. To avoid these warnings, change to the ** give a warning about it. To avoid these warnings, change to the
** default definition. ** default definition.
*/ */
#if defined(luaall_c) /* { */ #if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
#define LUAI_FUNC static defined(__ELF__) /* { */
#define LUAI_DDEC static
#define LUAI_DDEF static
#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
defined(__ELF__)
#define LUAI_FUNC __attribute__((visibility("hidden"))) extern #define LUAI_FUNC __attribute__((visibility("hidden"))) extern
#define LUAI_DDEC LUAI_FUNC #define LUAI_DDEC LUAI_FUNC
#define LUAI_DDEF /* empty */ #define LUAI_DDEF /* empty */
@@ -202,10 +205,15 @@
/* /*
@@ luai_writestring defines how 'print' prints its results. @@ luai_writestring/luai_writeline define how 'print' prints its results.
** They are only used in libraries and the stand-alone program. (The #if
** avoids including 'stdio.h' everywhere.)
*/ */
#if defined(LUA_LIB) || defined(lua_c)
#include <stdio.h> #include <stdio.h>
#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) #define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout))
#endif
/* /*
@@ luai_writestringerror defines how to print error messages. @@ luai_writestringerror defines how to print error messages.
@@ -237,6 +245,12 @@
*/ */
#define LUA_COMPAT_UNPACK #define LUA_COMPAT_UNPACK
/*
@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'.
** You can replace it with 'package.searchers'.
*/
#define LUA_COMPAT_LOADERS
/* /*
@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall. @@ macro 'lua_cpcall' emulates deprecated function lua_cpcall.
** You can call your C function directly (with light C functions). ** You can call your C function directly (with light C functions).
@@ -253,6 +267,12 @@
*/ */
#define LUA_COMPAT_LOG10 #define LUA_COMPAT_LOG10
/*
@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base
** library. You can rewrite 'loadstring(s)' as 'load(s)'.
*/
#define LUA_COMPAT_LOADSTRING
/* /*
@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library. @@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.
*/ */
@@ -371,21 +391,34 @@
@@ LUA_NUMBER_FMT is the format for writing numbers. @@ LUA_NUMBER_FMT is the format for writing numbers.
@@ lua_number2str converts a number to a string. @@ lua_number2str converts a number to a string.
@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. @@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
@@ lua_str2number converts a string to a number.
*/ */
#define LUA_NUMBER_SCAN "%lf" #define LUA_NUMBER_SCAN "%lf"
#define LUA_NUMBER_FMT "%.14g" #define LUA_NUMBER_FMT "%.14g"
#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) #define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ #define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */
/*
@@ lua_str2number converts a decimal numeric string to a number.
@@ lua_strx2number converts an hexadecimal numeric string to a number.
** In C99, 'strtod' do both conversions. C89, however, has no function
** to convert floating hexadecimal strings to numbers. For these
** systems, you can leave 'lua_strx2number' undefined and Lua will
** provide its own implementation.
*/
#define lua_str2number(s,p) strtod((s), (p)) #define lua_str2number(s,p) strtod((s), (p))
#if defined(LUA_USE_STRTODHEX)
#define lua_strx2number(s,p) strtod((s), (p))
#endif
/* /*
@@ The luai_num* macros define the primitive operations over numbers. @@ The luai_num* macros define the primitive operations over numbers.
*/ */
/* the following operations need the math library */ /* the following operations need the math library */
#if defined(lobject_c) || defined(lvm_c) || defined(luaall_c) #if defined(lobject_c) || defined(lvm_c)
#include <math.h> #include <math.h>
#define luai_nummod(L,a,b) ((a) - floor((a)/(b))*(b)) #define luai_nummod(L,a,b) ((a) - floor((a)/(b))*(b))
#define luai_numpow(L,a,b) (pow(a,b)) #define luai_numpow(L,a,b) (pow(a,b))
@@ -426,7 +459,7 @@
/* On a Microsoft compiler on a Pentium, use assembler to avoid clashes /* On a Microsoft compiler on a Pentium, use assembler to avoid clashes
with a DirectX idiosyncrasy */ with a DirectX idiosyncrasy */
#if defined(_MSC_VER) && defined(M_IX86) /* { */ #if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */
#define MS_ASMTRICK #define MS_ASMTRICK
@@ -438,11 +471,11 @@
/* /*
@@ LUA_IEEEENDIAN is the endianness of doubles in your machine @@ LUA_IEEEENDIAN is the endianness of doubles in your machine
@@ (0 for little endian, 1 for big endian); if not defined, Lua will ** (0 for little endian, 1 for big endian); if not defined, Lua will
@@ check it dynamically. ** check it dynamically.
*/ */
/* check for known architectures */ /* check for known architectures */
#if defined(__i386__) || defined(__i386) || defined(i386) || \ #if defined(__i386__) || defined(__i386) || defined(__X86__) || \
defined (__x86_64) defined (__x86_64)
#define LUA_IEEEENDIAN 0 #define LUA_IEEEENDIAN 0
#elif defined(__POWERPC__) || defined(__ppc__) #elif defined(__POWERPC__) || defined(__ppc__)
@@ -458,6 +491,29 @@
/* }================================================================== */ /* }================================================================== */
/*
@@ LUA_NANTRICK_LE/LUA_NANTRICK_BE controls the use of a trick to
** pack all types into a single double value, using NaN values to
** represent non-number values. The trick only works on 32-bit machines
** (ints and pointers are 32-bit values) with numbers represented as
** IEEE 754-2008 doubles with conventional endianess (12345678 or
** 87654321), in CPUs that do not produce signaling NaN values (all NaNs
** are quiet).
*/
#if defined(LUA_CORE) && \
defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */
/* little-endian architectures that satisfy those conditions */
#if defined(__i386__) || defined(__i386) || defined(__X86__) || \
defined(_M_IX86)
#define LUA_NANTRICK_LE
#endif
#endif /* } */
/* =================================================================== */ /* =================================================================== */

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lualib.h,v 1.40 2010/06/10 21:29:47 roberto Exp roberto $ ** $Id: lualib.h,v 1.42 2011/05/25 14:12:28 roberto Exp roberto $
** Lua standard libraries ** Lua standard libraries
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,9 +11,6 @@
#include "lua.h" #include "lua.h"
/* Key to file-handle type */
#define LUA_FILEHANDLE "FILE*"
LUAMOD_API int (luaopen_base) (lua_State *L); LUAMOD_API int (luaopen_base) (lua_State *L);
@@ -50,7 +47,7 @@ LUALIB_API void (luaL_openlibs) (lua_State *L);
#ifndef lua_assert #if !defined(lua_assert)
#define lua_assert(x) ((void)0) #define lua_assert(x) ((void)0)
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lundump.c,v 1.67 2010/10/13 21:04:52 lhf Exp $ ** $Id: lundump.c,v 1.71 2011/12/07 10:39:12 lhf Exp lhf $
** load precompiled Lua chunks ** load precompiled Lua chunks
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -38,9 +38,13 @@ static void error(LoadState* S, const char* why)
#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x)) #define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
#define LoadVector(S,b,n,size) LoadMem(S,b,n,size) #define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
#if !defined(luai_verifycode)
#define luai_verifycode(L,b,f) (f)
#endif
static void LoadBlock(LoadState* S, void* b, size_t size) static void LoadBlock(LoadState* S, void* b, size_t size)
{ {
if (luaZ_read(S->Z,b,size)!=0) error(S,"corrupted"); if (luaZ_read(S->Z,b,size)!=0) error(S,"truncated");
} }
static int LoadChar(LoadState* S) static int LoadChar(LoadState* S)
@@ -54,6 +58,7 @@ static int LoadInt(LoadState* S)
{ {
int x; int x;
LoadVar(S,x); LoadVar(S,x);
if (x<0) error(S,"corrupted");
return x; return x;
} }
@@ -73,7 +78,7 @@ static TString* LoadString(LoadState* S)
else else
{ {
char* s=luaZ_openspace(S->L,S->b,size); char* s=luaZ_openspace(S->L,S->b,size);
LoadBlock(S,s,size); LoadBlock(S,s,size*sizeof(char));
return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
} }
} }
@@ -131,8 +136,8 @@ static void LoadUpvalues(LoadState* S, Proto* f)
for (i=0; i<n; i++) f->upvalues[i].name=NULL; for (i=0; i<n; i++) f->upvalues[i].name=NULL;
for (i=0; i<n; i++) for (i=0; i<n; i++)
{ {
f->upvalues[i].instack=LoadChar(S); f->upvalues[i].instack=LoadByte(S);
f->upvalues[i].idx=LoadChar(S); f->upvalues[i].idx=LoadByte(S);
} }
} }
@@ -175,13 +180,23 @@ static Proto* LoadFunction(LoadState* S)
return f; return f;
} }
/* the code below must be consistent with the code in luaU_header */
#define N0 LUAC_HEADERSIZE
#define N1 (sizeof(LUA_SIGNATURE)-sizeof(char))
#define N2 N1+2
#define N3 N2+6
static void LoadHeader(LoadState* S) static void LoadHeader(LoadState* S)
{ {
char h[LUAC_HEADERSIZE]; lu_byte h[LUAC_HEADERSIZE];
char s[LUAC_HEADERSIZE]; lu_byte s[LUAC_HEADERSIZE];
luaU_header(h); luaU_header(h);
LoadBlock(S,s,LUAC_HEADERSIZE); memcpy(s,h,sizeof(char)); /* first char already read */
if (memcmp(h,s,LUAC_HEADERSIZE)!=0) error(S,"incompatible"); LoadBlock(S,s+sizeof(char),LUAC_HEADERSIZE-sizeof(char));
if (memcmp(h,s,N0)==0) return;
if (memcmp(h,s,N1)!=0) error(S,"not a");
if (memcmp(h,s,N2)!=0) error(S,"version mismatch in");
if (memcmp(h,s,N3)!=0) error(S,"incompatible"); else error(S,"corrupted");
} }
/* /*
@@ -200,25 +215,30 @@ Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
S.Z=Z; S.Z=Z;
S.b=buff; S.b=buff;
LoadHeader(&S); LoadHeader(&S);
return LoadFunction(&S); return luai_verifycode(L,buff,LoadFunction(&S));
} }
#define MYINT(s) (s[0]-'0')
#define VERSION MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)
#define FORMAT 0 /* this is the official format */
/* /*
* make header * make header for precompiled chunks
* if you make any changes in the header or in LUA_SIGNATURE, * if you change the code below be sure to update LoadHeader and FORMAT above
* be sure to update LUAC_HEADERSIZE accordingly in lundump.h. * and LUAC_HEADERSIZE in lundump.h
*/ */
void luaU_header (char* h) void luaU_header (lu_byte* h)
{ {
int x=1; int x=1;
memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1); memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-sizeof(char));
h+=sizeof(LUA_SIGNATURE)-1; h+=sizeof(LUA_SIGNATURE)-sizeof(char);
*h++=(char)LUAC_VERSION; *h++=cast_byte(VERSION);
*h++=(char)LUAC_FORMAT; *h++=cast_byte(FORMAT);
*h++=(char)*(char*)&x; /* endianness */ *h++=cast_byte(*(char*)&x); /* endianness */
*h++=(char)sizeof(int); *h++=cast_byte(sizeof(int));
*h++=(char)sizeof(size_t); *h++=cast_byte(sizeof(size_t));
*h++=(char)sizeof(Instruction); *h++=cast_byte(sizeof(Instruction));
*h++=(char)sizeof(lua_Number); *h++=cast_byte(sizeof(lua_Number));
*h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */ *h++=cast_byte(((lua_Number)0.5)==0); /* is lua_Number integral? */
memcpy(h,LUAC_TAIL,sizeof(LUAC_TAIL)-sizeof(char));
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lundump.h,v 1.39 2005/11/01 17:04:55 lhf Exp lhf $ ** $Id: lundump.h,v 1.44 2011/05/06 13:35:17 lhf Exp $
** load precompiled Lua chunks ** load precompiled Lua chunks
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -14,23 +14,15 @@
LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
/* make header; from lundump.c */ /* make header; from lundump.c */
LUAI_FUNC void luaU_header (char* h); LUAI_FUNC void luaU_header (lu_byte* h);
/* dump one chunk; from ldump.c */ /* dump one chunk; from ldump.c */
LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
#ifdef luac_c /* data to catch conversion errors */
/* print one chunk; from print.c */ #define LUAC_TAIL "\x19\x93\r\n\x1a\n"
LUAI_FUNC void luaU_print (const Proto* f, int full);
#endif
/* for header of binary files -- this is Lua 5.1 */ /* size in bytes of header of binary files */
#define LUAC_VERSION 0x51 #define LUAC_HEADERSIZE (sizeof(LUA_SIGNATURE)-sizeof(char)+2+6+sizeof(LUAC_TAIL)-sizeof(char))
/* for header of binary files -- this is the official format */
#define LUAC_FORMAT 0
/* size of header of binary files */
#define LUAC_HEADERSIZE 12
#endif #endif

204
lvm.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lvm.c,v 2.124 2010/10/25 19:01:37 roberto Exp roberto $ ** $Id: lvm.c,v 2.146 2011/11/29 15:54:38 roberto Exp roberto $
** Lua virtual machine ** Lua virtual machine
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -35,7 +35,7 @@
const TValue *luaV_tonumber (const TValue *obj, TValue *n) { const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
lua_Number num; lua_Number num;
if (ttisnumber(obj)) return obj; if (ttisnumber(obj)) return obj;
if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) { if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) {
setnvalue(n, num); setnvalue(n, num);
return n; return n;
} }
@@ -65,7 +65,7 @@ static void traceexec (lua_State *L) {
luaD_hook(L, LUA_HOOKCOUNT, -1); luaD_hook(L, LUA_HOOKCOUNT, -1);
} }
if (mask & LUA_MASKLINE) { if (mask & LUA_MASKLINE) {
Proto *p = ci_func(ci)->l.p; Proto *p = ci_func(ci)->p;
int npc = pcRel(ci->u.l.savedpc, p); int npc = pcRel(ci->u.l.savedpc, p);
int newline = getfuncline(p, npc); int newline = getfuncline(p, npc);
if (npc == 0 || /* call linehook when enter a new function, */ if (npc == 0 || /* call linehook when enter a new function, */
@@ -127,29 +127,38 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
int loop; int loop;
TValue temp;
for (loop = 0; loop < MAXTAGLOOP; loop++) { for (loop = 0; loop < MAXTAGLOOP; loop++) {
const TValue *tm; const TValue *tm;
if (ttistable(t)) { /* `t' is a table? */ if (ttistable(t)) { /* `t' is a table? */
Table *h = hvalue(t); Table *h = hvalue(t);
TValue *oldval = luaH_set(L, h, key); /* do a primitive set */ TValue *oldval = cast(TValue *, luaH_get(h, key));
if (!ttisnil(oldval) || /* result is not nil? */ /* if previous value is not nil, there must be a previous entry
(tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */ in the table; moreover, a metamethod has no relevance */
setobj2t(L, oldval, val); if (!ttisnil(oldval) ||
/* previous value is nil; must check the metamethod */
((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&
/* no metamethod; is there a previous entry in the table? */
(oldval != luaO_nilobject ||
/* no previous entry; must create one. (The next test is
always true; we only need the assignment.) */
(oldval = luaH_newkey(L, h, key), 1)))) {
/* no metamethod and (now) there is an entry with given key */
setobj2t(L, oldval, val); /* assign new value to that entry */
invalidateTMcache(h);
luaC_barrierback(L, obj2gco(h), val); luaC_barrierback(L, obj2gco(h), val);
return; return;
} }
/* else will try the tag method */ /* else will try the metamethod */
} }
else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) else /* not a table; check metamethod */
luaG_typeerror(L, t, "index"); if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
luaG_typeerror(L, t, "index");
/* there is a metamethod */
if (ttisfunction(tm)) { if (ttisfunction(tm)) {
callTM(L, tm, t, key, val, 0); callTM(L, tm, t, key, val, 0);
return; return;
} }
/* else repeat with 'tm' */ t = tm; /* else repeat with 'tm' */
setobj(L, &temp, tm); /* avoid pointing inside table (may rehash) */
t = &temp;
} }
luaG_runerror(L, "loop in settable"); luaG_runerror(L, "loop in settable");
} }
@@ -161,7 +170,6 @@ static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
if (ttisnil(tm)) if (ttisnil(tm))
tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
if (ttisnil(tm)) return 0; if (ttisnil(tm)) return 0;
if (event == TM_UNM) p2 = luaO_nilobject;
callTM(L, tm, p1, p2, res, 1); callTM(L, tm, p1, p2, res, 1);
return 1; return 1;
} }
@@ -175,7 +183,7 @@ static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2,
if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
tm2 = fasttm(L, mt2, event); tm2 = fasttm(L, mt2, event);
if (tm2 == NULL) return NULL; /* no metamethod */ if (tm2 == NULL) return NULL; /* no metamethod */
if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */ if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */
return tm1; return tm1;
return NULL; return NULL;
} }
@@ -218,9 +226,9 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
return luai_numlt(L, nvalue(l), nvalue(r)); return luai_numlt(L, nvalue(l), nvalue(r));
else if (ttisstring(l) && ttisstring(r)) else if (ttisstring(l) && ttisstring(r))
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
else if ((res = call_orderTM(L, l, r, TM_LT)) != -1) else if ((res = call_orderTM(L, l, r, TM_LT)) < 0)
return res; luaG_ordererror(L, l, r);
return luaG_ordererror(L, l, r); return res;
} }
@@ -230,17 +238,20 @@ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
return luai_numle(L, nvalue(l), nvalue(r)); return luai_numle(L, nvalue(l), nvalue(r));
else if (ttisstring(l) && ttisstring(r)) else if (ttisstring(l) && ttisstring(r))
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */ else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */
return res; return res;
else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */ else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */
return !res; luaG_ordererror(L, l, r);
return luaG_ordererror(L, l, r); return !res;
} }
int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2) { /*
** equality of Lua values. L == NULL means raw equality (no metamethods)
*/
int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {
const TValue *tm; const TValue *tm;
lua_assert(ttype(t1) == ttype(t2)); lua_assert(ttisequal(t1, t2));
switch (ttype(t1)) { switch (ttype(t1)) {
case LUA_TNIL: return 1; case LUA_TNIL: return 1;
case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
@@ -250,15 +261,19 @@ int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2) {
case LUA_TSTRING: return eqstr(rawtsvalue(t1), rawtsvalue(t2)); case LUA_TSTRING: return eqstr(rawtsvalue(t1), rawtsvalue(t2));
case LUA_TUSERDATA: { case LUA_TUSERDATA: {
if (uvalue(t1) == uvalue(t2)) return 1; if (uvalue(t1) == uvalue(t2)) return 1;
else if (L == NULL) return 0;
tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ); tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
break; /* will try TM */ break; /* will try TM */
} }
case LUA_TTABLE: { case LUA_TTABLE: {
if (hvalue(t1) == hvalue(t2)) return 1; if (hvalue(t1) == hvalue(t2)) return 1;
else if (L == NULL) return 0;
tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
break; /* will try TM */ break; /* will try TM */
} }
default: return gcvalue(t1) == gcvalue(t2); default:
lua_assert(iscollectable(t1));
return gcvalue(t1) == gcvalue(t2);
} }
if (tm == NULL) return 0; /* no TM? */ if (tm == NULL) return 0; /* no TM? */
callTM(L, tm, t1, t2, L->top, 1); /* call TM */ callTM(L, tm, t1, t2, L->top, 1); /* call TM */
@@ -286,18 +301,20 @@ void luaV_concat (lua_State *L, int total) {
char *buffer; char *buffer;
int i; int i;
/* collect total length */ /* collect total length */
for (n = 1; n < total && tostring(L, top-n-1); n++) { for (i = 1; i < total && tostring(L, top-i-1); i++) {
size_t l = tsvalue(top-n-1)->len; size_t l = tsvalue(top-i-1)->len;
if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow"); if (l >= (MAX_SIZET/sizeof(char)) - tl)
luaG_runerror(L, "string length overflow");
tl += l; tl += l;
} }
buffer = luaZ_openspace(L, &G(L)->buff, tl); buffer = luaZ_openspace(L, &G(L)->buff, tl);
tl = 0; tl = 0;
for (i=n; i>0; i--) { /* concat all strings */ n = i;
do { /* concat all strings */
size_t l = tsvalue(top-i)->len; size_t l = tsvalue(top-i)->len;
memcpy(buffer+tl, svalue(top-i), l); memcpy(buffer+tl, svalue(top-i), l * sizeof(char));
tl += l; tl += l;
} } while (--i > 0);
setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
} }
total -= n-1; /* got 'n' strings to create 1 new */ total -= n-1; /* got 'n' strings to create 1 new */
@@ -308,7 +325,7 @@ void luaV_concat (lua_State *L, int total) {
void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
const TValue *tm; const TValue *tm;
switch (ttype(rb)) { switch (ttypenv(rb)) {
case LUA_TTABLE: { case LUA_TTABLE: {
Table *h = hvalue(rb); Table *h = hvalue(rb);
tm = fasttm(L, h->metatable, TM_LEN); tm = fasttm(L, h->metatable, TM_LEN);
@@ -327,7 +344,7 @@ void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
break; break;
} }
} }
callTM(L, tm, rb, luaO_nilobject, ra, 1); callTM(L, tm, rb, rb, ra, 1);
} }
@@ -378,7 +395,7 @@ static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
Upvaldesc *uv = p->upvalues; Upvaldesc *uv = p->upvalues;
int i; int i;
Closure *ncl = luaF_newLclosure(L, p); Closure *ncl = luaF_newLclosure(L, p);
setclvalue(L, ra, ncl); /* anchor new closure in stack */ setclLvalue(L, ra, ncl); /* anchor new closure in stack */
for (i = 0; i < nup; i++) { /* fill in its upvalues */ for (i = 0; i < nup; i++) { /* fill in its upvalues */
if (uv[i].instack) /* upvalue refers to local variable? */ if (uv[i].instack) /* upvalue refers to local variable? */
ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx); ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
@@ -454,6 +471,11 @@ void luaV_finishOp (lua_State *L) {
** some macros for common tasks in `luaV_execute' ** some macros for common tasks in `luaV_execute'
*/ */
#if !defined luai_runtimecheck
#define luai_runtimecheck(L, c) /* void */
#endif
#define RA(i) (base+GETARG_A(i)) #define RA(i) (base+GETARG_A(i))
/* to be used after possible stack reallocation */ /* to be used after possible stack reallocation */
#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
@@ -466,12 +488,19 @@ void luaV_finishOp (lua_State *L) {
(k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++))) (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))
#define dojump(i) (ci->u.l.savedpc += (i)) /* execute a jump instruction */
#define dojump(ci,i,e) \
{ int a = GETARG_A(i); \
if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \
ci->u.l.savedpc += GETARG_sBx(i) + e; }
/* for test instructions, execute the jump instruction that follows it */
#define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); }
#define Protect(x) { {x;}; base = ci->u.l.base; } #define Protect(x) { {x;}; base = ci->u.l.base; }
#define checkGC(L) Protect(luaC_checkGC(L); luai_threadyield(L);) #define checkGC(L,c) Protect(luaC_condGC(L, c); luai_threadyield(L);)
#define arith_op(op,tm) { \ #define arith_op(op,tm) { \
@@ -486,6 +515,7 @@ void luaV_finishOp (lua_State *L) {
#define vmdispatch(o) switch(o) #define vmdispatch(o) switch(o)
#define vmcase(l,b) case l: {b} break; #define vmcase(l,b) case l: {b} break;
#define vmcasenb(l,b) case l: {b} /* nb = no break */
void luaV_execute (lua_State *L) { void luaV_execute (lua_State *L) {
CallInfo *ci = L->ci; CallInfo *ci = L->ci;
@@ -493,9 +523,8 @@ void luaV_execute (lua_State *L) {
TValue *k; TValue *k;
StkId base; StkId base;
newframe: /* reentry point when frame changes (call/return) */ newframe: /* reentry point when frame changes (call/return) */
lua_assert(isLua(ci));
lua_assert(ci == L->ci); lua_assert(ci == L->ci);
cl = &clvalue(ci->func)->l; cl = clLvalue(ci->func);
k = cl->p->k; k = cl->p->k;
base = ci->u.l.base; base = ci->u.l.base;
/* main loop of interpreter */ /* main loop of interpreter */
@@ -506,7 +535,7 @@ void luaV_execute (lua_State *L) {
(--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
Protect(traceexec(L)); Protect(traceexec(L));
} }
/* warning!! several calls may realloc the stack and invalidate `ra' */ /* WARNING: several calls may realloc the stack and invalidate `ra' */
ra = RA(i); ra = RA(i);
lua_assert(base == ci->u.l.base); lua_assert(base == ci->u.l.base);
lua_assert(base <= L->top && L->top < L->stack + L->stacksize); lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
@@ -515,7 +544,13 @@ void luaV_execute (lua_State *L) {
setobjs2s(L, ra, RB(i)); setobjs2s(L, ra, RB(i));
) )
vmcase(OP_LOADK, vmcase(OP_LOADK,
TValue *rb = KBx(i); TValue *rb = k + GETARG_Bx(i);
setobj2s(L, ra, rb);
)
vmcase(OP_LOADKX,
TValue *rb;
lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
rb = k + GETARG_Ax(*ci->u.l.savedpc++);
setobj2s(L, ra, rb); setobj2s(L, ra, rb);
) )
vmcase(OP_LOADBOOL, vmcase(OP_LOADBOOL,
@@ -523,10 +558,10 @@ void luaV_execute (lua_State *L) {
if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */ if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */
) )
vmcase(OP_LOADNIL, vmcase(OP_LOADNIL,
TValue *rb = RB(i); int b = GETARG_B(i);
do { do {
setnilvalue(rb--); setnilvalue(ra++);
} while (rb >= ra); } while (b--);
) )
vmcase(OP_GETUPVAL, vmcase(OP_GETUPVAL,
int b = GETARG_B(i); int b = GETARG_B(i);
@@ -558,7 +593,11 @@ void luaV_execute (lua_State *L) {
sethvalue(L, ra, t); sethvalue(L, ra, t);
if (b != 0 || c != 0) if (b != 0 || c != 0)
luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c)); luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
checkGC(L); checkGC(L,
L->top = ra + 1; /* limit of live values */
luaC_step(L);
L->top = ci->top; /* restore top */
)
) )
vmcase(OP_SELF, vmcase(OP_SELF,
StkId rb = RB(i); StkId rb = RB(i);
@@ -594,7 +633,8 @@ void luaV_execute (lua_State *L) {
} }
) )
vmcase(OP_NOT, vmcase(OP_NOT,
int res = l_isfalse(RB(i)); /* next assignment may change this value */ TValue *rb = RB(i);
int res = l_isfalse(rb); /* next assignment may change this value */
setbvalue(ra, res); setbvalue(ra, res);
) )
vmcase(OP_LEN, vmcase(OP_LEN,
@@ -603,49 +643,61 @@ void luaV_execute (lua_State *L) {
vmcase(OP_CONCAT, vmcase(OP_CONCAT,
int b = GETARG_B(i); int b = GETARG_B(i);
int c = GETARG_C(i); int c = GETARG_C(i);
StkId rb;
L->top = base + c + 1; /* mark the end of concat operands */ L->top = base + c + 1; /* mark the end of concat operands */
Protect(luaV_concat(L, c-b+1); checkGC(L);) Protect(luaV_concat(L, c - b + 1));
ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */
rb = b + base;
setobjs2s(L, ra, rb);
checkGC(L,
L->top = (ra >= rb ? ra + 1 : rb); /* limit of live values */
luaC_step(L);
)
L->top = ci->top; /* restore top */ L->top = ci->top; /* restore top */
setobjs2s(L, RA(i), base+b);
) )
vmcase(OP_JMP, vmcase(OP_JMP,
dojump(GETARG_sBx(i)); dojump(ci, i, 0);
) )
vmcase(OP_EQ, vmcase(OP_EQ,
TValue *rb = RKB(i); TValue *rb = RKB(i);
TValue *rc = RKC(i); TValue *rc = RKC(i);
Protect( Protect(
if (equalobj(L, rb, rc) == GETARG_A(i)) if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i))
dojump(GETARG_sBx(*ci->u.l.savedpc)); ci->u.l.savedpc++;
else
donextjump(ci);
) )
ci->u.l.savedpc++;
) )
vmcase(OP_LT, vmcase(OP_LT,
Protect( Protect(
if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i)) if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
dojump(GETARG_sBx(*ci->u.l.savedpc)); ci->u.l.savedpc++;
else
donextjump(ci);
) )
ci->u.l.savedpc++;
) )
vmcase(OP_LE, vmcase(OP_LE,
Protect( Protect(
if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
dojump(GETARG_sBx(*ci->u.l.savedpc)); ci->u.l.savedpc++;
else
donextjump(ci);
) )
ci->u.l.savedpc++;
) )
vmcase(OP_TEST, vmcase(OP_TEST,
if (GETARG_C(i) ? !l_isfalse(ra) : l_isfalse(ra)) if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
dojump(GETARG_sBx(*ci->u.l.savedpc)); ci->u.l.savedpc++;
ci->u.l.savedpc++; else
donextjump(ci);
) )
vmcase(OP_TESTSET, vmcase(OP_TESTSET,
TValue *rb = RB(i); TValue *rb = RB(i);
if (GETARG_C(i) ? !l_isfalse(rb) : l_isfalse(rb)) { if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
ci->u.l.savedpc++;
else {
setobjs2s(L, ra, rb); setobjs2s(L, ra, rb);
dojump(GETARG_sBx(*ci->u.l.savedpc)); donextjump(ci);
} }
ci->u.l.savedpc++;
) )
vmcase(OP_CALL, vmcase(OP_CALL,
int b = GETARG_B(i); int b = GETARG_B(i);
@@ -690,7 +742,7 @@ void luaV_execute (lua_State *L) {
goto newframe; /* restart luaV_execute over new Lua function */ goto newframe; /* restart luaV_execute over new Lua function */
} }
) )
vmcase(OP_RETURN, vmcasenb(OP_RETURN,
int b = GETARG_B(i); int b = GETARG_B(i);
if (b != 0) L->top = ra+b-1; if (b != 0) L->top = ra+b-1;
if (cl->p->sizep > 0) luaF_close(L, base); if (cl->p->sizep > 0) luaF_close(L, base);
@@ -711,7 +763,7 @@ void luaV_execute (lua_State *L) {
lua_Number limit = nvalue(ra+1); lua_Number limit = nvalue(ra+1);
if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)
: luai_numle(L, limit, idx)) { : luai_numle(L, limit, idx)) {
dojump(GETARG_sBx(i)); /* jump back */ ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
setnvalue(ra, idx); /* update internal index... */ setnvalue(ra, idx); /* update internal index... */
setnvalue(ra+3, idx); /* ...and external index */ setnvalue(ra+3, idx); /* ...and external index */
} }
@@ -727,9 +779,9 @@ void luaV_execute (lua_State *L) {
else if (!tonumber(pstep, ra+2)) else if (!tonumber(pstep, ra+2))
luaG_runerror(L, LUA_QL("for") " step must be a number"); luaG_runerror(L, LUA_QL("for") " step must be a number");
setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep))); setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
dojump(GETARG_sBx(i)); ci->u.l.savedpc += GETARG_sBx(i);
) )
vmcase(OP_TFORCALL, vmcasenb(OP_TFORCALL,
StkId cb = ra + 3; /* call base */ StkId cb = ra + 3; /* call base */
setobjs2s(L, cb+2, ra+2); setobjs2s(L, cb+2, ra+2);
setobjs2s(L, cb+1, ra+1); setobjs2s(L, cb+1, ra+1);
@@ -746,7 +798,7 @@ void luaV_execute (lua_State *L) {
l_tforloop: l_tforloop:
if (!ttisnil(ra + 1)) { /* continue loop? */ if (!ttisnil(ra + 1)) { /* continue loop? */
setobjs2s(L, ra, ra + 1); /* save control variable */ setobjs2s(L, ra, ra + 1); /* save control variable */
dojump(GETARG_sBx(i)); /* jump back */ ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
} }
) )
vmcase(OP_SETLIST, vmcase(OP_SETLIST,
@@ -759,28 +811,30 @@ void luaV_execute (lua_State *L) {
lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
c = GETARG_Ax(*ci->u.l.savedpc++); c = GETARG_Ax(*ci->u.l.savedpc++);
} }
luai_runtimecheck(L, ttistable(ra));
h = hvalue(ra); h = hvalue(ra);
last = ((c-1)*LFIELDS_PER_FLUSH) + n; last = ((c-1)*LFIELDS_PER_FLUSH) + n;
if (last > h->sizearray) /* needs more space? */ if (last > h->sizearray) /* needs more space? */
luaH_resizearray(L, h, last); /* pre-allocate it at once */ luaH_resizearray(L, h, last); /* pre-allocate it at once */
for (; n > 0; n--) { for (; n > 0; n--) {
TValue *val = ra+n; TValue *val = ra+n;
setobj2t(L, luaH_setint(L, h, last--), val); luaH_setint(L, h, last--, val);
luaC_barrierback(L, obj2gco(h), val); luaC_barrierback(L, obj2gco(h), val);
} }
L->top = ci->top; /* correct top (in case of previous open call) */ L->top = ci->top; /* correct top (in case of previous open call) */
) )
vmcase(OP_CLOSE,
luaF_close(L, ra);
)
vmcase(OP_CLOSURE, vmcase(OP_CLOSURE,
Proto *p = cl->p->p[GETARG_Bx(i)]; Proto *p = cl->p->p[GETARG_Bx(i)];
Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */ Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */
if (ncl == NULL) /* no match? */ if (ncl == NULL) /* no match? */
pushclosure(L, p, cl->upvals, base, ra); /* create a new one */ pushclosure(L, p, cl->upvals, base, ra); /* create a new one */
else else
setclvalue(L, ra, ncl); /* push cashed closure */ setclLvalue(L, ra, ncl); /* push cashed closure */
checkGC(L); checkGC(L,
L->top = ra + 1; /* limit of live values */
luaC_step(L);
L->top = ci->top; /* restore top */
)
) )
vmcase(OP_VARARG, vmcase(OP_VARARG,
int b = GETARG_B(i) - 1; int b = GETARG_B(i) - 1;

11
lvm.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lvm.h,v 2.13 2009/11/19 19:04:58 roberto Exp roberto $ ** $Id: lvm.h,v 2.16 2011/05/31 18:24:36 roberto Exp roberto $
** Lua virtual machine ** Lua virtual machine
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -17,12 +17,15 @@
#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL)) #define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))
#define equalobj(L,o1,o2) \ #define equalobj(L,o1,o2) (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))
(ttype(o1) == ttype(o2) && luaV_equalval_(L, o1, o2))
#define luaV_rawequalobj(t1,t2) \
(ttisequal(t1,t2) && luaV_equalobj_(NULL,t1,t2))
/* not to called directly */ /* not to called directly */
LUAI_FUNC int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2); LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);
LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);

32
lzio.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lzio.c,v 1.30 2005/05/17 19:49:15 roberto Exp roberto $ ** $Id: lzio.c,v 1.33 2011/02/23 13:13:10 roberto Exp roberto $
** a generic input stream interface ** a generic input stream interface
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -25,23 +25,11 @@ int luaZ_fill (ZIO *z) {
lua_unlock(L); lua_unlock(L);
buff = z->reader(L, z->data, &size); buff = z->reader(L, z->data, &size);
lua_lock(L); lua_lock(L);
if (buff == NULL || size == 0) return EOZ; if (buff == NULL || size == 0)
z->n = size - 1; return EOZ;
z->n = size - 1; /* discount char being returned */
z->p = buff; z->p = buff;
return char2int(*(z->p++)); return cast_uchar(*(z->p++));
}
int luaZ_lookahead (ZIO *z) {
if (z->n == 0) {
if (luaZ_fill(z) == EOZ)
return EOZ;
else {
z->n++; /* luaZ_fill removed first byte; put back it */
z->p--;
}
}
return char2int(*z->p);
} }
@@ -58,8 +46,14 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
size_t luaZ_read (ZIO *z, void *b, size_t n) { size_t luaZ_read (ZIO *z, void *b, size_t n) {
while (n) { while (n) {
size_t m; size_t m;
if (luaZ_lookahead(z) == EOZ) if (z->n == 0) { /* no bytes in buffer? */
return n; /* return number of missing bytes */ if (luaZ_fill(z) == EOZ) /* try to read more */
return n; /* no more input; return number of missing bytes */
else {
z->n++; /* luaZ_fill consumed first byte; put it back */
z->p--;
}
}
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
memcpy(b, z->p, m); memcpy(b, z->p, m);
z->n -= m; z->n -= m;

11
lzio.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lzio.h,v 1.21 2005/05/17 19:49:15 roberto Exp roberto $ ** $Id: lzio.h,v 1.25 2011/07/15 12:35:32 roberto Exp roberto $
** Buffered streams ** Buffered streams
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -17,11 +17,7 @@
typedef struct Zio ZIO; typedef struct Zio ZIO;
#define char2int(c) cast(int, cast(unsigned char, (c))) #define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z))
#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z))
#define zungetc(z) ((z)->n++, (z)->p--)
typedef struct Mbuffer { typedef struct Mbuffer {
@@ -50,7 +46,6 @@ LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
void *data); void *data);
LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */ LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */
LUAI_FUNC int luaZ_lookahead (ZIO *z);
@@ -59,7 +54,7 @@ LUAI_FUNC int luaZ_lookahead (ZIO *z);
struct Zio { struct Zio {
size_t n; /* bytes still unread */ size_t n; /* bytes still unread */
const char *p; /* current position in buffer */ const char *p; /* current position in buffer */
lua_Reader reader; lua_Reader reader; /* reader function */
void* data; /* additional data */ void* data; /* additional data */
lua_State *L; /* Lua state (for reader) */ lua_State *L; /* Lua state (for reader) */
}; };

View File

@@ -18,9 +18,9 @@ CWARNSC=-pedantic -Wextra \
-Wstrict-aliasing \ -Wstrict-aliasing \
# the next warnings generate to much noise, so they are disabled # the next warnings generate to much noise, so they are disabled
# -Wlogical-op \ # -Wlogical-op \
# -Wstrict-overflow=2 \
# -Wformat=2 \ # -Wformat=2 \
# -Wstrict-overflow=5 \ # -Wcast-qual \
# -Wcast-qual \
# The next warnings are not valid for C++ # The next warnings are not valid for C++
CWARNS= $(CWARNSC) \ CWARNS= $(CWARNSC) \
@@ -35,14 +35,17 @@ CWARNS= $(CWARNSC) \
# -DEXTERNMEMCHECK -DHARDSTACKTESTS -DHARDMEMTESTS -DTRACEMEM='"tempmem"' # -DEXTERNMEMCHECK -DHARDSTACKTESTS -DHARDMEMTESTS -DTRACEMEM='"tempmem"'
# -g -DLUA_USER_H='"ltests.h"' # -g -DLUA_USER_H='"ltests.h"'
# -fomit-frame-pointer #-pg -malign-double # -fomit-frame-pointer #-pg -malign-double
TESTS= -DLUA_USER_H='"ltests.h"' # -g -O0 # -DLUA_USE_CTYPE -DLUA_USE_APICHECK
TESTS= -DLUA_USER_H='"ltests.h"'
# -mtune=native -fomit-frame-pointer
LOCAL = $(TESTS) $(CWARNS) -g
LOCAL = $(TESTS) $(CWARNS)
# enable Linux goodies # enable Linux goodies
MYCFLAGS= $(LOCAL) -DLUA_USE_LINUX -DLUA_COMPAT_ALL -g MYCFLAGS= $(LOCAL) -DLUA_USE_LINUX -DLUA_COMPAT_ALL
MYLDFLAGS= -Wl,-E -g MYLDFLAGS= $(LOCAL) -Wl,-E
MYLIBS= -ldl -lreadline -lhistory -lncurses MYLIBS= -ldl -lreadline -lhistory -lncurses
@@ -116,6 +119,7 @@ echo:
$(ALL_O): makefile $(ALL_O): makefile
# DO NOT DELETE # DO NOT DELETE
# automatically made with 'gcc -MM'
lapi.o: lapi.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \ lapi.o: lapi.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \
lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h ltable.h lundump.h \ lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h ltable.h lundump.h \