Compare commits

...

462 Commits

Author SHA1 Message Date
Roberto Ierusalimschy
523c5d8e1c last changes by lhf. 2000-11-07 10:44:44 -02:00
Roberto Ierusalimschy
40a4c76773 setlinehook/setcallhook return old hook 2000-11-06 15:58:38 -02:00
Roberto Ierusalimschy
1385d81d20 2000-11-06 11:45:18 -02:00
Roberto Ierusalimschy
906d5dcc41 details 2000-11-06 11:45:18 -02:00
Roberto Ierusalimschy
93a5649d40 hooks may call `error' to break a chunk. 2000-11-06 11:19:08 -02:00
Roberto Ierusalimschy
df416661cc many changes 2000-10-31 16:20:01 -02:00
Roberto Ierusalimschy
67c1afff59 lua_settagmethod does not return old tag method 2000-10-31 11:10:24 -02:00
Roberto Ierusalimschy
03770ecfc9 comments 2000-10-31 10:44:07 -02:00
Roberto Ierusalimschy
7409678b5d DEBUG renamed to LUA_DEBUG 2000-10-30 15:50:00 -02:00
Roberto Ierusalimschy
d1c689af40 subtelties in layout of TString 2000-10-30 15:49:19 -02:00
Roberto Ierusalimschy
37e9c2e744 macro DEBUG renamed to LUA_DEBUG 2000-10-30 14:29:59 -02:00
Roberto Ierusalimschy
e42a219eeb `lua_typename' accepts LUA_TNONE 2000-10-30 11:07:48 -02:00
Roberto Ierusalimschy
b3959d58ff 2000-10-30 10:50:09 -02:00
Roberto Ierusalimschy
f379d06e24 all API functions are declared in a single line (to facilitate pre-processing). 2000-10-30 10:38:50 -02:00
Roberto Ierusalimschy
728ff20701 details 2000-10-30 10:20:29 -02:00
Roberto Ierusalimschy
2cbbf3933a new macro LUALIB_API (so the lib can be a separate DLL) 2000-10-27 14:15:53 -02:00
Roberto Ierusalimschy
e2b6b7de1b details 2000-10-27 09:39:52 -02:00
Roberto Ierusalimschy
563b1f5704 new way to ensure uniqueness of registry keys 2000-10-26 17:04:22 -02:00
Roberto Ierusalimschy
4670476584 details. 2000-10-26 16:44:26 -02:00
Roberto Ierusalimschy
89f98c0995 in function `read_file', realloc() doesn't free the buffer if it can't
allocate new memory
2000-10-26 10:53:55 -02:00
Roberto Ierusalimschy
b892f0a877 new API function `createuserdata' 2000-10-26 10:47:05 -02:00
Roberto Ierusalimschy
aadc35449e lua_settag does not pop its argument 2000-10-24 17:19:15 -02:00
Roberto Ierusalimschy
cdc8139e29 registry mechanism 2000-10-24 17:12:06 -02:00
Roberto Ierusalimschy
e833bd47c9 comments 2000-10-24 14:05:59 -02:00
Roberto Ierusalimschy
b7ffb128cb it is unsafe to allow Lua to get gc tag methods 2000-10-20 14:57:42 -02:00
Roberto Ierusalimschy
64eecc0b82 new macro LUA_API 2000-10-20 14:39:03 -02:00
Roberto Ierusalimschy
8b88ab07f7 more controled use of `sprintf' 2000-10-20 14:36:32 -02:00
Roberto Ierusalimschy
2779ceeb12 ((n)-1) may be negative (-1), and so it is not wise to keep it as unsigned 2000-10-18 15:19:09 -02:00
Roberto Ierusalimschy
e93c4547fe no more USERINIT (macro) 2000-10-17 11:36:24 -02:00
Roberto Ierusalimschy
0ffc676ce7 details 2000-10-11 14:47:50 -02:00
Roberto Ierusalimschy
18fb3ddb89 details. 2000-10-10 17:52:58 -02:00
Roberto Ierusalimschy
2bddbe6603 cannot change filename' before eventual call to freopen' 2000-10-10 17:51:39 -02:00
Roberto Ierusalimschy
e323338fd0 `nlineinfo' must include end flag. 2000-10-10 17:51:15 -02:00
Roberto Ierusalimschy
46b543ebef better treatment for errors inside _ERRORMETHOD 2000-10-09 13:46:43 -02:00
Roberto Ierusalimschy
79909a92e1 details 2000-10-09 11:47:46 -02:00
Roberto Ierusalimschy
d6232a0b2e better treatment for source names 2000-10-09 11:47:32 -02:00
Roberto Ierusalimschy
ae63a0e692 new implementation for some API functions 2000-10-06 16:29:26 -03:00
Roberto Ierusalimschy
cd3d446957 detail 2000-10-06 16:28:47 -03:00
Roberto Ierusalimschy
f01e6c6f1d small optimization in `sort' 2000-10-06 16:13:29 -03:00
Roberto Ierusalimschy
ad3816d0d1 luaD_call is more uniform 2000-10-06 09:45:25 -03:00
Roberto Ierusalimschy
046a3d6173 tag methods are always functions, so don't need to store a whole object 2000-10-05 10:00:17 -03:00
Roberto Ierusalimschy
001f2bdd0e new definition for types-tags 2000-10-05 09:14:08 -03:00
Roberto Ierusalimschy
cd2ddaded9 call hooks can only be called when `pc' is active (that is, inside
`execute'...)
2000-10-04 09:16:08 -03:00
Roberto Ierusalimschy
d68209e822 details. 2000-10-03 11:27:44 -03:00
Roberto Ierusalimschy
1088cde03c easier way to change type Number 2000-10-03 11:03:21 -03:00
Roberto Ierusalimschy
6759f3ec5e no more `proprietary' convertion algorithm (too complex) 2000-10-03 11:03:21 -03:00
Roberto Ierusalimschy
f6834f4393 new API function `lua_type' + new type lua_Type 2000-10-02 17:10:55 -03:00
Roberto Ierusalimschy
78bc8e553d new API for garbage collector 2000-10-02 11:47:43 -03:00
Roberto Ierusalimschy
dad808a73a new way to count `nblocks' for GC (try to count bytes). 2000-09-29 09:42:13 -03:00
Roberto Ierusalimschy
ca7fd50a4e small optimizations 2000-09-29 09:40:56 -03:00
Roberto Ierusalimschy
282ab366f4 bug: parser overwrites semantic information when looking ahead 2000-09-27 14:41:58 -03:00
Roberto Ierusalimschy
444d6a106b lua_tag should return LUA_NOTAG for non-valid indices 2000-09-27 09:51:39 -03:00
Roberto Ierusalimschy
13635f7de7 new version of protected execution 2000-09-25 13:22:42 -03:00
Roberto Ierusalimschy
d8a442206d lua_state (now called `L') should not be global 2000-09-25 13:15:52 -03:00
Roberto Ierusalimschy
c9c6f9747c GC may crash when checking C closures 2000-09-25 11:52:10 -03:00
Roberto Ierusalimschy
c2aa7bd72d bug: lua_gettable does not get key from stack top 2000-09-25 11:48:42 -03:00
Roberto Ierusalimschy
f9dd50cefc `read("*w")' should return nil at EOF 2000-09-22 15:14:06 -03:00
Roberto Ierusalimschy
dbde9f8817 wrong assert 2000-09-21 11:41:25 -03:00
Roberto Ierusalimschy
857a1204d8 by lhf 2000-09-21 11:18:43 -03:00
Roberto Ierusalimschy
d742b88fa1 final version (by lhf) 2000-09-20 15:43:54 -03:00
Roberto Ierusalimschy
eb822c314a macros to do jumps 2000-09-20 14:57:08 -03:00
Roberto Ierusalimschy
ab7aceb980 Tochange 2000-09-20 14:21:20 -03:00
Roberto Ierusalimschy
72b12e0956 error messages in lower case. 2000-09-20 09:54:17 -03:00
Roberto Ierusalimschy
5ed3bcd4ea warnings in Solaris 2000-09-19 05:42:35 -03:00
Roberto Ierusalimschy
7508fed673 final version for 4.0 beta 2000-09-18 16:46:37 -03:00
Roberto Ierusalimschy
aab4fde468 changes by lhf 2000-09-18 16:42:05 -03:00
Roberto Ierusalimschy
6ec4a0ef76 updates by lhf 2000-09-18 16:41:16 -03:00
Roberto Ierusalimschy
42ca3105ac small "by 1" bug 2000-09-18 16:39:49 -03:00
Roberto Ierusalimschy
6030d5fed4 avoid assignment to local structure 2000-09-18 16:39:26 -03:00
Roberto Ierusalimschy
91c003dcc2 details 2000-09-18 16:39:18 -03:00
Roberto Ierusalimschy
620d22f2a0 new API function lua_rawget 2000-09-14 11:09:31 -03:00
Roberto Ierusalimschy
f45cba42b5 details for OLD_ANSI 2000-09-13 17:12:14 -03:00
Roberto Ierusalimschy
2628a42480 re-implementation of deprecated functions (wiht compiler option) 2000-09-13 16:52:39 -03:00
Roberto Ierusalimschy
0b3b6850c9 `back-up' definition for ERRORMESSAGE 2000-09-12 15:42:32 -03:00
Roberto Ierusalimschy
5d033f33eb details in ERRORMESSAGE 2000-09-12 15:41:55 -03:00
Roberto Ierusalimschy
e143fed484 better standard error messages 2000-09-12 15:41:43 -03:00
Roberto Ierusalimschy
01ce1ce48c field short_src 2000-09-12 15:38:25 -03:00
Roberto Ierusalimschy
024ed4218f better name for source_id (short_src) 2000-09-12 15:38:02 -03:00
Roberto Ierusalimschy
c1f725ba4a read patterns (deprecated) use new auxlib's buffer system 2000-09-12 10:58:37 -03:00
Roberto Ierusalimschy
5d69960734 error codes as strings for dofile and dostring 2000-09-12 10:49:05 -03:00
Roberto Ierusalimschy
d1c351857d ERRORMESSAGE uses auxlib's buffer to build message string 2000-09-12 10:48:34 -03:00
Roberto Ierusalimschy
4ef14ba280 new function `luaL_addstring' 2000-09-12 10:48:22 -03:00
Roberto Ierusalimschy
b8d57092eb topointer handles only types that have no other "to" function 2000-09-12 10:47:46 -03:00
Roberto Ierusalimschy
0f59e3d7a7 details 2000-09-12 10:47:39 -03:00
Roberto Ierusalimschy
55c3bc2bcb _ALERT is used (and assumed) only by the libs 2000-09-12 10:46:59 -03:00
Roberto Ierusalimschy
8060193702 `lauxlib' is now part of the libraries (not used by core Lua) 2000-09-11 17:29:27 -03:00
Roberto Ierusalimschy
2779e81fbb API functions check stack overflow 2000-09-11 16:45:27 -03:00
Roberto Ierusalimschy
30f6e658d2 lua_newstate' renamed to lua_open' 2000-09-11 16:42:57 -03:00
Roberto Ierusalimschy
787a78f83e new scheme for buffers 2000-09-11 14:38:42 -03:00
Roberto Ierusalimschy
70c8a31092 obsolete module 2000-09-11 11:44:38 -03:00
Roberto Ierusalimschy
2018380e9f late `lbuiltin.c', now implemented through the official API (and
therefore distributed as a regular library).
2000-09-05 16:33:56 -03:00
Roberto Ierusalimschy
6e80c1cde1 new version for API 2000-09-05 16:33:32 -03:00
Roberto Ierusalimschy
f67f324377 deprecated files 2000-09-05 16:28:46 -03:00
Roberto Ierusalimschy
eebc9729e4 new versions by lhf 2000-09-04 15:53:41 -03:00
Roberto Ierusalimschy
6990b06467 finish with parse data before doing main chunk. 2000-09-04 15:52:51 -03:00
Roberto Ierusalimschy
cad91499dd no more support for single state 2000-09-04 15:27:32 -03:00
Roberto Ierusalimschy
ebdd4e8451 `call' doesn't use pack anymore 2000-08-31 18:02:55 -03:00
Roberto Ierusalimschy
9a21e81907 more builtin functions using official API 2000-08-31 18:01:43 -03:00
Roberto Ierusalimschy
f0b3cd1d6f new API functions pop', insert', and `move' 2000-08-31 17:23:40 -03:00
Roberto Ierusalimschy
fb5e6d5ac4 more functions implemented through the official API 2000-08-31 13:52:06 -03:00
Roberto Ierusalimschy
d63afba9d3 negative stack sizes are invalid, too. 2000-08-31 11:28:17 -03:00
Roberto Ierusalimschy
100bfec39a new implementation for `next' 2000-08-31 11:08:27 -03:00
Roberto Ierusalimschy
a290b84c67 dohook' to abstract callhook' and `linehook' 2000-08-31 10:31:44 -03:00
Roberto Ierusalimschy
1022b3c85e minimum size for stack 2000-08-31 10:30:39 -03:00
Roberto Ierusalimschy
a1d3e001b9 comments 2000-08-31 10:30:22 -03:00
Roberto Ierusalimschy
10b4799ce5 details 2000-08-31 10:30:10 -03:00
Roberto Ierusalimschy
a0de89d62a simpler tests for simpler API 2000-08-31 10:29:47 -03:00
Roberto Ierusalimschy
21dc77b2af errors may happen before function start running (with pc=-1) 2000-08-31 10:29:12 -03:00
Roberto Ierusalimschy
2d3ebba537 last version before new API 2000-08-30 15:58:46 -03:00
Roberto Ierusalimschy
a97f29f154 explicit stack control in the API 2000-08-29 17:43:28 -03:00
Roberto Ierusalimschy
4135f4f586 new API does not need tests that complex 2000-08-29 16:05:11 -03:00
Roberto Ierusalimschy
808525e417 new asserts for hooks 2000-08-29 16:01:34 -03:00
Roberto Ierusalimschy
48a968e6b5 gc tag method for nil could call line hook 2000-08-29 16:00:57 -03:00
Roberto Ierusalimschy
58adbde216 details 2000-08-29 11:57:23 -03:00
Roberto Ierusalimschy
9e74ca62d7 tests for lua_is* 2000-08-29 11:57:10 -03:00
Roberto Ierusalimschy
d396562b5e lua_equal also accepts out-of-range indices 2000-08-29 11:52:27 -03:00
Roberto Ierusalimschy
9d60598260 better definitions for MULTRET 2000-08-29 11:48:16 -03:00
Roberto Ierusalimschy
4e56c0d514 better implementation for luaV_pack 2000-08-29 11:41:56 -03:00
Roberto Ierusalimschy
ac12f4db4b C upvalues are the last arguments to a function 2000-08-29 11:33:31 -03:00
Roberto Ierusalimschy
b691d4344b L is not unused. 2000-08-28 17:22:21 -03:00
Roberto Ierusalimschy
9fdf73bc9a first version for new API 2000-08-28 14:57:04 -03:00
Roberto Ierusalimschy
f1fd9b5c2c intermediate version (only to avoid compiler errors) 2000-08-24 11:19:39 -03:00
Roberto Ierusalimschy
3723d790ae checkstack needs a correct stack 2000-08-22 17:53:30 -03:00
Roberto Ierusalimschy
b800c38b69 simpler code for settable and gettable 2000-08-22 17:49:29 -03:00
Roberto Ierusalimschy
5c0e79847c pragmas are no longer supported 2000-08-22 17:07:56 -03:00
Roberto Ierusalimschy
e662e0f1cd simpler way to access _INPUT and _OUTPUT 2000-08-22 14:47:17 -03:00
Roberto Ierusalimschy
c85162be27 new way to store local-variable information. 2000-08-22 14:44:17 -03:00
Roberto Ierusalimschy
bd39db46ed details 2000-08-21 11:34:43 -03:00
Roberto Ierusalimschy
90fb2e18e8 pushref' is more efficient (and probably more useful) than getref'. 2000-08-17 10:18:01 -03:00
Roberto Ierusalimschy
4365c31c89 new name for globaltable. 2000-08-15 17:14:27 -03:00
Roberto Ierusalimschy
44eb7d91ac comments 2000-08-15 15:28:48 -03:00
Roberto Ierusalimschy
ddc8d94a08 new name for `lua_[sg]etglobaltable' 2000-08-14 16:18:14 -03:00
Roberto Ierusalimschy
5d9cbdadfb cannot run symbolic execution for non-active functions 2000-08-14 14:59:20 -03:00
Roberto Ierusalimschy
58453dc1e1 small bug in symbolic execution 2000-08-14 14:46:27 -03:00
Roberto Ierusalimschy
f555e493f0 lua_state may not exist 2000-08-14 14:46:07 -03:00
Roberto Ierusalimschy
d1ffd1a1c5 details 2000-08-14 14:45:59 -03:00
Roberto Ierusalimschy
9e84bf18db still more debug information 2000-08-11 13:17:28 -03:00
Roberto Ierusalimschy
daf09c476f still better error messages 2000-08-10 16:50:47 -03:00
Roberto Ierusalimschy
e238efc536 default now is multi-state 2000-08-09 16:16:57 -03:00
Roberto Ierusalimschy
fdd04e7a7f first version of manual for 4.0 beta 2000-08-09 16:09:20 -03:00
Roberto Ierusalimschy
fb55c96706 obsolete module; not part of the oficial distribution 2000-08-09 11:50:13 -03:00
Roberto Ierusalimschy
c39bec81dc bug: lastpc was not initialized 2000-08-09 11:49:41 -03:00
Roberto Ierusalimschy
5f22f8961c better code for unary/binary operators 2000-08-09 11:49:13 -03:00
Roberto Ierusalimschy
a7c1390ffa syntax "function foo (...)" can be nested 2000-08-08 17:48:55 -03:00
Roberto Ierusalimschy
0802a9df9e no more options for debug information: it is always on 2000-08-08 17:42:07 -03:00
Roberto Ierusalimschy
f90bc248b3 new structure for line information 2000-08-08 15:26:05 -03:00
Roberto Ierusalimschy
d9e61e8cea new algorithm for traversing in GC to avoid deep recursion calls 2000-08-07 17:21:34 -03:00
Roberto Ierusalimschy
397905ef86 (much) better handling of memory alloction errors 2000-08-07 15:39:16 -03:00
Roberto Ierusalimschy
435f587ed0 (much) better handling of memory alloction errors 2000-08-04 16:38:35 -03:00
Roberto Ierusalimschy
ae55f3eead no varargs in Lua API 2000-06-30 16:17:08 -03:00
Roberto Ierusalimschy
cfba572076 remove dummy argument in LUA_ASSERT 2000-06-30 11:35:17 -03:00
Roberto Ierusalimschy
aa01d2568d symbolic execution must handle return and tailcall 2000-06-30 11:29:35 -03:00
Roberto Ierusalimschy
014a09c509 better error messages 2000-06-28 17:21:06 -03:00
Roberto Ierusalimschy
b622282973 local is valid only after adjust 2000-06-28 14:06:07 -03:00
Roberto Ierusalimschy
7f867eb0b9 tests for locals and line numbers 2000-06-28 14:06:07 -03:00
Roberto Ierusalimschy
5362426ffa error message 2000-06-28 14:03:56 -03:00
Roberto Ierusalimschy
906434011f better (?) treatment for 16-bit machines 2000-06-28 14:03:32 -03:00
Roberto Ierusalimschy
c07cebbbf6 details 2000-06-27 16:00:36 -03:00
Roberto Ierusalimschy
afef009fce new version of debug system 2000-06-26 16:28:31 -03:00
Roberto Ierusalimschy
b69e712713 new way to generate SETLINEs 2000-06-21 15:13:56 -03:00
Roberto Ierusalimschy
f517759507 details 2000-06-21 14:05:49 -03:00
Roberto Ierusalimschy
52062684e1 better control over use of `errno' 2000-06-20 14:13:21 -03:00
Roberto Ierusalimschy
83e3ec0117 no more labels 2000-06-19 15:26:23 -03:00
Roberto Ierusalimschy
feb2083730 better control of source name 2000-06-19 15:05:14 -03:00
Roberto Ierusalimschy
8d2baf719c comment 2000-06-19 15:04:41 -03:00
Roberto Ierusalimschy
88657809ac details 2000-06-19 10:15:15 -03:00
Roberto Ierusalimschy
2e1b32d873 optimizations for "while 1", "until nil", and the like 2000-06-16 14:51:40 -03:00
Roberto Ierusalimschy
89a3ec08f3 function lua_userinit is used only in single-state mode (by lua.c) 2000-06-16 14:22:43 -03:00
Roberto Ierusalimschy
e3ea307434 small changes to allow redefinition of some buffer sizes. 2000-06-16 14:16:34 -03:00
Roberto Ierusalimschy
18b0e8270d 32 characteres are more than enough for a good hash 2000-06-15 14:01:12 -03:00
Roberto Ierusalimschy
094880ef9e details 2000-06-12 11:37:18 -03:00
Roberto Ierusalimschy
1de5587184 `lua.h' is included before any other Lua header file 2000-06-12 10:52:05 -03:00
Roberto Ierusalimschy
8ca9534d04 access to `values' in TObject always through macros 2000-06-08 15:27:13 -03:00
Roberto Ierusalimschy
8bcf622876 new signature for `luaH_set' 2000-06-06 13:31:41 -03:00
Roberto Ierusalimschy
dbbf6c073b 0 (in MAX_SIZET) may be shorter than size_t 2000-06-06 13:27:11 -03:00
Roberto Ierusalimschy
292c953018 new auxiliar function `luaH_setstr' 2000-06-05 17:15:33 -03:00
Roberto Ierusalimschy
c542aac0b9 collect dead indices in tables 2000-06-05 17:07:53 -03:00
Roberto Ierusalimschy
dbfb810267 cleansing of lparser.c 2000-06-05 11:56:18 -03:00
Roberto Ierusalimschy
9c14b5e416 new test function to list strings from a function 2000-06-02 16:10:01 -03:00
Roberto Ierusalimschy
6b9bf49265 better to keep foreach' and foreachi'. 2000-06-02 16:08:56 -03:00
Roberto Ierusalimschy
989ad7232a changed to test macros for single-state use 2000-06-02 14:06:42 -03:00
Roberto Ierusalimschy
190c3be739 details 2000-05-31 13:53:30 -03:00
Roberto Ierusalimschy
7e30900def better field name 2000-05-30 16:00:31 -03:00
Roberto Ierusalimschy
f63d7753b8 files are closed when collected (again) 2000-05-30 15:55:16 -03:00
Roberto Ierusalimschy
50a82ec1b9 gc tag methods for udata are called in (reverse) tag order 2000-05-30 15:54:49 -03:00
Roberto Ierusalimschy
ed1751bc32 details 2000-05-29 11:48:03 -03:00
Roberto Ierusalimschy
8e617985fa functions for...' and raw...' are obsolete now 2000-05-26 16:17:57 -03:00
Roberto Ierusalimschy
c39345fba3 no more pragmas 2000-05-26 11:04:04 -03:00
Roberto Ierusalimschy
ed94a85f0c type details 2000-05-25 16:02:21 -03:00
Roberto Ierusalimschy
58fbdc76d5 better implementation for looh-ahead 2000-05-25 15:59:59 -03:00
Roberto Ierusalimschy
a301304612 accepts `$debug' in the middle of a function. 2000-05-25 15:26:42 -03:00
Roberto Ierusalimschy
677313da32 bug: record-constructor starting with an upvalue name gets an error 2000-05-24 15:04:17 -03:00
Roberto Ierusalimschy
ef62b340e0 code cleaner for 16 bits. 2000-05-24 10:54:49 -03:00
Roberto Ierusalimschy
5c2dd7a9e0 array `luaK_opproperties' keeps delta stack and mode for each opcode 2000-05-22 15:44:46 -03:00
Roberto Ierusalimschy
93d93a0bfb first implementation of `for' over tables 2000-05-15 16:48:04 -03:00
Roberto Ierusalimschy
9e1f94fc1c cannot change value of private locals (used to implement `for') 2000-05-15 16:30:41 -03:00
Roberto Ierusalimschy
8714cc02d6 `getinfo' gets information about non-active functions, too. 2000-05-12 16:49:18 -03:00
Roberto Ierusalimschy
69b45bb4e9 changes by lhf 2000-05-12 16:19:18 -03:00
Roberto Ierusalimschy
843f84f4ce first element in a list constructor is not adjusted to one value. 2000-05-12 15:12:04 -03:00
Roberto Ierusalimschy
b803c0600e details 2000-05-11 15:57:19 -03:00
Roberto Ierusalimschy
8ac0bbf64b new option `-c' to close lua. 2000-05-10 14:00:21 -03:00
Roberto Ierusalimschy
dc1e4f5073 missing define for `lua_dobuffer' single-state 2000-05-10 13:35:18 -03:00
Roberto Ierusalimschy
330e51bed3 string hash uses one single hash table 2000-05-10 13:33:20 -03:00
Roberto Ierusalimschy
44b71ca816 defines for _ERRORMESSAGE and _ALERT 2000-05-09 11:50:16 -03:00
Roberto Ierusalimschy
bad6365540 details 2000-05-08 17:49:05 -03:00
Roberto Ierusalimschy
91f34fb05c lua.h should not use names without prefix lua_ (`TObject', for instance) 2000-05-08 16:37:10 -03:00
Roberto Ierusalimschy
11a7022067 global variables are stored in a Lua table 2000-05-08 16:32:53 -03:00
Roberto Ierusalimschy
35a6ed2838 detail (error message) 2000-05-08 15:46:34 -03:00
Roberto Ierusalimschy
cfe6ca819b default for `getstack' is to get everything 2000-05-08 10:21:35 -03:00
Roberto Ierusalimschy
fe5c37ae95 BUG: `strfind' gets wrong subject length when there is an offset 2000-05-02 15:32:22 -03:00
Roberto Ierusalimschy
c31f02948f [C++ Warning] lparser.c(326): W8066 Unreachable code.
[C++ Warning] lparser.c(486): W8004 'nargs' is assigned a value that is never used.
2000-04-27 14:39:56 -03:00
Roberto Ierusalimschy
c9f91c6fe3 [C++ Warning]: W8084 Suggest parentheses to clarify precedence. 2000-04-27 14:39:15 -03:00
Roberto Ierusalimschy
66d620674c IntPoint does not need L 2000-04-26 10:43:25 -03:00
Roberto Ierusalimschy
84790bb953 "conceptual" bug 2000-04-26 10:43:10 -03:00
Roberto Ierusalimschy
534c3a64d3 small optimizations for table access 2000-04-25 13:55:09 -03:00
Roberto Ierusalimschy
b9c98cd4d9 entry for new version (4.0a) 2000-04-25 13:45:39 -03:00
Roberto Ierusalimschy
0e8855e171 final version (by lhf) 2000-04-25 13:44:31 -03:00
Roberto Ierusalimschy
2ae9c856cf more uniform names 2000-04-24 18:05:11 -03:00
Roberto Ierusalimschy
c4409f69ab details 2000-04-19 10:41:37 -03:00
Roberto Ierusalimschy
89a9c36281 no more `register' declarations: leave it to the compiler. 2000-04-19 10:36:25 -03:00
Roberto Ierusalimschy
8f2fba5877 using new constructs (for & break) in the examples and code fragments 2000-04-17 16:23:48 -03:00
Roberto Ierusalimschy
62824137d6 no more `seterrormethod' function 2000-04-17 16:23:12 -03:00
Roberto Ierusalimschy
71219ccc39 simpler version of `luaK_tostack' 2000-04-17 11:05:34 -03:00
Roberto Ierusalimschy
870f61d299 code redistribution 2000-04-14 15:12:35 -03:00
Roberto Ierusalimschy
c845ec777a new order for modules (better locality??) 2000-04-14 14:52:09 -03:00
Roberto Ierusalimschy
e408cf61a2 new version number 2000-04-14 14:48:20 -03:00
Roberto Ierusalimschy
4e90768635 lots of changes (almost ready for 4.0) 2000-04-14 14:47:55 -03:00
Roberto Ierusalimschy
c1666a13e3 better code organization 2000-04-14 14:47:24 -03:00
Roberto Ierusalimschy
e02750ec60 new type for CFunction (for "pure" C) 2000-04-14 14:46:37 -03:00
Roberto Ierusalimschy
0b56646baf new function `getargs' 2000-04-14 14:46:29 -03:00
Roberto Ierusalimschy
634c3d57e9 optimization for SETLOCAL was too specific. 2000-04-14 14:46:15 -03:00
Roberto Ierusalimschy
4aa9ad6514 functions must return explicit `nil' on failure 2000-04-14 14:44:20 -03:00
Roberto Ierusalimschy
d76b1a0eef base' for tonumber' must be >= 2. 2000-04-13 15:08:18 -03:00
Roberto Ierusalimschy
e7c8393682 optimization INCLOCAL is not necessary, with `for' 2000-04-13 13:51:01 -03:00
Roberto Ierusalimschy
ceaa97ff5b tonumber must return `nil' when convertion fails. 2000-04-13 13:46:43 -03:00
Roberto Ierusalimschy
2bb77cdaed keep opcodes in the right order 2000-04-12 16:56:50 -03:00
Roberto Ierusalimschy
f9cf402fbd first implementation of FOR 2000-04-12 15:57:19 -03:00
Roberto Ierusalimschy
0c3fe2c44b comment 2000-04-12 15:47:03 -03:00
Roberto Ierusalimschy
0433e42023 no more repeat ... end. 2000-04-11 15:37:18 -03:00
Roberto Ierusalimschy
0810bc707f new syntax: |label| 2000-04-10 16:21:14 -03:00
Roberto Ierusalimschy
c3b73cbeb8 comments (detail) 2000-04-10 16:20:24 -03:00
Roberto Ierusalimschy
1eabd0549e comments 2000-04-07 16:35:31 -03:00
Roberto Ierusalimschy
54dd5cc7fd reorganization of lcode.c 2000-04-07 16:35:20 -03:00
Roberto Ierusalimschy
031978798c more optimizations 2000-04-07 10:13:11 -03:00
Roberto Ierusalimschy
14251c5a56 name changes + new operation - old operation 2000-04-07 10:12:50 -03:00
Roberto Ierusalimschy
42130ed712 name changes 2000-04-07 10:11:49 -03:00
Roberto Ierusalimschy
d615e78e08 new optimization: jumps to jumps 2000-04-06 14:36:52 -03:00
Roberto Ierusalimschy
c6965ce551 new functions: disassembler and get limit. 2000-04-06 14:35:23 -03:00
Roberto Ierusalimschy
22329e4cdf implementation of BREAK 2000-04-05 14:51:58 -03:00
Roberto Ierusalimschy
9f734094f9 `nil' is optional for next and nextvar (and is not for tonumber & tag). 2000-04-04 17:49:32 -03:00
Roberto Ierusalimschy
4e7e9e8de5 new opcode INCLOCAL. 2000-04-04 17:48:44 -03:00
Roberto Ierusalimschy
3e45496295 syntactical details 2000-04-03 10:44:55 -03:00
Roberto Ierusalimschy
e30327728c BUG: tostring() without arguments gives seg. fault. 2000-04-03 10:20:33 -03:00
Roberto Ierusalimschy
36e1390631 details. 2000-03-31 13:28:45 -03:00
Roberto Ierusalimschy
8f0f54ec38 name change 2000-03-30 17:55:50 -03:00
Roberto Ierusalimschy
556a89e537 new names for debug types 2000-03-30 14:19:48 -03:00
Roberto Ierusalimschy
e2c60eda16 `luaT_validevent' is exported, because compatibility module for fallbacks
uses it.
2000-03-30 13:41:51 -03:00
Roberto Ierusalimschy
a69356e9e0 no more special cases for closures with 0 upvalues (performance is the same,
memory use a little higher, code much simpler).
2000-03-29 17:19:20 -03:00
Roberto Ierusalimschy
b53dc0c485 TAG_ARRAY -> TAG_TABLE 2000-03-27 17:10:21 -03:00
Roberto Ierusalimschy
63e230a16b comments 2000-03-27 17:08:33 -03:00
Roberto Ierusalimschy
102a1be615 no more support for gc TM for tables 2000-03-27 17:08:02 -03:00
Roberto Ierusalimschy
4c03196697 lua_setstate makes no sense with explicit multiple states 2000-03-27 11:00:35 -03:00
Roberto Ierusalimschy
54633d7c7d new name for llimits.h 2000-03-24 16:49:23 -03:00
Roberto Ierusalimschy
13578517c7 new file to keep all limits and instalation-dependent definitions 2000-03-24 14:26:08 -03:00
Roberto Ierusalimschy
213e9febc8 limits now are in `llims.n' 2000-03-24 14:26:08 -03:00
Roberto Ierusalimschy
47b4bf5964 small refactoring. 2000-03-24 09:18:30 -03:00
Roberto Ierusalimschy
415ee1a24f SETLINEs for reserved words, too. 2000-03-24 09:17:53 -03:00
Roberto Ierusalimschy
5f3c5ace95 message detail 2000-03-22 13:24:13 -03:00
Roberto Ierusalimschy
441469f803 new option `-s' + argv ends with NULL (so we don't need argc). 2000-03-20 17:27:32 -03:00
Roberto Ierusalimschy
1157c2a7e4 better(?) treatment for SETLINE + while optimization is too complex for
only 3% of maximum improvement.
2000-03-20 16:15:37 -03:00
Roberto Ierusalimschy
374cc888f4 better(?) treatment for SETLINE 2000-03-20 16:15:37 -03:00
Roberto Ierusalimschy
bb9605bbc9 tags can be positive values 2000-03-20 16:14:54 -03:00
Roberto Ierusalimschy
6759299880 new implementation for handling I/O tags + setglobal TM for tracing
changes in _INPUT/_OUTPUT
2000-03-20 16:13:45 -03:00
Roberto Ierusalimschy
da7eb34cd6 optimization for "while 1" and "repeat until nil" 2000-03-17 11:46:04 -03:00
Roberto Ierusalimschy
2c8e28d75a small changes 2000-03-17 10:09:46 -03:00
Roberto Ierusalimschy
4fb8e93c36 small optimization for i..'' 2000-03-17 10:09:12 -03:00
Roberto Ierusalimschy
7f77431950 detail 2000-03-16 18:06:16 -03:00
Roberto Ierusalimschy
87367e97f3 more information about memory use 2000-03-16 17:35:07 -03:00
Roberto Ierusalimschy
06f08f5634 small problems with limits and jumps 2000-03-16 15:03:09 -03:00
Roberto Ierusalimschy
3860c5934e details. 2000-03-15 17:50:33 -03:00
Roberto Ierusalimschy
f0b697e01c details 2000-03-13 17:37:16 -03:00
Roberto Ierusalimschy
73aa465a8e some name changes 2000-03-10 15:37:44 -03:00
Roberto Ierusalimschy
3d0577f4b9 small optimizations. 2000-03-10 11:38:10 -03:00
Roberto Ierusalimschy
977b8f65f0 comment detail. 2000-03-10 11:01:05 -03:00
Roberto Ierusalimschy
e3cf93ddb6 first implementation of "threaded code" for boolean operations 2000-03-09 10:57:37 -03:00
Roberto Ierusalimschy
88b306f495 some optimizations 2000-03-08 21:19:22 -03:00
Roberto Ierusalimschy
563de491be a better way to control optimizations. 2000-03-04 17:18:15 -03:00
Roberto Ierusalimschy
29e0193425 details 2000-03-03 17:30:47 -03:00
Roberto Ierusalimschy
61f97a8ace maybe a concat right associative allows some optimizations... 2000-03-03 17:29:25 -03:00
Roberto Ierusalimschy
d1ea38580a change of code generation design (independent functions for each opcode) 2000-03-03 15:53:17 -03:00
Roberto Ierusalimschy
3c9d999424 many details (most by lhf). 2000-03-03 11:58:26 -03:00
Roberto Ierusalimschy
f7840a3e0b new algorithm to parse expressions + distribution of code between lparser
and lcode.
2000-03-03 09:33:59 -03:00
Roberto Ierusalimschy
1780e2c977 lua_settable should check stack space (it could call a T.M.) 2000-03-02 09:44:29 -03:00
Roberto Ierusalimschy
fa14cbf8e8 comments 2000-03-02 09:32:53 -03:00
Roberto Ierusalimschy
4d4e6f07c0 all order operators use a single tag method (<) 2000-02-22 16:12:46 -02:00
Roberto Ierusalimschy
5cecf0ea9f it is better to control stack space where it is needed. 2000-02-22 15:54:16 -02:00
Roberto Ierusalimschy
3bc925138e first version of code optimizer 2000-02-22 11:31:43 -02:00
Roberto Ierusalimschy
39e1f079bd code generator (and optimizer) for Lua 2000-02-22 11:31:19 -02:00
Roberto Ierusalimschy
075da266e5 there is no need to use shorts... 2000-02-21 16:33:26 -02:00
Roberto Ierusalimschy
228a62f799 details 2000-02-21 16:30:42 -02:00
Roberto Ierusalimschy
7c2fb15bec need "string.h" to use "strchr". 2000-02-21 16:30:06 -02:00
Roberto Ierusalimschy
1f01998516 nobody uses memmove any more. 2000-02-17 16:30:36 -02:00
Roberto Ierusalimschy
c929376d59 must include a definition for NULL 2000-02-17 16:30:36 -02:00
Roberto Ierusalimschy
3afe85b2ce new version for INSTRUCTION formats 2000-02-14 14:51:08 -02:00
Roberto Ierusalimschy
52aad0ab59 removing implementation for better error messages (must rethink it...) 2000-02-11 14:52:54 -02:00
Roberto Ierusalimschy
74f1c3d025 small changes for "clean C" 2000-02-08 14:39:42 -02:00
Roberto Ierusalimschy
1f691a4fcd renaming of some opcodes and fields 2000-01-28 14:53:00 -02:00
Roberto Ierusalimschy
d6b9f49aaf only need to reset buffer for strings, numbers, and names. 2000-01-26 16:51:49 -02:00
Roberto Ierusalimschy
d83c2a8455 performance details. 2000-01-25 16:44:21 -02:00
Roberto Ierusalimschy
d11e5adf55 `const' array in protos breaked in 3 arrays (for strings, numbers, and
prototypes).
2000-01-25 11:57:18 -02:00
Roberto Ierusalimschy
99e340b2ba keep `top' in registers when running basic tasks (settable, getglobal, ...) 2000-01-24 18:14:07 -02:00
Roberto Ierusalimschy
9744255ae9 error in call must be propagated 2000-01-24 18:11:26 -02:00
Roberto Ierusalimschy
512b15b601 small optimizations (relational operators) 2000-01-19 14:50:30 -02:00
Roberto Ierusalimschy
33d3504889 new debug API 2000-01-19 14:50:14 -02:00
Roberto Ierusalimschy
2877bad4c2 new debug API (first version) 2000-01-19 10:00:45 -02:00
Roberto Ierusalimschy
27163f032e Auxiliary functions from Debug Interface module 2000-01-14 15:15:44 -02:00
Roberto Ierusalimschy
eab57ed6fd details 2000-01-13 14:30:47 -02:00
Roberto Ierusalimschy
ea45f3eb28 better separation between debug code and regular code 2000-01-13 14:30:47 -02:00
Roberto Ierusalimschy
46ec57cbc6 little change when calling tag methods 2000-01-13 13:56:03 -02:00
Roberto Ierusalimschy
62787f1b1f `exp' is "reserved word" in Visual-C++ ;-) 2000-01-12 14:24:39 -02:00
Roberto Ierusalimschy
dcb7bb514e details (error messages) 2000-01-10 15:34:38 -02:00
Roberto Ierusalimschy
b3aaa048b0 bug: cannot reopen stdin (for binary mode) 1999-12-30 16:40:57 -02:00
Roberto Ierusalimschy
aee07c6599 details 1999-12-30 16:29:46 -02:00
Roberto Ierusalimschy
bcdbdaccc3 more debug information (still with bug for tag methods...) 1999-12-30 16:28:40 -02:00
Roberto Ierusalimschy
5cafe5af02 tag method must be a function 1999-12-30 16:27:03 -02:00
Roberto Ierusalimschy
607012ece1 tag method must be a function
+ error message must be a string
1999-12-30 16:27:03 -02:00
Roberto Ierusalimschy
0652906e7a details. 1999-12-30 10:40:29 -02:00
Roberto Ierusalimschy
4d1b815b60 return gives wrong line in debug information. 1999-12-29 16:07:10 -02:00
Roberto Ierusalimschy
4ebc183e56 bug: return gives wrong line in debug information. 1999-12-29 16:07:10 -02:00
Roberto Ierusalimschy
298d0abff7 first version of extra debug information (NAME) 1999-12-29 14:31:15 -02:00
Roberto Ierusalimschy
4fbe775154 details 1999-12-29 14:24:03 -02:00
Roberto Ierusalimschy
aabefe9d68 details. 1999-12-28 17:23:41 -02:00
Roberto Ierusalimschy
fb60283974 better error messages 1999-12-28 09:52:49 -02:00
Roberto Ierusalimschy
acdb0b741e comments. 1999-12-27 15:33:22 -02:00
Roberto Ierusalimschy
5b08fcd5a1 no more "lua" in error messages 1999-12-27 11:04:53 -02:00
Roberto Ierusalimschy
b1b0c219f5 new ttypes to distinguish between C closures and Lua closures. 1999-12-23 16:19:57 -02:00
Roberto Ierusalimschy
be3212de78 details 1999-12-22 14:58:36 -02:00
Roberto Ierusalimschy
2eaf9a00ae little bug: `1ea' got a wrong token at the error message 1999-12-22 14:58:36 -02:00
Roberto Ierusalimschy
6c79a0a80d new way to control hooks inside hooks (now the control is done inside Lua) 1999-12-21 16:04:41 -02:00
Roberto Ierusalimschy
3daeabb606 new way to pass arguments: with option `-f' 1999-12-21 15:34:23 -02:00
Roberto Ierusalimschy
cfdebfbc53 debug information for parameters use line 0 for them (as they are
always visible).
1999-12-21 15:31:28 -02:00
Roberto Ierusalimschy
d61d5bef9d details 1999-12-20 11:10:38 -02:00
Roberto Ierusalimschy
4450efc97e new chunkid for C functions (`luaL_chunkid') 1999-12-20 11:09:45 -02:00
Roberto Ierusalimschy
de65253f2d new way to handle _PROMPT 1999-12-20 11:03:20 -02:00
Roberto Ierusalimschy
12b45c2df2 luaS_newfixedstring renamed to luaS_newfixed 1999-12-14 16:42:57 -02:00
Roberto Ierusalimschy
1b15206cf9 many details + code redistribution 1999-12-14 16:33:29 -02:00
Roberto Ierusalimschy
e6d56cd2d8 module for internal use only, with functions for internal tests 1999-12-14 16:31:20 -02:00
Roberto Ierusalimschy
c16c63cc59 new module with the debug API functions 1999-12-14 16:31:20 -02:00
Roberto Ierusalimschy
dea54a7c71 comments 1999-12-09 18:01:48 -02:00
Roberto Ierusalimschy
544eeb1f9c details 1999-12-07 10:05:34 -02:00
Roberto Ierusalimschy
b3fe203c36 keep it simple 1999-12-07 10:05:34 -02:00
Roberto Ierusalimschy
9c142740c1 stack may not be empty after a correct run... 1999-12-07 09:42:54 -02:00
Roberto Ierusalimschy
7621cc2aa5 for the future... 1999-12-07 09:36:16 -02:00
Roberto Ierusalimschy
ba1f504970 `optimization' doesn't seem to make any difference... 1999-12-06 17:30:53 -02:00
Roberto Ierusalimschy
617be66015 better control (and error recovery) for begin/end blocks 1999-12-06 10:03:45 -02:00
Roberto Ierusalimschy
f356eb010b configurable stack size + some corrections in error recovery in
`protectedrun'
1999-12-06 09:43:58 -02:00
Roberto Ierusalimschy
3e38fd2463 `lua_setfallback' leaves things on the stack, so it is better to protect
it.
1999-12-06 09:43:09 -02:00
Roberto Ierusalimschy
533beedad2 new tests for begin/end blocks and multi-state 1999-12-06 09:42:18 -02:00
Roberto Ierusalimschy
968ad49da6 `lua_newstate' gets the inital stack size and other arguments 1999-12-06 09:41:28 -02:00
Roberto Ierusalimschy
1fdb445e7d details. 1999-12-06 09:40:55 -02:00
Roberto Ierusalimschy
c7119a93f0 new language for testC (debugging facility) 1999-12-03 16:02:54 -02:00
Roberto Ierusalimschy
3c9e29f56d details 1999-12-03 09:26:23 -02:00
Roberto Ierusalimschy
72afb6debb modifications by lhf 1999-12-02 17:11:51 -02:00
Roberto Ierusalimschy
b097076678 missing include 1999-12-02 14:41:29 -02:00
Roberto Ierusalimschy
8223ff473f lua_Object is a pointer to the stack (because now the stack doen't move) 1999-12-02 14:24:45 -02:00
Roberto Ierusalimschy
fe237ad808 fixed stack; first version. 1999-12-01 17:50:08 -02:00
Roberto Ierusalimschy
3181dfefee details 1999-11-30 11:06:50 -02:00
Roberto Ierusalimschy
764e095d7f object' and string' are very busy names... 1999-11-29 17:31:29 -02:00
Roberto Ierusalimschy
2b3ea61342 mistake in change for multi-state (gc threshold was not corrected) 1999-11-29 17:12:07 -02:00
Roberto Ierusalimschy
49af08e3e7 new name for lua_equal(obj); LUA_NOOBJECT is equal to LUA_NOOBJECT 1999-11-29 17:11:36 -02:00
Roberto Ierusalimschy
c5fa0895e9 table sizes don't need to be primes; power of 2 gives the same performance. 1999-11-29 14:38:48 -02:00
Roberto Ierusalimschy
d015f1fc02 table sizes don't need to be primes; power of 2 gives the same performance. 1999-11-26 16:59:20 -02:00
Roberto Ierusalimschy
790690a223 new way to keep function arguments (with StkId instead of copy) 1999-11-26 16:53:03 -02:00
Roberto Ierusalimschy
33b8a01032 new way to code CALLs + passing multiple arguments between function calls 1999-11-25 16:59:43 -02:00
Roberto Ierusalimschy
d29ce75737 new signature for function luaD_call (old luaD_calln) 1999-11-25 16:58:51 -02:00
Roberto Ierusalimschy
878ef96127 comment 1999-11-25 16:44:02 -02:00
Roberto Ierusalimschy
e5743adb21 macros key', val', and `node' don't need the state 1999-11-23 11:58:02 -02:00
Roberto Ierusalimschy
514783de9d simpler without `init_hash' 1999-11-22 16:24:50 -02:00
Roberto Ierusalimschy
7d1499ba88 new macro luaL_openl 1999-11-22 15:39:51 -02:00
Roberto Ierusalimschy
29ede6aa13 first implementation of multiple states (reentrant code). 1999-11-22 11:12:07 -02:00
Roberto Ierusalimschy
951897c093 last warnings in Visual C 1999-11-16 10:50:48 -02:00
Roberto Ierusalimschy
a34677e4f4 details 1999-11-12 11:54:44 -02:00
Roberto Ierusalimschy
573372665a new API function `lua_equalobj' 1999-11-11 15:02:40 -02:00
Roberto Ierusalimschy
a6755e2f1a BUG: `strfind' does not handle \0 in plain search. 1999-11-11 14:45:04 -02:00
Roberto Ierusalimschy
a4628a02cf better ways to test lock mechanism 1999-11-10 13:41:11 -02:00
Roberto Ierusalimschy
0c725b2492 buffer can shrink when too big 1999-11-10 13:40:46 -02:00
Roberto Ierusalimschy
d915cf4f9d ways to measure number of `blocks' for GC + details 1999-11-10 13:39:35 -02:00
Roberto Ierusalimschy
53fb65d394 better implementation of `lua_ref' (much better...) 1999-11-10 13:37:50 -02:00
Roberto Ierusalimschy
a7fa7bafc8 new warnings with option "-W" (gcc) 1999-11-09 15:59:35 -02:00
Roberto Ierusalimschy
cde179b369 new implementation for global variable values (separated from strings) 1999-11-04 15:23:12 -02:00
Roberto Ierusalimschy
80b39d83c3 default `success' for exit is more useful. 1999-10-26 09:00:12 -02:00
Roberto Ierusalimschy
5a48255c9f invariant tests over tables performed externally, through a built-in
function (when DEBUG is ion).
1999-10-26 08:53:40 -02:00
Roberto Ierusalimschy
bbab974717 details (comments) 1999-10-25 11:35:44 -02:00
Roberto Ierusalimschy
910836fb53 warnings from Visual C++ 1999-10-19 11:33:22 -02:00
Roberto Ierusalimschy
8e7451512f some more `const's 1999-10-14 17:46:57 -02:00
Roberto Ierusalimschy
4e9f2d13d5 new implementation of hash tables. 1999-10-14 17:13:31 -02:00
Roberto Ierusalimschy
b6ebbb2fee better assertions. 1999-10-14 15:53:35 -02:00
Roberto Ierusalimschy
c5fee7615e new implementation for string hashing, with chaining. 1999-10-11 14:13:42 -02:00
Roberto Ierusalimschy
cca78b5c71 Visual C++ warning 1999-10-11 14:06:01 -02:00
Roberto Ierusalimschy
d435b7acd8 read patterns are deprecated; new option `read(n)' to read n bytes. 1999-10-07 17:18:36 -02:00
Roberto Ierusalimschy
63ccf42397 new API function 'lua_type'. 1999-10-07 17:04:30 -02:00
Roberto Ierusalimschy
1942b58609 details 1999-10-05 16:33:43 -02:00
Roberto Ierusalimschy
4343420d4d simplified version of `gc' tag method (only for userdata now). 1999-10-04 15:51:04 -02:00
Roberto Ierusalimschy
1f7103e05d implementation of lua_ref (previously in module `lmem'). 1999-10-04 15:50:24 -02:00
Roberto Ierusalimschy
dcc10accea temporary version 1999-09-29 09:56:22 -03:00
Roberto Ierusalimschy
e2fc5aa684 checks table size only when element is a new one 1999-09-28 09:27:06 -03:00
Roberto Ierusalimschy
d53e2d2386 details 1999-09-27 15:00:25 -03:00
Roberto Ierusalimschy
cf9a22396c "luaH_set" only needs to check size when key is new 1999-09-22 11:38:45 -03:00
Roberto Ierusalimschy
17374d2daa `put_luaObjectonTop' must be public (to be used by lfback.c), and so
it must have a "public" name: `luaA_putObjectOnTop'
1999-09-21 13:10:13 -03:00
Roberto Ierusalimschy
04265655a8 compatibility with old fallback system now provided by external module 1999-09-20 11:57:29 -03:00
Roberto Ierusalimschy
e10788b2ff reorganization of `stat' function. 1999-09-20 11:15:18 -03:00
Roberto Ierusalimschy
7eb2f18621 remove of some useless #includes 1999-09-17 13:53:54 -03:00
Roberto Ierusalimschy
a8a75fb7ab details 1999-09-13 16:42:02 -03:00
Roberto Ierusalimschy
ae3ecc2d4a tonumber'e1' and tonumber(' ', x), for x!=10, gave 0 instead of nil. 1999-09-08 17:45:18 -03:00
Roberto Ierusalimschy
2e13cd77ab new interface for `luaO_strtod', which now checks signal, too. 1999-09-06 17:34:18 -03:00
Roberto Ierusalimschy
ff9c0da783 test first the most common case. 1999-09-06 17:19:22 -03:00
Roberto Ierusalimschy
f7fe04d4b7 details. 1999-09-06 12:24:46 -03:00
Roberto Ierusalimschy
82699d0c4f new interface for `luaO_strtod', which now checks signal, too. 1999-09-06 10:55:09 -03:00
Roberto Ierusalimschy
88866208f0 luaL_arg_check' always has an extramsg'. 1999-09-06 10:13:03 -03:00
Roberto Ierusalimschy
7d365a5c7a in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
1999-09-02 10:13:22 -03:00
Roberto Ierusalimschy
52a206366d bug: in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
1999-09-02 10:13:22 -03:00
Roberto Ierusalimschy
b2c89ed2d2 new mechanism to access argv from a script 1999-08-18 14:40:54 -03:00
Roberto Ierusalimschy
2a03170ebd random(0) and random(x,0) are wrong (0 is read as no argument!). 1999-08-18 11:40:51 -03:00
Roberto Ierusalimschy
05f55cc062 more warning checking (mainly related to const strings). 1999-08-17 17:21:52 -03:00
Roberto Ierusalimschy
c787dccd9b "const" !!! 1999-08-16 17:52:00 -03:00
Roberto Ierusalimschy
b44e35b773 new constants LUA_NOREF and LUA_REFNIL. 1999-08-11 14:00:59 -03:00
Roberto Ierusalimschy
21843f022a writeto, readfrom, and closefile must return an error code when
closing a file.
1999-08-10 10:05:16 -03:00
Roberto Ierusalimschy
900257e814 char-set may contain '%]' 1999-08-10 09:55:56 -03:00
Roberto Ierusalimschy
a82c8185bc details 1999-08-10 09:55:47 -03:00
Roberto Ierusalimschy
4bbe0679a8 variables _INPUT and _OUTPUT should be read as rawglobal. 1999-07-22 16:35:50 -03:00
Roberto Ierusalimschy
438598aeea details. 1999-07-22 16:35:41 -03:00
Roberto Ierusalimschy
e9a670695a details 1999-07-22 16:29:42 -03:00
Roberto Ierusalimschy
16024861bd new format for numbers in precompiled code (as strings) 1999-07-08 09:43:23 -03:00
Roberto Ierusalimschy
3f43aaa23f new RedHat defines PI :-( 1999-07-07 14:54:08 -03:00
Roberto Ierusalimschy
3b4c831ca9 some systems do not reset signal handlers when a signal happens 1999-07-02 15:22:38 -03:00
Roberto Ierusalimschy
3fdab3981b no more automatic setlocale. 1999-06-24 16:42:02 -03:00
Roberto Ierusalimschy
88b65da4d7 simplifications. 1999-06-23 10:48:39 -03:00
Roberto Ierusalimschy
521b38532a better interfaces for luaD_calln (x luaD_call) 1999-06-22 17:37:23 -03:00
Roberto Ierusalimschy
36b6fe8d17 better treatment for arbitrary limits 1999-06-17 14:04:03 -03:00
Roberto Ierusalimschy
d4dce57f5c cannot assign to unlimited variables, because it causes overflow in
the number of returns of a function.
1999-06-16 10:35:01 -03:00
Roberto Ierusalimschy
5c19ed2a13 bigger limit for number of local variables and upvalues 1999-06-16 10:22:04 -03:00
Roberto Ierusalimschy
5caf7f4a33 tremove erases its previous last element (to avoid locking potential
garbagge).
1999-05-27 17:21:03 -03:00
Roberto Ierusalimschy
3b533ea7c7 foreach, foreachi, foreachvar points to function in stack when stack
can be reallocated.
1999-05-24 14:53:49 -03:00
Roberto Ierusalimschy
995775e1cb tighter control on the stack when debugging 1999-05-24 14:53:03 -03:00
Roberto Ierusalimschy
abfc885079 when debugging, move and erase old blocks to realloc. 1999-05-24 14:51:05 -03:00
Roberto Ierusalimschy
613b60c156 detail 1999-05-21 16:54:06 -03:00
Roberto Ierusalimschy
cdd0fe9946 some C compilers cannot initialize a local struct 1999-05-21 16:41:49 -03:00
Roberto Ierusalimschy
bc8619342a better control of stack size (only for DEBUG). 1999-05-21 14:23:15 -03:00
Roberto Ierusalimschy
48326500d0 longer marks when controling memory leaks 1999-05-20 17:43:06 -03:00
Roberto Ierusalimschy
c8d219798a lhf 1999-05-17 11:12:01 -03:00
Roberto Ierusalimschy
34695d4f4a details (message text) 1999-05-14 09:24:20 -03:00
Roberto Ierusalimschy
924bbe020b bigger limits 1999-05-14 09:24:04 -03:00
Roberto Ierusalimschy
3aa500b524 new pattern item '+' 1999-05-11 17:46:28 -03:00
Roberto Ierusalimschy
f1861ee210 no more beta 1999-05-11 17:29:19 -03:00
Roberto Ierusalimschy
705eae9fe4 there is no need for a size for Cblocks 1999-05-11 17:08:20 -03:00
Roberto Ierusalimschy
6eb1399a1c array Cblocks should grow dynamically 1999-05-11 11:19:32 -03:00
Roberto Ierusalimschy
c390f73e3b block must always have a power-of-2 size (even at the limit) 1999-05-11 11:18:40 -03:00
Roberto Ierusalimschy
73308c7605 warnings by clinio 1999-05-10 10:54:01 -03:00
Roberto Ierusalimschy
288fa05602 opcodes with LONGARG do not use byte variants. 1999-05-06 11:41:41 -03:00
Roberto Ierusalimschy
7808ea3a5f new implementation for '*' in patterns + new option '+' 1999-05-05 16:23:11 -03:00
Roberto Ierusalimschy
732741b62f cannot use (i=i+1) 1999-05-05 16:21:57 -03:00
Roberto Ierusalimschy
cc0f635ef7 '$' at end of pattern was matching regular '$', too. 1999-04-30 11:12:05 -03:00
55 changed files with 11565 additions and 8665 deletions

164
bugs
View File

@@ -1,9 +1,12 @@
** lua.stx / llex.c ** lua.stx / llex.c
Tue Dec 2 10:45:48 EDT 1997 Tue Dec 2 10:45:48 EDT 1997
>> BUG: "lastline" was not reset on function entry, so debug information >> BUG: "lastline" was not reset on function entry, so debug information
>> started only in the 2nd line of a function. >> started only in the 2nd line of a function.
=================================================================
--- Version 3.1 alpha --- Version 3.1 alpha
** lua.c ** lua.c
@@ -13,7 +16,7 @@ Thu Jan 15 14:34:58 EDT 1998
** lbuiltin.c / lobject.h ** lbuiltin.c / lobject.h
Thu Jan 15 14:34:58 EDT 1998 Thu Jan 15 14:34:58 EDT 1998
>> MAX_WORD may be bigger than MAX_INT >> MAX_WORD may be bigger than MAX_INT
(by lhf)
** llex.c ** llex.c
Mon Jan 19 18:17:18 EDT 1998 Mon Jan 19 18:17:18 EDT 1998
@@ -42,6 +45,8 @@ Mon May 18 19:20:00 EST 1998
>> arguments for "format" 'x', 'X', 'o' and 'u' must be unsigned int. >> arguments for "format" 'x', 'X', 'o' and 'u' must be unsigned int.
=================================================================
--- Version 3.1 --- Version 3.1
** liolib.c / lauxlib.c ** liolib.c / lauxlib.c
@@ -52,11 +57,13 @@ of view) when functions have upvalues.
** lstrlib.c ** lstrlib.c
Tue Nov 10 17:29:36 EDT 1998 Tue Nov 10 17:29:36 EDT 1998
>> gsub/strfind do not check whether captures are properly finished. >> gsub/strfind do not check whether captures are properly finished.
(by roberto/tomas)
** lbuiltin.c ** lbuiltin.c
Fri Dec 18 11:22:55 EDT 1998 Fri Dec 18 11:22:55 EDT 1998
>> "tonumber" goes crazy with negative numbers in other bases (not 10), >> "tonumber" goes crazy with negative numbers in other bases (not 10),
because "strtol" returns long, not unsigned long. because "strtol" returns long, not unsigned long.
(by Visual C++)
** lstrlib.c ** lstrlib.c
Mon Jan 4 10:41:40 EDT 1999 Mon Jan 4 10:41:40 EDT 1999
@@ -70,8 +77,161 @@ lua_isnumber can modify it.
** lstrlib.c ** lstrlib.c
Thu Feb 4 17:08:50 EDT 1999 Thu Feb 4 17:08:50 EDT 1999
>> format "%s" may break limit of "sprintf" on some machines. >> format "%s" may break limit of "sprintf" on some machines.
(by Marcelo Sales)
** lzio.c ** lzio.c
Thu Mar 4 11:49:37 EST 1999 Thu Mar 4 11:49:37 EST 1999
>> file stream cannot call fread after EOF. >> file stream cannot call fread after EOF.
(by lhf)
=================================================================
--- Version 3.2 (beta)
** lstrlib.c
Fri Apr 30 11:10:20 EST 1999
>> '$' at end of pattern was matching regular '$', too.
(by anna; since 2.5)
** lbuiltin.c
Fri May 21 17:15:11 EST 1999
>> foreach, foreachi, foreachvar points to function in stack when stack
can be reallocated.
(by tomas; since 3.2 beta)
** lparser.c
Wed Jun 16 10:32:46 EST 1999
>> cannot assign to unlimited variables, because it causes overflow in
the number of returns of a function.
(since 3.1)
=================================================================
--- Version 3.2
** lmathlib.c
Wed Aug 18 11:28:38 EST 1999
>> random(0) and random(x,0) are wrong (0 is read as no argument!).
(by Dave Bollinger; since 3.1)
** lparser.c
Thu Sep 2 10:07:20 EST 1999
>> in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
(by Supratik Champati; since 3.2 beta)
** lobject.c / lbuiltin.c
Wed Sep 8 17:41:54 EST 1999
>> tonumber'e1' and tonumber(' ', x), for x!=10, gave 0 instead of nil.
(since 3.1)
** lstrlib.c
Thu Nov 11 14:36:30 EDT 1999
>> `strfind' does not handle \0 in plain search.
(by Jon Kleiser; since 3.1)
** lparser.c
Wed Dec 29 16:05:43 EDT 1999
>> return gives wrong line in debug information
(by lhf; since 3.2 [at least])
** ldo.c
Thu Dec 30 16:39:33 EDT 1999
>> cannot reopen stdin (for binary mode)
(by lhf & roberto; since 3.1)
** lapi.c
Thu Mar 2 09:41:53 EST 2000
>> lua_settable should check stack space (it could call a T.M.)
(by lhf & celes; since 3.2; it was already fixed by fixed stack)
** lparser.c
Mon Apr 3 09:59:06 EST 2000
>> '%' should be in expfollow
(by Edgar Toernig; since 3.1; it was already fixed)
** lbuiltin.c
Mon Apr 3 10:05:05 EST 2000
>> tostring() without arguments gives seg. fault.
(by Edgar Toernig; since 3.0)
=================================================================
--- Version 4.0 alpha
Tested with full test suites (as locked in Mon Apr 24 14:23:11 EST 2000)
in the following platforms:
* Linux - gcc, g++
* AIX - gcc
* Solaris - gcc, cc
* IRIX - cc, cc-purify
* Windows - Visual C++ (.c e .cpp, warning level=4)
** lstrlib.c
Tue May 2 15:27:58 EST 2000
>> `strfind' gets wrong subject length when there is an offset
(by Jon Kleiser; since 4.0a)
** lparser.c
Fri May 12 15:11:12 EST 2000
>> first element in a list constructor is not adjusted to one value
>> (e.g. «a = {gsub('a','a','')}»)
(by Tomas; since 4.0a)
** lparser.c
Wed May 24 14:50:16 EST 2000
>> record-constructor starting with an upvalue name gets an error
>> (e.g. «local a; function f() x = {a=1} end»)
(by Edgar Toernig; since 3.1)
** lparser.c
Tue Aug 29 15:56:05 EST 2000
>> error message for `for' uses `while'
(since 4.0a; already corrected)
** lgc.c
Tue Aug 29 15:57:41 EST 2000
>> gc tag method for nil could call line hook
(by ry; since ?)
=================================================================
--- Version 4.0 Beta
** liolib.c
Fri Sep 22 15:12:37 EST 2000
>> `read("*w")' should return nil at EOF
(by roberto; since 4.0b)
** lvm.c
Mon Sep 25 11:47:48 EST 2000
>> lua_gettable does not get key from stack top
(by Philip Yi; since 4.0b)
** lgc.c
Mon Sep 25 11:50:48 EST 2000
>> GC may crash when checking locked C closures
(by Philip Yi; since 4.0b)
** lapi.c
Wed Sep 27 09:50:19 EST 2000
>> lua_tag should return LUA_NOTAG for non-valid indices
(by Paul Hankin; since 4.0b)
** llex.h / llex.c / lparser.c
Wed Sep 27 13:39:45 EST 2000
>> parser overwrites semantic information when looking ahead
>> (e.g. «a = {print'foo'}»)
(by Edgar Toernig; since 4.0b, deriving from previous bug)
** liolib.c
Thu Oct 26 10:50:46 EDT 2000
>> in function `read_file', realloc() doesn't free the buffer if it can't
>> allocate new memory
(by Mauro Vezzosi; since 4.0b)

968
lapi.c

File diff suppressed because it is too large Load Diff

11
lapi.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lapi.h,v 1.3 1999/02/22 19:13:12 roberto Exp roberto $ ** $Id: lapi.h,v 1.19 2000/08/28 17:57:04 roberto Exp roberto $
** Auxiliary functions from Lua API ** Auxiliary functions from Lua API
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -8,15 +8,10 @@
#define lapi_h #define lapi_h
#include "lua.h"
#include "lobject.h" #include "lobject.h"
TObject *luaA_Address (lua_Object o); TObject *luaA_index (lua_State *L, int index);
void luaA_pushobject (TObject *o); void luaA_pushobject (lua_State *L, const TObject *o);
void luaA_packresults (void);
int luaA_passresults (void);
TaggedString *luaA_nextvar (TaggedString *g);
int luaA_next (Hash *t, int i);
#endif #endif

241
lauxlib.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lauxlib.c,v 1.16 1999/03/10 14:19:41 roberto Exp roberto $ ** $Id: lauxlib.c,v 1.42 2000/10/30 12:38:50 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
*/ */
@@ -9,18 +9,19 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
/* Please Notice: This file uses only the official API of Lua /* This file uses only the official API of Lua.
** Any function declared here could be written as an application function. ** Any function declared here could be written as an application function.
** With care, these functions can be used by other libraries. ** With care, these functions can be used by other libraries.
*/ */
#include "lauxlib.h"
#include "lua.h" #include "lua.h"
#include "lauxlib.h"
#include "luadebug.h" #include "luadebug.h"
int luaL_findstring (char *name, char *list[]) { LUALIB_API int luaL_findstring (const char *name, const char *const list[]) {
int i; int i;
for (i=0; list[i]; i++) for (i=0; list[i]; i++)
if (strcmp(list[i], name) == 0) if (strcmp(list[i], name) == 0)
@@ -28,106 +29,188 @@ int luaL_findstring (char *name, char *list[]) {
return -1; /* name not found */ return -1; /* name not found */
} }
void luaL_argerror (int numarg, char *extramsg) { LUALIB_API void luaL_argerror (lua_State *L, int narg, const char *extramsg) {
lua_Function f = lua_stackedfunction(0); lua_Debug ar;
char *funcname; lua_getstack(L, 0, &ar);
lua_getobjname(f, &funcname); lua_getinfo(L, "n", &ar);
numarg -= lua_nups(f); if (ar.name == NULL)
if (funcname == NULL) ar.name = "?";
funcname = "?"; luaL_verror(L, "bad argument #%d to `%.50s' (%.100s)",
if (extramsg == NULL) narg, ar.name, extramsg);
luaL_verror("bad argument #%d to function `%.50s'", numarg, funcname);
else
luaL_verror("bad argument #%d to function `%.50s' (%.100s)",
numarg, funcname, extramsg);
}
char *luaL_check_lstr (int numArg, long *len)
{
lua_Object o = lua_getparam(numArg);
luaL_arg_check(lua_isstring(o), numArg, "string expected");
if (len) *len = lua_strlen(o);
return lua_getstring(o);
}
char *luaL_opt_lstr (int numArg, char *def, long *len)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
luaL_check_lstr(numArg, len);
}
double luaL_check_number (int numArg)
{
lua_Object o = lua_getparam(numArg);
luaL_arg_check(lua_isnumber(o), numArg, "number expected");
return lua_getnumber(o);
} }
double luaL_opt_number (int numArg, double def) static void type_error (lua_State *L, int narg, int t) {
{ char buff[50];
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def : sprintf(buff, "%.8s expected, got %.8s", lua_typename(L, t),
luaL_check_number(numArg); lua_typename(L, lua_type(L, narg)));
} luaL_argerror(L, narg, buff);
lua_Object luaL_tablearg (int arg)
{
lua_Object o = lua_getparam(arg);
luaL_arg_check(lua_istable(o), arg, "table expected");
return o;
} }
lua_Object luaL_functionarg (int arg)
{ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
lua_Object o = lua_getparam(arg); if (space > lua_stackspace(L))
luaL_arg_check(lua_isfunction(o), arg, "function expected"); luaL_verror(L, "stack overflow (%.30s)", mes);
return o;
} }
lua_Object luaL_nonnullarg (int numArg)
{ LUALIB_API void luaL_checktype(lua_State *L, int narg, int t) {
lua_Object o = lua_getparam(numArg); if (lua_type(L, narg) != t)
luaL_arg_check(o != LUA_NOOBJECT, numArg, "value expected"); type_error(L, narg, t);
return o;
} }
void luaL_openlib (struct luaL_reg *l, int n)
{ LUALIB_API void luaL_checkany (lua_State *L, int narg) {
if (lua_type(L, narg) == LUA_TNONE)
luaL_argerror(L, narg, "value expected");
}
LUALIB_API const char *luaL_check_lstr (lua_State *L, int narg, size_t *len) {
const char *s = lua_tostring(L, narg);
if (!s) type_error(L, narg, LUA_TSTRING);
if (len) *len = lua_strlen(L, narg);
return s;
}
LUALIB_API const char *luaL_opt_lstr (lua_State *L, int narg, const char *def, size_t *len) {
if (lua_isnull(L, narg)) {
if (len)
*len = (def ? strlen(def) : 0);
return def;
}
else return luaL_check_lstr(L, narg, len);
}
LUALIB_API double luaL_check_number (lua_State *L, int narg) {
double d = lua_tonumber(L, narg);
if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
type_error(L, narg, LUA_TNUMBER);
return d;
}
LUALIB_API double luaL_opt_number (lua_State *L, int narg, double def) {
if (lua_isnull(L, narg)) return def;
else return luaL_check_number(L, narg);
}
LUALIB_API void luaL_openlib (lua_State *L, const struct luaL_reg *l, int n) {
int i; int i;
lua_open(); /* make sure lua is already open */
for (i=0; i<n; i++) for (i=0; i<n; i++)
lua_register(l[i].name, l[i].func); lua_register(L, l[i].name, l[i].func);
} }
void luaL_verror (char *fmt, ...) LUALIB_API void luaL_verror (lua_State *L, const char *fmt, ...) {
{
char buff[500]; char buff[500];
va_list argp; va_list argp;
va_start(argp, fmt); va_start(argp, fmt);
vsprintf(buff, fmt, argp); vsprintf(buff, fmt, argp);
va_end(argp); va_end(argp);
lua_error(buff); lua_error(L, buff);
} }
void luaL_chunkid (char *out, char *source, int len) { /*
len -= 13; /* 13 = strlen("string ''...\0") */ ** {======================================================
if (*source == '@') ** Generic Buffer manipulation
sprintf(out, "file `%.*s'", len, source+1); ** =======================================================
else if (*source == '(') */
strcpy(out, "(C code)");
#define buffempty(B) ((B)->p == (B)->buffer)
#define bufflen(B) ((B)->p - (B)->buffer)
#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
#define LIMIT (LUA_MINSTACK/2)
static int emptybuffer (luaL_Buffer *B) {
size_t l = bufflen(B);
if (l == 0) return 0; /* put nothing on stack */
else { else {
char *b = strchr(source , '\n'); /* stop string at first new line */ lua_pushlstring(B->L, B->buffer, l);
int lim = (b && (b-source)<len) ? b-source : len; B->p = B->buffer;
sprintf(out, "string `%.*s'", lim, source); B->level++;
strcpy(out+lim+(13-5), "...'"); /* 5 = strlen("...'\0") */ return 1;
} }
} }
void luaL_filesource (char *out, char *filename, int len) { static void adjuststack (luaL_Buffer *B) {
if (filename == NULL) filename = "(stdin)"; if (B->level > 1) {
sprintf(out, "@%.*s", len-2, filename); /* -2 for '@' and '\0' */ lua_State *L = B->L;
int toget = 1; /* number of levels to concat */
size_t toplen = lua_strlen(L, -1);
do {
size_t l = lua_strlen(L, -(toget+1));
if (B->level - toget + 1 >= LIMIT || toplen > l) {
toplen += l;
toget++;
}
else break;
} while (toget < B->level);
if (toget >= 2) {
lua_concat(L, toget);
B->level = B->level - toget + 1;
}
}
} }
LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
if (emptybuffer(B))
adjuststack(B);
return B->buffer;
}
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
while (l--)
luaL_putchar(B, *s++);
}
LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
luaL_addlstring(B, s, strlen(s));
}
LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
emptybuffer(B);
if (B->level == 0)
lua_pushlstring(B->L, NULL, 0);
else if (B->level > 1)
lua_concat(B->L, B->level);
B->level = 1;
}
LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
lua_State *L = B->L;
size_t vl = lua_strlen(L, -1);
if (vl <= bufffree(B)) { /* fit into buffer? */
memcpy(B->p, lua_tostring(L, -1), vl); /* put it there */
B->p += vl;
lua_pop(L, 1); /* remove from stack */
}
else {
if (emptybuffer(B))
lua_insert(L, -2); /* put buffer before new value */
B->level++; /* add new value into B stack */
adjuststack(B);
}
}
LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
B->L = L;
B->p = B->buffer;
B->level = 0;
}
/* }====================================================== */

113
lauxlib.h
View File

@@ -1,53 +1,100 @@
/* /*
** $Id: lauxlib.h,v 1.11 1999/03/04 21:17:26 roberto Exp roberto $ ** $Id: lauxlib.h,v 1.29 2000/10/27 16:15:53 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
*/ */
#ifndef auxlib_h #ifndef lauxlib_h
#define auxlib_h #define lauxlib_h
#include <stddef.h>
#include <stdio.h>
#include "lua.h" #include "lua.h"
#ifndef LUALIB_API
#define LUALIB_API extern
#endif
struct luaL_reg { struct luaL_reg {
char *name; const char *name;
lua_CFunction func; lua_CFunction func;
}; };
#define luaL_arg_check(cond,numarg,extramsg) if (!(cond)) \ LUALIB_API void luaL_openlib (lua_State *L, const struct luaL_reg *l, int n);
luaL_argerror(numarg,extramsg) LUALIB_API void luaL_argerror (lua_State *L, int numarg, const char *extramsg);
LUALIB_API const char *luaL_check_lstr (lua_State *L, int numArg, size_t *len);
LUALIB_API const char *luaL_opt_lstr (lua_State *L, int numArg, const char *def, size_t *len);
LUALIB_API double luaL_check_number (lua_State *L, int numArg);
LUALIB_API double luaL_opt_number (lua_State *L, int numArg, double def);
void luaL_openlib (struct luaL_reg *l, int n); LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg);
void luaL_argerror (int numarg, char *extramsg); LUALIB_API void luaL_checktype (lua_State *L, int narg, int t);
#define luaL_check_string(n) (luaL_check_lstr((n), NULL)) LUALIB_API void luaL_checkany (lua_State *L, int narg);
char *luaL_check_lstr (int numArg, long *len);
#define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL)) LUALIB_API void luaL_verror (lua_State *L, const char *fmt, ...);
char *luaL_opt_lstr (int numArg, char *def, long *len); LUALIB_API int luaL_findstring (const char *name, const char *const list[]);
double luaL_check_number (int numArg);
#define luaL_check_int(n) ((int)luaL_check_number(n))
#define luaL_check_long(n) ((long)luaL_check_number(n))
double luaL_opt_number (int numArg, double def); /*
#define luaL_opt_int(n,d) ((int)luaL_opt_number(n,d)) ** ===============================================================
#define luaL_opt_long(n,d) ((long)luaL_opt_number(n,d)) ** some useful macros
lua_Object luaL_functionarg (int arg); ** ===============================================================
lua_Object luaL_tablearg (int arg); */
lua_Object luaL_nonnullarg (int numArg);
void luaL_verror (char *fmt, ...); #define luaL_arg_check(L, cond,numarg,extramsg) if (!(cond)) \
char *luaL_openspace (int size); luaL_argerror(L, numarg,extramsg)
void luaL_resetbuffer (void); #define luaL_check_string(L,n) (luaL_check_lstr(L, (n), NULL))
void luaL_addchar (int c); #define luaL_opt_string(L,n,d) (luaL_opt_lstr(L, (n), (d), NULL))
int luaL_getsize (void); #define luaL_check_int(L,n) ((int)luaL_check_number(L, n))
void luaL_addsize (int n); #define luaL_check_long(L,n) ((long)luaL_check_number(L, n))
int luaL_newbuffer (int size); #define luaL_opt_int(L,n,d) ((int)luaL_opt_number(L, n,d))
void luaL_oldbuffer (int old); #define luaL_opt_long(L,n,d) ((long)luaL_opt_number(L, n,d))
char *luaL_buffer (void); #define luaL_openl(L,a) luaL_openlib(L, a, (sizeof(a)/sizeof(a[0])))
int luaL_findstring (char *name, char *list[]);
void luaL_chunkid (char *out, char *source, int len);
void luaL_filesource (char *out, char *filename, int len); /*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
#ifndef LUAL_BUFFERSIZE
#define LUAL_BUFFERSIZE BUFSIZ
#endif
typedef struct luaL_Buffer {
char *p; /* current position in buffer */
int level;
lua_State *L;
char buffer[LUAL_BUFFERSIZE];
} luaL_Buffer;
#define luaL_putchar(B,c) \
((void)((B)->p < &(B)->buffer[LUAL_BUFFERSIZE] || luaL_prepbuffer(B)), \
(*(B)->p++ = (char)(c)))
#define luaL_addsize(B,n) ((B)->p += (n))
LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B);
LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B);
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s);
LUALIB_API void luaL_addvalue (luaL_Buffer *B);
LUALIB_API void luaL_pushresult (luaL_Buffer *B);
/* }====================================================== */
#endif #endif

651
lbaselib.c Normal file
View File

@@ -0,0 +1,651 @@
/*
** $Id: lbaselib.c,v 1.16 2000/10/31 13:10:24 roberto Exp roberto $
** Basic library
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "luadebug.h"
#include "lualib.h"
/*
** If your system does not support `stderr', redefine this function, or
** redefine _ERRORMESSAGE so that it won't need _ALERT.
*/
static int luaB__ALERT (lua_State *L) {
fputs(luaL_check_string(L, 1), stderr);
return 0;
}
/*
** Basic implementation of _ERRORMESSAGE.
** The library `liolib' redefines _ERRORMESSAGE for better error information.
*/
static int luaB__ERRORMESSAGE (lua_State *L) {
luaL_checktype(L, 1, LUA_TSTRING);
lua_getglobal(L, LUA_ALERT);
if (lua_isfunction(L, -1)) { /* avoid error loop if _ALERT is not defined */
lua_Debug ar;
lua_pushstring(L, "error: ");
lua_pushvalue(L, 1);
if (lua_getstack(L, 1, &ar)) {
lua_getinfo(L, "Sl", &ar);
if (ar.source && ar.currentline > 0) {
char buff[100];
sprintf(buff, "\n <%.70s: line %d>", ar.short_src, ar.currentline);
lua_pushstring(L, buff);
lua_concat(L, 2);
}
}
lua_pushstring(L, "\n");
lua_concat(L, 3);
lua_rawcall(L, 1, 0);
}
return 0;
}
/*
** If your system does not support `stdout', you can just remove this function.
** If you need, you can define your own `print' function, following this
** model but changing `fputs' to put the strings at a proper place
** (a console window or a log file, for instance).
*/
static int luaB_print (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
int i;
lua_getglobal(L, "tostring");
for (i=1; i<=n; i++) {
const char *s;
lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */
lua_rawcall(L, 1, 1);
s = lua_tostring(L, -1); /* get result */
if (s == NULL)
lua_error(L, "`tostring' must return a string to `print'");
if (i>1) fputs("\t", stdout);
fputs(s, stdout);
lua_pop(L, 1); /* pop result */
}
fputs("\n", stdout);
return 0;
}
static int luaB_tonumber (lua_State *L) {
int base = luaL_opt_int(L, 2, 10);
if (base == 10) { /* standard conversion */
luaL_checkany(L, 1);
if (lua_isnumber(L, 1)) {
lua_pushnumber(L, lua_tonumber(L, 1));
return 1;
}
}
else {
const char *s1 = luaL_check_string(L, 1);
char *s2;
unsigned long n;
luaL_arg_check(L, 2 <= base && base <= 36, 2, "base out of range");
n = strtoul(s1, &s2, base);
if (s1 != s2) { /* at least one valid digit? */
while (isspace((unsigned char)*s2)) s2++; /* skip trailing spaces */
if (*s2 == '\0') { /* no invalid trailing characters? */
lua_pushnumber(L, n);
return 1;
}
}
}
lua_pushnil(L); /* else not a number */
return 1;
}
static int luaB_error (lua_State *L) {
lua_error(L, luaL_opt_string(L, 1, NULL));
return 0; /* to avoid warnings */
}
static int luaB_setglobal (lua_State *L) {
luaL_checkany(L, 2);
lua_setglobal(L, luaL_check_string(L, 1));
return 0;
}
static int luaB_getglobal (lua_State *L) {
lua_getglobal(L, luaL_check_string(L, 1));
return 1;
}
static int luaB_tag (lua_State *L) {
luaL_checkany(L, 1);
lua_pushnumber(L, lua_tag(L, 1));
return 1;
}
static int luaB_settag (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, 1); /* push table */
lua_settag(L, luaL_check_int(L, 2));
return 1; /* return table */
}
static int luaB_newtag (lua_State *L) {
lua_pushnumber(L, lua_newtag(L));
return 1;
}
static int luaB_copytagmethods (lua_State *L) {
lua_pushnumber(L, lua_copytagmethods(L, luaL_check_int(L, 1),
luaL_check_int(L, 2)));
return 1;
}
static int luaB_globals (lua_State *L) {
lua_getglobals(L); /* value to be returned */
if (!lua_isnull(L, 1)) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, 1); /* new table of globals */
lua_setglobals(L);
}
return 1;
}
static int luaB_rawget (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
lua_rawget(L, -2);
return 1;
}
static int luaB_rawset (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
luaL_checkany(L, 3);
lua_rawset(L, -3);
return 1;
}
static int luaB_settagmethod (lua_State *L) {
int tag = luaL_check_int(L, 1);
const char *event = luaL_check_string(L, 2);
luaL_arg_check(L, lua_isfunction(L, 3) || lua_isnil(L, 3), 3,
"function or nil expected");
if (strcmp(event, "gc") == 0)
lua_error(L, "deprecated use: cannot set the `gc' tag method from Lua");
lua_gettagmethod(L, tag, event);
lua_pushvalue(L, 3);
lua_settagmethod(L, tag, event);
return 1;
}
static int luaB_gettagmethod (lua_State *L) {
int tag = luaL_check_int(L, 1);
const char *event = luaL_check_string(L, 2);
if (strcmp(event, "gc") == 0)
lua_error(L, "deprecated use: cannot get the `gc' tag method from Lua");
lua_gettagmethod(L, tag, event);
return 1;
}
static int luaB_gcinfo (lua_State *L) {
lua_pushnumber(L, lua_getgccount(L));
lua_pushnumber(L, lua_getgcthreshold(L));
return 2;
}
static int luaB_collectgarbage (lua_State *L) {
lua_setgcthreshold(L, luaL_opt_int(L, 1, 0));
return 0;
}
static int luaB_type (lua_State *L) {
luaL_checkany(L, 1);
lua_pushstring(L, lua_typename(L, lua_type(L, 1)));
return 1;
}
static int luaB_next (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
if (lua_next(L, 1))
return 2;
else {
lua_pushnil(L);
return 1;
}
}
static int passresults (lua_State *L, int status, int oldtop) {
static const char *const errornames[] =
{"ok", "run-time error", "file error", "syntax error",
"memory error", "error in error handling"};
if (status == 0) {
int nresults = lua_gettop(L) - oldtop;
if (nresults > 0)
return nresults; /* results are already on the stack */
else {
lua_pushuserdata(L, NULL); /* at least one result to signal no errors */
return 1;
}
}
else { /* error */
lua_pushnil(L);
lua_pushstring(L, errornames[status]); /* error code */
return 2;
}
}
static int luaB_dostring (lua_State *L) {
int oldtop = lua_gettop(L);
size_t l;
const char *s = luaL_check_lstr(L, 1, &l);
if (*s == '\27') /* binary files start with ESC... */
lua_error(L, "`dostring' cannot run pre-compiled code");
return passresults(L, lua_dobuffer(L, s, l, luaL_opt_string(L, 2, s)), oldtop);
}
static int luaB_dofile (lua_State *L) {
int oldtop = lua_gettop(L);
const char *fname = luaL_opt_string(L, 1, NULL);
return passresults(L, lua_dofile(L, fname), oldtop);
}
static int luaB_call (lua_State *L) {
int oldtop;
const char *options = luaL_opt_string(L, 3, "");
int err = 0; /* index of old error method */
int i, status;
int n;
luaL_checktype(L, 2, LUA_TTABLE);
n = lua_getn(L, 2);
if (!lua_isnull(L, 4)) { /* set new error method */
lua_getglobal(L, LUA_ERRORMESSAGE);
err = lua_gettop(L); /* get index */
lua_pushvalue(L, 4);
lua_setglobal(L, LUA_ERRORMESSAGE);
}
oldtop = lua_gettop(L); /* top before function-call preparation */
/* push function */
lua_pushvalue(L, 1);
luaL_checkstack(L, n, "too many arguments");
for (i=0; i<n; i++) /* push arg[1...n] */
lua_rawgeti(L, 2, i+1);
status = lua_call(L, n, LUA_MULTRET);
if (err != 0) { /* restore old error method */
lua_pushvalue(L, err);
lua_setglobal(L, LUA_ERRORMESSAGE);
}
if (status != 0) { /* error in call? */
if (strchr(options, 'x'))
lua_pushnil(L); /* return nil to signal the error */
else
lua_error(L, NULL); /* propagate error without additional messages */
return 1;
}
if (strchr(options, 'p')) /* pack results? */
lua_error(L, "deprecated option `p' in `call'");
return lua_gettop(L) - oldtop; /* results are already on the stack */
}
static int luaB_tostring (lua_State *L) {
char buff[64];
switch (lua_type(L, 1)) {
case LUA_TNUMBER:
lua_pushstring(L, lua_tostring(L, 1));
return 1;
case LUA_TSTRING:
lua_pushvalue(L, 1);
return 1;
case LUA_TTABLE:
sprintf(buff, "table: %p", lua_topointer(L, 1));
break;
case LUA_TFUNCTION:
sprintf(buff, "function: %p", lua_topointer(L, 1));
break;
case LUA_TUSERDATA:
sprintf(buff, "userdata(%d): %p", lua_tag(L, 1), lua_touserdata(L, 1));
break;
case LUA_TNIL:
lua_pushstring(L, "nil");
return 1;
default:
luaL_argerror(L, 1, "value expected");
}
lua_pushstring(L, buff);
return 1;
}
static int luaB_foreachi (lua_State *L) {
int n, i;
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
n = lua_getn(L, 1);
for (i=1; i<=n; i++) {
lua_pushvalue(L, 2); /* function */
lua_pushnumber(L, i); /* 1st argument */
lua_rawgeti(L, 1, i); /* 2nd argument */
lua_rawcall(L, 2, 1);
if (!lua_isnil(L, -1))
return 1;
lua_pop(L, 1); /* remove nil result */
}
return 0;
}
static int luaB_foreach (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushnil(L); /* first index */
for (;;) {
if (lua_next(L, 1) == 0)
return 0;
lua_pushvalue(L, 2); /* function */
lua_pushvalue(L, -3); /* key */
lua_pushvalue(L, -3); /* value */
lua_rawcall(L, 2, 1);
if (!lua_isnil(L, -1))
return 1;
lua_pop(L, 2); /* remove value and result */
}
}
static int luaB_assert (lua_State *L) {
luaL_checkany(L, 1);
if (lua_isnil(L, 1))
luaL_verror(L, "assertion failed! %.90s", luaL_opt_string(L, 2, ""));
return 0;
}
static int luaB_getn (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushnumber(L, lua_getn(L, 1));
return 1;
}
static int luaB_tinsert (lua_State *L) {
int v = lua_gettop(L); /* last argument: to be inserted */
int n, pos;
luaL_checktype(L, 1, LUA_TTABLE);
n = lua_getn(L, 1);
if (v == 2) /* called with only 2 arguments */
pos = n+1;
else
pos = luaL_check_int(L, 2); /* 2nd argument is the position */
lua_pushstring(L, "n");
lua_pushnumber(L, n+1);
lua_rawset(L, 1); /* t.n = n+1 */
for (; n>=pos; n--) {
lua_rawgeti(L, 1, n);
lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */
}
lua_pushvalue(L, v);
lua_rawseti(L, 1, pos); /* t[pos] = v */
return 0;
}
static int luaB_tremove (lua_State *L) {
int pos, n;
luaL_checktype(L, 1, LUA_TTABLE);
n = lua_getn(L, 1);
pos = luaL_opt_int(L, 2, n);
if (n <= 0) return 0; /* table is "empty" */
lua_rawgeti(L, 1, pos); /* result = t[pos] */
for ( ;pos<n; pos++) {
lua_rawgeti(L, 1, pos+1);
lua_rawseti(L, 1, pos); /* a[pos] = a[pos+1] */
}
lua_pushstring(L, "n");
lua_pushnumber(L, n-1);
lua_rawset(L, 1); /* t.n = n-1 */
lua_pushnil(L);
lua_rawseti(L, 1, n); /* t[n] = nil */
return 1;
}
/*
** {======================================================
** Quicksort
** (based on `Algorithms in MODULA-3', Robert Sedgewick;
** Addison-Wesley, 1993.)
*/
static void set2 (lua_State *L, int i, int j) {
lua_rawseti(L, 1, i);
lua_rawseti(L, 1, j);
}
static int sort_comp (lua_State *L, int a, int b) {
/* WARNING: the caller (auxsort) must ensure stack space */
if (!lua_isnil(L, 2)) { /* function? */
int res;
lua_pushvalue(L, 2);
lua_pushvalue(L, a-1); /* -1 to compensate function */
lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
lua_rawcall(L, 2, 1);
res = !lua_isnil(L, -1);
lua_pop(L, 1);
return res;
}
else /* a < b? */
return lua_lessthan(L, a, b);
}
static void auxsort (lua_State *L, int l, int u) {
while (l < u) { /* for tail recursion */
int i, j;
/* sort elements a[l], a[(l+u)/2] and a[u] */
lua_rawgeti(L, 1, l);
lua_rawgeti(L, 1, u);
if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
set2(L, l, u); /* swap a[l] - a[u] */
else
lua_pop(L, 2);
if (u-l == 1) break; /* only 2 elements */
i = (l+u)/2;
lua_rawgeti(L, 1, i);
lua_rawgeti(L, 1, l);
if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
set2(L, i, l);
else {
lua_pop(L, 1); /* remove a[l] */
lua_rawgeti(L, 1, u);
if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
set2(L, i, u);
else
lua_pop(L, 2);
}
if (u-l == 2) break; /* only 3 elements */
lua_rawgeti(L, 1, i); /* Pivot */
lua_pushvalue(L, -1);
lua_rawgeti(L, 1, u-1);
set2(L, i, u-1);
/* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
i = l; j = u-1;
for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
/* repeat ++i until a[i] >= P */
while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
if (i>u) lua_error(L, "invalid order function for sorting");
lua_pop(L, 1); /* remove a[i] */
}
/* repeat --j until a[j] <= P */
while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
if (j<l) lua_error(L, "invalid order function for sorting");
lua_pop(L, 1); /* remove a[j] */
}
if (j<i) {
lua_pop(L, 3); /* pop pivot, a[i], a[j] */
break;
}
set2(L, i, j);
}
lua_rawgeti(L, 1, u-1);
lua_rawgeti(L, 1, i);
set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
/* a[l..i-1] <= a[i] == P <= a[i+1..u] */
/* adjust so that smaller "half" is in [j..i] and larger one in [l..u] */
if (i-l < u-i) {
j=l; i=i-1; l=i+2;
}
else {
j=i+1; i=u; u=j-2;
}
auxsort(L, j, i); /* call recursively the smaller one */
} /* repeat the routine for the larger one */
}
static int luaB_sort (lua_State *L) {
int n;
luaL_checktype(L, 1, LUA_TTABLE);
n = lua_getn(L, 1);
if (!lua_isnull(L, 2)) /* is there a 2nd argument? */
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_settop(L, 2); /* make sure there is two arguments */
auxsort(L, 1, n);
return 0;
}
/* }====================================================== */
/*
** {======================================================
** Deprecated functions to manipulate global environment.
** =======================================================
*/
#define num_deprecated 4
static const struct luaL_reg deprecated_names [num_deprecated] = {
{"foreachvar", luaB_foreach},
{"nextvar", luaB_next},
{"rawgetglobal", luaB_rawget},
{"rawsetglobal", luaB_rawset}
};
#ifdef LUA_DEPRECATEDFUNCS
/*
** call corresponding function inserting `globals' as first argument
*/
static int deprecated_func (lua_State *L) {
lua_insert(L, 1); /* upvalue is the function to be called */
lua_getglobals(L);
lua_insert(L, 2); /* table of globals is 1o argument */
lua_rawcall(L, lua_gettop(L)-1, LUA_MULTRET);
return lua_gettop(L); /* return all results */
}
static void deprecated_funcs (lua_State *L) {
int i;
for (i=0; i<num_deprecated; i++) {
lua_pushcfunction(L, deprecated_names[i].func);
lua_pushcclosure(L, deprecated_func, 1);
lua_setglobal(L, deprecated_names[i].name);
}
}
#else
/*
** gives an explicit error in any attempt to call a deprecated function
*/
static int deprecated_func (lua_State *L) {
luaL_verror(L, "function `%.20s' is deprecated", lua_tostring(L, -1));
return 0; /* to avoid warnings */
}
static void deprecated_funcs (lua_State *L) {
int i;
for (i=0; i<num_deprecated; i++) {
lua_pushstring(L, deprecated_names[i].name);
lua_pushcclosure(L, deprecated_func, 1);
lua_setglobal(L, deprecated_names[i].name);
}
}
#endif
/* }====================================================== */
static const struct luaL_reg base_funcs[] = {
{LUA_ALERT, luaB__ALERT},
{LUA_ERRORMESSAGE, luaB__ERRORMESSAGE},
{"call", luaB_call},
{"collectgarbage", luaB_collectgarbage},
{"copytagmethods", luaB_copytagmethods},
{"dofile", luaB_dofile},
{"dostring", luaB_dostring},
{"error", luaB_error},
{"foreach", luaB_foreach},
{"foreachi", luaB_foreachi},
{"gcinfo", luaB_gcinfo},
{"getglobal", luaB_getglobal},
{"gettagmethod", luaB_gettagmethod},
{"globals", luaB_globals},
{"newtag", luaB_newtag},
{"next", luaB_next},
{"print", luaB_print},
{"rawget", luaB_rawget},
{"rawset", luaB_rawset},
{"rawgettable", luaB_rawget}, /* for compatibility */
{"rawsettable", luaB_rawset}, /* for compatibility */
{"setglobal", luaB_setglobal},
{"settag", luaB_settag},
{"settagmethod", luaB_settagmethod},
{"tag", luaB_tag},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
{"type", luaB_type},
{"assert", luaB_assert},
{"getn", luaB_getn},
{"sort", luaB_sort},
{"tinsert", luaB_tinsert},
{"tremove", luaB_tremove}
};
LUALIB_API void lua_baselibopen (lua_State *L) {
luaL_openl(L, base_funcs);
lua_pushstring(L, LUA_VERSION);
lua_setglobal(L, "_VERSION");
deprecated_funcs(L);
}

View File

@@ -1,75 +0,0 @@
/*
** $Id: lbuffer.c,v 1.8 1999/02/25 19:20:40 roberto Exp roberto $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#include <stdio.h>
#include "lauxlib.h"
#include "lmem.h"
#include "lstate.h"
/*-------------------------------------------------------
** Auxiliary buffer
-------------------------------------------------------*/
#define EXTRABUFF 32
#define openspace(size) if (L->Mbuffnext+(size) > L->Mbuffsize) Openspace(size)
static void Openspace (int size) {
lua_State *l = L; /* to optimize */
size += EXTRABUFF;
l->Mbuffsize = l->Mbuffnext+size;
luaM_growvector(l->Mbuffer, l->Mbuffnext, size, char, arrEM, MAX_INT);
}
char *luaL_openspace (int size) {
openspace(size);
return L->Mbuffer+L->Mbuffnext;
}
void luaL_addchar (int c) {
openspace(1);
L->Mbuffer[L->Mbuffnext++] = (char)c;
}
void luaL_resetbuffer (void) {
L->Mbuffnext = L->Mbuffbase;
}
void luaL_addsize (int n) {
L->Mbuffnext += n;
}
int luaL_getsize (void) {
return L->Mbuffnext-L->Mbuffbase;
}
int luaL_newbuffer (int size) {
int old = L->Mbuffbase;
openspace(size);
L->Mbuffbase = L->Mbuffnext;
return old;
}
void luaL_oldbuffer (int old) {
L->Mbuffnext = L->Mbuffbase;
L->Mbuffbase = old;
}
char *luaL_buffer (void) {
return L->Mbuffer+L->Mbuffbase;
}

View File

@@ -1,726 +0,0 @@
/*
** $Id: lbuiltin.c,v 1.55 1999/03/01 20:22:16 roberto Exp roberto $
** Built-in functions
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lapi.h"
#include "lauxlib.h"
#include "lbuiltin.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lua.h"
#include "lundump.h"
#include "lvm.h"
/*
** {======================================================
** Auxiliary functions
** =======================================================
*/
static void pushtagstring (TaggedString *s) {
TObject o;
o.ttype = LUA_T_STRING;
o.value.ts = s;
luaA_pushobject(&o);
}
static real getsize (Hash *h) {
real max = 0;
int i;
for (i = 0; i<nhash(h); i++) {
Node *n = h->node+i;
if (ttype(ref(n)) == LUA_T_NUMBER &&
ttype(val(n)) != LUA_T_NIL &&
nvalue(ref(n)) > max)
max = nvalue(ref(n));
}
return max;
}
static real getnarg (Hash *a) {
TObject index;
TObject *value;
/* value = table.n */
ttype(&index) = LUA_T_STRING;
tsvalue(&index) = luaS_new("n");
value = luaH_get(a, &index);
return (ttype(value) == LUA_T_NUMBER) ? nvalue(value) : getsize(a);
}
static Hash *gethash (int arg) {
return avalue(luaA_Address(luaL_tablearg(arg)));
}
/* }====================================================== */
/*
** {======================================================
** Functions that use only the official API
** =======================================================
*/
/*
** If your system does not support "stderr", redefine this function, or
** redefine _ERRORMESSAGE so that it won't need _ALERT.
*/
static void luaB_alert (void) {
fputs(luaL_check_string(1), stderr);
}
/*
** Standard implementation of _ERRORMESSAGE.
** The library "iolib" redefines _ERRORMESSAGE for better error information.
*/
static void error_message (void) {
lua_Object al = lua_rawgetglobal("_ALERT");
if (lua_isfunction(al)) { /* avoid error loop if _ALERT is not defined */
char buff[600];
sprintf(buff, "lua error: %.500s\n", luaL_check_string(1));
lua_pushstring(buff);
lua_callfunction(al);
}
}
/*
** If your system does not support "stdout", just remove this function.
** If you need, you can define your own "print" function, following this
** model but changing "fputs" to put the strings at a proper place
** (a console window or a log file, for instance).
*/
#define MAXPRINT 40
static void luaB_print (void) {
lua_Object args[MAXPRINT];
lua_Object obj;
int n = 0;
int i;
while ((obj = lua_getparam(n+1)) != LUA_NOOBJECT) {
luaL_arg_check(n < MAXPRINT, n+1, "too many arguments");
args[n++] = obj;
}
for (i=0; i<n; i++) {
lua_pushobject(args[i]);
if (lua_call("tostring"))
lua_error("error in `tostring' called by `print'");
obj = lua_getresult(1);
if (!lua_isstring(obj))
lua_error("`tostring' must return a string to `print'");
if (i>0) fputs("\t", stdout);
fputs(lua_getstring(obj), stdout);
}
fputs("\n", stdout);
}
static void luaB_tonumber (void) {
int base = luaL_opt_int(2, 10);
if (base == 10) { /* standard conversion */
lua_Object o = lua_getparam(1);
if (lua_isnumber(o)) lua_pushnumber(lua_getnumber(o));
else lua_pushnil(); /* not a number */
}
else {
char *s = luaL_check_string(1);
long n;
luaL_arg_check(0 <= base && base <= 36, 2, "base out of range");
n = strtol(s, &s, base);
while (isspace((unsigned char)*s)) s++; /* skip trailing spaces */
if (*s) lua_pushnil(); /* invalid format: return nil */
else lua_pushnumber(n);
}
}
static void luaB_error (void) {
lua_error(lua_getstring(lua_getparam(1)));
}
static void luaB_setglobal (void) {
char *n = luaL_check_string(1);
lua_Object value = luaL_nonnullarg(2);
lua_pushobject(value);
lua_setglobal(n);
lua_pushobject(value); /* return given value */
}
static void luaB_rawsetglobal (void) {
char *n = luaL_check_string(1);
lua_Object value = luaL_nonnullarg(2);
lua_pushobject(value);
lua_rawsetglobal(n);
lua_pushobject(value); /* return given value */
}
static void luaB_getglobal (void) {
lua_pushobject(lua_getglobal(luaL_check_string(1)));
}
static void luaB_rawgetglobal (void) {
lua_pushobject(lua_rawgetglobal(luaL_check_string(1)));
}
static void luaB_luatag (void) {
lua_pushnumber(lua_tag(lua_getparam(1)));
}
static void luaB_settag (void) {
lua_Object o = luaL_tablearg(1);
lua_pushobject(o);
lua_settag(luaL_check_int(2));
lua_pushobject(o); /* return first argument */
}
static void luaB_newtag (void) {
lua_pushnumber(lua_newtag());
}
static void luaB_copytagmethods (void) {
lua_pushnumber(lua_copytagmethods(luaL_check_int(1),
luaL_check_int(2)));
}
static void luaB_rawgettable (void) {
lua_pushobject(luaL_nonnullarg(1));
lua_pushobject(luaL_nonnullarg(2));
lua_pushobject(lua_rawgettable());
}
static void luaB_rawsettable (void) {
lua_pushobject(luaL_nonnullarg(1));
lua_pushobject(luaL_nonnullarg(2));
lua_pushobject(luaL_nonnullarg(3));
lua_rawsettable();
}
static void luaB_settagmethod (void) {
lua_Object nf = luaL_nonnullarg(3);
lua_pushobject(nf);
lua_pushobject(lua_settagmethod(luaL_check_int(1), luaL_check_string(2)));
}
static void luaB_gettagmethod (void) {
lua_pushobject(lua_gettagmethod(luaL_check_int(1), luaL_check_string(2)));
}
static void luaB_seterrormethod (void) {
lua_Object nf = luaL_functionarg(1);
lua_pushobject(nf);
lua_pushobject(lua_seterrormethod());
}
static void luaB_collectgarbage (void) {
lua_pushnumber(lua_collectgarbage(luaL_opt_int(1, 0)));
}
/* }====================================================== */
/*
** {======================================================
** Functions that could use only the official API but
** do not, for efficiency.
** =======================================================
*/
static void luaB_dostring (void) {
long l;
char *s = luaL_check_lstr(1, &l);
if (*s == ID_CHUNK)
lua_error("`dostring' cannot run pre-compiled code");
if (lua_dobuffer(s, l, luaL_opt_string(2, s)) == 0)
if (luaA_passresults() == 0)
lua_pushuserdata(NULL); /* at least one result to signal no errors */
}
static void luaB_dofile (void) {
char *fname = luaL_opt_string(1, NULL);
if (lua_dofile(fname) == 0)
if (luaA_passresults() == 0)
lua_pushuserdata(NULL); /* at least one result to signal no errors */
}
static void luaB_call (void) {
lua_Object f = luaL_nonnullarg(1);
Hash *arg = gethash(2);
char *options = luaL_opt_string(3, "");
lua_Object err = lua_getparam(4);
int narg = (int)getnarg(arg);
int i, status;
if (err != LUA_NOOBJECT) { /* set new error method */
lua_pushobject(err);
err = lua_seterrormethod();
}
/* push arg[1...n] */
luaD_checkstack(narg);
for (i=0; i<narg; i++)
*(L->stack.top++) = *luaH_getint(arg, i+1);
status = lua_callfunction(f);
if (err != LUA_NOOBJECT) { /* restore old error method */
lua_pushobject(err);
lua_seterrormethod();
}
if (status != 0) { /* error in call? */
if (strchr(options, 'x')) {
lua_pushnil();
return; /* return nil to signal the error */
}
else
lua_error(NULL);
}
else { /* no errors */
if (strchr(options, 'p'))
luaA_packresults();
else
luaA_passresults();
}
}
static void luaB_nextvar (void) {
TObject *o = luaA_Address(luaL_nonnullarg(1));
TaggedString *g;
if (ttype(o) == LUA_T_NIL)
g = NULL;
else {
luaL_arg_check(ttype(o) == LUA_T_STRING, 1, "variable name expected");
g = tsvalue(o);
}
if (!luaA_nextvar(g))
lua_pushnil();
}
static void luaB_next (void) {
Hash *a = gethash(1);
TObject *k = luaA_Address(luaL_nonnullarg(2));
int i = (ttype(k) == LUA_T_NIL) ? 0 : luaH_pos(a, k)+1;
if (luaA_next(a, i) == 0)
lua_pushnil();
}
static void luaB_tostring (void) {
lua_Object obj = lua_getparam(1);
TObject *o = luaA_Address(obj);
char buff[64];
switch (ttype(o)) {
case LUA_T_NUMBER:
lua_pushstring(lua_getstring(obj));
return;
case LUA_T_STRING:
lua_pushobject(obj);
return;
case LUA_T_ARRAY:
sprintf(buff, "table: %p", (void *)o->value.a);
break;
case LUA_T_CLOSURE:
sprintf(buff, "function: %p", (void *)o->value.cl);
break;
case LUA_T_PROTO:
sprintf(buff, "function: %p", (void *)o->value.tf);
break;
case LUA_T_CPROTO:
sprintf(buff, "function: %p", (void *)o->value.f);
break;
case LUA_T_USERDATA:
sprintf(buff, "userdata: %p", o->value.ts->u.d.v);
break;
case LUA_T_NIL:
lua_pushstring("nil");
return;
default:
LUA_INTERNALERROR("invalid type");
}
lua_pushstring(buff);
}
static void luaB_type (void) {
lua_Object o = luaL_nonnullarg(1);
lua_pushstring(luaO_typename(luaA_Address(o)));
lua_pushnumber(lua_tag(o));
}
/* }====================================================== */
/*
** {======================================================
** "Extra" functions
** These functions can be written in Lua, so you can
** delete them if you need a tiny Lua implementation.
** If you delete them, remove their entries in array
** "builtin_funcs".
** =======================================================
*/
static void luaB_assert (void) {
lua_Object p = lua_getparam(1);
if (p == LUA_NOOBJECT || lua_isnil(p))
luaL_verror("assertion failed! %.100s", luaL_opt_string(2, ""));
}
static void luaB_foreachi (void) {
Hash *t = gethash(1);
TObject *f = luaA_Address(luaL_functionarg(2));
int i;
int n = (int)getnarg(t);
luaD_checkstack(3); /* for f, ref, and val */
for (i=1; i<=n; i++) {
*(L->stack.top++) = *f;
ttype(L->stack.top) = LUA_T_NUMBER; nvalue(L->stack.top++) = i;
*(L->stack.top++) = *luaH_getint(t, i);
luaD_calln(2, 1);
if (ttype(L->stack.top-1) != LUA_T_NIL)
return;
L->stack.top--;
}
}
static void luaB_foreach (void) {
Hash *a = gethash(1);
TObject *f = luaA_Address(luaL_functionarg(2));
int i;
luaD_checkstack(3); /* for f, ref, and val */
for (i=0; i<a->nhash; i++) {
Node *nd = &(a->node[i]);
if (ttype(val(nd)) != LUA_T_NIL) {
*(L->stack.top++) = *f;
*(L->stack.top++) = *ref(nd);
*(L->stack.top++) = *val(nd);
luaD_calln(2, 1);
if (ttype(L->stack.top-1) != LUA_T_NIL)
return;
L->stack.top--; /* remove result */
}
}
}
static void luaB_foreachvar (void) {
TObject *f = luaA_Address(luaL_functionarg(1));
GCnode *g;
luaD_checkstack(4); /* for extra var name, f, var name, and globalval */
for (g = L->rootglobal.next; g; g = g->next) {
TaggedString *s = (TaggedString *)g;
if (s->u.s.globalval.ttype != LUA_T_NIL) {
pushtagstring(s); /* keep (extra) s on stack to avoid GC */
*(L->stack.top++) = *f;
pushtagstring(s);
*(L->stack.top++) = s->u.s.globalval;
luaD_calln(2, 1);
if (ttype(L->stack.top-1) != LUA_T_NIL) {
L->stack.top--;
*(L->stack.top-1) = *L->stack.top; /* remove extra s */
return;
}
L->stack.top-=2; /* remove result and extra s */
}
}
}
static void luaB_getn (void) {
lua_pushnumber(getnarg(gethash(1)));
}
static void luaB_tinsert (void) {
Hash *a = gethash(1);
lua_Object v = lua_getparam(3);
int n = (int)getnarg(a);
int pos;
if (v != LUA_NOOBJECT)
pos = luaL_check_int(2);
else { /* called with only 2 arguments */
v = luaL_nonnullarg(2);
pos = n+1;
}
luaV_setn(a, n+1); /* increment field "n" */
for ( ;n>=pos; n--)
luaH_move(a, n, n+1);
luaH_setint(a, pos, luaA_Address(v));
}
static void luaB_tremove (void) {
Hash *a = gethash(1);
int n = (int)getnarg(a);
int pos = luaL_opt_int(2, n);
if (n <= 0) return; /* table is "empty" */
luaA_pushobject(luaH_getint(a, pos)); /* push result */
luaV_setn(a, n-1); /* decrement field "n" */
for ( ;pos<n; pos++)
luaH_move(a, pos+1, pos);
}
/* {
** Quicksort
*/
static void swap (Hash *a, int i, int j) {
TObject temp;
temp = *luaH_getint(a, i);
luaH_move(a, j, i);
luaH_setint(a, j, &temp);
}
static int sort_comp (TObject *f, TObject *a, TObject *b) {
/* notice: the caller (auxsort) must check stack space */
if (f) {
*(L->stack.top) = *f;
*(L->stack.top+1) = *a;
*(L->stack.top+2) = *b;
L->stack.top += 3;
luaD_calln(2, 1);
}
else { /* a < b? */
*(L->stack.top) = *a;
*(L->stack.top+1) = *b;
L->stack.top += 2;
luaV_comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
}
return ttype(--(L->stack.top)) != LUA_T_NIL;
}
static void auxsort (Hash *a, int l, int u, TObject *f) {
while (l < u) { /* for tail recursion */
TObject *P;
int i, j;
/* sort elements a[l], a[(l+u)/2] and a[u] */
if (sort_comp(f, luaH_getint(a, u), luaH_getint(a, l))) /* a[l]>a[u]? */
swap(a, l, u);
if (u-l == 1) break; /* only 2 elements */
i = (l+u)/2;
P = luaH_getint(a, i);
if (sort_comp(f, P, luaH_getint(a, l))) /* a[l]>a[i]? */
swap(a, l, i);
else if (sort_comp(f, luaH_getint(a, u), P)) /* a[i]>a[u]? */
swap(a, i, u);
if (u-l == 2) break; /* only 3 elements */
P = L->stack.top++;
*P = *luaH_getint(a, i); /* save pivot on stack (for GC) */
swap(a, i, u-1); /* put median element as pivot (a[u-1]) */
/* a[l] <= P == a[u-1] <= a[u], only needs to sort from l+1 to u-2 */
i = l; j = u-1;
for (;;) {
/* invariant: a[l..i] <= P <= a[j..u] */
while (sort_comp(f, luaH_getint(a, ++i), P)) /* stop when a[i] >= P */
if (i>u) lua_error("invalid order function for sorting");
while (sort_comp(f, P, luaH_getint(a, --j))) /* stop when a[j] <= P */
if (j<l) lua_error("invalid order function for sorting");
if (j<i) break;
swap(a, i, j);
}
swap(a, u-1, i); /* swap pivot (a[u-1]) with a[i] */
L->stack.top--; /* remove pivot from stack */
/* a[l..i-1] <= a[i] == P <= a[i+1..u] */
/* adjust so that smaller "half" is in [j..i] and larger one in [l..u] */
if (i-l < u-i) {
j=l; i=i-1; l=i+2;
}
else {
j=i+1; i=u; u=j-2;
}
auxsort(a, j, i, f); /* call recursively the smaller one */
} /* repeat the routine for the larger one */
}
static void luaB_sort (void) {
lua_Object t = lua_getparam(1);
Hash *a = gethash(1);
int n = (int)getnarg(a);
lua_Object func = lua_getparam(2);
TObject *f = luaA_Address(func);
luaL_arg_check(!f || lua_isfunction(func), 2, "function expected");
luaD_checkstack(4); /* for Pivot, f, a, b (sort_comp) */
auxsort(a, 1, n, f);
lua_pushobject(t);
}
/* }}===================================================== */
/*
** ====================================================== */
#ifdef DEBUG
/*
** {======================================================
** some DEBUG functions
** =======================================================
*/
static void mem_query (void) {
lua_pushnumber(totalmem);
lua_pushnumber(numblocks);
}
static void query_strings (void) {
lua_pushnumber(L->string_root[luaL_check_int(1)].nuse);
}
static void countlist (void) {
char *s = luaL_check_string(1);
GCnode *l = (s[0]=='t') ? L->roottable.next : (s[0]=='c') ? L->rootcl.next :
(s[0]=='p') ? L->rootproto.next : L->rootglobal.next;
int i=0;
while (l) {
i++;
l = l->next;
}
lua_pushnumber(i);
}
static void testC (void) {
#define getnum(s) ((*s++) - '0')
#define getname(s) (nome[0] = *s++, nome)
static int locks[10];
lua_Object reg[10];
char nome[2];
char *s = luaL_check_string(1);
nome[1] = 0;
for (;;) {
switch (*s++) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
lua_pushnumber(*(s-1) - '0');
break;
case 'c': reg[getnum(s)] = lua_createtable(); break;
case 'C': { lua_CFunction f = lua_getcfunction(lua_getglobal(getname(s)));
lua_pushcclosure(f, getnum(s));
break;
}
case 'P': reg[getnum(s)] = lua_pop(); break;
case 'g': { int n=getnum(s); reg[n]=lua_getglobal(getname(s)); break; }
case 'G': { int n = getnum(s);
reg[n] = lua_rawgetglobal(getname(s));
break;
}
case 'l': locks[getnum(s)] = lua_ref(1); break;
case 'L': locks[getnum(s)] = lua_ref(0); break;
case 'r': { int n=getnum(s); reg[n]=lua_getref(locks[getnum(s)]); break; }
case 'u': lua_unref(locks[getnum(s)]); break;
case 'p': { int n = getnum(s); reg[n] = lua_getparam(getnum(s)); break; }
case '=': lua_setglobal(getname(s)); break;
case 's': lua_pushstring(getname(s)); break;
case 'o': lua_pushobject(reg[getnum(s)]); break;
case 'f': lua_call(getname(s)); break;
case 'i': reg[getnum(s)] = lua_gettable(); break;
case 'I': reg[getnum(s)] = lua_rawgettable(); break;
case 't': lua_settable(); break;
case 'T': lua_rawsettable(); break;
case 'N' : lua_pushstring(lua_nextvar(lua_getstring(reg[getnum(s)])));
break;
case 'n' : { int n=getnum(s);
n=lua_next(reg[n], (int)lua_getnumber(reg[getnum(s)]));
lua_pushnumber(n); break;
}
default: luaL_verror("unknown command in `testC': %c", *(s-1));
}
if (*s == 0) return;
if (*s++ != ' ') lua_error("missing ` ' between commands in `testC'");
}
}
/* }====================================================== */
#endif
static struct luaL_reg builtin_funcs[] = {
#ifdef LUA_COMPAT2_5
{"setfallback", luaT_setfallback},
#endif
#ifdef DEBUG
{"testC", testC},
{"totalmem", mem_query},
{"count", countlist},
{"querystr", query_strings},
#endif
{"_ALERT", luaB_alert},
{"_ERRORMESSAGE", error_message},
{"call", luaB_call},
{"collectgarbage", luaB_collectgarbage},
{"copytagmethods", luaB_copytagmethods},
{"dofile", luaB_dofile},
{"dostring", luaB_dostring},
{"error", luaB_error},
{"getglobal", luaB_getglobal},
{"gettagmethod", luaB_gettagmethod},
{"newtag", luaB_newtag},
{"next", luaB_next},
{"nextvar", luaB_nextvar},
{"print", luaB_print},
{"rawgetglobal", luaB_rawgetglobal},
{"rawgettable", luaB_rawgettable},
{"rawsetglobal", luaB_rawsetglobal},
{"rawsettable", luaB_rawsettable},
{"seterrormethod", luaB_seterrormethod},
{"setglobal", luaB_setglobal},
{"settag", luaB_settag},
{"settagmethod", luaB_settagmethod},
{"tag", luaB_luatag},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
{"type", luaB_type},
/* "Extra" functions */
{"assert", luaB_assert},
{"foreach", luaB_foreach},
{"foreachi", luaB_foreachi},
{"foreachvar", luaB_foreachvar},
{"getn", luaB_getn},
{"sort", luaB_sort},
{"tinsert", luaB_tinsert},
{"tremove", luaB_tremove}
};
#define INTFUNCSIZE (sizeof(builtin_funcs)/sizeof(builtin_funcs[0]))
void luaB_predefine (void) {
/* pre-register mem error messages, to avoid loop when error arises */
luaS_newfixedstring(tableEM);
luaS_newfixedstring(memEM);
luaL_openlib(builtin_funcs, (sizeof(builtin_funcs)/sizeof(builtin_funcs[0])));
lua_pushstring(LUA_VERSION);
lua_setglobal("_VERSION");
}

View File

@@ -1,14 +0,0 @@
/*
** $Id: $
** Built-in functions
** See Copyright Notice in lua.h
*/
#ifndef lbuiltin_h
#define lbuiltin_h
void luaB_predefine (void);
#endif

701
lcode.c Normal file
View File

@@ -0,0 +1,701 @@
/*
** $Id: lcode.c,v 1.50 2000/08/31 14:08:27 roberto Exp roberto $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#include "stdlib.h"
#include "lua.h"
#include "lcode.h"
#include "ldo.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
void luaK_error (LexState *ls, const char *msg) {
luaX_error(ls, msg, ls->t.token);
}
/*
** Returns the the previous instruction, for optimizations.
** If there is a jump target between this and the current instruction,
** returns a dummy instruction to avoid wrong optimizations.
*/
static Instruction previous_instruction (FuncState *fs) {
if (fs->pc > fs->lasttarget) /* no jumps to current position? */
return fs->f->code[fs->pc-1]; /* returns previous instruction */
else
return CREATE_0(OP_END); /* no optimizations after an `END' */
}
int luaK_jump (FuncState *fs) {
int j = luaK_code1(fs, OP_JMP, NO_JUMP);
if (j == fs->lasttarget) { /* possible jumps to this jump? */
luaK_concat(fs, &j, fs->jlt); /* keep them on hold */
fs->jlt = NO_JUMP;
}
return j;
}
static void luaK_fixjump (FuncState *fs, int pc, int dest) {
Instruction *jmp = &fs->f->code[pc];
if (dest == NO_JUMP)
SETARG_S(*jmp, NO_JUMP); /* point to itself to represent end of list */
else { /* jump is relative to position following jump instruction */
int offset = dest-(pc+1);
if (abs(offset) > MAXARG_S)
luaK_error(fs->ls, "control structure too long");
SETARG_S(*jmp, offset);
}
}
static int luaK_getjump (FuncState *fs, int pc) {
int offset = GETARG_S(fs->f->code[pc]);
if (offset == NO_JUMP) /* point to itself represents end of list */
return NO_JUMP; /* end of list */
else
return (pc+1)+offset; /* turn offset into absolute position */
}
/*
** returns current `pc' and marks it as a jump target (to avoid wrong
** optimizations with consecutive instructions not in the same basic block).
** discharge list of jumps to last target.
*/
int luaK_getlabel (FuncState *fs) {
if (fs->pc != fs->lasttarget) {
int lasttarget = fs->lasttarget;
fs->lasttarget = fs->pc;
luaK_patchlist(fs, fs->jlt, lasttarget); /* discharge old list `jlt' */
fs->jlt = NO_JUMP; /* nobody jumps to this new label (yet) */
}
return fs->pc;
}
void luaK_deltastack (FuncState *fs, int delta) {
fs->stacklevel += delta;
if (fs->stacklevel > fs->f->maxstacksize) {
if (fs->stacklevel > MAXSTACK)
luaK_error(fs->ls, "function or expression too complex");
fs->f->maxstacksize = fs->stacklevel;
}
}
void luaK_kstr (LexState *ls, int c) {
luaK_code1(ls->fs, OP_PUSHSTRING, c);
}
static int number_constant (FuncState *fs, Number r) {
/* check whether `r' has appeared within the last LOOKBACKNUMS entries */
Proto *f = fs->f;
int c = f->nknum;
int lim = c < LOOKBACKNUMS ? 0 : c-LOOKBACKNUMS;
while (--c >= lim)
if (f->knum[c] == r) return c;
/* not found; create a new entry */
luaM_growvector(fs->L, f->knum, f->nknum, 1, Number,
"constant table overflow", MAXARG_U);
c = f->nknum++;
f->knum[c] = r;
return c;
}
void luaK_number (FuncState *fs, Number f) {
if (f <= (Number)MAXARG_S && (Number)(int)f == f)
luaK_code1(fs, OP_PUSHINT, (int)f); /* f has a short integer value */
else
luaK_code1(fs, OP_PUSHNUM, number_constant(fs, f));
}
void luaK_adjuststack (FuncState *fs, int n) {
if (n > 0)
luaK_code1(fs, OP_POP, n);
else
luaK_code1(fs, OP_PUSHNIL, -n);
}
int luaK_lastisopen (FuncState *fs) {
/* check whether last instruction is an open function call */
Instruction i = previous_instruction(fs);
if (GET_OPCODE(i) == OP_CALL && GETARG_B(i) == MULT_RET)
return 1;
else return 0;
}
void luaK_setcallreturns (FuncState *fs, int nresults) {
if (luaK_lastisopen(fs)) { /* expression is an open function call? */
SETARG_B(fs->f->code[fs->pc-1], nresults); /* set number of results */
luaK_deltastack(fs, nresults); /* push results */
}
}
static int discharge (FuncState *fs, expdesc *var) {
switch (var->k) {
case VLOCAL:
luaK_code1(fs, OP_GETLOCAL, var->u.index);
break;
case VGLOBAL:
luaK_code1(fs, OP_GETGLOBAL, var->u.index);
break;
case VINDEXED:
luaK_code0(fs, OP_GETTABLE);
break;
case VEXP:
return 0; /* nothing to do */
}
var->k = VEXP;
var->u.l.t = var->u.l.f = NO_JUMP;
return 1;
}
static void discharge1 (FuncState *fs, expdesc *var) {
discharge(fs, var);
/* if it has jumps then it is already discharged */
if (var->u.l.t == NO_JUMP && var->u.l.f == NO_JUMP)
luaK_setcallreturns(fs, 1); /* call must return 1 value */
}
void luaK_storevar (LexState *ls, const expdesc *var) {
FuncState *fs = ls->fs;
switch (var->k) {
case VLOCAL:
luaK_code1(fs, OP_SETLOCAL, var->u.index);
break;
case VGLOBAL:
luaK_code1(fs, OP_SETGLOBAL, var->u.index);
break;
case VINDEXED: /* table is at top-3; pop 3 elements after operation */
luaK_code2(fs, OP_SETTABLE, 3, 3);
break;
default:
LUA_INTERNALERROR("invalid var kind to store");
}
}
static OpCode invertjump (OpCode op) {
switch (op) {
case OP_JMPNE: return OP_JMPEQ;
case OP_JMPEQ: return OP_JMPNE;
case OP_JMPLT: return OP_JMPGE;
case OP_JMPLE: return OP_JMPGT;
case OP_JMPGT: return OP_JMPLE;
case OP_JMPGE: return OP_JMPLT;
case OP_JMPT: case OP_JMPONT: return OP_JMPF;
case OP_JMPF: case OP_JMPONF: return OP_JMPT;
default:
LUA_INTERNALERROR("invalid jump instruction");
return OP_END; /* to avoid warnings */
}
}
static void luaK_patchlistaux (FuncState *fs, int list, int target,
OpCode special, int special_target) {
Instruction *code = fs->f->code;
while (list != NO_JUMP) {
int next = luaK_getjump(fs, list);
Instruction *i = &code[list];
OpCode op = GET_OPCODE(*i);
if (op == special) /* this `op' already has a value */
luaK_fixjump(fs, list, special_target);
else {
luaK_fixjump(fs, list, target); /* do the patch */
if (op == OP_JMPONT) /* remove eventual values */
SET_OPCODE(*i, OP_JMPT);
else if (op == OP_JMPONF)
SET_OPCODE(*i, OP_JMPF);
}
list = next;
}
}
void luaK_patchlist (FuncState *fs, int list, int target) {
if (target == fs->lasttarget) /* same target that list `jlt'? */
luaK_concat(fs, &fs->jlt, list); /* delay fixing */
else
luaK_patchlistaux(fs, list, target, OP_END, 0);
}
static int need_value (FuncState *fs, int list, OpCode hasvalue) {
/* check whether list has a jump without a value */
for (; list != NO_JUMP; list = luaK_getjump(fs, list))
if (GET_OPCODE(fs->f->code[list]) != hasvalue) return 1;
return 0; /* not found */
}
void luaK_concat (FuncState *fs, int *l1, int l2) {
if (*l1 == NO_JUMP)
*l1 = l2;
else {
int list = *l1;
for (;;) { /* traverse `l1' */
int next = luaK_getjump(fs, list);
if (next == NO_JUMP) { /* end of list? */
luaK_fixjump(fs, list, l2);
return;
}
list = next;
}
}
}
static void luaK_testgo (FuncState *fs, expdesc *v, int invert, OpCode jump) {
int prevpos; /* position of last instruction */
Instruction *previous;
int *golist, *exitlist;
if (!invert) {
golist = &v->u.l.f; /* go if false */
exitlist = &v->u.l.t; /* exit if true */
}
else {
golist = &v->u.l.t; /* go if true */
exitlist = &v->u.l.f; /* exit if false */
}
discharge1(fs, v);
prevpos = fs->pc-1;
previous = &fs->f->code[prevpos];
LUA_ASSERT(*previous==previous_instruction(fs), "no jump allowed here");
if (!ISJUMP(GET_OPCODE(*previous)))
prevpos = luaK_code1(fs, jump, NO_JUMP);
else { /* last instruction is already a jump */
if (invert)
SET_OPCODE(*previous, invertjump(GET_OPCODE(*previous)));
}
luaK_concat(fs, exitlist, prevpos); /* insert last jump in `exitlist' */
luaK_patchlist(fs, *golist, luaK_getlabel(fs));
*golist = NO_JUMP;
}
void luaK_goiftrue (FuncState *fs, expdesc *v, int keepvalue) {
luaK_testgo(fs, v, 1, keepvalue ? OP_JMPONF : OP_JMPF);
}
static void luaK_goiffalse (FuncState *fs, expdesc *v, int keepvalue) {
luaK_testgo(fs, v, 0, keepvalue ? OP_JMPONT : OP_JMPT);
}
static int code_label (FuncState *fs, OpCode op, int arg) {
luaK_getlabel(fs); /* those instructions may be jump targets */
return luaK_code1(fs, op, arg);
}
void luaK_tostack (LexState *ls, expdesc *v, int onlyone) {
FuncState *fs = ls->fs;
if (!discharge(fs, v)) { /* `v' is an expression? */
OpCode previous = GET_OPCODE(fs->f->code[fs->pc-1]);
if (!ISJUMP(previous) && v->u.l.f == NO_JUMP && v->u.l.t == NO_JUMP) {
/* expression has no jumps */
if (onlyone)
luaK_setcallreturns(fs, 1); /* call must return 1 value */
}
else { /* expression has jumps */
int final; /* position after whole expression */
int j = NO_JUMP; /* eventual jump over values */
int p_nil = NO_JUMP; /* position of an eventual PUSHNIL */
int p_1 = NO_JUMP; /* position of an eventual PUSHINT */
if (ISJUMP(previous) || need_value(fs, v->u.l.f, OP_JMPONF)
|| need_value(fs, v->u.l.t, OP_JMPONT)) {
/* expression needs values */
if (ISJUMP(previous))
luaK_concat(fs, &v->u.l.t, fs->pc-1); /* put `previous' in t. list */
else {
j = code_label(fs, OP_JMP, NO_JUMP); /* to jump over both pushes */
/* correct stack for compiler and symbolic execution */
luaK_adjuststack(fs, 1);
}
p_nil = code_label(fs, OP_PUSHNILJMP, 0);
p_1 = code_label(fs, OP_PUSHINT, 1);
luaK_patchlist(fs, j, luaK_getlabel(fs));
}
final = luaK_getlabel(fs);
luaK_patchlistaux(fs, v->u.l.f, p_nil, OP_JMPONF, final);
luaK_patchlistaux(fs, v->u.l.t, p_1, OP_JMPONT, final);
v->u.l.f = v->u.l.t = NO_JUMP;
}
}
}
void luaK_prefix (LexState *ls, UnOpr op, expdesc *v) {
FuncState *fs = ls->fs;
if (op == OPR_MINUS) {
luaK_tostack(ls, v, 1);
luaK_code0(fs, OP_MINUS);
}
else { /* op == NOT */
Instruction *previous;
discharge1(fs, v);
previous = &fs->f->code[fs->pc-1];
if (ISJUMP(GET_OPCODE(*previous)))
SET_OPCODE(*previous, invertjump(GET_OPCODE(*previous)));
else
luaK_code0(fs, OP_NOT);
/* interchange true and false lists */
{ int temp = v->u.l.f; v->u.l.f = v->u.l.t; v->u.l.t = temp; }
}
}
void luaK_infix (LexState *ls, BinOpr op, expdesc *v) {
FuncState *fs = ls->fs;
switch (op) {
case OPR_AND:
luaK_goiftrue(fs, v, 1);
break;
case OPR_OR:
luaK_goiffalse(fs, v, 1);
break;
default:
luaK_tostack(ls, v, 1); /* all other binary operators need a value */
}
}
static const struct {
OpCode opcode; /* opcode for each binary operator */
int arg; /* default argument for the opcode */
} codes[] = { /* ORDER OPR */
{OP_ADD, 0}, {OP_SUB, 0}, {OP_MULT, 0}, {OP_DIV, 0},
{OP_POW, 0}, {OP_CONCAT, 2},
{OP_JMPNE, NO_JUMP}, {OP_JMPEQ, NO_JUMP},
{OP_JMPLT, NO_JUMP}, {OP_JMPLE, NO_JUMP},
{OP_JMPGT, NO_JUMP}, {OP_JMPGE, NO_JUMP}
};
void luaK_posfix (LexState *ls, BinOpr op, expdesc *v1, expdesc *v2) {
FuncState *fs = ls->fs;
switch (op) {
case OPR_AND: {
LUA_ASSERT(v1->u.l.t == NO_JUMP, "list must be closed");
discharge1(fs, v2);
v1->u.l.t = v2->u.l.t;
luaK_concat(fs, &v1->u.l.f, v2->u.l.f);
break;
}
case OPR_OR: {
LUA_ASSERT(v1->u.l.f == NO_JUMP, "list must be closed");
discharge1(fs, v2);
v1->u.l.f = v2->u.l.f;
luaK_concat(fs, &v1->u.l.t, v2->u.l.t);
break;
}
default: {
luaK_tostack(ls, v2, 1); /* `v2' must be a value */
luaK_code1(fs, codes[op].opcode, codes[op].arg);
}
}
}
static void codelineinfo (FuncState *fs) {
Proto *f = fs->f;
LexState *ls = fs->ls;
if (ls->lastline > fs->lastline) {
luaM_growvector(fs->L, f->lineinfo, f->nlineinfo, 2, int,
"line info overflow", MAX_INT);
if (ls->lastline > fs->lastline+1)
f->lineinfo[f->nlineinfo++] = -(ls->lastline - (fs->lastline+1));
f->lineinfo[f->nlineinfo++] = fs->pc;
fs->lastline = ls->lastline;
}
}
int luaK_code0 (FuncState *fs, OpCode o) {
return luaK_code2(fs, o, 0, 0);
}
int luaK_code1 (FuncState *fs, OpCode o, int arg1) {
return luaK_code2(fs, o, arg1, 0);
}
int luaK_code2 (FuncState *fs, OpCode o, int arg1, int arg2) {
Instruction i = previous_instruction(fs);
int delta = luaK_opproperties[o].push - luaK_opproperties[o].pop;
int optm = 0; /* 1 when there is an optimization */
switch (o) {
case OP_CLOSURE: {
delta = -arg2+1;
break;
}
case OP_SETTABLE: {
delta = -arg2;
break;
}
case OP_SETLIST: {
if (arg2 == 0) return NO_JUMP; /* nothing to do */
delta = -arg2;
break;
}
case OP_SETMAP: {
if (arg1 == 0) return NO_JUMP; /* nothing to do */
delta = -2*arg1;
break;
}
case OP_RETURN: {
if (GET_OPCODE(i) == OP_CALL && GETARG_B(i) == MULT_RET) {
SET_OPCODE(i, OP_TAILCALL);
SETARG_B(i, arg1);
optm = 1;
}
break;
}
case OP_PUSHNIL: {
if (arg1 == 0) return NO_JUMP; /* nothing to do */
delta = arg1;
switch(GET_OPCODE(i)) {
case OP_PUSHNIL: SETARG_U(i, GETARG_U(i)+arg1); optm = 1; break;
default: break;
}
break;
}
case OP_POP: {
if (arg1 == 0) return NO_JUMP; /* nothing to do */
delta = -arg1;
switch(GET_OPCODE(i)) {
case OP_SETTABLE: SETARG_B(i, GETARG_B(i)+arg1); optm = 1; break;
default: break;
}
break;
}
case OP_GETTABLE: {
switch(GET_OPCODE(i)) {
case OP_PUSHSTRING: /* `t.x' */
SET_OPCODE(i, OP_GETDOTTED);
optm = 1;
break;
case OP_GETLOCAL: /* `t[i]' */
SET_OPCODE(i, OP_GETINDEXED);
optm = 1;
break;
default: break;
}
break;
}
case OP_ADD: {
switch(GET_OPCODE(i)) {
case OP_PUSHINT: SET_OPCODE(i, OP_ADDI); optm = 1; break; /* `a+k' */
default: break;
}
break;
}
case OP_SUB: {
switch(GET_OPCODE(i)) {
case OP_PUSHINT: /* `a-k' */
i = CREATE_S(OP_ADDI, -GETARG_S(i));
optm = 1;
break;
default: break;
}
break;
}
case OP_CONCAT: {
delta = -arg1+1;
switch(GET_OPCODE(i)) {
case OP_CONCAT: /* `a..b..c' */
SETARG_U(i, GETARG_U(i)+1);
optm = 1;
break;
default: break;
}
break;
}
case OP_MINUS: {
switch(GET_OPCODE(i)) {
case OP_PUSHINT: /* `-k' */
SETARG_S(i, -GETARG_S(i));
optm = 1;
break;
case OP_PUSHNUM: /* `-k' */
SET_OPCODE(i, OP_PUSHNEGNUM);
optm = 1;
break;
default: break;
}
break;
}
case OP_JMPNE: {
if (i == CREATE_U(OP_PUSHNIL, 1)) { /* `a~=nil' */
i = CREATE_S(OP_JMPT, NO_JUMP);
optm = 1;
}
break;
}
case OP_JMPEQ: {
if (i == CREATE_U(OP_PUSHNIL, 1)) { /* `a==nil' */
i = CREATE_0(OP_NOT);
delta = -1; /* just undo effect of previous PUSHNIL */
optm = 1;
}
break;
}
case OP_JMPT:
case OP_JMPONT: {
switch (GET_OPCODE(i)) {
case OP_NOT: {
i = CREATE_S(OP_JMPF, NO_JUMP);
optm = 1;
break;
}
case OP_PUSHINT: {
if (o == OP_JMPT) { /* JMPONT must keep original integer value */
i = CREATE_S(OP_JMP, NO_JUMP);
optm = 1;
}
break;
}
case OP_PUSHNIL: {
if (GETARG_U(i) == 1) {
fs->pc--; /* erase previous instruction */
luaK_deltastack(fs, -1); /* correct stack */
return NO_JUMP;
}
break;
}
default: break;
}
break;
}
case OP_JMPF:
case OP_JMPONF: {
switch (GET_OPCODE(i)) {
case OP_NOT: {
i = CREATE_S(OP_JMPT, NO_JUMP);
optm = 1;
break;
}
case OP_PUSHINT: { /* `while 1 do ...' */
fs->pc--; /* erase previous instruction */
luaK_deltastack(fs, -1); /* correct stack */
return NO_JUMP;
}
case OP_PUSHNIL: { /* `repeat ... until nil' */
if (GETARG_U(i) == 1) {
i = CREATE_S(OP_JMP, NO_JUMP);
optm = 1;
}
break;
}
default: break;
}
break;
}
case OP_GETDOTTED:
case OP_GETINDEXED:
case OP_TAILCALL:
case OP_ADDI: {
LUA_INTERNALERROR("instruction used only for optimizations");
break;
}
default: {
LUA_ASSERT(delta != VD, "invalid delta");
break;
}
}
luaK_deltastack(fs, delta);
if (optm) { /* optimize: put instruction in place of last one */
fs->f->code[fs->pc-1] = i; /* change previous instruction */
return fs->pc-1; /* do not generate new instruction */
}
/* else build new instruction */
switch ((enum Mode)luaK_opproperties[o].mode) {
case iO: i = CREATE_0(o); break;
case iU: i = CREATE_U(o, arg1); break;
case iS: i = CREATE_S(o, arg1); break;
case iAB: i = CREATE_AB(o, arg1, arg2); break;
}
codelineinfo(fs);
/* put new instruction in code array */
luaM_growvector(fs->L, fs->f->code, fs->pc, 1, Instruction,
"code size overflow", MAX_INT);
fs->f->code[fs->pc] = i;
return fs->pc++;
}
const struct OpProperties luaK_opproperties[NUM_OPCODES] = {
{iO, 0, 0}, /* OP_END */
{iU, 0, 0}, /* OP_RETURN */
{iAB, 0, 0}, /* OP_CALL */
{iAB, 0, 0}, /* OP_TAILCALL */
{iU, VD, 0}, /* OP_PUSHNIL */
{iU, VD, 0}, /* OP_POP */
{iS, 1, 0}, /* OP_PUSHINT */
{iU, 1, 0}, /* OP_PUSHSTRING */
{iU, 1, 0}, /* OP_PUSHNUM */
{iU, 1, 0}, /* OP_PUSHNEGNUM */
{iU, 1, 0}, /* OP_PUSHUPVALUE */
{iU, 1, 0}, /* OP_GETLOCAL */
{iU, 1, 0}, /* OP_GETGLOBAL */
{iO, 1, 2}, /* OP_GETTABLE */
{iU, 1, 1}, /* OP_GETDOTTED */
{iU, 1, 1}, /* OP_GETINDEXED */
{iU, 2, 1}, /* OP_PUSHSELF */
{iU, 1, 0}, /* OP_CREATETABLE */
{iU, 0, 1}, /* OP_SETLOCAL */
{iU, 0, 1}, /* OP_SETGLOBAL */
{iAB, VD, 0}, /* OP_SETTABLE */
{iAB, VD, 0}, /* OP_SETLIST */
{iU, VD, 0}, /* OP_SETMAP */
{iO, 1, 2}, /* OP_ADD */
{iS, 1, 1}, /* OP_ADDI */
{iO, 1, 2}, /* OP_SUB */
{iO, 1, 2}, /* OP_MULT */
{iO, 1, 2}, /* OP_DIV */
{iO, 1, 2}, /* OP_POW */
{iU, VD, 0}, /* OP_CONCAT */
{iO, 1, 1}, /* OP_MINUS */
{iO, 1, 1}, /* OP_NOT */
{iS, 0, 2}, /* OP_JMPNE */
{iS, 0, 2}, /* OP_JMPEQ */
{iS, 0, 2}, /* OP_JMPLT */
{iS, 0, 2}, /* OP_JMPLE */
{iS, 0, 2}, /* OP_JMPGT */
{iS, 0, 2}, /* OP_JMPGE */
{iS, 0, 1}, /* OP_JMPT */
{iS, 0, 1}, /* OP_JMPF */
{iS, 0, 1}, /* OP_JMPONT */
{iS, 0, 1}, /* OP_JMPONF */
{iS, 0, 0}, /* OP_JMP */
{iO, 0, 0}, /* OP_PUSHNILJMP */
{iS, 0, 0}, /* OP_FORPREP */
{iS, 0, 3}, /* OP_FORLOOP */
{iS, 2, 0}, /* OP_LFORPREP */
{iS, 0, 3}, /* OP_LFORLOOP */
{iAB, VD, 0} /* OP_CLOSURE */
};

70
lcode.h Normal file
View File

@@ -0,0 +1,70 @@
/*
** $Id: lcode.h,v 1.15 2000/06/28 20:20:36 roberto Exp roberto $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#ifndef lcode_h
#define lcode_h
#include "llex.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
/*
** Marks the end of a patch list. It is an invalid value both as an absolute
** address, and as a list link (would link an element to itself).
*/
#define NO_JUMP (-1)
/*
** grep "ORDER OPR" if you change these enums
*/
typedef enum BinOpr {
OPR_ADD, OPR_SUB, OPR_MULT, OPR_DIV, OPR_POW,
OPR_CONCAT,
OPR_NE, OPR_EQ, OPR_LT, OPR_LE, OPR_GT, OPR_GE,
OPR_AND, OPR_OR,
OPR_NOBINOPR
} BinOpr;
typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_NOUNOPR } UnOpr;
enum Mode {iO, iU, iS, iAB}; /* instruction format */
#define VD 100 /* flag for variable delta */
extern const struct OpProperties {
char mode;
unsigned char push;
unsigned char pop;
} luaK_opproperties[];
void luaK_error (LexState *ls, const char *msg);
int luaK_code0 (FuncState *fs, OpCode o);
int luaK_code1 (FuncState *fs, OpCode o, int arg1);
int luaK_code2 (FuncState *fs, OpCode o, int arg1, int arg2);
int luaK_jump (FuncState *fs);
void luaK_patchlist (FuncState *fs, int list, int target);
void luaK_concat (FuncState *fs, int *l1, int l2);
void luaK_goiftrue (FuncState *fs, expdesc *v, int keepvalue);
int luaK_getlabel (FuncState *fs);
void luaK_deltastack (FuncState *fs, int delta);
void luaK_kstr (LexState *ls, int c);
void luaK_number (FuncState *fs, Number f);
void luaK_adjuststack (FuncState *fs, int n);
int luaK_lastisopen (FuncState *fs);
void luaK_setcallreturns (FuncState *fs, int nresults);
void luaK_tostack (LexState *ls, expdesc *v, int onlyone);
void luaK_storevar (LexState *ls, const expdesc *var);
void luaK_prefix (LexState *ls, UnOpr op, expdesc *v);
void luaK_infix (LexState *ls, BinOpr op, expdesc *v);
void luaK_posfix (LexState *ls, BinOpr op, expdesc *v1, expdesc *v2);
#endif

311
ldblib.c
View File

@@ -1,217 +1,188 @@
/* /*
** $Id: ldblib.c,v 1.4 1999/02/04 17:47:59 roberto Exp roberto $ ** $Id: ldblib.c,v 1.28 2000/11/06 13:19:08 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
*/ */
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "lauxlib.h"
#include "lua.h" #include "lua.h"
#include "lauxlib.h"
#include "luadebug.h" #include "luadebug.h"
#include "lualib.h" #include "lualib.h"
static void settabss (lua_Object t, char *i, char *v) { static void settabss (lua_State *L, const char *i, const char *v) {
lua_pushobject(t); lua_pushstring(L, i);
lua_pushstring(i); lua_pushstring(L, v);
lua_pushstring(v); lua_settable(L, -3);
lua_settable();
} }
static void settabsi (lua_Object t, char *i, int v) { static void settabsi (lua_State *L, const char *i, int v) {
lua_pushobject(t); lua_pushstring(L, i);
lua_pushstring(i); lua_pushnumber(L, v);
lua_pushnumber(v); lua_settable(L, -3);
lua_settable();
} }
static lua_Object getfuncinfo (lua_Object func) { static int getinfo (lua_State *L) {
lua_Object result = lua_createtable(); lua_Debug ar;
char *str; const char *options = luaL_opt_string(L, 2, "flnSu");
int line; char buff[20];
lua_funcinfo(func, &str, &line); if (lua_isnumber(L, 1)) {
if (line == -1) /* C function? */ if (!lua_getstack(L, (int)lua_tonumber(L, 1), &ar)) {
settabss(result, "kind", "C"); lua_pushnil(L); /* level out of range */
else if (line == 0) { /* "main"? */ return 1;
settabss(result, "kind", "chunk");
settabss(result, "source", str);
}
else { /* Lua function */
settabss(result, "kind", "Lua");
settabsi(result, "def_line", line);
settabss(result, "source", str);
}
if (line != 0) { /* is it not a "main"? */
char *kind = lua_getobjname(func, &str);
if (*kind) {
settabss(result, "name", str);
settabss(result, "where", kind);
} }
} }
return result; else if (lua_isfunction(L, 1)) {
} lua_pushvalue(L, 1);
sprintf(buff, ">%.10s", options);
options = buff;
static void getstack (void) {
lua_Object func = lua_stackedfunction(luaL_check_int(1));
if (func == LUA_NOOBJECT) /* level out of range? */
return;
else {
lua_Object result = getfuncinfo(func);
int currline = lua_currentline(func);
if (currline > 0)
settabsi(result, "current", currline);
lua_pushobject(result);
lua_pushstring("func");
lua_pushobject(func);
lua_settable(); /* result.func = func */
lua_pushobject(result);
} }
} else
luaL_argerror(L, 1, "function or level expected");
if (!lua_getinfo(L, options, &ar))
static void funcinfo (void) { luaL_argerror(L, 2, "invalid option");
lua_pushobject(getfuncinfo(luaL_functionarg(1))); lua_newtable(L);
} for (; *options; options++) {
switch (*options) {
case 'S':
static int findlocal (lua_Object func, int arg) { settabss(L, "source", ar.source);
lua_Object v = lua_getparam(arg); if (ar.source)
if (lua_isnumber(v)) settabss(L, "short_src", ar.short_src);
return (int)lua_getnumber(v); settabsi(L, "linedefined", ar.linedefined);
else { settabss(L, "what", ar.what);
char *name = luaL_check_string(arg); break;
int i = 0; case 'l':
int result = -1; settabsi(L, "currentline", ar.currentline);
char *vname; break;
while (lua_getlocal(func, ++i, &vname) != LUA_NOOBJECT) { case 'u':
if (strcmp(name, vname) == 0) settabsi(L, "nups", ar.nups);
result = i; /* keep looping to get the last var with this name */ break;
} case 'n':
if (result == -1) settabss(L, "name", ar.name);
luaL_verror("no local variable `%.50s' at given level", name); settabss(L, "namewhat", ar.namewhat);
return result; break;
} case 'f':
} lua_pushstring(L, "func");
lua_pushvalue(L, -3);
lua_settable(L, -3);
static void getlocal (void) {
lua_Object func = lua_stackedfunction(luaL_check_int(1));
lua_Object val;
char *name;
if (func == LUA_NOOBJECT) /* level out of range? */
return; /* return nil */
else if (lua_getparam(2) != LUA_NOOBJECT) { /* 2nd argument? */
if ((val = lua_getlocal(func, findlocal(func, 2), &name)) != LUA_NOOBJECT) {
lua_pushobject(val);
lua_pushstring(name);
}
/* else return nil */
}
else { /* collect all locals in a table */
lua_Object result = lua_createtable();
int i;
for (i=1; ;i++) {
if ((val = lua_getlocal(func, i, &name)) == LUA_NOOBJECT)
break; break;
lua_pushobject(result);
lua_pushstring(name);
lua_pushobject(val);
lua_settable(); /* result[name] = value */
} }
lua_pushobject(result);
} }
return 1; /* return table */
} }
static int getlocal (lua_State *L) {
static void setlocal (void) { lua_Debug ar;
lua_Object func = lua_stackedfunction(luaL_check_int(1)); const char *name;
int numvar; if (!lua_getstack(L, luaL_check_int(L, 1), &ar)) /* level out of range? */
luaL_arg_check(func != LUA_NOOBJECT, 1, "level out of range"); luaL_argerror(L, 1, "level out of range");
numvar = findlocal(func, 2); name = lua_getlocal(L, &ar, luaL_check_int(L, 2));
lua_pushobject(luaL_nonnullarg(3)); if (name) {
if (!lua_setlocal(func, numvar)) lua_pushstring(L, name);
lua_error("no such local variable"); lua_pushvalue(L, -2);
} return 2;
static int linehook = -1; /* Lua reference to line hook function */
static int callhook = -1; /* Lua reference to call hook function */
static void dohook (int ref) {
lua_LHFunction oldlinehook = lua_setlinehook(NULL);
lua_CHFunction oldcallhook = lua_setcallhook(NULL);
lua_callfunction(lua_getref(ref));
lua_setlinehook(oldlinehook);
lua_setcallhook(oldcallhook);
}
static void linef (int line) {
lua_pushnumber(line);
dohook(linehook);
}
static void callf (lua_Function func, char *file, int line) {
if (func != LUA_NOOBJECT) {
lua_pushobject(func);
lua_pushstring(file);
lua_pushnumber(line);
}
dohook(callhook);
}
static void setcallhook (void) {
lua_Object f = lua_getparam(1);
lua_unref(callhook);
if (f == LUA_NOOBJECT) {
callhook = -1;
lua_setcallhook(NULL);
} }
else { else {
lua_pushobject(f); lua_pushnil(L);
callhook = lua_ref(1); return 1;
lua_setcallhook(callf);
} }
} }
static void setlinehook (void) { static int setlocal (lua_State *L) {
lua_Object f = lua_getparam(1); lua_Debug ar;
lua_unref(linehook); if (!lua_getstack(L, luaL_check_int(L, 1), &ar)) /* level out of range? */
if (f == LUA_NOOBJECT) { luaL_argerror(L, 1, "level out of range");
linehook = -1; luaL_checkany(L, 3);
lua_setlinehook(NULL); lua_pushstring(L, lua_setlocal(L, &ar, luaL_check_int(L, 2)));
} return 1;
else {
lua_pushobject(f);
linehook = lua_ref(1);
lua_setlinehook(linef);
}
} }
static struct luaL_reg dblib[] = {
{"funcinfo", funcinfo}, /* dummy variables (to define unique addresses) */
static char key1, key2;
#define KEY_CALLHOOK (&key1)
#define KEY_LINEHOOK (&key2)
static void hookf (lua_State *L, void *key) {
lua_getregistry(L);
lua_pushuserdata(L, key);
lua_gettable(L, -2);
if (lua_isfunction(L, -1)) {
lua_pushvalue(L, 1);
lua_rawcall(L, 1, 0);
}
else
lua_pop(L, 1); /* pop result from gettable */
lua_pop(L, 1); /* pop table */
}
static void callf (lua_State *L, lua_Debug *ar) {
lua_pushstring(L, ar->event);
hookf(L, KEY_CALLHOOK);
}
static void linef (lua_State *L, lua_Debug *ar) {
lua_pushnumber(L, ar->currentline);
hookf(L, KEY_LINEHOOK);
}
static void sethook (lua_State *L, void *key, lua_Hook hook,
lua_Hook (*sethookf)(lua_State * L, lua_Hook h)) {
lua_settop(L, 1);
if (lua_isnil(L, 1))
(*sethookf)(L, NULL);
else if (lua_isfunction(L, 1))
(*sethookf)(L, hook);
else
luaL_argerror(L, 1, "function expected");
lua_getregistry(L);
lua_pushuserdata(L, key);
lua_pushvalue(L, -1); /* dup key */
lua_gettable(L, -3); /* get old value */
lua_pushvalue(L, -2); /* key (again) */
lua_pushvalue(L, 1);
lua_settable(L, -5); /* set new value */
}
static int setcallhook (lua_State *L) {
sethook(L, KEY_CALLHOOK, callf, lua_setcallhook);
return 1;
}
static int setlinehook (lua_State *L) {
sethook(L, KEY_LINEHOOK, linef, lua_setlinehook);
return 1;
}
static const struct luaL_reg dblib[] = {
{"getlocal", getlocal}, {"getlocal", getlocal},
{"getstack", getstack}, {"getinfo", getinfo},
{"setcallhook", setcallhook}, {"setcallhook", setcallhook},
{"setlinehook", setlinehook}, {"setlinehook", setlinehook},
{"setlocal", setlocal} {"setlocal", setlocal}
}; };
void lua_dblibopen (void) { LUALIB_API void lua_dblibopen (lua_State *L) {
luaL_openlib(dblib, (sizeof(dblib)/sizeof(dblib[0]))); luaL_openl(L, dblib);
} }

466
ldebug.c Normal file
View File

@@ -0,0 +1,466 @@
/*
** $Id: ldebug.c,v 1.49 2000/10/27 11:39:52 roberto Exp roberto $
** Debug Interface
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#include "lua.h"
#include "lapi.h"
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "luadebug.h"
static const char *getfuncname (lua_State *L, StkId f, const char **name);
static void setnormalized (TObject *d, const TObject *s) {
if (ttype(s) == LUA_TMARK) {
clvalue(d) = infovalue(s)->func;
ttype(d) = LUA_TFUNCTION;
}
else *d = *s;
}
static int isLmark (StkId o) {
return (o && ttype(o) == LUA_TMARK && !infovalue(o)->func->isC);
}
LUA_API lua_Hook lua_setcallhook (lua_State *L, lua_Hook func) {
lua_Hook oldhook = L->callhook;
L->callhook = func;
return oldhook;
}
LUA_API lua_Hook lua_setlinehook (lua_State *L, lua_Hook func) {
lua_Hook oldhook = L->linehook;
L->linehook = func;
return oldhook;
}
static StkId aux_stackedfunction (lua_State *L, int level, StkId top) {
int i;
for (i = (top-1) - L->stack; i>=0; i--) {
if (is_T_MARK(L->stack[i].ttype)) {
if (level == 0)
return L->stack+i;
level--;
}
}
return NULL;
}
LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
StkId f = aux_stackedfunction(L, level, L->top);
if (f == NULL) return 0; /* there is no such level */
else {
ar->_func = f;
return 1;
}
}
static int nups (StkId f) {
switch (ttype(f)) {
case LUA_TFUNCTION:
return clvalue(f)->nupvalues;
case LUA_TMARK:
return infovalue(f)->func->nupvalues;
default:
return 0;
}
}
int luaG_getline (int *lineinfo, int pc, int refline, int *prefi) {
int refi;
if (lineinfo == NULL || pc == -1)
return -1; /* no line info or function is not active */
refi = prefi ? *prefi : 0;
if (lineinfo[refi] < 0)
refline += -lineinfo[refi++];
LUA_ASSERT(lineinfo[refi] >= 0, "invalid line info");
while (lineinfo[refi] > pc) {
refline--;
refi--;
if (lineinfo[refi] < 0)
refline -= -lineinfo[refi--];
LUA_ASSERT(lineinfo[refi] >= 0, "invalid line info");
}
for (;;) {
int nextline = refline + 1;
int nextref = refi + 1;
if (lineinfo[nextref] < 0)
nextline += -lineinfo[nextref++];
LUA_ASSERT(lineinfo[nextref] >= 0, "invalid line info");
if (lineinfo[nextref] > pc)
break;
refline = nextline;
refi = nextref;
}
if (prefi) *prefi = refi;
return refline;
}
static int currentpc (StkId f) {
CallInfo *ci = infovalue(f);
LUA_ASSERT(isLmark(f), "function has no pc");
if (ci->pc)
return (*ci->pc - ci->func->f.l->code) - 1;
else
return -1; /* function is not active */
}
static int currentline (StkId f) {
if (!isLmark(f))
return -1; /* only active lua functions have current-line information */
else {
CallInfo *ci = infovalue(f);
int *lineinfo = ci->func->f.l->lineinfo;
return luaG_getline(lineinfo, currentpc(f), 1, NULL);
}
}
static Proto *getluaproto (StkId f) {
return (isLmark(f) ? infovalue(f)->func->f.l : NULL);
}
LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
const char *name;
StkId f = ar->_func;
Proto *fp = getluaproto(f);
if (!fp) return NULL; /* `f' is not a Lua function? */
name = luaF_getlocalname(fp, n, currentpc(f));
if (!name) return NULL;
luaA_pushobject(L, (f+1)+(n-1)); /* push value */
return name;
}
LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
const char *name;
StkId f = ar->_func;
Proto *fp = getluaproto(f);
L->top--; /* pop new value */
if (!fp) return NULL; /* `f' is not a Lua function? */
name = luaF_getlocalname(fp, n, currentpc(f));
if (!name || name[0] == '(') return NULL; /* `(' starts private locals */
*((f+1)+(n-1)) = *L->top;
return name;
}
static void infoLproto (lua_Debug *ar, Proto *f) {
ar->source = f->source->str;
ar->linedefined = f->lineDefined;
ar->what = "Lua";
}
static void funcinfo (lua_State *L, lua_Debug *ar, StkId func) {
Closure *cl = NULL;
switch (ttype(func)) {
case LUA_TFUNCTION:
cl = clvalue(func);
break;
case LUA_TMARK:
cl = infovalue(func)->func;
break;
default:
lua_error(L, "value for `lua_getinfo' is not a function");
}
if (cl->isC) {
ar->source = "=C";
ar->linedefined = -1;
ar->what = "C";
}
else
infoLproto(ar, cl->f.l);
luaO_chunkid(ar->short_src, ar->source, sizeof(ar->short_src));
if (ar->linedefined == 0)
ar->what = "main";
}
static const char *travtagmethods (lua_State *L, const TObject *o) {
if (ttype(o) == LUA_TFUNCTION) {
int e;
for (e=0; e<TM_N; e++) {
int t;
for (t=0; t<=L->last_tag; t++)
if (clvalue(o) == luaT_gettm(L, t, e))
return luaT_eventname[e];
}
}
return NULL;
}
static const char *travglobals (lua_State *L, const TObject *o) {
Hash *g = L->gt;
int i;
for (i=0; i<g->size; i++) {
if (luaO_equalObj(o, val(node(g, i))) &&
ttype(key(node(g, i))) == LUA_TSTRING)
return tsvalue(key(node(g, i)))->str;
}
return NULL;
}
static void getname (lua_State *L, StkId f, lua_Debug *ar) {
TObject o;
setnormalized(&o, f);
/* try to find a name for given function */
if ((ar->name = travglobals(L, &o)) != NULL)
ar->namewhat = "global";
/* not found: try tag methods */
else if ((ar->name = travtagmethods(L, &o)) != NULL)
ar->namewhat = "tag-method";
else ar->namewhat = ""; /* not found at all */
}
LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
StkId func;
int isactive = (*what != '>');
if (isactive)
func = ar->_func;
else {
what++; /* skip the '>' */
func = L->top - 1;
}
for (; *what; what++) {
switch (*what) {
case 'S': {
funcinfo(L, ar, func);
break;
}
case 'l': {
ar->currentline = currentline(func);
break;
}
case 'u': {
ar->nups = nups(func);
break;
}
case 'n': {
ar->namewhat = (isactive) ? getfuncname(L, func, &ar->name) : NULL;
if (ar->namewhat == NULL)
getname(L, func, ar);
break;
}
case 'f': {
setnormalized(L->top, func);
incr_top; /* push function */
break;
}
default: return 0; /* invalid option */
}
}
if (!isactive) L->top--; /* pop function */
return 1;
}
/*
** {======================================================
** Symbolic Execution
** =======================================================
*/
static int pushpc (int *stack, int pc, int top, int n) {
while (n--)
stack[top++] = pc-1;
return top;
}
static Instruction luaG_symbexec (const Proto *pt, int lastpc, int stackpos) {
int stack[MAXSTACK]; /* stores last instruction that changed a stack entry */
const Instruction *code = pt->code;
int top = pt->numparams;
int pc = 0;
if (pt->is_vararg) /* varargs? */
top++; /* `arg' */
while (pc < lastpc) {
const Instruction i = code[pc++];
LUA_ASSERT(0 <= top && top <= pt->maxstacksize, "wrong stack");
switch (GET_OPCODE(i)) {
case OP_RETURN: {
LUA_ASSERT(top >= GETARG_U(i), "wrong stack");
top = GETARG_U(i);
break;
}
case OP_TAILCALL: {
LUA_ASSERT(top >= GETARG_A(i), "wrong stack");
top = GETARG_B(i);
break;
}
case OP_CALL: {
int nresults = GETARG_B(i);
if (nresults == MULT_RET) nresults = 1;
LUA_ASSERT(top >= GETARG_A(i), "wrong stack");
top = pushpc(stack, pc, GETARG_A(i), nresults);
break;
}
case OP_PUSHNIL: {
top = pushpc(stack, pc, top, GETARG_U(i));
break;
}
case OP_POP: {
top -= GETARG_U(i);
break;
}
case OP_SETTABLE:
case OP_SETLIST: {
top -= GETARG_B(i);
break;
}
case OP_SETMAP: {
top -= 2*GETARG_U(i);
break;
}
case OP_CONCAT: {
top -= GETARG_U(i);
stack[top++] = pc-1;
break;
}
case OP_CLOSURE: {
top -= GETARG_B(i);
stack[top++] = pc-1;
break;
}
case OP_JMPONT:
case OP_JMPONF: {
int newpc = pc + GETARG_S(i);
/* jump is forward and do not skip `lastpc'? */
if (pc < newpc && newpc <= lastpc) {
stack[top-1] = pc-1; /* value comes from `and'/`or' */
pc = newpc; /* do the jump */
}
else
top--; /* do not jump; pop value */
break;
}
default: {
OpCode op = GET_OPCODE(i);
LUA_ASSERT(luaK_opproperties[op].push != VD,
"invalid opcode for default");
top -= luaK_opproperties[op].pop;
LUA_ASSERT(top >= 0, "wrong stack");
top = pushpc(stack, pc, top, luaK_opproperties[op].push);
}
}
}
return code[stack[stackpos]];
}
static const char *getobjname (lua_State *L, StkId obj, const char **name) {
StkId func = aux_stackedfunction(L, 0, obj);
if (!isLmark(func))
return NULL; /* not an active Lua function */
else {
Proto *p = infovalue(func)->func->f.l;
int pc = currentpc(func);
int stackpos = obj - (func+1); /* func+1 == function base */
Instruction i = luaG_symbexec(p, pc, stackpos);
LUA_ASSERT(pc != -1, "function must be active");
switch (GET_OPCODE(i)) {
case OP_GETGLOBAL: {
*name = p->kstr[GETARG_U(i)]->str;
return "global";
}
case OP_GETLOCAL: {
*name = luaF_getlocalname(p, GETARG_U(i)+1, pc);
LUA_ASSERT(*name, "local must exist");
return "local";
}
case OP_PUSHSELF:
case OP_GETDOTTED: {
*name = p->kstr[GETARG_U(i)]->str;
return "field";
}
default:
return NULL; /* no useful name found */
}
}
}
static const char *getfuncname (lua_State *L, StkId f, const char **name) {
StkId func = aux_stackedfunction(L, 0, f); /* calling function */
if (!isLmark(func))
return NULL; /* not an active Lua function */
else {
Proto *p = infovalue(func)->func->f.l;
int pc = currentpc(func);
Instruction i;
if (pc == -1) return NULL; /* function is not activated */
i = p->code[pc];
switch (GET_OPCODE(i)) {
case OP_CALL: case OP_TAILCALL:
return getobjname(L, (func+1)+GETARG_A(i), name);
default:
return NULL; /* no useful name found */
}
}
}
/* }====================================================== */
void luaG_typeerror (lua_State *L, StkId o, const char *op) {
const char *name;
const char *kind = getobjname(L, o, &name);
const char *t = luaO_typename(o);
if (kind)
luaO_verror(L, "attempt to %.30s %.20s `%.40s' (a %.10s value)",
op, kind, name, t);
else
luaO_verror(L, "attempt to %.30s a %.10s value", op, t);
}
void luaG_binerror (lua_State *L, StkId p1, int t, const char *op) {
if (ttype(p1) == t) p1++;
LUA_ASSERT(ttype(p1) != t, "must be an error");
luaG_typeerror(L, p1, op);
}
void luaG_ordererror (lua_State *L, StkId top) {
const char *t1 = luaO_typename(top-2);
const char *t2 = luaO_typename(top-1);
if (t1[2] == t2[2])
luaO_verror(L, "attempt to compare two %.10s values", t1);
else
luaO_verror(L, "attempt to compare %.10s with %.10s", t1, t2);
}

21
ldebug.h Normal file
View File

@@ -0,0 +1,21 @@
/*
** $Id: ldebug.h,v 1.6 2000/10/02 20:10:55 roberto Exp roberto $
** Auxiliary functions from Debug Interface module
** See Copyright Notice in lua.h
*/
#ifndef ldebug_h
#define ldebug_h
#include "lstate.h"
#include "luadebug.h"
void luaG_typeerror (lua_State *L, StkId o, const char *op);
void luaG_binerror (lua_State *L, StkId p1, int t, const char *op);
int luaG_getline (int *lineinfo, int pc, int refline, int *refi);
void luaG_ordererror (lua_State *L, StkId top);
#endif

584
ldo.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldo.c,v 1.40 1999/03/10 14:23:07 roberto Exp roberto $ ** $Id: ldo.c,v 1.108 2000/10/20 16:39:03 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
*/ */
@@ -10,386 +10,376 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "lauxlib.h" #include "lua.h"
#include "ldebug.h"
#include "ldo.h" #include "ldo.h"
#include "lfunc.h"
#include "lgc.h" #include "lgc.h"
#include "lmem.h" #include "lmem.h"
#include "lobject.h" #include "lobject.h"
#include "lparser.h" #include "lparser.h"
#include "lstate.h" #include "lstate.h"
#include "lstring.h" #include "lstring.h"
#include "ltable.h"
#include "ltm.h" #include "ltm.h"
#include "lua.h"
#include "luadebug.h"
#include "lundump.h" #include "lundump.h"
#include "lvm.h" #include "lvm.h"
#include "lzio.h" #include "lzio.h"
/* space to handle stack overflow errors */
#ifndef STACK_LIMIT #define EXTRA_STACK (2*LUA_MINSTACK)
#define STACK_LIMIT 6000
#endif
void luaD_init (lua_State *L, int stacksize) {
#define STACK_UNIT 128 L->stack = luaM_newvector(L, stacksize+EXTRA_STACK, TObject);
L->nblocks += stacksize*sizeof(TObject);
L->stack_last = L->stack+(stacksize-1);
void luaD_init (void) { L->stacksize = stacksize;
L->stack.stack = luaM_newvector(STACK_UNIT, TObject); L->Cbase = L->top = L->stack;
L->stack.top = L->stack.stack;
L->stack.last = L->stack.stack+(STACK_UNIT-1);
} }
void luaD_checkstack (int n) { void luaD_checkstack (lua_State *L, int n) {
struct Stack *S = &L->stack; if (L->stack_last - L->top <= n) { /* stack overflow? */
if (S->last-S->top <= n) { if (L->stack_last-L->stack > (L->stacksize-1)) {
StkId top = S->top-S->stack; /* overflow while handling overflow */
int stacksize = (S->last-S->stack)+STACK_UNIT+n; luaD_breakrun(L, LUA_ERRERR); /* break run without error message */
luaM_reallocvector(S->stack, stacksize, TObject); }
S->last = S->stack+(stacksize-1); else {
S->top = S->stack + top; L->stack_last += EXTRA_STACK; /* to be used by error message */
if (stacksize >= STACK_LIMIT) { /* stack overflow? */ lua_error(L, "stack overflow");
if (lua_stackedfunction(100) == LUA_NOOBJECT) /* 100 funcs on stack? */
lua_error("Lua2C - C2Lua overflow"); /* doesn't look like a rec. loop */
else
lua_error("stack size overflow");
} }
} }
} }
static void restore_stack_limit (lua_State *L) {
if (L->top - L->stack < L->stacksize - 1)
L->stack_last = L->stack + (L->stacksize-1);
}
/* /*
** Adjust stack. Set top to the given value, pushing NILs if needed. ** Adjust stack. Set top to base+extra, pushing NILs if needed.
** (we cannot add base+extra unless we are sure it fits in the stack;
** otherwise the result of such operation on pointers is undefined)
*/ */
void luaD_adjusttop (StkId newtop) { void luaD_adjusttop (lua_State *L, StkId base, int extra) {
int diff = newtop-(L->stack.top-L->stack.stack); int diff = extra-(L->top-base);
if (diff <= 0) if (diff <= 0)
L->stack.top += diff; L->top = base+extra;
else { else {
luaD_checkstack(diff); luaD_checkstack(L, diff);
while (diff--) while (diff--)
ttype(L->stack.top++) = LUA_T_NIL; ttype(L->top++) = LUA_TNIL;
} }
} }
/* /*
** Open a hole below "nelems" from the L->stack.top. ** Open a hole inside the stack at `pos'
*/ */
void luaD_openstack (int nelems) static void luaD_openstack (lua_State *L, StkId pos) {
{ int i = L->top-pos;
luaO_memup(L->stack.top-nelems+1, L->stack.top-nelems, while (i--) pos[i+1] = pos[i];
nelems*sizeof(TObject));
incr_top; incr_top;
} }
void luaD_lineHook (int line) static void dohook (lua_State *L, lua_Debug *ar, lua_Hook hook) {
{ StkId old_Cbase = L->Cbase;
struct C_Lua_Stack oldCLS = L->Cstack; StkId old_top = L->Cbase = L->top;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
L->Cstack.num = 0; L->allowhooks = 0; /* cannot call hooks inside a hook */
(*L->linehook)(line); (*hook)(L, ar);
L->stack.top = L->stack.stack+old_top; LUA_ASSERT(L->allowhooks == 0, "invalid allow");
L->Cstack = oldCLS; L->allowhooks = 1;
L->top = old_top;
L->Cbase = old_Cbase;
} }
void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn) void luaD_lineHook (lua_State *L, StkId func, int line, lua_Hook linehook) {
{ if (L->allowhooks) {
struct C_Lua_Stack oldCLS = L->Cstack; lua_Debug ar;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack; ar._func = func;
L->Cstack.num = 0; ar.event = "line";
if (isreturn) ar.currentline = line;
(*L->callhook)(LUA_NOOBJECT, "(return)", 0); dohook(L, &ar, linehook);
else {
TObject *f = L->stack.stack+base-1;
if (tf)
(*L->callhook)(Ref(f), tf->source->str, tf->lineDefined);
else
(*L->callhook)(Ref(f), "(C)", -1);
} }
L->stack.top = L->stack.stack+old_top; }
L->Cstack = oldCLS;
static void luaD_callHook (lua_State *L, StkId func, lua_Hook callhook,
const char *event) {
if (L->allowhooks) {
lua_Debug ar;
ar._func = func;
ar.event = event;
infovalue(func)->pc = NULL; /* function is not active */
dohook(L, &ar, callhook);
}
}
static StkId callCclosure (lua_State *L, const struct Closure *cl, StkId base) {
int nup = cl->nupvalues; /* number of upvalues */
StkId old_Cbase = L->Cbase;
int n;
L->Cbase = base; /* new base for C function */
luaD_checkstack(L, nup+LUA_MINSTACK); /* ensure minimum stack size */
for (n=0; n<nup; n++) /* copy upvalues as extra arguments */
*(L->top++) = cl->upvalue[n];
n = (*cl->f.c)(L); /* do the actual call */
L->Cbase = old_Cbase; /* restore old C base */
return L->top - n; /* return index of first result */
}
void luaD_callTM (lua_State *L, Closure *f, int nParams, int nResults) {
StkId base = L->top - nParams;
luaD_openstack(L, base);
clvalue(base) = f;
ttype(base) = LUA_TFUNCTION;
luaD_call(L, base, nResults);
} }
/* /*
** Call a C function. ** Call a function (C or Lua). The function to be called is at *func.
** Cstack.num is the number of arguments; Cstack.lua2C points to the ** The arguments are on the stack, right after the function.
** first argument. Returns an index to the first result from C. ** When returns, the results are on the stack, starting at the original
*/ ** function position.
static StkId callC (lua_CFunction f, StkId base) ** The number of results is nResults, unless nResults=LUA_MULTRET.
{ */
struct C_Lua_Stack *CS = &L->Cstack; void luaD_call (lua_State *L, StkId func, int nResults) {
struct C_Lua_Stack oldCLS = *CS; lua_Hook callhook;
StkId firstResult; StkId firstResult;
int numarg = (L->stack.top-L->stack.stack) - base; CallInfo ci;
CS->num = numarg; Closure *cl;
CS->lua2C = base; if (ttype(func) != LUA_TFUNCTION) {
CS->base = base+numarg; /* == top-stack */ /* `func' is not a function; check the `function' tag method */
if (L->callhook) Closure *tm = luaT_gettmbyObj(L, func, TM_FUNCTION);
luaD_callHook(base, NULL, 0); if (tm == NULL)
(*f)(); /* do the actual call */ luaG_typeerror(L, func, "call");
if (L->callhook) /* func may have changed callhook */ luaD_openstack(L, func);
luaD_callHook(base, NULL, 1); clvalue(func) = tm; /* tag method is the new function to be called */
firstResult = CS->base; ttype(func) = LUA_TFUNCTION;
*CS = oldCLS; }
return firstResult; cl = clvalue(func);
} ci.func = cl;
infovalue(func) = &ci;
ttype(func) = LUA_TMARK;
static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base) callhook = L->callhook;
{ if (callhook)
TObject *pbase; luaD_callHook(L, func, callhook, "call");
int nup = cl->nelems; /* number of upvalues */ firstResult = (cl->isC ? callCclosure(L, cl, func+1) :
luaD_checkstack(nup); luaV_execute(L, cl, func+1));
pbase = L->stack.stack+base; /* care: previous call may change this */ if (callhook) /* same hook that was active at entry */
/* open space for upvalues as extra arguments */ luaD_callHook(L, func, callhook, "return");
luaO_memup(pbase+nup, pbase, (L->stack.top-pbase)*sizeof(TObject)); LUA_ASSERT(ttype(func) == LUA_TMARK, "invalid tag");
/* copy upvalues into stack */ /* move results to `func' (to erase parameters and function) */
memcpy(pbase, cl->consts+1, nup*sizeof(TObject)); if (nResults == LUA_MULTRET) {
L->stack.top += nup; while (firstResult < L->top) /* copy all results */
return callC(f, base); *func++ = *firstResult++;
} L->top = func;
}
else { /* copy at most `nResults' */
void luaD_callTM (TObject *f, int nParams, int nResults) { for (; nResults > 0 && firstResult < L->top; nResults--)
luaD_openstack(nParams); *func++ = *firstResult++;
*(L->stack.top-nParams-1) = *f; L->top = func;
luaD_calln(nParams, nResults); for (; nResults > 0; nResults--) { /* if there are not enough results */
} ttype(L->top) = LUA_TNIL; /* adjust the stack */
incr_top; /* must check stack space */
/*
** Call a function (C or Lua). The parameters must be on the L->stack.stack,
** between [L->stack.stack+base,L->stack.top). The function to be called is at L->stack.stack+base-1.
** When returns, the results are on the L->stack.stack, between [L->stack.stack+base-1,L->stack.top).
** The number of results is nResults, unless nResults=MULT_RET.
*/
void luaD_call (StkId base, int nResults)
{
StkId firstResult;
TObject *func = L->stack.stack+base-1;
int i;
switch (ttype(func)) {
case LUA_T_CPROTO:
ttype(func) = LUA_T_CMARK;
firstResult = callC(fvalue(func), base);
break;
case LUA_T_PROTO:
ttype(func) = LUA_T_PMARK;
firstResult = luaV_execute(NULL, tfvalue(func), base);
break;
case LUA_T_CLOSURE: {
Closure *c = clvalue(func);
TObject *proto = &(c->consts[0]);
ttype(func) = LUA_T_CLMARK;
firstResult = (ttype(proto) == LUA_T_CPROTO) ?
callCclosure(c, fvalue(proto), base) :
luaV_execute(c, tfvalue(proto), base);
break;
}
default: { /* func is not a function */
/* Check the tag method for invalid functions */
TObject *im = luaT_getimbyObj(func, IM_FUNCTION);
if (ttype(im) == LUA_T_NIL)
lua_error("call expression not a function");
luaD_callTM(im, (L->stack.top-L->stack.stack)-(base-1), nResults);
return;
} }
} }
/* adjust the number of results */ luaC_checkGC(L);
if (nResults != MULT_RET)
luaD_adjusttop(firstResult+nResults);
/* move results to base-1 (to erase parameters and function) */
base--;
nResults = L->stack.top - (L->stack.stack+firstResult); /* actual number of results */
for (i=0; i<nResults; i++)
*(L->stack.stack+base+i) = *(L->stack.stack+firstResult+i);
L->stack.top -= firstResult-base;
}
void luaD_calln (int nArgs, int nResults) {
luaD_call((L->stack.top-L->stack.stack)-nArgs, nResults);
} }
/* /*
** Traverse all objects on L->stack.stack ** Execute a protected call.
*/ */
void luaD_travstack (int (*fn)(TObject *)) struct CallS { /* data to `f_call' */
{ StkId func;
StkId i; int nresults;
for (i = (L->stack.top-1)-L->stack.stack; i>=0; i--) };
fn(L->stack.stack+i);
static void f_call (lua_State *L, void *ud) {
struct CallS *c = (struct CallS *)ud;
luaD_call(L, c->func, c->nresults);
} }
LUA_API int lua_call (lua_State *L, int nargs, int nresults) {
static void message (char *s) { StkId func = L->top - (nargs+1); /* function to be called */
TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval); struct CallS c;
if (ttype(em) == LUA_T_PROTO || ttype(em) == LUA_T_CPROTO ||
ttype(em) == LUA_T_CLOSURE) {
*L->stack.top = *em;
incr_top;
lua_pushstring(s);
luaD_calln(1, 0);
}
}
/*
** Reports an error, and jumps up to the available recover label
*/
void lua_error (char *s) {
if (s) message(s);
if (L->errorJmp)
longjmp(*((jmp_buf *)L->errorJmp), 1);
else {
message("exit(1). Unable to recover.\n");
exit(1);
}
}
/*
** Call the function at L->Cstack.base, and incorporate results on
** the Lua2C structure.
*/
static void do_callinc (int nResults)
{
StkId base = L->Cstack.base;
luaD_call(base+1, nResults);
L->Cstack.lua2C = base; /* position of the new results */
L->Cstack.num = (L->stack.top-L->stack.stack) - base; /* number of results */
L->Cstack.base = base + L->Cstack.num; /* incorporate results on stack */
}
/*
** Execute a protected call. Assumes that function is at L->Cstack.base and
** parameters are on top of it. Leave nResults on the stack.
*/
int luaD_protectedrun (int nResults) {
volatile struct C_Lua_Stack oldCLS = L->Cstack;
jmp_buf myErrorJmp;
volatile int status;
jmp_buf *volatile oldErr = L->errorJmp;
L->errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0) {
do_callinc(nResults);
status = 0;
}
else { /* an error occurred: restore L->Cstack and L->stack.top */
L->Cstack = oldCLS;
L->stack.top = L->stack.stack+L->Cstack.base;
status = 1;
}
L->errorJmp = oldErr;
return status;
}
/*
** returns 0 = chunk loaded; 1 = error; 2 = no more chunks to load
*/
static int protectedparser (ZIO *z, int bin) {
volatile struct C_Lua_Stack oldCLS = L->Cstack;
jmp_buf myErrorJmp;
volatile int status;
TProtoFunc *volatile tf;
jmp_buf *volatile oldErr = L->errorJmp;
L->errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0) {
tf = bin ? luaU_undump1(z) : luaY_parser(z);
status = 0;
}
else { /* an error occurred: restore L->Cstack and L->stack.top */
L->Cstack = oldCLS;
L->stack.top = L->stack.stack+L->Cstack.base;
tf = NULL;
status = 1;
}
L->errorJmp = oldErr;
if (status) return 1; /* error code */
if (tf == NULL) return 2; /* 'natural' end */
luaD_adjusttop(L->Cstack.base+1); /* one slot for the pseudo-function */
L->stack.stack[L->Cstack.base].ttype = LUA_T_PROTO;
L->stack.stack[L->Cstack.base].value.tf = tf;
luaV_closure(0);
return 0;
}
static int do_main (ZIO *z, int bin) {
int status; int status;
int debug = L->debug; /* save debug status */ c.func = func; c.nresults = nresults;
do { status = luaD_runprotected(L, f_call, &c);
long old_blocks = (luaC_checkGC(), L->nblocks); if (status != 0) /* an error occurred? */
status = protectedparser(z, bin); L->top = func; /* remove parameters from the stack */
if (status == 1) return 1; /* error */
else if (status == 2) return 0; /* 'natural' end */
else {
unsigned long newelems2 = 2*(L->nblocks-old_blocks);
L->GCthreshold += newelems2;
status = luaD_protectedrun(MULT_RET);
L->GCthreshold -= newelems2;
}
} while (bin && status == 0);
L->debug = debug; /* restore debug status */
return status; return status;
} }
void luaD_gcIM (TObject *o) /*
{ ** Execute a protected parser.
TObject *im = luaT_getimbyObj(o, IM_GC); */
if (ttype(im) != LUA_T_NIL) { struct ParserS { /* data to `f_parser' */
*L->stack.top = *o; ZIO *z;
incr_top; int bin;
luaD_callTM(im, 1, 0); };
}
static void f_parser (lua_State *L, void *ud) {
struct ParserS *p = (struct ParserS *)ud;
Proto *tf = p->bin ? luaU_undump(L, p->z) : luaY_parser(L, p->z);
luaV_Lclosure(L, tf, 0);
} }
#define MAXFILENAME 260 /* maximum part of a file name kept */ static int protectedparser (lua_State *L, ZIO *z, int bin) {
struct ParserS p;
unsigned long old_blocks;
int status;
p.z = z; p.bin = bin;
luaC_checkGC(L);
old_blocks = L->nblocks;
status = luaD_runprotected(L, f_parser, &p);
if (status == 0) {
/* add new memory to threshold (as it probably will stay) */
L->GCthreshold += (L->nblocks - old_blocks);
}
else if (status == LUA_ERRRUN) /* an error occurred: correct error code */
status = LUA_ERRSYNTAX;
return status;
}
int lua_dofile (char *filename) {
static int parse_file (lua_State *L, const char *filename) {
ZIO z; ZIO z;
int status; int status;
int c; int bin; /* flag for file mode */
int bin; int c; /* look ahead char */
char source[MAXFILENAME];
FILE *f = (filename == NULL) ? stdin : fopen(filename, "r"); FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
if (f == NULL) if (f == NULL) return LUA_ERRFILE; /* unable to open file */
return 2;
c = fgetc(f); c = fgetc(f);
ungetc(c, f); ungetc(c, f);
bin = (c == ID_CHUNK); bin = (c == ID_CHUNK);
if (bin) if (bin && f != stdin) {
f = freopen(filename, "rb", f); /* set binary mode */ f = freopen(filename, "rb", f); /* set binary mode */
luaL_filesource(source, filename, sizeof(source)); if (f == NULL) return LUA_ERRFILE; /* unable to reopen file */
luaZ_Fopen(&z, f, source); }
status = do_main(&z, bin); lua_pushstring(L, "@");
lua_pushstring(L, (filename == NULL) ? "(stdin)" : filename);
lua_concat(L, 2);
filename = lua_tostring(L, -1); /* filename = '@'..filename */
lua_pop(L, 1); /* OK: there is no GC during parser */
luaZ_Fopen(&z, f, filename);
status = protectedparser(L, &z, bin);
if (f != stdin) if (f != stdin)
fclose(f); fclose(f);
return status; return status;
} }
int lua_dostring (char *str) { LUA_API int lua_dofile (lua_State *L, const char *filename) {
return lua_dobuffer(str, strlen(str), str); int status = parse_file(L, filename);
if (status == 0) /* parse OK? */
status = lua_call(L, 0, LUA_MULTRET); /* call main */
return status;
} }
int lua_dobuffer (char *buff, int size, char *name) { static int parse_buffer (lua_State *L, const char *buff, size_t size,
const char *name) {
ZIO z; ZIO z;
if (!name) name = "?"; if (!name) name = "?";
luaZ_mopen(&z, buff, size, name); luaZ_mopen(&z, buff, size, name);
return do_main(&z, buff[0]==ID_CHUNK); return protectedparser(L, &z, buff[0]==ID_CHUNK);
} }
LUA_API int lua_dobuffer (lua_State *L, const char *buff, size_t size, const char *name) {
int status = parse_buffer(L, buff, size, name);
if (status == 0) /* parse OK? */
status = lua_call(L, 0, LUA_MULTRET); /* call main */
return status;
}
LUA_API int lua_dostring (lua_State *L, const char *str) {
return lua_dobuffer(L, str, strlen(str), str);
}
/*
** {======================================================
** Error-recover functions (based on long jumps)
** =======================================================
*/
/* chain list of long jump buffers */
struct lua_longjmp {
jmp_buf b;
struct lua_longjmp *previous;
volatile int status; /* error code */
};
static void message (lua_State *L, const char *s) {
const TObject *em = luaH_getglobal(L, LUA_ERRORMESSAGE);
if (ttype(em) == LUA_TFUNCTION) {
*L->top = *em;
incr_top;
lua_pushstring(L, s);
luaD_call(L, L->top-2, 0);
}
}
/*
** Reports an error, and jumps up to the available recovery label
*/
LUA_API void lua_error (lua_State *L, const char *s) {
if (s) message(L, s);
luaD_breakrun(L, LUA_ERRRUN);
}
void luaD_breakrun (lua_State *L, int errcode) {
if (L->errorJmp) {
L->errorJmp->status = errcode;
longjmp(L->errorJmp->b, 1);
}
else {
if (errcode != LUA_ERRMEM)
message(L, "unable to recover; exiting\n");
exit(EXIT_FAILURE);
}
}
int luaD_runprotected (lua_State *L, void (*f)(lua_State *, void *), void *ud) {
StkId oldCbase = L->Cbase;
StkId oldtop = L->top;
struct lua_longjmp lj;
int allowhooks = L->allowhooks;
lj.status = 0;
lj.previous = L->errorJmp; /* chain new error handler */
L->errorJmp = &lj;
if (setjmp(lj.b) == 0)
(*f)(L, ud);
else { /* an error occurred: restore the state */
L->allowhooks = allowhooks;
L->Cbase = oldCbase;
L->top = oldtop;
restore_stack_limit(L);
}
L->errorJmp = lj.previous; /* restore old error handler */
return lj.status;
}
/* }====================================================== */

34
ldo.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ldo.h,v 1.4 1997/12/15 16:17:20 roberto Exp roberto $ ** $Id: ldo.h,v 1.27 2000/10/05 13:00:17 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
*/ */
@@ -12,36 +12,22 @@
#include "lstate.h" #include "lstate.h"
#define MULT_RET 255
/* /*
** macro to increment stack top. ** macro to increment stack top.
** There must be always an empty slot at the L->stack.top ** There must be always an empty slot at the L->stack.top
*/ */
#define incr_top { if (L->stack.top >= L->stack.last) luaD_checkstack(1); \ #define incr_top {if (L->top == L->stack_last) luaD_checkstack(L, 1); L->top++;}
L->stack.top++; }
/* macros to convert from lua_Object to (TObject *) and back */ void luaD_init (lua_State *L, int stacksize);
void luaD_adjusttop (lua_State *L, StkId base, int extra);
void luaD_lineHook (lua_State *L, StkId func, int line, lua_Hook linehook);
void luaD_call (lua_State *L, StkId func, int nResults);
void luaD_callTM (lua_State *L, Closure *f, int nParams, int nResults);
void luaD_checkstack (lua_State *L, int n);
#define Address(lo) ((lo)+L->stack.stack-1) void luaD_breakrun (lua_State *L, int errcode);
#define Ref(st) ((st)-L->stack.stack+1) int luaD_runprotected (lua_State *L, void (*f)(lua_State *, void *), void *ud);
void luaD_init (void);
void luaD_adjusttop (StkId newtop);
void luaD_openstack (int nelems);
void luaD_lineHook (int line);
void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn);
void luaD_call (StkId base, int nResults);
void luaD_calln (int nArgs, int nResults);
void luaD_callTM (TObject *f, int nParams, int nResults);
int luaD_protectedrun (int nResults);
void luaD_gcIM (TObject *o);
void luaD_travstack (int (*fn)(TObject *));
void luaD_checkstack (int n);
#endif #endif

125
lfunc.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lfunc.c,v 1.9 1998/06/19 16:14:09 roberto Exp roberto $ ** $Id: lfunc.c,v 1.33 2000/10/18 17:19:09 roberto Exp roberto $
** Auxiliary functions to manipulate prototypes and closures ** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -7,92 +7,103 @@
#include <stdlib.h> #include <stdlib.h>
#include "lua.h"
#include "lfunc.h" #include "lfunc.h"
#include "lmem.h" #include "lmem.h"
#include "lstate.h" #include "lstate.h"
#define gcsizeproto(p) 5 /* approximate "weight" for a prototype */
#define gcsizeclosure(c) 1 /* approximate "weight" for a closure */ #define sizeclosure(n) ((int)sizeof(Closure) + (int)sizeof(TObject)*((n)-1))
Closure *luaF_newclosure (lua_State *L, int nelems) {
Closure *luaF_newclosure (int nelems) int size = sizeclosure(nelems);
{ Closure *c = (Closure *)luaM_malloc(L, size);
Closure *c = (Closure *)luaM_malloc(sizeof(Closure)+nelems*sizeof(TObject)); c->next = L->rootcl;
luaO_insertlist(&(L->rootcl), (GCnode *)c); L->rootcl = c;
L->nblocks += gcsizeclosure(c); c->mark = c;
c->nelems = nelems; c->nupvalues = nelems;
L->nblocks += size;
return c; return c;
} }
TProtoFunc *luaF_newproto (void) Proto *luaF_newproto (lua_State *L) {
{ Proto *f = luaM_new(L, Proto);
TProtoFunc *f = luaM_new(TProtoFunc); f->knum = NULL;
f->nknum = 0;
f->kstr = NULL;
f->nkstr = 0;
f->kproto = NULL;
f->nkproto = 0;
f->code = NULL; f->code = NULL;
f->ncode = 0;
f->numparams = 0;
f->is_vararg = 0;
f->maxstacksize = 0;
f->marked = 0;
f->lineinfo = NULL;
f->nlineinfo = 0;
f->nlocvars = 0;
f->locvars = NULL;
f->lineDefined = 0; f->lineDefined = 0;
f->source = NULL; f->source = NULL;
f->consts = NULL; f->next = L->rootproto; /* chain in list of protos */
f->nconsts = 0; L->rootproto = f;
f->locvars = NULL;
luaO_insertlist(&(L->rootproto), (GCnode *)f);
L->nblocks += gcsizeproto(f);
return f; return f;
} }
static size_t protosize (Proto *f) {
static void freefunc (TProtoFunc *f) return sizeof(Proto)
{ + f->nknum*sizeof(Number)
luaM_free(f->code); + f->nkstr*sizeof(TString *)
luaM_free(f->locvars); + f->nkproto*sizeof(Proto *)
luaM_free(f->consts); + f->ncode*sizeof(Instruction)
luaM_free(f); + f->nlocvars*sizeof(struct LocVar)
+ f->nlineinfo*sizeof(int);
} }
void luaF_freeproto (TProtoFunc *l) void luaF_protook (lua_State *L, Proto *f, int pc) {
{ f->ncode = pc; /* signal that proto was properly created */
while (l) { L->nblocks += protosize(f);
TProtoFunc *next = (TProtoFunc *)l->head.next;
L->nblocks -= gcsizeproto(l);
freefunc(l);
l = next;
}
} }
void luaF_freeclosure (Closure *l) void luaF_freeproto (lua_State *L, Proto *f) {
{ if (f->ncode > 0) /* function was properly created? */
while (l) { L->nblocks -= protosize(f);
Closure *next = (Closure *)l->head.next; luaM_free(L, f->code);
L->nblocks -= gcsizeclosure(l); luaM_free(L, f->locvars);
luaM_free(l); luaM_free(L, f->kstr);
l = next; luaM_free(L, f->knum);
} luaM_free(L, f->kproto);
luaM_free(L, f->lineinfo);
luaM_free(L, f);
}
void luaF_freeclosure (lua_State *L, Closure *c) {
L->nblocks -= sizeclosure(c->nupvalues);
luaM_free(L, c);
} }
/* /*
** Look for n-th local variable at line "line" in function "func". ** Look for n-th local variable at line `line' in function `func'.
** Returns NULL if not found. ** Returns NULL if not found.
*/ */
char *luaF_getlocalname (TProtoFunc *func, int local_number, int line) const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
{ int i;
int count = 0; for (i = 0; i<f->nlocvars && f->locvars[i].startpc <= pc; i++) {
char *varname = NULL; if (pc < f->locvars[i].endpc) { /* is variable active? */
LocVar *lv = func->locvars; local_number--;
if (lv == NULL) if (local_number == 0)
return NULL; return f->locvars[i].varname->str;
for (; lv->line != -1 && lv->line < line; lv++) {
if (lv->varname) { /* register */
if (++count == local_number)
varname = lv->varname->str;
} }
else /* unregister */
if (--count < local_number)
varname = NULL;
} }
return varname; return NULL; /* not found */
} }

15
lfunc.h
View File

@@ -1,6 +1,6 @@
/* /*
** $Id: lfunc.h,v 1.4 1997/11/19 17:29:23 roberto Exp roberto $ ** $Id: lfunc.h,v 1.12 2000/06/26 19:28:31 roberto Exp roberto $
** Lua Function structures ** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -12,12 +12,13 @@
TProtoFunc *luaF_newproto (void); Proto *luaF_newproto (lua_State *L);
Closure *luaF_newclosure (int nelems); void luaF_protook (lua_State *L, Proto *f, int pc);
void luaF_freeproto (TProtoFunc *l); Closure *luaF_newclosure (lua_State *L, int nelems);
void luaF_freeclosure (Closure *l); void luaF_freeproto (lua_State *L, Proto *f);
void luaF_freeclosure (lua_State *L, Closure *c);
char *luaF_getlocalname (TProtoFunc *func, int local_number, int line); const char *luaF_getlocalname (const Proto *func, int local_number, int pc);
#endif #endif

480
lgc.c
View File

@@ -1,9 +1,10 @@
/* /*
** $Id: lgc.c,v 1.22 1999/02/26 15:48:55 roberto Exp roberto $ ** $Id: lgc.c,v 1.71 2000/10/05 13:00:17 roberto Exp roberto $
** Garbage Collector ** Garbage Collector
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include "lua.h"
#include "ldo.h" #include "ldo.h"
#include "lfunc.h" #include "lfunc.h"
@@ -14,262 +15,339 @@
#include "lstring.h" #include "lstring.h"
#include "ltable.h" #include "ltable.h"
#include "ltm.h" #include "ltm.h"
#include "lua.h"
typedef struct GCState {
Hash *tmark; /* list of marked tables to be visited */
Closure *cmark; /* list of marked closures to be visited */
} GCState;
static int markobject (TObject *o); static void markobject (GCState *st, TObject *o);
/* mark a string; marks larger than 1 cannot be changed */
#define strmark(s) {if ((s)->marked == 0) (s)->marked = 1;}
/* static void protomark (Proto *f) {
** ======================================================= if (!f->marked) {
** REF mechanism int i;
** ======================================================= f->marked = 1;
*/ strmark(f->source);
for (i=0; i<f->nkstr; i++)
strmark(f->kstr[i]);
int luaC_ref (TObject *o, int lock) { for (i=0; i<f->nkproto; i++)
int ref; protomark(f->kproto[i]);
if (ttype(o) == LUA_T_NIL) for (i=0; i<f->nlocvars; i++) /* mark local-variable names */
ref = -1; /* special ref for nil */ strmark(f->locvars[i].varname);
else {
for (ref=0; ref<L->refSize; ref++)
if (L->refArray[ref].status == FREE)
break;
if (ref == L->refSize) { /* no more empty spaces? */
luaM_growvector(L->refArray, L->refSize, 1, struct ref, refEM, MAX_INT);
L->refSize++;
}
L->refArray[ref].o = *o;
L->refArray[ref].status = lock ? LOCK : HOLD;
} }
return ref;
} }
void lua_unref (int ref) static void markstack (lua_State *L, GCState *st) {
{ StkId o;
if (ref >= 0 && ref < L->refSize) for (o=L->stack; o<L->top; o++)
L->refArray[ref].status = FREE; markobject(st, o);
} }
TObject* luaC_getref (int ref) static void marklock (lua_State *L, GCState *st) {
{
if (ref == -1)
return &luaO_nilobject;
if (ref >= 0 && ref < L->refSize &&
(L->refArray[ref].status == LOCK || L->refArray[ref].status == HOLD))
return &L->refArray[ref].o;
else
return NULL;
}
static void travlock (void)
{
int i; int i;
for (i=0; i<L->refSize; i++) for (i=0; i<L->refSize; i++) {
if (L->refArray[i].status == LOCK) if (L->refArray[i].st == LOCK)
markobject(&L->refArray[i].o); markobject(st, &L->refArray[i].o);
}
} }
static int ismarked (TObject *o) static void markclosure (GCState *st, Closure *cl) {
{ if (!ismarked(cl)) {
if (!cl->isC)
protomark(cl->f.l);
cl->mark = st->cmark; /* chain it for later traversal */
st->cmark = cl;
}
}
static void marktagmethods (lua_State *L, GCState *st) {
int e;
for (e=0; e<TM_N; e++) {
int t;
for (t=0; t<=L->last_tag; t++) {
Closure *cl = luaT_gettm(L, t, e);
if (cl) markclosure(st, cl);
}
}
}
static void markobject (GCState *st, TObject *o) {
switch (ttype(o)) {
case LUA_TUSERDATA: case LUA_TSTRING:
strmark(tsvalue(o));
break;
case LUA_TMARK:
markclosure(st, infovalue(o)->func);
break;
case LUA_TFUNCTION:
markclosure(st, clvalue(o));
break;
case LUA_TTABLE: {
if (!ismarked(hvalue(o))) {
hvalue(o)->mark = st->tmark; /* chain it in list of marked */
st->tmark = hvalue(o);
}
break;
}
default: break; /* numbers, etc */
}
}
static void markall (lua_State *L) {
GCState st;
st.cmark = NULL;
st.tmark = L->gt; /* put table of globals in mark list */
L->gt->mark = NULL;
marktagmethods(L, &st); /* mark tag methods */
markstack(L, &st); /* mark stack objects */
marklock(L, &st); /* mark locked objects */
for (;;) { /* mark tables and closures */
if (st.cmark) {
int i;
Closure *f = st.cmark; /* get first closure from list */
st.cmark = f->mark; /* remove it from list */
for (i=0; i<f->nupvalues; i++) /* mark its upvalues */
markobject(&st, &f->upvalue[i]);
}
else if (st.tmark) {
int i;
Hash *h = st.tmark; /* get first table from list */
st.tmark = h->mark; /* remove it from list */
for (i=0; i<h->size; i++) {
Node *n = node(h, i);
if (ttype(key(n)) != LUA_TNIL) {
if (ttype(val(n)) == LUA_TNIL)
luaH_remove(h, key(n)); /* dead element; try to remove it */
markobject(&st, &n->key);
markobject(&st, &n->val);
}
}
}
else break; /* nothing else to mark */
}
}
static int hasmark (const TObject *o) {
/* valid only for locked objects */ /* valid only for locked objects */
switch (o->ttype) { switch (o->ttype) {
case LUA_T_STRING: case LUA_T_USERDATA: case LUA_TSTRING: case LUA_TUSERDATA:
return o->value.ts->head.marked; return tsvalue(o)->marked;
case LUA_T_ARRAY: case LUA_TTABLE:
return o->value.a->head.marked; return ismarked(hvalue(o));
case LUA_T_CLOSURE: case LUA_TFUNCTION:
return o->value.cl->head.marked; return ismarked(clvalue(o));
case LUA_T_PROTO: default: /* number */
return o->value.tf->head.marked;
#ifdef DEBUG
case LUA_T_LINE: case LUA_T_CLMARK:
case LUA_T_CMARK: case LUA_T_PMARK:
LUA_INTERNALERROR("invalid type");
#endif
default: /* nil, number or cproto */
return 1; return 1;
} }
} }
static void invalidaterefs (void) /* macro for internal debugging; check if a link of free refs is valid */
{ #define VALIDLINK(L, st,n) (NONEXT <= (st) && (st) < (n))
static void invalidaterefs (lua_State *L) {
int n = L->refSize;
int i; int i;
for (i=0; i<L->refSize; i++) for (i=0; i<n; i++) {
if (L->refArray[i].status == HOLD && !ismarked(&L->refArray[i].o)) struct Ref *r = &L->refArray[i];
L->refArray[i].status = COLLECTED; if (r->st == HOLD && !hasmark(&r->o))
} r->st = COLLECTED;
LUA_ASSERT((r->st == LOCK && hasmark(&r->o)) ||
(r->st == HOLD && hasmark(&r->o)) ||
r->st == COLLECTED ||
void luaC_hashcallIM (Hash *l) r->st == NONEXT ||
{ (r->st < n && VALIDLINK(L, L->refArray[r->st].st, n)),
TObject t; "inconsistent ref table");
ttype(&t) = LUA_T_ARRAY;
for (; l; l=(Hash *)l->head.next) {
avalue(&t) = l;
luaD_gcIM(&t);
} }
LUA_ASSERT(VALIDLINK(L, L->refFree, n), "inconsistent ref table");
} }
void luaC_strcallIM (TaggedString *l)
{ static void collectproto (lua_State *L) {
TObject o; Proto **p = &L->rootproto;
ttype(&o) = LUA_T_USERDATA; Proto *next;
for (; l; l=(TaggedString *)l->head.next) while ((next = *p) != NULL) {
if (l->constindex == -1) { /* is userdata? */ if (next->marked) {
tsvalue(&o) = l; next->marked = 0;
luaD_gcIM(&o); p = &next->next;
} }
} else {
*p = next->next;
luaF_freeproto(L, next);
static GCnode *listcollect (GCnode *l)
{
GCnode *frees = NULL;
while (l) {
GCnode *next = l->next;
l->marked = 0;
while (next && !next->marked) {
l->next = next->next;
next->next = frees;
frees = next;
next = l->next;
} }
l = next;
}
return frees;
}
static void strmark (TaggedString *s)
{
if (!s->head.marked)
s->head.marked = 1;
}
static void protomark (TProtoFunc *f) {
if (!f->head.marked) {
int i;
f->head.marked = 1;
strmark(f->source);
for (i=0; i<f->nconsts; i++)
markobject(&f->consts[i]);
} }
} }
static void closuremark (Closure *f) static void collectclosure (lua_State *L) {
{ Closure **p = &L->rootcl;
if (!f->head.marked) { Closure *next;
int i; while ((next = *p) != NULL) {
f->head.marked = 1; if (ismarked(next)) {
for (i=f->nelems; i>=0; i--) next->mark = next; /* unmark */
markobject(&f->consts[i]); p = &next->next;
}
else {
*p = next->next;
luaF_freeclosure(L, next);
}
} }
} }
static void hashmark (Hash *h) static void collecttable (lua_State *L) {
{ Hash **p = &L->roottable;
if (!h->head.marked) { Hash *next;
int i; while ((next = *p) != NULL) {
h->head.marked = 1; if (ismarked(next)) {
for (i=0; i<nhash(h); i++) { next->mark = next; /* unmark */
Node *n = node(h,i); p = &next->next;
if (ttype(ref(n)) != LUA_T_NIL) { }
markobject(&n->ref); else {
markobject(&n->val); *p = next->next;
luaH_free(L, next);
}
}
}
static void checktab (lua_State *L, stringtable *tb) {
if (tb->nuse < (lint32)(tb->size/4) && tb->size > 10)
luaS_resize(L, tb, tb->size/2); /* table is too big */
}
static void collectstrings (lua_State *L, int all) {
int i;
for (i=0; i<L->strt.size; i++) { /* for each list */
TString **p = &L->strt.hash[i];
TString *next;
while ((next = *p) != NULL) {
if (next->marked && !all) { /* preserve? */
if (next->marked < FIXMARK) /* does not change FIXMARKs */
next->marked = 0;
p = &next->nexthash;
}
else { /* collect */
*p = next->nexthash;
L->strt.nuse--;
L->nblocks -= sizestring(next->len);
luaM_free(L, next);
} }
} }
} }
checktab(L, &L->strt);
} }
static void globalmark (void) static void collectudata (lua_State *L, int all) {
{ int i;
TaggedString *g; for (i=0; i<L->udt.size; i++) { /* for each list */
for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next){ TString **p = &L->udt.hash[i];
LUA_ASSERT(g->constindex >= 0, "userdata in global list"); TString *next;
if (g->u.s.globalval.ttype != LUA_T_NIL) { while ((next = *p) != NULL) {
markobject(&g->u.s.globalval); LUA_ASSERT(next->marked <= 1, "udata cannot be fixed");
strmark(g); /* cannot collect non nil global variables */ if (next->marked && !all) { /* preserve? */
next->marked = 0;
p = &next->nexthash;
}
else { /* collect */
int tag = next->u.d.tag;
*p = next->nexthash;
next->nexthash = L->TMtable[tag].collected; /* chain udata */
L->TMtable[tag].collected = next;
L->nblocks -= sizestring(next->len);
L->udt.nuse--;
}
}
}
checktab(L, &L->udt);
}
#define MINBUFFER 256
static void checkMbuffer (lua_State *L) {
if (L->Mbuffsize > MINBUFFER*2) { /* is buffer too big? */
size_t newsize = L->Mbuffsize/2; /* still larger than MINBUFFER */
L->nblocks += (newsize - L->Mbuffsize)*sizeof(char);
L->Mbuffsize = newsize;
luaM_reallocvector(L, L->Mbuffer, newsize, char);
}
}
static void callgcTM (lua_State *L, const TObject *o) {
Closure *tm = luaT_gettmbyObj(L, o, TM_GC);
if (tm != NULL) {
int oldah = L->allowhooks;
L->allowhooks = 0; /* stop debug hooks during GC tag methods */
luaD_checkstack(L, 2);
clvalue(L->top) = tm;
ttype(L->top) = LUA_TFUNCTION;
*(L->top+1) = *o;
L->top += 2;
luaD_call(L, L->top-2, 0);
L->allowhooks = oldah; /* restore hooks */
}
}
static void callgcTMudata (lua_State *L) {
int tag;
TObject o;
ttype(&o) = LUA_TUSERDATA;
L->GCthreshold = 2*L->nblocks; /* avoid GC during tag methods */
for (tag=L->last_tag; tag>=0; tag--) { /* for each tag (in reverse order) */
TString *udata;
while ((udata = L->TMtable[tag].collected) != NULL) {
L->TMtable[tag].collected = udata->nexthash; /* remove it from list */
tsvalue(&o) = udata;
callgcTM(L, &o);
luaM_free(L, udata);
} }
} }
} }
static int markobject (TObject *o) void luaC_collect (lua_State *L, int all) {
{ collectudata(L, all);
switch (ttype(o)) { callgcTMudata(L);
case LUA_T_USERDATA: case LUA_T_STRING: collectstrings(L, all);
strmark(tsvalue(o)); collecttable(L);
break; collectproto(L);
case LUA_T_ARRAY: collectclosure(L);
hashmark(avalue(o));
break;
case LUA_T_CLOSURE: case LUA_T_CLMARK:
closuremark(o->value.cl);
break;
case LUA_T_PROTO: case LUA_T_PMARK:
protomark(o->value.tf);
break;
default: break; /* numbers, cprotos, etc */
}
return 0;
} }
static void luaC_collectgarbage (lua_State *L) {
static void markall (void) markall(L);
{ invalidaterefs(L); /* check unlocked references */
luaD_travstack(markobject); /* mark stack objects */ luaC_collect(L, 0);
globalmark(); /* mark global variable values and names */ checkMbuffer(L);
travlock(); /* mark locked objects */ L->GCthreshold = 2*L->nblocks; /* set new threshold */
luaT_travtagmethods(markobject); /* mark fallbacks */ callgcTM(L, &luaO_nilobject);
} }
long lua_collectgarbage (long limit) void luaC_checkGC (lua_State *L) {
{
unsigned long recovered = L->nblocks; /* to subtract nblocks after gc */
Hash *freetable;
TaggedString *freestr;
TProtoFunc *freefunc;
Closure *freeclos;
markall();
invalidaterefs();
freestr = luaS_collector();
freetable = (Hash *)listcollect(&(L->roottable));
freefunc = (TProtoFunc *)listcollect(&(L->rootproto));
freeclos = (Closure *)listcollect(&(L->rootcl));
L->GCthreshold *= 4; /* to avoid GC during GC */
luaC_hashcallIM(freetable); /* GC tag methods for tables */
luaC_strcallIM(freestr); /* GC tag methods for userdata */
luaD_gcIM(&luaO_nilobject); /* GC tag method for nil (signal end of GC) */
luaH_free(freetable);
luaS_free(freestr);
luaF_freeproto(freefunc);
luaF_freeclosure(freeclos);
recovered = recovered-L->nblocks;
L->GCthreshold = (limit == 0) ? 2*L->nblocks : L->nblocks+limit;
return recovered;
}
void luaC_checkGC (void)
{
if (L->nblocks >= L->GCthreshold) if (L->nblocks >= L->GCthreshold)
lua_collectgarbage(0); luaC_collectgarbage(L);
} }

9
lgc.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lgc.h,v 1.3 1997/11/19 17:29:23 roberto Exp roberto $ ** $Id: lgc.h,v 1.7 1999/11/22 13:12:07 roberto Exp roberto $
** Garbage Collector ** Garbage Collector
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,11 +11,8 @@
#include "lobject.h" #include "lobject.h"
void luaC_checkGC (void); void luaC_collect (lua_State *L, int all);
TObject* luaC_getref (int ref); void luaC_checkGC (lua_State *L);
int luaC_ref (TObject *o, int lock);
void luaC_hashcallIM (Hash *l);
void luaC_strcallIM (TaggedString *l);
#endif #endif

13
linit.c
View File

@@ -1,17 +1,8 @@
/* /*
** $Id: linit.c,v 1.1 1999/01/08 16:47:44 roberto Exp $ ** $Id: linit.c,v 1.5 2000/06/16 17:22:43 roberto Exp roberto $
** Initialization of libraries for lua.c ** Initialization of libraries for lua.c
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include "lua.h" >>>>>>> This module is now obsolete, and is not part of Lua. <<<<<<<<<
#include "lualib.h"
void lua_userinit (void) {
lua_iolibopen();
lua_strlibopen();
lua_mathlibopen();
lua_dblibopen();
}

800
liolib.c

File diff suppressed because it is too large Load Diff

530
llex.c
View File

@@ -1,222 +1,115 @@
/* /*
** $Id: llex.c,v 1.33 1999/03/11 18:59:19 roberto Exp roberto $ ** $Id: llex.c,v 1.71 2000/09/27 17:41:58 roberto Exp roberto $
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include <ctype.h> #include <ctype.h>
#include <stdio.h>
#include <string.h> #include <string.h>
#include "lauxlib.h" #include "lua.h"
#include "llex.h" #include "llex.h"
#include "lmem.h" #include "lmem.h"
#include "lobject.h" #include "lobject.h"
#include "lparser.h" #include "lparser.h"
#include "lstate.h" #include "lstate.h"
#include "lstring.h" #include "lstring.h"
#include "ltable.h"
#include "luadebug.h" #include "luadebug.h"
#include "lzio.h" #include "lzio.h"
#define next(LS) (LS->current = zgetc(LS->lex_z)) #define next(LS) (LS->current = zgetc(LS->z))
#define save(c) luaL_addchar(c)
#define save_and_next(LS) (save(LS->current), next(LS)) /* ORDER RESERVED */
static const char *const token2string [] = {
"and", "break", "do", "else", "elseif", "end", "for",
"function", "if", "local", "nil", "not", "or", "repeat", "return", "then",
"until", "while", "", "..", "...", "==", ">=", "<=", "~=", "", "", "<eof>"};
char *reserved [] = {"and", "do", "else", "elseif", "end", "function", void luaX_init (lua_State *L) {
"if", "local", "nil", "not", "or", "repeat", "return", "then",
"until", "while"};
void luaX_init (void) {
int i; int i;
for (i=0; i<(sizeof(reserved)/sizeof(reserved[0])); i++) { for (i=0; i<NUM_RESERVED; i++) {
TaggedString *ts = luaS_new(reserved[i]); TString *ts = luaS_new(L, token2string[i]);
ts->head.marked = FIRST_RESERVED+i; /* reserved word (always > 255) */ ts->marked = (unsigned char)(RESERVEDMARK+i); /* reserved word */
} }
} }
#define MAXSRC 40 #define MAXSRC 80
void luaX_syntaxerror (LexState *ls, char *s, char *token) {
void luaX_checklimit (LexState *ls, int val, int limit, const char *msg) {
if (val > limit) {
char buff[100];
sprintf(buff, "too many %.50s (limit=%d)", msg, limit);
luaX_error(ls, buff, ls->t.token);
}
}
void luaX_syntaxerror (LexState *ls, const char *s, const char *token) {
char buff[MAXSRC]; char buff[MAXSRC];
luaL_chunkid(buff, zname(ls->lex_z), sizeof(buff)); luaO_chunkid(buff, ls->source->str, sizeof(buff));
if (token[0] == '\0') luaO_verror(ls->L, "%.99s;\n last token read: `%.30s' at line %d in %.80s",
token = "<eof>";
luaL_verror("%.100s;\n last token read: `%.50s' at line %d in %.50s",
s, token, ls->linenumber, buff); s, token, ls->linenumber, buff);
} }
void luaX_error (LexState *ls, char *s) { void luaX_error (LexState *ls, const char *s, int token) {
save('\0'); char buff[TOKEN_LEN];
luaX_syntaxerror(ls, s, luaL_buffer()); luaX_token2str(token, buff);
if (buff[0] == '\0')
luaX_syntaxerror(ls, s, ls->L->Mbuffer);
else
luaX_syntaxerror(ls, s, buff);
} }
void luaX_token2str (int token, char *s) { void luaX_token2str (int token, char *s) {
if (token < 255) { if (token < 256) {
s[0] = (char)token; s[0] = (char)token;
s[1] = '\0'; s[1] = '\0';
} }
else else
strcpy(s, reserved[token-FIRST_RESERVED]); strcpy(s, token2string[token-FIRST_RESERVED]);
} }
static void luaX_invalidchar (LexState *ls, int c) { static void luaX_invalidchar (LexState *ls, int c) {
char buff[10]; char buff[8];
sprintf(buff, "0x%02X", c); sprintf(buff, "0x%02X", c);
luaX_syntaxerror(ls, "invalid control char", buff); luaX_syntaxerror(ls, "invalid control char", buff);
} }
static void firstline (LexState *LS) static void inclinenumber (LexState *LS) {
{
int c = zgetc(LS->lex_z);
if (c == '#')
while ((c=zgetc(LS->lex_z)) != '\n' && c != EOZ) /* skip first line */;
zungetc(LS->lex_z);
}
void luaX_setinput (LexState *LS, ZIO *z)
{
LS->current = '\n';
LS->linenumber = 0;
LS->iflevel = 0;
LS->ifstate[0].skip = 0;
LS->ifstate[0].elsepart = 1; /* to avoid a free $else */
LS->lex_z = z;
LS->fs = NULL;
firstline(LS);
luaL_resetbuffer();
}
/*
** =======================================================
** PRAGMAS
** =======================================================
*/
#define PRAGMASIZE 20
static void skipspace (LexState *LS)
{
while (LS->current == ' ' || LS->current == '\t' || LS->current == '\r')
next(LS);
}
static int checkcond (LexState *LS, char *buff)
{
static char *opts[] = {"nil", "1", NULL};
int i = luaL_findstring(buff, opts);
if (i >= 0) return i;
else if (isalpha((unsigned char)buff[0]) || buff[0] == '_')
return luaS_globaldefined(buff);
else {
luaX_syntaxerror(LS, "invalid $if condition", buff);
return 0; /* to avoid warnings */
}
}
static void readname (LexState *LS, char *buff)
{
int i = 0;
skipspace(LS);
while (isalnum(LS->current) || LS->current == '_') {
if (i >= PRAGMASIZE) {
buff[PRAGMASIZE] = 0;
luaX_syntaxerror(LS, "pragma too long", buff);
}
buff[i++] = (char)LS->current;
next(LS);
}
buff[i] = 0;
}
static void inclinenumber (LexState *LS);
static void ifskip (LexState *LS)
{
while (LS->ifstate[LS->iflevel].skip) {
if (LS->current == '\n')
inclinenumber(LS);
else if (LS->current == EOZ)
luaX_error(LS, "input ends inside a $if");
else next(LS);
}
}
static void inclinenumber (LexState *LS)
{
static char *pragmas [] =
{"debug", "nodebug", "endinput", "end", "ifnot", "if", "else", NULL};
next(LS); /* skip '\n' */ next(LS); /* skip '\n' */
++LS->linenumber; ++LS->linenumber;
if (LS->current == '$') { /* is a pragma? */ luaX_checklimit(LS, LS->linenumber, MAX_INT, "lines in a chunk");
char buff[PRAGMASIZE+1]; }
int ifnot = 0;
int skip = LS->ifstate[LS->iflevel].skip;
next(LS); /* skip $ */ void luaX_setinput (lua_State *L, LexState *LS, ZIO *z, TString *source) {
readname(LS, buff); LS->L = L;
switch (luaL_findstring(buff, pragmas)) { LS->lookahead.token = TK_EOS; /* no look-ahead token */
case 0: /* debug */ LS->z = z;
if (!skip) L->debug = 1; LS->fs = NULL;
break; LS->linenumber = 1;
case 1: /* nodebug */ LS->lastline = 1;
if (!skip) L->debug = 0; LS->source = source;
break; next(LS); /* read first char */
case 2: /* endinput */ if (LS->current == '#') {
if (!skip) { do { /* skip first line */
LS->current = EOZ; next(LS);
LS->iflevel = 0; /* to allow $endinput inside a $if */ } while (LS->current != '\n' && LS->current != EOZ);
}
break;
case 3: /* end */
if (LS->iflevel-- == 0)
luaX_syntaxerror(LS, "unmatched $end", "$end");
break;
case 4: /* ifnot */
ifnot = 1;
/* go through */
case 5: /* if */
if (LS->iflevel == MAX_IFS-1)
luaX_syntaxerror(LS, "too many nested $ifs", "$if");
readname(LS, buff);
LS->iflevel++;
LS->ifstate[LS->iflevel].elsepart = 0;
LS->ifstate[LS->iflevel].condition = checkcond(LS, buff) ? !ifnot : ifnot;
LS->ifstate[LS->iflevel].skip = skip || !LS->ifstate[LS->iflevel].condition;
break;
case 6: /* else */
if (LS->ifstate[LS->iflevel].elsepart)
luaX_syntaxerror(LS, "unmatched $else", "$else");
LS->ifstate[LS->iflevel].elsepart = 1;
LS->ifstate[LS->iflevel].skip = LS->ifstate[LS->iflevel-1].skip ||
LS->ifstate[LS->iflevel].condition;
break;
default:
luaX_syntaxerror(LS, "unknown pragma", buff);
}
skipspace(LS);
if (LS->current == '\n') /* pragma must end with a '\n' ... */
inclinenumber(LS);
else if (LS->current != EOZ) /* or eof */
luaX_syntaxerror(LS, "invalid pragma format", buff);
ifskip(LS);
} }
} }
@@ -224,55 +117,172 @@ static void inclinenumber (LexState *LS)
/* /*
** ======================================================= ** =======================================================
** LEXICAL ANALIZER ** LEXICAL ANALYZER
** ======================================================= ** =======================================================
*/ */
/* use Mbuffer to store names, literal strings and numbers */
static int read_long_string (LexState *LS) { #define EXTRABUFF 128
#define checkbuffer(L, n, len) if ((len)+(n) > L->Mbuffsize) \
luaO_openspace(L, (len)+(n)+EXTRABUFF)
#define save(L, c, l) (L->Mbuffer[l++] = (char)c)
#define save_and_next(L, LS, l) (save(L, LS->current, l), next(LS))
static const char *readname (LexState *LS) {
lua_State *L = LS->L;
size_t l = 0;
checkbuffer(L, 10, l);
do {
checkbuffer(L, 10, l);
save_and_next(L, LS, l);
} while (isalnum(LS->current) || LS->current == '_');
save(L, '\0', l);
return L->Mbuffer;
}
/* LUA_NUMBER */
static void read_number (LexState *LS, int comma, SemInfo *seminfo) {
lua_State *L = LS->L;
size_t l = 0;
checkbuffer(L, 10, l);
if (comma) save(L, '.', l);
while (isdigit(LS->current)) {
checkbuffer(L, 10, l);
save_and_next(L, LS, l);
}
if (LS->current == '.') {
save_and_next(L, LS, l);
if (LS->current == '.') {
save_and_next(L, LS, l);
save(L, '\0', l);
luaX_error(LS, "ambiguous syntax"
" (decimal point x string concatenation)", TK_NUMBER);
}
}
while (isdigit(LS->current)) {
checkbuffer(L, 10, l);
save_and_next(L, LS, l);
}
if (LS->current == 'e' || LS->current == 'E') {
save_and_next(L, LS, l); /* read 'E' */
if (LS->current == '+' || LS->current == '-')
save_and_next(L, LS, l); /* optional exponent sign */
while (isdigit(LS->current)) {
checkbuffer(L, 10, l);
save_and_next(L, LS, l);
}
}
save(L, '\0', l);
if (!luaO_str2d(L->Mbuffer, &seminfo->r))
luaX_error(LS, "malformed number", TK_NUMBER);
}
static void read_long_string (LexState *LS, SemInfo *seminfo) {
lua_State *L = LS->L;
int cont = 0; int cont = 0;
size_t l = 0;
checkbuffer(L, 10, l);
save(L, '[', l); /* save first '[' */
save_and_next(L, LS, l); /* pass the second '[' */
for (;;) { for (;;) {
checkbuffer(L, 10, l);
switch (LS->current) { switch (LS->current) {
case EOZ: case EOZ:
luaX_error(LS, "unfinished long string"); save(L, '\0', l);
return EOS; /* to avoid warnings */ luaX_error(LS, "unfinished long string", TK_STRING);
break; /* to avoid warnings */
case '[': case '[':
save_and_next(LS); save_and_next(L, LS, l);
if (LS->current == '[') { if (LS->current == '[') {
cont++; cont++;
save_and_next(LS); save_and_next(L, LS, l);
} }
continue; continue;
case ']': case ']':
save_and_next(LS); save_and_next(L, LS, l);
if (LS->current == ']') { if (LS->current == ']') {
if (cont == 0) goto endloop; if (cont == 0) goto endloop;
cont--; cont--;
save_and_next(LS); save_and_next(L, LS, l);
} }
continue; continue;
case '\n': case '\n':
save('\n'); save(L, '\n', l);
inclinenumber(LS); inclinenumber(LS);
continue; continue;
default: default:
save_and_next(LS); save_and_next(L, LS, l);
} }
} endloop: } endloop:
save_and_next(LS); /* skip the second ']' */ save_and_next(L, LS, l); /* skip the second ']' */
LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+2), save(L, '\0', l);
L->Mbuffnext-L->Mbuffbase-4); seminfo->ts = luaS_newlstr(L, L->Mbuffer+2, l-5);
return STRING;
} }
int luaX_lex (LexState *LS) { static void read_string (LexState *LS, int del, SemInfo *seminfo) {
luaL_resetbuffer(); lua_State *L = LS->L;
size_t l = 0;
checkbuffer(L, 10, l);
save_and_next(L, LS, l);
while (LS->current != del) {
checkbuffer(L, 10, l);
switch (LS->current) {
case EOZ: case '\n':
save(L, '\0', l);
luaX_error(LS, "unfinished string", TK_STRING);
break; /* to avoid warnings */
case '\\':
next(LS); /* do not save the '\' */
switch (LS->current) {
case 'a': save(L, '\a', l); next(LS); break;
case 'b': save(L, '\b', l); next(LS); break;
case 'f': save(L, '\f', l); next(LS); break;
case 'n': save(L, '\n', l); next(LS); break;
case 'r': save(L, '\r', l); next(LS); break;
case 't': save(L, '\t', l); next(LS); break;
case 'v': save(L, '\v', l); next(LS); break;
case '\n': save(L, '\n', l); inclinenumber(LS); break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
int c = 0;
int i = 0;
do {
c = 10*c + (LS->current-'0');
next(LS);
} while (++i<3 && isdigit(LS->current));
if (c != (unsigned char)c) {
save(L, '\0', l);
luaX_error(LS, "escape sequence too large", TK_STRING);
}
save(L, c, l);
break;
}
default: /* handles \\, \", \', and \? */
save_and_next(L, LS, l);
}
break;
default:
save_and_next(L, LS, l);
}
}
save_and_next(L, LS, l); /* skip delimiter */
save(L, '\0', l);
seminfo->ts = luaS_newlstr(L, L->Mbuffer+1, l-3);
}
int luaX_lex (LexState *LS, SemInfo *seminfo) {
for (;;) { for (;;) {
switch (LS->current) { switch (LS->current) {
case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */ case ' ': case '\t': case '\r': /* `\r' to avoid problems with DOS */
next(LS); next(LS);
continue; continue;
@@ -280,159 +290,89 @@ int luaX_lex (LexState *LS) {
inclinenumber(LS); inclinenumber(LS);
continue; continue;
case '$':
luaX_error(LS, "unexpected `$' (pragmas are no longer supported)", '$');
break;
case '-': case '-':
save_and_next(LS); next(LS);
if (LS->current != '-') return '-'; if (LS->current != '-') return '-';
do { next(LS); } while (LS->current != '\n' && LS->current != EOZ); do { next(LS); } while (LS->current != '\n' && LS->current != EOZ);
luaL_resetbuffer();
continue; continue;
case '[': case '[':
save_and_next(LS); next(LS);
if (LS->current != '[') return '['; if (LS->current != '[') return '[';
else { else {
save_and_next(LS); /* pass the second '[' */ read_long_string(LS, seminfo);
return read_long_string(LS); return TK_STRING;
} }
case '=': case '=':
save_and_next(LS); next(LS);
if (LS->current != '=') return '='; if (LS->current != '=') return '=';
else { save_and_next(LS); return EQ; } else { next(LS); return TK_EQ; }
case '<': case '<':
save_and_next(LS); next(LS);
if (LS->current != '=') return '<'; if (LS->current != '=') return '<';
else { save_and_next(LS); return LE; } else { next(LS); return TK_LE; }
case '>': case '>':
save_and_next(LS); next(LS);
if (LS->current != '=') return '>'; if (LS->current != '=') return '>';
else { save_and_next(LS); return GE; } else { next(LS); return TK_GE; }
case '~': case '~':
save_and_next(LS); next(LS);
if (LS->current != '=') return '~'; if (LS->current != '=') return '~';
else { save_and_next(LS); return NE; } else { next(LS); return TK_NE; }
case '"': case '"':
case '\'': { case '\'':
int del = LS->current; read_string(LS, LS->current, seminfo);
save_and_next(LS); return TK_STRING;
while (LS->current != del) {
switch (LS->current) {
case EOZ:
case '\n':
luaX_error(LS, "unfinished string");
return EOS; /* to avoid warnings */
case '\\':
next(LS); /* do not save the '\' */
switch (LS->current) {
case 'a': save('\a'); next(LS); break;
case 'b': save('\b'); next(LS); break;
case 'f': save('\f'); next(LS); break;
case 'n': save('\n'); next(LS); break;
case 'r': save('\r'); next(LS); break;
case 't': save('\t'); next(LS); break;
case 'v': save('\v'); next(LS); break;
case '\n': save('\n'); inclinenumber(LS); break;
default : {
if (isdigit(LS->current)) {
int c = 0;
int i = 0;
do {
c = 10*c + (LS->current-'0');
next(LS);
} while (++i<3 && isdigit(LS->current));
if (c != (unsigned char)c)
luaX_error(LS, "escape sequence too large");
save(c);
}
else { /* handles \, ", ', and ? */
save(LS->current);
next(LS);
}
break;
}
}
break;
default:
save_and_next(LS);
}
}
save_and_next(LS); /* skip delimiter */
LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+1),
L->Mbuffnext-L->Mbuffbase-2);
return STRING;
}
case '.': case '.':
save_and_next(LS); next(LS);
if (LS->current == '.') if (LS->current == '.') {
{ next(LS);
save_and_next(LS); if (LS->current == '.') {
if (LS->current == '.') next(LS);
{ return TK_DOTS; /* ... */
save_and_next(LS);
return DOTS; /* ... */
} }
else return CONC; /* .. */ else return TK_CONCAT; /* .. */
} }
else if (!isdigit(LS->current)) return '.'; else if (!isdigit(LS->current)) return '.';
goto fraction; /* LS->current is a digit: goes through to number */ else {
read_number(LS, 1, seminfo);
return TK_NUMBER;
}
case '0': case '1': case '2': case '3': case '4': case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': case '5': case '6': case '7': case '8': case '9':
do { read_number(LS, 0, seminfo);
save_and_next(LS); return TK_NUMBER;
} while (isdigit(LS->current));
if (LS->current == '.') {
save_and_next(LS);
if (LS->current == '.') {
save('.');
luaX_error(LS,
"ambiguous syntax (decimal point x string concatenation)");
}
}
fraction:
while (isdigit(LS->current))
save_and_next(LS);
if (toupper(LS->current) == 'E') {
save_and_next(LS); /* read 'E' */
save_and_next(LS); /* read '+', '-' or first digit */
while (isdigit(LS->current))
save_and_next(LS);
}
save('\0');
LS->seminfo.r = luaO_str2d(L->Mbuffer+L->Mbuffbase);
if (LS->seminfo.r < 0)
luaX_error(LS, "invalid numeric format");
return NUMBER;
case EOZ: case EOZ:
if (LS->iflevel > 0) return TK_EOS;
luaX_error(LS, "input ends inside a $if");
return EOS; case '_': goto tname;
default: default:
if (LS->current != '_' && !isalpha(LS->current)) { if (!isalpha(LS->current)) {
int c = LS->current; int c = LS->current;
if (iscntrl(c)) if (iscntrl(c))
luaX_invalidchar(LS, c); luaX_invalidchar(LS, c);
save_and_next(LS); next(LS);
return c; return c;
} }
else { /* identifier or reserved word */ tname: { /* identifier or reserved word */
TaggedString *ts; TString *ts = luaS_new(LS->L, readname(LS));
do { if (ts->marked >= RESERVEDMARK) /* reserved word? */
save_and_next(LS); return ts->marked-RESERVEDMARK+FIRST_RESERVED;
} while (isalnum(LS->current) || LS->current == '_'); seminfo->ts = ts;
save('\0'); return TK_NAME;
ts = luaS_new(L->Mbuffer+L->Mbuffbase);
if (ts->head.marked >= FIRST_RESERVED)
return ts->head.marked; /* reserved word */
LS->seminfo.ts = ts;
return NAME;
} }
} }
} }

74
llex.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: llex.h,v 1.10 1998/07/24 18:02:38 roberto Exp roberto $ ** $Id: llex.h,v 1.30 2000/06/21 18:13:56 roberto Exp roberto $
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,51 +11,61 @@
#include "lzio.h" #include "lzio.h"
#define FIRST_RESERVED 260 #define FIRST_RESERVED 257
/* maximum length of a reserved word (+1 for terminal 0) */ /* maximum length of a reserved word (+1 for final 0) */
#define TOKEN_LEN 15 #define TOKEN_LEN 15
/*
* WARNING: if you change the order of this enumeration,
* grep "ORDER RESERVED"
*/
enum RESERVED { enum RESERVED {
/* terminal symbols denoted by reserved words */ /* terminal symbols denoted by reserved words */
AND = FIRST_RESERVED, TK_AND = FIRST_RESERVED, TK_BREAK,
DO, ELSE, ELSEIF, END, FUNCTION, IF, LOCAL, NIL, NOT, OR, TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FOR, TK_FUNCTION, TK_IF, TK_LOCAL,
REPEAT, RETURN, THEN, UNTIL, WHILE, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_RETURN, TK_THEN, TK_UNTIL, TK_WHILE,
/* other terminal symbols */ /* other terminal symbols */
NAME, CONC, DOTS, EQ, GE, LE, NE, NUMBER, STRING, EOS}; TK_NAME, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
TK_STRING, TK_EOS
#define MAX_IFS 5
/* "ifstate" keeps the state of each nested $if the lexical is dealing with. */
struct ifState {
int elsepart; /* true if it's in the $else part */
int condition; /* true if $if condition is true */
int skip; /* true if part must be skipped */
}; };
/* number of reserved words */
#define NUM_RESERVED ((int)(TK_WHILE-FIRST_RESERVED+1))
typedef union {
Number r;
TString *ts;
} SemInfo; /* semantics information */
typedef struct Token {
int token;
SemInfo seminfo;
} Token;
typedef struct LexState { typedef struct LexState {
int current; /* look ahead character */ int current; /* current character */
int token; /* look ahead token */ Token t; /* current token */
struct FuncState *fs; /* 'FuncState' is private for the parser */ Token lookahead; /* look ahead token */
union { struct FuncState *fs; /* `FuncState' is private to the parser */
real r; struct lua_State *L;
TaggedString *ts; struct zio *z; /* input stream */
} seminfo; /* semantics information */
struct zio *lex_z; /* input stream */
int linenumber; /* input line counter */ int linenumber; /* input line counter */
int iflevel; /* level of nested $if's (for lexical analysis) */ int lastline; /* line of last token `consumed' */
struct ifState ifstate[MAX_IFS]; TString *source; /* current source name */
} LexState; } LexState;
void luaX_init (void); void luaX_init (lua_State *L);
void luaX_setinput (LexState *LS, ZIO *z); void luaX_setinput (lua_State *L, LexState *LS, ZIO *z, TString *source);
int luaX_lex (LexState *LS); int luaX_lex (LexState *LS, SemInfo *seminfo);
void luaX_syntaxerror (LexState *ls, char *s, char *token); void luaX_checklimit (LexState *ls, int val, int limit, const char *msg);
void luaX_error (LexState *ls, char *s); void luaX_syntaxerror (LexState *ls, const char *s, const char *token);
void luaX_error (LexState *ls, const char *s, int token);
void luaX_token2str (int token, char *s); void luaX_token2str (int token, char *s);

204
llimits.h Normal file
View File

@@ -0,0 +1,204 @@
/*
** $Id: llimits.h,v 1.18 2000/10/09 13:47:32 roberto Exp roberto $
** Limits, basic types, and some other "installation-dependent" definitions
** See Copyright Notice in lua.h
*/
#ifndef llimits_h
#define llimits_h
#include <limits.h>
#include <stddef.h>
/*
** try to find number of bits in an integer
*/
#ifndef BITS_INT
/* avoid overflows in comparison */
#if INT_MAX-20 < 32760
#define BITS_INT 16
#else
#if INT_MAX > 2147483640L
/* machine has at least 32 bits */
#define BITS_INT 32
#else
#error "you must define BITS_INT with number of bits in an integer"
#endif
#endif
#endif
/*
** Define the type `number' of Lua
** GREP LUA_NUMBER to change that
*/
#ifndef LUA_NUM_TYPE
#define LUA_NUM_TYPE double
#endif
typedef LUA_NUM_TYPE Number;
/* function to convert a Number to a string */
#define NUMBER_FMT "%.16g" /* LUA_NUMBER */
#define lua_number2str(s,n) sprintf((s), NUMBER_FMT, (n))
/* function to convert a string to a Number */
#define lua_str2number(s,p) strtod((s), (p))
typedef unsigned long lint32; /* unsigned int with at least 32 bits */
#define MAX_SIZET ((size_t)(~(size_t)0)-2)
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
/*
** conversion of pointer to int (for hashing only)
** (the shift removes bits that are usually 0 because of alignment)
*/
#define IntPoint(p) (((unsigned long)(p)) >> 3)
#define MINPOWER2 4 /* minimum size for "growing" vectors */
#ifndef DEFAULT_STACK_SIZE
#define DEFAULT_STACK_SIZE 1024
#endif
/* type to ensure maximum alignment */
union L_Umaxalign { double d; char *s; long l; };
/*
** type for virtual-machine instructions
** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
** For a very small machine, you may change that to 2 bytes (and adjust
** the following limits accordingly)
*/
typedef unsigned long Instruction;
/*
** size and position of opcode arguments.
** For an instruction with 2 bytes, size is 16, and size_b can be 5
** (accordingly, size_u will be 10, and size_a will be 5)
*/
#define SIZE_INSTRUCTION 32
#define SIZE_B 9
#define SIZE_OP 6
#define SIZE_U (SIZE_INSTRUCTION-SIZE_OP)
#define POS_U SIZE_OP
#define POS_B SIZE_OP
#define SIZE_A (SIZE_INSTRUCTION-(SIZE_OP+SIZE_B))
#define POS_A (SIZE_OP+SIZE_B)
/*
** limits for opcode arguments.
** we use (signed) int to manipulate most arguments,
** so they must fit in BITS_INT-1 bits (-1 for sign)
*/
#if SIZE_U < BITS_INT-1
#define MAXARG_U ((1<<SIZE_U)-1)
#define MAXARG_S (MAXARG_U>>1) /* `S' is signed */
#else
#define MAXARG_U MAX_INT
#define MAXARG_S MAX_INT
#endif
#if SIZE_A < BITS_INT-1
#define MAXARG_A ((1<<SIZE_A)-1)
#else
#define MAXARG_A MAX_INT
#endif
#if SIZE_B < BITS_INT-1
#define MAXARG_B ((1<<SIZE_B)-1)
#else
#define MAXARG_B MAX_INT
#endif
/* maximum stack size in a function */
#ifndef MAXSTACK
#define MAXSTACK 250
#endif
#if MAXSTACK > MAXARG_B
#undef MAXSTACK
#define MAXSTACK MAXARG_B
#endif
/* maximum number of local variables */
#ifndef MAXLOCALS
#define MAXLOCALS 200 /* arbitrary limit (<MAXSTACK) */
#endif
#if MAXLOCALS>=MAXSTACK
#undef MAXLOCALS
#define MAXLOCALS (MAXSTACK-1)
#endif
/* maximum number of upvalues */
#ifndef MAXUPVALUES
#define MAXUPVALUES 32 /* arbitrary limit (<=MAXARG_B) */
#endif
#if MAXUPVALUES>MAXARG_B
#undef MAXUPVALUES
#define MAXUPVALUES MAXARG_B
#endif
/* maximum number of variables in the left side of an assignment */
#ifndef MAXVARSLH
#define MAXVARSLH 100 /* arbitrary limit (<MULT_RET) */
#endif
#if MAXVARSLH>=MULT_RET
#undef MAXVARSLH
#define MAXVARSLH (MULT_RET-1)
#endif
/* maximum number of parameters in a function */
#ifndef MAXPARAMS
#define MAXPARAMS 100 /* arbitrary limit (<MAXLOCALS) */
#endif
#if MAXPARAMS>=MAXLOCALS
#undef MAXPARAMS
#define MAXPARAMS (MAXLOCALS-1)
#endif
/* number of list items to accumulate before a SETLIST instruction */
#define LFIELDS_PER_FLUSH 64
#if LFIELDS_PER_FLUSH>(MAXSTACK/4)
#undef LFIELDS_PER_FLUSH
#define LFIELDS_PER_FLUSH (MAXSTACK/4)
#endif
/* number of record items to accumulate before a SETMAP instruction */
/* (each item counts 2 elements on the stack: an index and a value) */
#define RFIELDS_PER_FLUSH (LFIELDS_PER_FLUSH/2)
/* maximum lookback to find a real constant (for code generation) */
#ifndef LOOKBACKNUMS
#define LOOKBACKNUMS 20 /* arbitrary constant */
#endif
#endif

View File

@@ -1,6 +1,6 @@
/* /*
** $Id: lmathlib.c,v 1.15 1999/01/04 12:41:12 roberto Exp roberto $ ** $Id: lmathlib.c,v 1.31 2000/10/27 16:15:53 roberto Exp roberto $
** Lua standard mathematical library ** Standard mathematical library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -8,13 +8,15 @@
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
#include "lauxlib.h"
#include "lua.h" #include "lua.h"
#include "lauxlib.h"
#include "lualib.h" #include "lualib.h"
#define PI (3.14159265358979323846) #undef PI
#define RADIANS_PER_DEGREE (PI/180.0) #define PI (3.14159265358979323846)
#define RADIANS_PER_DEGREE (PI/180.0)
@@ -31,139 +33,173 @@
#endif #endif
static void math_abs (void) { static int math_abs (lua_State *L) {
lua_pushnumber(fabs(luaL_check_number(1))); lua_pushnumber(L, fabs(luaL_check_number(L, 1)));
return 1;
} }
static void math_sin (void) { static int math_sin (lua_State *L) {
lua_pushnumber(sin(TORAD(luaL_check_number(1)))); lua_pushnumber(L, sin(TORAD(luaL_check_number(L, 1))));
return 1;
} }
static void math_cos (void) { static int math_cos (lua_State *L) {
lua_pushnumber(cos(TORAD(luaL_check_number(1)))); lua_pushnumber(L, cos(TORAD(luaL_check_number(L, 1))));
return 1;
} }
static void math_tan (void) { static int math_tan (lua_State *L) {
lua_pushnumber(tan(TORAD(luaL_check_number(1)))); lua_pushnumber(L, tan(TORAD(luaL_check_number(L, 1))));
return 1;
} }
static void math_asin (void) { static int math_asin (lua_State *L) {
lua_pushnumber(FROMRAD(asin(luaL_check_number(1)))); lua_pushnumber(L, FROMRAD(asin(luaL_check_number(L, 1))));
return 1;
} }
static void math_acos (void) { static int math_acos (lua_State *L) {
lua_pushnumber(FROMRAD(acos(luaL_check_number(1)))); lua_pushnumber(L, FROMRAD(acos(luaL_check_number(L, 1))));
return 1;
} }
static void math_atan (void) { static int math_atan (lua_State *L) {
lua_pushnumber(FROMRAD(atan(luaL_check_number(1)))); lua_pushnumber(L, FROMRAD(atan(luaL_check_number(L, 1))));
return 1;
} }
static void math_atan2 (void) { static int math_atan2 (lua_State *L) {
lua_pushnumber(FROMRAD(atan2(luaL_check_number(1), luaL_check_number(2)))); lua_pushnumber(L, FROMRAD(atan2(luaL_check_number(L, 1), luaL_check_number(L, 2))));
return 1;
} }
static void math_ceil (void) { static int math_ceil (lua_State *L) {
lua_pushnumber(ceil(luaL_check_number(1))); lua_pushnumber(L, ceil(luaL_check_number(L, 1)));
return 1;
} }
static void math_floor (void) { static int math_floor (lua_State *L) {
lua_pushnumber(floor(luaL_check_number(1))); lua_pushnumber(L, floor(luaL_check_number(L, 1)));
return 1;
} }
static void math_mod (void) { static int math_mod (lua_State *L) {
lua_pushnumber(fmod(luaL_check_number(1), luaL_check_number(2))); lua_pushnumber(L, fmod(luaL_check_number(L, 1), luaL_check_number(L, 2)));
return 1;
} }
static void math_sqrt (void) { static int math_sqrt (lua_State *L) {
lua_pushnumber(sqrt(luaL_check_number(1))); lua_pushnumber(L, sqrt(luaL_check_number(L, 1)));
return 1;
} }
static void math_pow (void) { static int math_pow (lua_State *L) {
lua_pushnumber(pow(luaL_check_number(1), luaL_check_number(2))); lua_pushnumber(L, pow(luaL_check_number(L, 1), luaL_check_number(L, 2)));
return 1;
} }
static void math_log (void) { static int math_log (lua_State *L) {
lua_pushnumber(log(luaL_check_number(1))); lua_pushnumber(L, log(luaL_check_number(L, 1)));
return 1;
} }
static void math_log10 (void) { static int math_log10 (lua_State *L) {
lua_pushnumber(log10(luaL_check_number(1))); lua_pushnumber(L, log10(luaL_check_number(L, 1)));
return 1;
} }
static void math_exp (void) { static int math_exp (lua_State *L) {
lua_pushnumber(exp(luaL_check_number(1))); lua_pushnumber(L, exp(luaL_check_number(L, 1)));
return 1;
} }
static void math_deg (void) { static int math_deg (lua_State *L) {
lua_pushnumber(luaL_check_number(1)/RADIANS_PER_DEGREE); lua_pushnumber(L, luaL_check_number(L, 1)/RADIANS_PER_DEGREE);
return 1;
} }
static void math_rad (void) { static int math_rad (lua_State *L) {
lua_pushnumber(luaL_check_number(1)*RADIANS_PER_DEGREE); lua_pushnumber(L, luaL_check_number(L, 1)*RADIANS_PER_DEGREE);
return 1;
} }
static void math_frexp (void) { static int math_frexp (lua_State *L) {
int e; int e;
lua_pushnumber(frexp(luaL_check_number(1), &e)); lua_pushnumber(L, frexp(luaL_check_number(L, 1), &e));
lua_pushnumber(e); lua_pushnumber(L, e);
return 2;
} }
static void math_ldexp (void) { static int math_ldexp (lua_State *L) {
lua_pushnumber(ldexp(luaL_check_number(1), luaL_check_int(2))); lua_pushnumber(L, ldexp(luaL_check_number(L, 1), luaL_check_int(L, 2)));
return 1;
} }
static void math_min (void) { static int math_min (lua_State *L) {
int i = 1; int n = lua_gettop(L); /* number of arguments */
double dmin = luaL_check_number(i); double dmin = luaL_check_number(L, 1);
while (lua_getparam(++i) != LUA_NOOBJECT) { int i;
double d = luaL_check_number(i); for (i=2; i<=n; i++) {
double d = luaL_check_number(L, i);
if (d < dmin) if (d < dmin)
dmin = d; dmin = d;
} }
lua_pushnumber(dmin); lua_pushnumber(L, dmin);
return 1;
} }
static void math_max (void) { static int math_max (lua_State *L) {
int i = 1; int n = lua_gettop(L); /* number of arguments */
double dmax = luaL_check_number(i); double dmax = luaL_check_number(L, 1);
while (lua_getparam(++i) != LUA_NOOBJECT) { int i;
double d = luaL_check_number(i); for (i=2; i<=n; i++) {
double d = luaL_check_number(L, i);
if (d > dmax) if (d > dmax)
dmax = d; dmax = d;
} }
lua_pushnumber(dmax); lua_pushnumber(L, dmax);
return 1;
} }
static void math_random (void) { static int math_random (lua_State *L) {
/* the '%' avoids the (rare) case of r==1, and is needed also because on /* the '%' avoids the (rare) case of r==1, and is needed also because on
some systems (SunOS!) "rand()" may return a value bigger than RAND_MAX */ some systems (SunOS!) "rand()" may return a value larger than RAND_MAX */
double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX; double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX;
int l = luaL_opt_int(1, 0); switch (lua_gettop(L)) { /* check number of arguments */
if (l == 0) case 0: { /* no arguments */
lua_pushnumber(r); lua_pushnumber(L, r); /* Number between 0 and 1 */
else { break;
int u = luaL_opt_int(2, 0);
if (u == 0) {
u = l;
l = 1;
} }
luaL_arg_check(l<=u, 1, "interval is empty"); case 1: { /* only upper limit */
lua_pushnumber((int)(r*(u-l+1))+l); int u = luaL_check_int(L, 1);
luaL_arg_check(L, 1<=u, 1, "interval is empty");
lua_pushnumber(L, (int)(r*u)+1); /* integer between 1 and `u' */
break;
}
case 2: { /* lower and upper limits */
int l = luaL_check_int(L, 1);
int u = luaL_check_int(L, 2);
luaL_arg_check(L, l<=u, 2, "interval is empty");
lua_pushnumber(L, (int)(r*(u-l+1))+l); /* integer between `l' and `u' */
break;
}
default: lua_error(L, "wrong number of arguments");
} }
return 1;
} }
static void math_randomseed (void) { static int math_randomseed (lua_State *L) {
srand(luaL_check_int(1)); srand(luaL_check_int(L, 1));
return 0;
} }
static struct luaL_reg mathlib[] = { static const struct luaL_reg mathlib[] = {
{"abs", math_abs}, {"abs", math_abs},
{"sin", math_sin}, {"sin", math_sin},
{"cos", math_cos}, {"cos", math_cos},
@@ -192,11 +228,11 @@ static struct luaL_reg mathlib[] = {
/* /*
** Open math library ** Open math library
*/ */
void lua_mathlibopen (void) { LUALIB_API void lua_mathlibopen (lua_State *L) {
luaL_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0]))); luaL_openl(L, mathlib);
lua_pushcfunction(math_pow); lua_pushcfunction(L, math_pow);
lua_pushnumber(0); /* to get its tag */ lua_settagmethod(L, LUA_TNUMBER, "pow");
lua_settagmethod(lua_tag(lua_pop()), "pow"); lua_pushnumber(L, PI);
lua_pushnumber(PI); lua_setglobal("PI"); lua_setglobal(L, "PI");
} }

219
lmem.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lmem.c,v 1.13 1999/02/26 15:50:10 roberto Exp roberto $ ** $Id: lmem.c,v 1.38 2000/10/26 12:47:05 roberto Exp roberto $
** Interface to Memory Manager ** Interface to Memory Manager
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -7,14 +7,108 @@
#include <stdlib.h> #include <stdlib.h>
#include "lmem.h"
#include "lstate.h"
#include "lua.h" #include "lua.h"
#include "ldo.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#ifdef LUA_DEBUG
/*
** {======================================================================
** Controlled version for realloc.
** =======================================================================
*/
#include <assert.h>
#include <limits.h>
#include <string.h>
#define realloc(b, s) debug_realloc(b, s)
#define malloc(b) debug_realloc(NULL, b)
#define free(b) debug_realloc(b, 0)
/* ensures maximum alignment for HEADER */
#define HEADER (sizeof(union L_Umaxalign))
#define MARKSIZE 16
#define MARK 0x55 /* 01010101 (a nice pattern) */
#define blocksize(b) ((unsigned long *)((char *)(b) - HEADER))
unsigned long memdebug_numblocks = 0;
unsigned long memdebug_total = 0;
unsigned long memdebug_maxmem = 0;
unsigned long memdebug_memlimit = LONG_MAX;
static void *checkblock (void *block) {
unsigned long *b = blocksize(block);
unsigned long size = *b;
int i;
for (i=0;i<MARKSIZE;i++)
assert(*(((char *)b)+HEADER+size+i) == MARK+i); /* corrupted block? */
memdebug_numblocks--;
memdebug_total -= size;
return b;
}
static void freeblock (void *block) {
if (block) {
size_t size = *blocksize(block);
block = checkblock(block);
memset(block, -1, size+HEADER+MARKSIZE); /* erase block */
(free)(block); /* free original block */
}
}
static void *debug_realloc (void *block, size_t size) {
if (size == 0) {
freeblock(block);
return NULL;
}
else if (memdebug_total+size > memdebug_memlimit)
return NULL; /* to test memory allocation errors */
else {
size_t realsize = HEADER+size+MARKSIZE;
char *newblock = (char *)(malloc)(realsize); /* alloc a new block */
int i;
if (realsize < size) return NULL; /* overflow! */
if (newblock == NULL) return NULL;
if (block) {
size_t oldsize = *blocksize(block);
if (oldsize > size) oldsize = size;
memcpy(newblock+HEADER, block, oldsize);
freeblock(block); /* erase (and check) old copy */
}
memdebug_total += size;
if (memdebug_total > memdebug_maxmem) memdebug_maxmem = memdebug_total;
memdebug_numblocks++;
*(unsigned long *)newblock = size;
for (i=0;i<MARKSIZE;i++)
*(newblock+HEADER+size+i) = (char)(MARK+i);
return newblock+HEADER;
}
}
/* }====================================================================== */
#endif
/* /*
** real ANSI systems do not need these tests; ** Real ISO (ANSI) systems do not need these tests;
** but some systems (Sun OS) are not that ANSI... ** but some systems (Sun OS) are not that ISO...
*/ */
#ifdef OLD_ANSI #ifdef OLD_ANSI
#define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s)) #define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
@@ -22,114 +116,35 @@
#endif #endif
#define MINSIZE 16 /* minimum size for "growing" vectors */ void *luaM_growaux (lua_State *L, void *block, size_t nelems,
int inc, size_t size, const char *errormsg, size_t limit) {
size_t newn = nelems+inc;
if (nelems >= limit-inc) lua_error(L, errormsg);
#ifndef DEBUG if ((newn ^ nelems) <= nelems || /* still the same power-of-2 limit? */
(nelems > 0 && newn < MINPOWER2)) /* or block already is MINPOWER2? */
static unsigned long power2 (unsigned long n) {
unsigned long p = MINSIZE;
while (p<=n) p<<=1;
return p;
}
void *luaM_growaux (void *block, unsigned long nelems, int inc, int size,
char *errormsg, unsigned long limit) {
unsigned long newn = nelems+inc;
if ((newn ^ nelems) <= nelems || /* still the same power of 2 limit? */
(nelems > 0 && newn < MINSIZE)) /* or block already is MINSIZE? */
return block; /* do not need to reallocate */ return block; /* do not need to reallocate */
else { /* it crossed a power of 2 boundary; grow to next power */ else /* it crossed a power-of-2 boundary; grow to next power */
if (newn >= limit) return luaM_realloc(L, block, luaO_power2(newn)*size);
lua_error(errormsg);
newn = power2(newn);
if (newn > limit)
newn = limit;
return luaM_realloc(block, newn*size);
}
} }
/* /*
** generic allocation routine. ** generic allocation routine.
*/ */
void *luaM_realloc (void *block, unsigned long size) { void *luaM_realloc (lua_State *L, void *block, lint32 size) {
size_t s = (size_t)size;
if (s != size)
lua_error("memory allocation error: block too big");
if (size == 0) { if (size == 0) {
free(block); /* block may be NULL, that is OK for free */ free(block); /* block may be NULL; that is OK for free */
return NULL; return NULL;
} }
block = realloc(block, s); else if (size >= MAX_SIZET)
if (block == NULL) lua_error(L, "memory allocation error: block too big");
lua_error(memEM); block = realloc(block, size);
if (block == NULL) {
if (L)
luaD_breakrun(L, LUA_ERRMEM); /* break run without error message */
else return NULL; /* error before creating state! */
}
return block; return block;
} }
#else
/* DEBUG */
#include <string.h>
void *luaM_growaux (void *block, unsigned long nelems, int inc, int size,
char *errormsg, unsigned long limit) {
unsigned long newn = nelems+inc;
if (newn >= limit)
lua_error(errormsg);
return luaM_realloc(block, newn*size);
}
#define HEADER (sizeof(double))
#define MARK 55
unsigned long numblocks = 0;
unsigned long totalmem = 0;
static void *checkblock (void *block) {
unsigned long *b = (unsigned long *)((char *)block - HEADER);
unsigned long size = *b;
LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK,
"corrupted block");
numblocks--;
totalmem -= size;
return b;
}
void *luaM_realloc (void *block, unsigned long size) {
unsigned long realsize = HEADER+size+1;
if (realsize != (size_t)realsize)
lua_error("memory allocation error: block too big");
if (size == 0) {
if (block) {
unsigned long *b = (unsigned long *)((char *)block - HEADER);
memset(block, -1, *b); /* erase block */
block = checkblock(block);
}
free(block);
return NULL;
}
if (block)
block = checkblock(block);
block = (unsigned long *)realloc(block, realsize);
if (block == NULL)
lua_error(memEM);
totalmem += size;
numblocks++;
*(unsigned long *)block = size;
*(((char *)block)+size+HEADER) = MARK;
return (unsigned long *)((char *)block+HEADER);
}
#endif

45
lmem.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lmem.h,v 1.7 1999/02/25 15:16:26 roberto Exp roberto $ ** $Id: lmem.h,v 1.15 2000/08/07 18:39:16 roberto Exp roberto $
** Interface to Memory Manager ** Interface to Memory Manager
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -8,32 +8,33 @@
#define lmem_h #define lmem_h
#include <stdlib.h> #include <stddef.h>
/* memory error messages */ #include "llimits.h"
#define codeEM "code size overflow" #include "lua.h"
#define constantEM "constant table overflow"
#define refEM "reference table overflow"
#define tableEM "table overflow"
#define memEM "not enough memory"
#define arrEM "internal array bigger than `int' limit"
void *luaM_realloc (void *oldblock, unsigned long size); void *luaM_realloc (lua_State *L, void *oldblock, lint32 size);
void *luaM_growaux (void *block, unsigned long nelems, int inc, int size, void *luaM_growaux (lua_State *L, void *block, size_t nelems,
char *errormsg, unsigned long limit); int inc, size_t size, const char *errormsg,
size_t limit);
#define luaM_free(b) luaM_realloc((b), 0) #define luaM_free(L, b) luaM_realloc(L, (b), 0)
#define luaM_malloc(t) luaM_realloc(NULL, (t)) #define luaM_malloc(L, t) luaM_realloc(L, NULL, (t))
#define luaM_new(t) ((t *)luaM_malloc(sizeof(t))) #define luaM_new(L, t) ((t *)luaM_malloc(L, sizeof(t)))
#define luaM_newvector(n,t) ((t *)luaM_malloc((n)*sizeof(t))) #define luaM_newvector(L, n,t) ((t *)luaM_malloc(L, (n)*(lint32)sizeof(t)))
#define luaM_growvector(v,nelems,inc,t,e,l) \
((v)=(t *)luaM_growaux(v,nelems,inc,sizeof(t),e,l)) #define luaM_growvector(L, v,nelems,inc,t,e,l) \
#define luaM_reallocvector(v,n,t) ((v)=(t *)luaM_realloc(v,(n)*sizeof(t))) ((v)=(t *)luaM_growaux(L, v,nelems,inc,sizeof(t),e,l))
#define luaM_reallocvector(L, v,n,t) \
((v)=(t *)luaM_realloc(L, v,(n)*(lint32)sizeof(t)))
#ifdef DEBUG #ifdef LUA_DEBUG
extern unsigned long numblocks; extern unsigned long memdebug_numblocks;
extern unsigned long totalmem; extern unsigned long memdebug_total;
extern unsigned long memdebug_maxmem;
extern unsigned long memdebug_memlimit;
#endif #endif

190
lobject.c
View File

@@ -1,129 +1,125 @@
/* /*
** $Id: lobject.c,v 1.18 1999/02/26 15:48:30 roberto Exp roberto $ ** $Id: lobject.c,v 1.54 2000/10/10 19:53:20 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
*/ */
#include <ctype.h> #include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "lobject.h"
#include "lua.h" #include "lua.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
char *luaO_typenames[] = { /* ORDER LUA_T */
"userdata", "number", "string", "table", "function", "function",
"nil", "function", "mark", "mark", "mark", "line", NULL const TObject luaO_nilobject = {LUA_TNIL, {NULL}};
const char *const luaO_typenames[] = {
"userdata", "nil", "number", "string", "table", "function"
}; };
TObject luaO_nilobject = {LUA_T_NIL, {NULL}};
/*
** returns smaller power of 2 larger than `n' (minimum is MINPOWER2)
/* hash dimensions values */ */
static long dimensions[] = lint32 luaO_power2 (lint32 n) {
{5L, 11L, 23L, 47L, 97L, 197L, 397L, 797L, 1597L, 3203L, 6421L, lint32 p = MINPOWER2;
12853L, 25717L, 51437L, 102811L, 205619L, 411233L, 822433L, while (p<=n) p<<=1;
1644817L, 3289613L, 6579211L, 13158023L, MAX_INT}; return p;
int luaO_redimension (int oldsize)
{
int i;
for (i=0; dimensions[i]<MAX_INT; i++) {
if (dimensions[i] > oldsize)
return dimensions[i];
}
lua_error("tableEM");
return 0; /* to avoid warnings */
} }
int luaO_equalval (TObject *t1, TObject *t2) { int luaO_equalObj (const TObject *t1, const TObject *t2) {
if (ttype(t1) != ttype(t2)) return 0;
switch (ttype(t1)) { switch (ttype(t1)) {
case LUA_T_NIL: return 1; case LUA_TNUMBER:
case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2); return nvalue(t1) == nvalue(t2);
case LUA_T_STRING: case LUA_T_USERDATA: return svalue(t1) == svalue(t2); case LUA_TSTRING: case LUA_TUSERDATA:
case LUA_T_ARRAY: return avalue(t1) == avalue(t2); return tsvalue(t1) == tsvalue(t2);
case LUA_T_PROTO: return tfvalue(t1) == tfvalue(t2); case LUA_TTABLE:
case LUA_T_CPROTO: return fvalue(t1) == fvalue(t2); return hvalue(t1) == hvalue(t2);
case LUA_T_CLOSURE: return t1->value.cl == t2->value.cl; case LUA_TFUNCTION:
return clvalue(t1) == clvalue(t2);
default: default:
LUA_INTERNALERROR("invalid type"); LUA_ASSERT(ttype(t1) == LUA_TNIL, "invalid type");
return 0; /* UNREACHABLE */ return 1; /* LUA_TNIL */
} }
} }
void luaO_insertlist (GCnode *root, GCnode *node) char *luaO_openspace (lua_State *L, size_t n) {
{ if (n > L->Mbuffsize) {
node->next = root->next; luaM_reallocvector(L, L->Mbuffer, n, char);
root->next = node; L->nblocks += (n - L->Mbuffsize)*sizeof(char);
node->marked = 0; L->Mbuffsize = n;
}
#ifdef OLD_ANSI
void luaO_memup (void *dest, void *src, int size) {
while (size--)
((char *)dest)[size]=((char *)src)[size];
}
void luaO_memdown (void *dest, void *src, int size) {
int i;
for (i=0; i<size; i++)
((char *)dest)[i]=((char *)src)[i];
}
#endif
static double expten (unsigned int e) {
double exp = 10.0;
double res = 1.0;
for (; e; e>>=1) {
if (e & 1) res *= exp;
exp *= exp;
} }
return res; return L->Mbuffer;
} }
double luaO_str2d (char *s) { /* LUA_NUMBER */ int luaO_str2d (const char *s, Number *result) { /* LUA_NUMBER */
double a = 0.0; char *endptr;
int point = 0; Number res = lua_str2number(s, &endptr);
while (isdigit((unsigned char)*s)) { if (endptr == s) return 0; /* no conversion */
a = 10.0*a + (*(s++)-'0'); while (isspace((unsigned char)*endptr)) endptr++;
if (*endptr != '\0') return 0; /* invalid trailing characters? */
*result = res;
return 1;
}
/* maximum length of a string format for `luaO_verror' */
#define MAX_VERROR 280
/* this function needs to handle only '%d' and '%.XXs' formats */
void luaO_verror (lua_State *L, const char *fmt, ...) {
va_list argp;
char buff[MAX_VERROR]; /* to hold formatted message */
va_start(argp, fmt);
vsprintf(buff, fmt, argp);
va_end(argp);
lua_error(L, buff);
}
void luaO_chunkid (char *out, const char *source, int bufflen) {
if (*source == '=') {
strncpy(out, source+1, bufflen); /* remove first char */
out[bufflen-1] = '\0'; /* ensures null termination */
} }
if (*s == '.') { else {
s++; if (*source == '@') {
while (isdigit((unsigned char)*s)) { int l;
a = 10.0*a + (*(s++)-'0'); source++; /* skip the `@' */
point++; bufflen -= sizeof("file `...%s'");
l = strlen(source);
if (l>bufflen) {
source += (l-bufflen); /* get last part of file name */
sprintf(out, "file `...%.99s'", source);
}
else
sprintf(out, "file `%.99s'", source);
}
else {
int len = strcspn(source, "\n"); /* stop at first newline */
bufflen -= sizeof("string \"%.*s...\"");
if (len > bufflen) len = bufflen;
if (source[len] != '\0') { /* must truncate? */
strcpy(out, "string \"");
out += strlen(out);
strncpy(out, source, len);
strcpy(out+len, "...\"");
}
else
sprintf(out, "string \"%.99s\"", source);
} }
} }
if (toupper((unsigned char)*s) == 'E') {
int e = 0;
int sig = 1;
s++;
if (*s == '-') {
s++;
sig = -1;
}
else if (*s == '+') s++;
if (!isdigit((unsigned char)*s)) return -1; /* no digit in the exponent? */
do {
e = 10*e + (*(s++)-'0');
} while (isdigit((unsigned char)*s));
point -= sig*e;
}
while (isspace((unsigned char)*s)) s++;
if (*s != '\0') return -1; /* invalid trailing characters? */
if (point > 0)
a /= expten(point);
else if (point < 0)
a *= expten(-point);
return a;
} }

256
lobject.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lobject.h,v 1.27 1999/03/04 21:17:26 roberto Exp roberto $ ** $Id: lobject.h,v 1.81 2000/10/30 16:29:59 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
*/ */
@@ -8,197 +8,197 @@
#define lobject_h #define lobject_h
#include <limits.h> #include "llimits.h"
#include "lua.h" #include "lua.h"
#ifdef DEBUG #ifdef LUA_DEBUG
#include "lauxlib.h" #undef NDEBUG
#define LUA_INTERNALERROR(s) \ #include <assert.h>
luaL_verror("INTERNAL ERROR - %s [%s:%d]",(s),__FILE__,__LINE__) #define LUA_INTERNALERROR(s) assert(((void)s,0))
#define LUA_ASSERT(c,s) { if (!(c)) LUA_INTERNALERROR(s); } #define LUA_ASSERT(c,s) assert(((void)s,(c)))
#else #else
#define LUA_INTERNALERROR(s) /* empty */ #define LUA_INTERNALERROR(s) /* empty */
#define LUA_ASSERT(c,s) /* empty */ #define LUA_ASSERT(c,s) /* empty */
#endif #endif
/* #ifdef LUA_DEBUG
** "real" is the type "number" of Lua /* to avoid warnings, and make sure value is really unused */
** GREP LUA_NUMBER to change that #define UNUSED(x) (x=0, (void)(x))
*/ #else
#ifndef LUA_NUM_TYPE #define UNUSED(x) ((void)(x)) /* to avoid warnings */
#define LUA_NUM_TYPE double
#endif #endif
typedef LUA_NUM_TYPE real; /* mark for closures active in the stack */
#define LUA_TMARK 6
#define Byte lua_Byte /* some systems have Byte as a predefined type */
typedef unsigned char Byte; /* unsigned 8 bits */
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ /* tags for values visible from Lua == first user-created tag */
#define NUM_TAGS 6
typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hashing) */
/* /* check whether `t' is a mark */
** Lua TYPES #define is_T_MARK(t) ((t) == LUA_TMARK)
** WARNING: if you change the order of this enumeration,
** grep "ORDER LUA_T"
*/
typedef enum {
LUA_T_USERDATA = 0, /* tag default for userdata */
LUA_T_NUMBER = -1, /* fixed tag for numbers */
LUA_T_STRING = -2, /* fixed tag for strings */
LUA_T_ARRAY = -3, /* tag default for tables (or arrays) */
LUA_T_PROTO = -4, /* fixed tag for functions */
LUA_T_CPROTO = -5, /* fixed tag for Cfunctions */
LUA_T_NIL = -6, /* last "pre-defined" tag */
LUA_T_CLOSURE = -7,
LUA_T_CLMARK = -8, /* mark for closures */
LUA_T_PMARK = -9, /* mark for Lua prototypes */
LUA_T_CMARK = -10, /* mark for C prototypes */
LUA_T_LINE = -11
} lua_Type;
#define NUM_TAGS 7
typedef union { typedef union {
lua_CFunction f; /* LUA_T_CPROTO, LUA_T_CMARK */ struct TString *ts; /* LUA_TSTRING, LUA_TUSERDATA */
real n; /* LUA_T_NUMBER */ struct Closure *cl; /* LUA_TFUNCTION */
struct TaggedString *ts; /* LUA_T_STRING, LUA_T_USERDATA */ struct Hash *a; /* LUA_TTABLE */
struct TProtoFunc *tf; /* LUA_T_PROTO, LUA_T_PMARK */ struct CallInfo *i; /* LUA_TLMARK */
struct Closure *cl; /* LUA_T_CLOSURE, LUA_T_CLMARK */ Number n; /* LUA_TNUMBER */
struct Hash *a; /* LUA_T_ARRAY */
int i; /* LUA_T_LINE */
} Value; } Value;
typedef struct TObject { /* Macros to access values */
lua_Type ttype; #define ttype(o) ((o)->ttype)
#define nvalue(o) ((o)->value.n)
#define tsvalue(o) ((o)->value.ts)
#define clvalue(o) ((o)->value.cl)
#define hvalue(o) ((o)->value.a)
#define infovalue(o) ((o)->value.i)
#define svalue(o) (tsvalue(o)->str)
typedef struct lua_TObject {
int ttype;
Value value; Value value;
} TObject; } TObject;
/*
** generic header for garbage collector lists
*/
typedef struct GCnode {
struct GCnode *next;
int marked;
} GCnode;
/* /*
** String headers for string table ** String headers for string table
*/ */
typedef struct TaggedString { /*
GCnode head; ** most `malloc' libraries allocate memory in blocks of 8 bytes. TSPACK
unsigned long hash; ** tries to make sizeof(TString) a multiple of this granularity, to reduce
int constindex; /* hint to reuse constants (= -1 if this is a userdata) */ ** waste of space.
*/
#define TSPACK ((int)sizeof(int))
typedef struct TString {
union { union {
struct { struct { /* for strings */
TObject globalval; unsigned long hash;
long len; /* if this is a string, here is its length */ int constindex; /* hint to reuse constants */
} s; } s;
struct { struct { /* for userdata */
int tag; int tag;
void *v; /* if this is a userdata, here is its value */ void *value;
} d; } d;
} u; } u;
char str[1]; /* \0 byte already reserved */ size_t len;
} TaggedString; struct TString *nexthash; /* chain for hash table */
int marked;
char str[TSPACK]; /* variable length string!! must be the last field! */
} TString;
/* /*
** Function Prototypes ** Function Prototypes
*/ */
typedef struct TProtoFunc { typedef struct Proto {
GCnode head; Number *knum; /* Number numbers used by the function */
struct TObject *consts; int nknum; /* size of `knum' */
int nconsts; struct TString **kstr; /* strings used by the function */
Byte *code; /* ends with opcode ENDCODE */ int nkstr; /* size of `kstr' */
struct Proto **kproto; /* functions defined inside the function */
int nkproto; /* size of `kproto' */
Instruction *code;
int ncode; /* size of `code'; when 0 means an incomplete `Proto' */
short numparams;
short is_vararg;
short maxstacksize;
short marked;
struct Proto *next;
/* debug information */
int *lineinfo; /* map from opcodes to source lines */
int nlineinfo; /* size of `lineinfo' */
int nlocvars;
struct LocVar *locvars; /* information about local variables */
int lineDefined; int lineDefined;
TaggedString *source; TString *source;
struct LocVar *locvars; /* ends with line = -1 */ } Proto;
} TProtoFunc;
typedef struct LocVar { typedef struct LocVar {
TaggedString *varname; /* NULL signals end of scope */ TString *varname;
int line; int startpc; /* first point where variable is active */
int endpc; /* first point where variable is dead */
} LocVar; } LocVar;
/* Macros to access structure members */
#define ttype(o) ((o)->ttype)
#define nvalue(o) ((o)->value.n)
#define svalue(o) ((o)->value.ts->str)
#define tsvalue(o) ((o)->value.ts)
#define clvalue(o) ((o)->value.cl)
#define avalue(o) ((o)->value.a)
#define fvalue(o) ((o)->value.f)
#define tfvalue(o) ((o)->value.tf)
#define protovalue(o) ((o)->value.cl->consts)
/* /*
** Closures ** Closures
*/ */
typedef struct Closure { typedef struct Closure {
GCnode head; union {
int nelems; /* not included the first one (always the prototype) */ lua_CFunction c; /* C functions */
TObject consts[1]; /* at least one for prototype */ struct Proto *l; /* Lua functions */
} f;
struct Closure *next;
struct Closure *mark; /* marked closures (point to itself when not marked) */
short isC; /* 0 for Lua functions, 1 for C functions */
short nupvalues;
TObject upvalue[1];
} Closure; } Closure;
#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->isC)
typedef struct node {
TObject ref; typedef struct Node {
TObject key;
TObject val; TObject val;
struct Node *next; /* for chaining */
} Node; } Node;
typedef struct Hash { typedef struct Hash {
GCnode head;
Node *node; Node *node;
int nhash;
int nuse;
int htag; int htag;
int size;
Node *firstfree; /* this position is free; all positions after it are full */
struct Hash *next;
struct Hash *mark; /* marked tables (point to itself when not marked) */
} Hash; } Hash;
extern char *luaO_typenames[]; /* unmarked tables and closures are represented by pointing `mark' to
** themselves
#define luaO_typename(o) luaO_typenames[-ttype(o)] */
#define ismarked(x) ((x)->mark != (x))
extern TObject luaO_nilobject; /*
** informations about a call (for debugging)
*/
typedef struct CallInfo {
struct Closure *func; /* function being called */
const Instruction **pc; /* current pc of called function */
int lastpc; /* last pc traced */
int line; /* current line */
int refi; /* current index in `lineinfo' */
} CallInfo;
#define luaO_equalObj(t1,t2) ((ttype(t1) != ttype(t2)) ? 0 \
: luaO_equalval(t1,t2))
int luaO_equalval (TObject *t1, TObject *t2);
int luaO_redimension (int oldsize);
void luaO_insertlist (GCnode *root, GCnode *node);
double luaO_str2d (char *s);
#ifdef OLD_ANSI extern const TObject luaO_nilobject;
void luaO_memup (void *dest, void *src, int size); extern const char *const luaO_typenames[];
void luaO_memdown (void *dest, void *src, int size);
#else
#include <string.h> #define luaO_typename(o) (luaO_typenames[ttype(o)])
#define luaO_memup(d,s,n) memmove(d,s,n)
#define luaO_memdown(d,s,n) memmove(d,s,n)
#endif lint32 luaO_power2 (lint32 n);
char *luaO_openspace (lua_State *L, size_t n);
int luaO_equalObj (const TObject *t1, const TObject *t2);
int luaO_str2d (const char *s, Number *result);
void luaO_verror (lua_State *L, const char *fmt, ...);
void luaO_chunkid (char *out, const char *source, int len);
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lopcodes.h,v 1.31 1999/03/05 21:16:07 roberto Exp roberto $ ** $Id: lopcodes.h,v 1.67 2000/08/29 14:48:16 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
*/ */
@@ -7,132 +7,162 @@
#ifndef lopcodes_h #ifndef lopcodes_h
#define lopcodes_h #define lopcodes_h
#include "llimits.h"
/*===========================================================================
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits. Moreover,
an instruction can have 0, 1, or 2 arguments. Instructions can
have the following types:
type 0: no arguments
type 1: 1 unsigned argument in the higher bits (called `U')
type 2: 1 signed argument in the higher bits (`S')
type 3: 1st unsigned argument in the higher bits (`A')
2nd unsigned argument in the middle bits (`B')
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding
unsigned argument.
The size of each argument is defined in `llimits.h'. The usual is an
instruction with 32 bits, U arguments with 26 bits (32-6), B arguments
with 9 bits, and A arguments with 17 bits (32-6-9). For small
installations, the instruction size can be 16, so U has 10 bits,
and A and B have 5 bits each.
===========================================================================*/
/* creates a mask with `n' 1 bits at position `p' */
#define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p)
/* creates a mask with `n' 0 bits at position `p' */
#define MASK0(n,p) (~MASK1(n,p))
/* /*
** NOTICE: variants of the same opcode must be consecutive: First, those ** the following macros help to manipulate instructions
** with word parameter, then with byte parameter.
*/ */
#define CREATE_0(o) ((Instruction)(o))
#define GET_OPCODE(i) ((OpCode)((i)&MASK1(SIZE_OP,0)))
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,0)) | (Instruction)(o)))
#define CREATE_U(o,u) ((Instruction)(o) | ((Instruction)(u)<<POS_U))
#define GETARG_U(i) ((int)((i)>>POS_U))
#define SETARG_U(i,u) ((i) = (((i)&MASK0(SIZE_U,POS_U)) | \
((Instruction)(u)<<POS_U)))
#define CREATE_S(o,s) CREATE_U((o),(s)+MAXARG_S)
#define GETARG_S(i) (GETARG_U(i)-MAXARG_S)
#define SETARG_S(i,s) SETARG_U((i),(s)+MAXARG_S)
#define CREATE_AB(o,a,b) ((Instruction)(o) | ((Instruction)(a)<<POS_A) \
| ((Instruction)(b)<<POS_B))
#define GETARG_A(i) ((int)((i)>>POS_A))
#define SETARG_A(i,a) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
((Instruction)(a)<<POS_A)))
#define GETARG_B(i) ((int)(((i)>>POS_B) & MASK1(SIZE_B,0)))
#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
((Instruction)(b)<<POS_B)))
/*
** K = U argument used as index to `kstr'
** J = S argument used as jump offset (relative to pc of next instruction)
** L = unsigned argument used as index of local variable
** N = U argument used as index to `knum'
*/
typedef enum { typedef enum {
/* name parm before after side effect /*----------------------------------------------------------------------
-----------------------------------------------------------------------------*/ name args stack before stack after side effects
ENDCODE,/* - - (return) */ ------------------------------------------------------------------------*/
RETCODE,/* b - (return) */ OP_END,/* - - (return) no results */
OP_RETURN,/* U v_n-v_x(at u) (return) returns v_x-v_n */
CALL,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */ OP_CALL,/* A B v_n-v_1 f(at a) r_b-r_1 f(v1,...,v_n) */
OP_TAILCALL,/* A B v_n-v_1 f(at a) (return) f(v1,...,v_n) */
TAILCALL,/* b c v_c...v_1 f (return) f(v1,...,v_c) */ OP_PUSHNIL,/* U - nil_1-nil_u */
OP_POP,/* U a_u-a_1 - */
PUSHNIL,/* b - nil_0...nil_b */ OP_PUSHINT,/* S - (Number)s */
POP,/* b a_b...a_1 - */ OP_PUSHSTRING,/* K - KSTR[k] */
OP_PUSHNUM,/* N - KNUM[n] */
OP_PUSHNEGNUM,/* N - -KNUM[n] */
PUSHNUMBERW,/* w - (float)w */ OP_PUSHUPVALUE,/* U - Closure[u] */
PUSHNUMBER,/* b - (float)b */
PUSHNUMBERNEGW,/* w - (float)-w */ OP_GETLOCAL,/* L - LOC[l] */
PUSHNUMBERNEG,/* b - (float)-b */ OP_GETGLOBAL,/* K - VAR[KSTR[k]] */
PUSHCONSTANTW,/*w - CNST[w] */ OP_GETTABLE,/* - i t t[i] */
PUSHCONSTANT,/* b - CNST[b] */ OP_GETDOTTED,/* K t t[KSTR[k]] */
OP_GETINDEXED,/* L t t[LOC[l]] */
OP_PUSHSELF,/* K t t t[KSTR[k]] */
PUSHUPVALUE,/* b - Closure[b] */ OP_CREATETABLE,/* U - newarray(size = u) */
PUSHLOCAL,/* b - LOC[b] */ OP_SETLOCAL,/* L x - LOC[l]=x */
OP_SETGLOBAL,/* K x - VAR[KSTR[k]]=x */
OP_SETTABLE,/* A B v a_a-a_1 i t (pops b values) t[i]=v */
GETGLOBALW,/* w - VAR[CNST[w]] */ OP_SETLIST,/* A B v_b-v_1 t t t[i+a*FPF]=v_i */
GETGLOBAL,/* b - VAR[CNST[b]] */ OP_SETMAP,/* U v_u k_u - v_1 k_1 t t t[k_i]=v_i */
GETTABLE,/* - i t t[i] */ OP_ADD,/* - y x x+y */
OP_ADDI,/* S x x+s */
OP_SUB,/* - y x x-y */
OP_MULT,/* - y x x*y */
OP_DIV,/* - y x x/y */
OP_POW,/* - y x x^y */
OP_CONCAT,/* U v_u-v_1 v1..-..v_u */
OP_MINUS,/* - x -x */
OP_NOT,/* - x (x==nil)? 1 : nil */
GETDOTTEDW,/* w t t[CNST[w]] */ OP_JMPNE,/* J y x - (x~=y)? PC+=s */
GETDOTTED,/* b t t[CNST[b]] */ OP_JMPEQ,/* J y x - (x==y)? PC+=s */
OP_JMPLT,/* J y x - (x<y)? PC+=s */
OP_JMPLE,/* J y x - (x<y)? PC+=s */
OP_JMPGT,/* J y x - (x>y)? PC+=s */
OP_JMPGE,/* J y x - (x>=y)? PC+=s */
PUSHSELFW,/* w t t t[CNST[w]] */ OP_JMPT,/* J x - (x~=nil)? PC+=s */
PUSHSELF,/* b t t t[CNST[b]] */ OP_JMPF,/* J x - (x==nil)? PC+=s */
OP_JMPONT,/* J x (x~=nil)? x : - (x~=nil)? PC+=s */
OP_JMPONF,/* J x (x==nil)? x : - (x==nil)? PC+=s */
OP_JMP,/* J - - PC+=s */
CREATEARRAYW,/* w - newarray(size = w) */ OP_PUSHNILJMP,/* - - nil PC++; */
CREATEARRAY,/* b - newarray(size = b) */
SETLOCAL,/* b x - LOC[b]=x */ OP_FORPREP,/* J */
OP_FORLOOP,/* J */
SETGLOBALW,/* w x - VAR[CNST[w]]=x */ OP_LFORPREP,/* J */
SETGLOBAL,/* b x - VAR[CNST[b]]=x */ OP_LFORLOOP,/* J */
SETTABLEPOP,/* - v i t - t[i]=v */ OP_CLOSURE/* A B v_b-v_1 closure(KPROTO[a], v_1-v_b) */
SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
SETLISTW,/* w c v_c...v_1 t t t[i+w*FPF]=v_i */
SETLIST,/* b c v_c...v_1 t t t[i+b*FPF]=v_i */
SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
NEQOP,/* - y x (x~=y)? 1 : nil */
EQOP,/* - y x (x==y)? 1 : nil */
LTOP,/* - y x (x<y)? 1 : nil */
LEOP,/* - y x (x<y)? 1 : nil */
GTOP,/* - y x (x>y)? 1 : nil */
GEOP,/* - y x (x>=y)? 1 : nil */
ADDOP,/* - y x x+y */
SUBOP,/* - y x x-y */
MULTOP,/* - y x x*y */
DIVOP,/* - y x x/y */
POWOP,/* - y x x^y */
CONCOP,/* - y x x..y */
MINUSOP,/* - x -x */
NOTOP,/* - x (x==nil)? 1 : nil */
ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
JMPW,/* w - - PC+=w */
JMP,/* b - - PC+=b */
IFFJMPW,/* w x - (x==nil)? PC+=w */
IFFJMP,/* b x - (x==nil)? PC+=b */
IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
IFTUPJMP,/* b x - (x!=nil)? PC-=b */
IFFUPJMPW,/* w x - (x==nil)? PC-=w */
IFFUPJMP,/* b x - (x==nil)? PC-=b */
CLOSUREW,/* w c v_c...v_1 closure(CNST[w], v_c...v_1) */
CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
SETLINEW,/* w - - LINE=w */
SETLINE,/* b - - LINE=b */
LONGARGW,/* w (add w*(1<<16) to arg of next instruction) */
LONGARG,/* b (add b*(1<<16) to arg of next instruction) */
CHECKSTACK /* b (assert #temporaries == b; only for internal debuging!) */
} OpCode; } OpCode;
#define NUM_OPCODES ((int)OP_CLOSURE+1)
#define RFIELDS_PER_FLUSH 32 /* records (SETMAP) */
#define LFIELDS_PER_FLUSH 64 /* FPF - lists (SETLIST) */
#define ZEROVARARG 64
/* maximum value of an arg of 3 bytes; must fit in an "int" */ #define ISJUMP(o) (OP_JMPNE <= (o) && (o) <= OP_JMP)
#if MAX_INT < (1<<24)
#define MAX_ARG MAX_INT
#else
#define MAX_ARG ((1<<24)-1)
#endif
/* maximum value of a word of 2 bytes; cannot be bigger than MAX_ARG */
#if MAX_ARG < (1<<16)
#define MAX_WORD MAX_ARG /* special code to fit a LUA_MULTRET inside an argB */
#else #define MULT_RET 255 /* (<=MAXARG_B) */
#define MAX_WORD ((1<<16)-1) #if MULT_RET>MAXARG_B
#undef MULT_RET
#define MULT_RET MAXARG_B
#endif #endif
/* maximum value of a byte */
#define MAX_BYTE ((1<<8)-1)
#endif #endif

2237
lparser.c

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lparser.h,v 1.2 1997/12/22 20:57:18 roberto Exp roberto $ ** $Id: lparser.h,v 1.25 2000/09/29 12:42:13 roberto Exp roberto $
** LL(1) Parser and code generator for Lua ** LL(1) Parser and code generator for Lua
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,10 +11,50 @@
#include "lzio.h" #include "lzio.h"
void luaY_codedebugline (int line); /*
TProtoFunc *luaY_parser (ZIO *z); ** Expression descriptor
void luaY_error (char *s); */
void luaY_syntaxerror (char *s, char *token);
typedef enum {
VGLOBAL,
VLOCAL,
VINDEXED,
VEXP
} expkind;
typedef struct expdesc {
expkind k;
union {
int index; /* VGLOBAL: `kstr' index of global name; VLOCAL: stack index */
struct {
int t; /* patch list of `exit when true' */
int f; /* patch list of `exit when false' */
} l;
} u;
} expdesc;
/* state needed to generate code for a given function */
typedef struct FuncState {
Proto *f; /* current function header */
struct FuncState *prev; /* enclosing function */
struct LexState *ls; /* lexical state */
struct lua_State *L; /* copy of the Lua state */
int pc; /* next position to code */
int lasttarget; /* `pc' of last `jump target' */
int jlt; /* list of jumps to `lasttarget' */
short stacklevel; /* number of values on activation register */
short nactloc; /* number of active local variables */
short nupvalues; /* number of upvalues */
int lastline; /* line where last `lineinfo' was generated */
struct Breaklabel *bl; /* chain of breakable blocks */
expdesc upvalues[MAXUPVALUES]; /* upvalues */
int actloc[MAXLOCALS]; /* local-variable stack (indices to locvars) */
} FuncState;
Proto *luaY_parser (lua_State *L, ZIO *z);
#endif #endif

151
lstate.c
View File

@@ -1,13 +1,15 @@
/* /*
** $Id: lstate.c,v 1.9 1999/02/25 15:17:01 roberto Exp roberto $ ** $Id: lstate.c,v 1.47 2000/10/26 12:47:05 roberto Exp roberto $
** Global State ** Global State
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include "lbuiltin.h" #include <stdio.h>
#include "lua.h"
#include "ldo.h" #include "ldo.h"
#include "lfunc.h"
#include "lgc.h" #include "lgc.h"
#include "llex.h" #include "llex.h"
#include "lmem.h" #include "lmem.h"
@@ -17,68 +19,103 @@
#include "ltm.h" #include "ltm.h"
lua_State *lua_state = NULL; #ifdef LUA_DEBUG
static lua_State *lua_state = NULL;
void luaB_opentests (lua_State *L);
#endif
void lua_open (void) /*
{ ** built-in implementation for ERRORMESSAGE. In a "correct" environment
if (lua_state) return; ** ERRORMESSAGE should have an external definition, and so this function
lua_state = luaM_new(lua_State); ** would not be used.
L->Cstack.base = 0; */
L->Cstack.lua2C = 0; static int errormessage (lua_State *L) {
L->Cstack.num = 0; const char *s = lua_tostring(L, 1);
L->errorJmp = NULL; if (s == NULL) s = "(no message)";
fprintf(stderr, "error: %s\n", s);
return 0;
}
/*
** open parts that may cause memory-allocation errors
*/
static void f_luaopen (lua_State *L, void *ud) {
int stacksize = *(int *)ud;
if (stacksize == 0)
stacksize = DEFAULT_STACK_SIZE;
else
stacksize += LUA_MINSTACK;
L->gt = luaH_new(L, 10); /* table of globals */
luaD_init(L, stacksize);
luaS_init(L);
luaX_init(L);
luaT_init(L);
lua_newtable(L);
lua_ref(L, 1); /* create registry */
lua_register(L, LUA_ERRORMESSAGE, errormessage);
#ifdef LUA_DEBUG
luaB_opentests(L);
if (lua_state == NULL) lua_state = L; /* keep first state to be opened */
#endif
LUA_ASSERT(lua_gettop(L) == 0, "wrong API stack");
}
LUA_API lua_State *lua_open (int stacksize) {
lua_State *L = luaM_new(NULL, lua_State);
if (L == NULL) return NULL; /* memory allocation error */
L->stack = NULL;
L->strt.size = L->udt.size = 0;
L->strt.nuse = L->udt.nuse = 0;
L->strt.hash = NULL;
L->udt.hash = NULL;
L->Mbuffer = NULL; L->Mbuffer = NULL;
L->Mbuffbase = 0;
L->Mbuffsize = 0; L->Mbuffsize = 0;
L->Mbuffnext = 0; L->rootproto = NULL;
L->numCblocks = 0; L->rootcl = NULL;
L->debug = 0; L->roottable = NULL;
L->callhook = NULL; L->TMtable = NULL;
L->linehook = NULL; L->last_tag = -1;
L->rootproto.next = NULL;
L->rootproto.marked = 0;
L->rootcl.next = NULL;
L->rootcl.marked = 0;
L->rootglobal.next = NULL;
L->rootglobal.marked = 0;
L->roottable.next = NULL;
L->roottable.marked = 0;
L->IMtable = NULL;
L->refArray = NULL; L->refArray = NULL;
L->refSize = 0; L->refSize = 0;
L->GCthreshold = GARBAGE_BLOCK; L->refFree = NONEXT;
L->nblocks = 0; L->nblocks = sizeof(lua_State);
luaD_init(); L->GCthreshold = MAX_INT; /* to avoid GC during pre-definitions */
luaS_init(); L->callhook = NULL;
luaX_init(); L->linehook = NULL;
luaT_init(); L->allowhooks = 1;
luaB_predefine(); L->errorJmp = NULL;
if (luaD_runprotected(L, f_luaopen, &stacksize) != 0) {
/* memory allocation error: free partial state */
lua_close(L);
return NULL;
}
L->GCthreshold = 2*L->nblocks;
return L;
} }
void lua_close (void) LUA_API void lua_close (lua_State *L) {
{ LUA_ASSERT(L != lua_state || lua_gettop(L) == 0, "garbage in C stack");
TaggedString *alludata = luaS_collectudata(); luaC_collect(L, 1); /* collect all elements */
L->GCthreshold = MAX_INT; /* to avoid GC during GC */ LUA_ASSERT(L->rootproto == NULL, "list should be empty");
luaC_hashcallIM((Hash *)L->roottable.next); /* GC t.methods for tables */ LUA_ASSERT(L->rootcl == NULL, "list should be empty");
luaC_strcallIM(alludata); /* GC tag methods for userdata */ LUA_ASSERT(L->roottable == NULL, "list should be empty");
luaD_gcIM(&luaO_nilobject); /* GC tag method for nil (signal end of GC) */ luaS_freeall(L);
luaH_free((Hash *)L->roottable.next); if (L->stack)
luaF_freeproto((TProtoFunc *)L->rootproto.next); L->nblocks -= (L->stack_last - L->stack + 1)*sizeof(TObject);
luaF_freeclosure((Closure *)L->rootcl.next); luaM_free(L, L->stack);
luaS_free(alludata); L->nblocks -= (L->last_tag+1)*sizeof(struct TM);
luaS_freeall(); luaM_free(L, L->TMtable);
luaM_free(L->stack.stack); L->nblocks -= (L->refSize)*sizeof(struct Ref);
luaM_free(L->IMtable); luaM_free(L, L->refArray);
luaM_free(L->refArray); L->nblocks -= (L->Mbuffsize)*sizeof(char);
luaM_free(L->Mbuffer); luaM_free(L, L->Mbuffer);
luaM_free(L); LUA_ASSERT(L->nblocks == sizeof(lua_State), "wrong count for nblocks");
L = NULL; luaM_free(L, L);
#ifdef DEBUG LUA_ASSERT(L != lua_state || memdebug_numblocks == 0, "memory leak!");
printf("total de blocos: %ld\n", numblocks); LUA_ASSERT(L != lua_state || memdebug_total == 0,"memory leak!");
printf("total de memoria: %ld\n", totalmem);
#endif
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstate.h,v 1.15 1999/02/25 15:17:01 roberto Exp roberto $ ** $Id: lstate.h,v 1.40 2000/09/29 12:42:13 roberto Exp roberto $
** Global State ** Global State
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -7,80 +7,71 @@
#ifndef lstate_h #ifndef lstate_h
#define lstate_h #define lstate_h
#include <setjmp.h>
#include "lobject.h" #include "lobject.h"
#include "lua.h" #include "lua.h"
#include "luadebug.h" #include "luadebug.h"
#define MAX_C_BLOCKS 10
#define GARBAGE_BLOCK 150 typedef TObject *StkId; /* index to stack elements */
typedef int StkId; /* index to stack elements */ /*
** marks for Reference array
*/
#define NONEXT -1 /* to end the free list */
#define HOLD -2
#define COLLECTED -3
#define LOCK -4
struct Stack {
TObject *top;
TObject *stack;
TObject *last;
};
struct C_Lua_Stack { struct Ref {
StkId base; /* when Lua calls C or C calls Lua, points to */ TObject o;
/* the first slot after the last parameter. */ int st; /* can be LOCK, HOLD, COLLECTED, or next (for free list) */
StkId lua2C; /* points to first element of "array" lua2C */
int num; /* size of "array" lua2C */
}; };
typedef struct { struct lua_longjmp; /* defined in ldo.c */
struct TM; /* defined in ltm.h */
typedef struct stringtable {
int size; int size;
int nuse; /* number of elements (including EMPTYs) */ lint32 nuse; /* number of elements */
TaggedString **hash; TString **hash;
} stringtable; } stringtable;
enum Status {LOCK, HOLD, FREE, COLLECTED};
struct ref {
TObject o;
enum Status status;
};
struct lua_State { struct lua_State {
/* thread-specific state */ /* thread-specific state */
struct Stack stack; /* Lua stack */ StkId top; /* first free slot in the stack */
struct C_Lua_Stack Cstack; /* C2lua struct */ StkId stack; /* stack base */
jmp_buf *errorJmp; /* current error recover point */ StkId stack_last; /* last free slot in the stack */
int stacksize;
StkId Cbase; /* base for current C function */
struct lua_longjmp *errorJmp; /* current error recover point */
char *Mbuffer; /* global buffer */ char *Mbuffer; /* global buffer */
int Mbuffbase; /* current first position of Mbuffer */ size_t Mbuffsize; /* size of Mbuffer */
int Mbuffsize; /* size of Mbuffer */
int Mbuffnext; /* next position to fill in Mbuffer */
struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];
int numCblocks; /* number of nested Cblocks */
int debug;
lua_CHFunction callhook;
lua_LHFunction linehook;
/* global state */ /* global state */
GCnode rootproto; /* list of all prototypes */ Proto *rootproto; /* list of all prototypes */
GCnode rootcl; /* list of all closures */ Closure *rootcl; /* list of all closures */
GCnode roottable; /* list of all tables */ Hash *roottable; /* list of all tables */
GCnode rootglobal; /* list of strings with global values */ stringtable strt; /* hash table for strings */
stringtable *string_root; /* array of hash tables for strings and udata */ stringtable udt; /* hash table for udata */
struct IM *IMtable; /* table for tag methods */ Hash *gt; /* table for globals */
int last_tag; /* last used tag in IMtable */ struct TM *TMtable; /* table for tag methods */
struct ref *refArray; /* locked objects */ int last_tag; /* last used tag in TMtable */
struct Ref *refArray; /* locked objects */
int refSize; /* size of refArray */ int refSize; /* size of refArray */
int refFree; /* list of free positions in refArray */
unsigned long GCthreshold; unsigned long GCthreshold;
unsigned long nblocks; /* number of 'blocks' currently allocated */ unsigned long nblocks; /* number of `bytes' currently allocated */
lua_Hook callhook;
lua_Hook linehook;
int allowhooks;
}; };
#define L lua_state
#endif #endif

351
lstring.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstring.c,v 1.18 1999/02/08 16:28:48 roberto Exp roberto $ ** $Id: lstring.c,v 1.44 2000/10/26 12:47:05 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
*/ */
@@ -7,292 +7,149 @@
#include <string.h> #include <string.h>
#include "lua.h"
#include "lmem.h" #include "lmem.h"
#include "lobject.h" #include "lobject.h"
#include "lstate.h" #include "lstate.h"
#include "lstring.h" #include "lstring.h"
#include "lua.h"
#define NUM_HASHSTR 31 /*
#define NUM_HASHUDATA 31 ** type equivalent to TString, but with maximum alignment requirements
#define NUM_HASHS (NUM_HASHSTR+NUM_HASHUDATA) */
union L_UTString {
TString ts;
#define gcsizestring(l) (1+(l/64)) /* "weight" for a string with length 'l' */ union L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
};
static TaggedString EMPTY = {{NULL, 2}, 0L, 0, void luaS_init (lua_State *L) {
{{{LUA_T_NIL, {NULL}}, 0L}}, {0}}; L->strt.hash = luaM_newvector(L, 1, TString *);
L->udt.hash = luaM_newvector(L, 1, TString *);
L->nblocks += 2*sizeof(TString *);
void luaS_init (void) { L->strt.size = L->udt.size = 1;
int i; L->strt.nuse = L->udt.nuse = 0;
L->string_root = luaM_newvector(NUM_HASHS, stringtable); L->strt.hash[0] = L->udt.hash[0] = NULL;
for (i=0; i<NUM_HASHS; i++) {
L->string_root[i].size = 0;
L->string_root[i].nuse = 0;
L->string_root[i].hash = NULL;
}
} }
static unsigned long hash_s (char *s, long l) { void luaS_freeall (lua_State *L) {
unsigned long h = 0; /* seed */ LUA_ASSERT(L->strt.nuse==0, "non-empty string table");
while (l--) L->nblocks -= (L->strt.size + L->udt.size)*sizeof(TString *);
h = h ^ ((h<<5)+(h>>2)+(unsigned char)*(s++)); luaM_free(L, L->strt.hash);
LUA_ASSERT(L->udt.nuse==0, "non-empty udata table");
luaM_free(L, L->udt.hash);
}
static unsigned long hash_s (const char *s, size_t l) {
unsigned long h = l; /* seed */
size_t step = (l>>5)|1; /* if string is too long, don't hash all its chars */
for (; l>=step; l-=step)
h = h ^ ((h<<5)+(h>>2)+(unsigned char)*(s++));
return h; return h;
} }
static int newsize (stringtable *tb) {
int size = tb->size;
int realuse = 0;
int i;
/* count how many entries are really in use */
for (i=0; i<size; i++)
if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)
realuse++;
return luaO_redimension((realuse+1)*2); /* +1 is the new element */
}
void luaS_resize (lua_State *L, stringtable *tb, int newsize) {
static void grow (stringtable *tb) { TString **newhash = luaM_newvector(L, newsize, TString *);
int ns = newsize(tb);
TaggedString **newhash = luaM_newvector(ns, TaggedString *);
int i; int i;
for (i=0; i<ns; i++) for (i=0; i<newsize; i++) newhash[i] = NULL;
newhash[i] = NULL;
/* rehash */ /* rehash */
tb->nuse = 0;
for (i=0; i<tb->size; i++) { for (i=0; i<tb->size; i++) {
if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY) { TString *p = tb->hash[i];
unsigned long h = tb->hash[i]->hash; while (p) { /* for each node in the list */
int h1 = h%ns; TString *next = p->nexthash; /* save next */
while (newhash[h1]) { unsigned long h = (tb == &L->strt) ? p->u.s.hash : IntPoint(p->u.d.value);
h1 += (h&(ns-2)) + 1; /* double hashing */ int h1 = h&(newsize-1); /* new position */
if (h1 >= ns) h1 -= ns; LUA_ASSERT(h%newsize == (h&(newsize-1)),
} "a&(x-1) == a%x, for x power of 2");
newhash[h1] = tb->hash[i]; p->nexthash = newhash[h1]; /* chain it in new position */
tb->nuse++; newhash[h1] = p;
p = next;
} }
} }
luaM_free(tb->hash); luaM_free(L, tb->hash);
tb->size = ns; L->nblocks += (newsize - tb->size)*sizeof(TString *);
tb->size = newsize;
tb->hash = newhash; tb->hash = newhash;
} }
static TaggedString *newone_s (char *str, long l, unsigned long h) { static void newentry (lua_State *L, stringtable *tb, TString *ts, int h) {
TaggedString *ts = (TaggedString *)luaM_malloc(sizeof(TaggedString)+l); ts->nexthash = tb->hash[h]; /* chain new entry */
tb->hash[h] = ts;
tb->nuse++;
if (tb->nuse > (lint32)tb->size && tb->size < MAX_INT/2) /* too crowded? */
luaS_resize(L, tb, tb->size*2);
}
TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
unsigned long h = hash_s(str, l);
int h1 = h & (L->strt.size-1);
TString *ts;
for (ts = L->strt.hash[h1]; ts; ts = ts->nexthash) {
if (ts->len == l && (memcmp(str, ts->str, l) == 0))
return ts;
}
/* not found */
ts = (TString *)luaM_malloc(L, sizestring(l));
ts->marked = 0;
ts->nexthash = NULL;
ts->len = l;
ts->u.s.hash = h;
ts->u.s.constindex = 0;
memcpy(ts->str, str, l); memcpy(ts->str, str, l);
ts->str[l] = 0; /* ending 0 */ ts->str[l] = 0; /* ending 0 */
ts->u.s.globalval.ttype = LUA_T_NIL; /* initialize global value */ L->nblocks += sizestring(l);
ts->u.s.len = l; newentry(L, &L->strt, ts, h1); /* insert it on table */
ts->constindex = 0;
L->nblocks += gcsizestring(l);
ts->head.marked = 0;
ts->head.next = (GCnode *)ts; /* signal it is in no list */
ts->hash = h;
return ts; return ts;
} }
static TaggedString *newone_u (char *buff, int tag, unsigned long h) {
TaggedString *ts = luaM_new(TaggedString); TString *luaS_newudata (lua_State *L, size_t s, void *udata) {
ts->u.d.v = buff; union L_UTString *uts = (union L_UTString *)luaM_malloc(L,
ts->u.d.tag = (tag == LUA_ANYTAG) ? 0 : tag; (lint32)sizeof(union L_UTString)+s);
ts->constindex = -1; /* tag -> this is a userdata */ TString *ts = &uts->ts;
L->nblocks++; ts->marked = 0;
ts->head.marked = 0; ts->nexthash = NULL;
ts->head.next = (GCnode *)ts; /* signal it is in no list */ ts->len = s;
ts->hash = h; ts->u.d.tag = 0;
ts->u.d.value = (udata == NULL) ? uts+1 : udata;
L->nblocks += sizestring(s);
/* insert it on table */
newentry(L, &L->udt, ts, IntPoint(ts->u.d.value) & (L->udt.size-1));
return ts; return ts;
} }
static TaggedString *insert_s (char *str, long l, stringtable *tb) {
TaggedString *ts; TString *luaS_createudata (lua_State *L, void *udata, int tag) {
unsigned long h = hash_s(str, l); int h1 = IntPoint(udata) & (L->udt.size-1);
int size = tb->size; TString *ts;
int j = -1; for (ts = L->udt.hash[h1]; ts; ts = ts->nexthash) {
int h1; if (udata == ts->u.d.value && (tag == ts->u.d.tag || tag == LUA_ANYTAG))
if ((long)tb->nuse*3 >= (long)size*2) {
grow(tb);
size = tb->size;
}
h1 = h%size;
while ((ts = tb->hash[h1]) != NULL) {
if (ts == &EMPTY)
j = h1;
else if (ts->u.s.len == l && (memcmp(str, ts->str, l) == 0))
return ts; return ts;
h1 += (h&(size-2)) + 1; /* double hashing */
if (h1 >= size) h1 -= size;
} }
/* not found */ /* not found */
if (j != -1) /* is there an EMPTY space? */ ts = luaS_newudata(L, 0, udata);
h1 = j; if (tag != LUA_ANYTAG)
else ts->u.d.tag = tag;
tb->nuse++;
ts = tb->hash[h1] = newone_s(str, l, h);
return ts; return ts;
} }
static TaggedString *insert_u (void *buff, int tag, stringtable *tb) { TString *luaS_new (lua_State *L, const char *str) {
TaggedString *ts; return luaS_newlstr(L, str, strlen(str));
unsigned long h = (unsigned long)buff; }
int size = tb->size;
int j = -1;
int h1; TString *luaS_newfixed (lua_State *L, const char *str) {
if ((long)tb->nuse*3 >= (long)size*2) { TString *ts = luaS_new(L, str);
grow(tb); if (ts->marked == 0) ts->marked = FIXMARK; /* avoid GC */
size = tb->size;
}
h1 = h%size;
while ((ts = tb->hash[h1]) != NULL) {
if (ts == &EMPTY)
j = h1;
else if ((tag == ts->u.d.tag || tag == LUA_ANYTAG) && buff == ts->u.d.v)
return ts;
h1 += (h&(size-2)) + 1; /* double hashing */
if (h1 >= size) h1 -= size;
}
/* not found */
if (j != -1) /* is there an EMPTY space? */
h1 = j;
else
tb->nuse++;
ts = tb->hash[h1] = newone_u(buff, tag, h);
return ts; return ts;
} }
TaggedString *luaS_createudata (void *udata, int tag) {
int t = ((unsigned)udata%NUM_HASHUDATA)+NUM_HASHSTR;
return insert_u(udata, tag, &L->string_root[t]);
}
TaggedString *luaS_newlstr (char *str, long l) {
int t = (l==0) ? 0 : ((int)((unsigned char)str[0]*l))%NUM_HASHSTR;
return insert_s(str, l, &L->string_root[t]);
}
TaggedString *luaS_new (char *str) {
return luaS_newlstr(str, strlen(str));
}
TaggedString *luaS_newfixedstring (char *str) {
TaggedString *ts = luaS_new(str);
if (ts->head.marked == 0)
ts->head.marked = 2; /* avoid GC */
return ts;
}
void luaS_free (TaggedString *l) {
while (l) {
TaggedString *next = (TaggedString *)l->head.next;
L->nblocks -= (l->constindex == -1) ? 1 : gcsizestring(l->u.s.len);
luaM_free(l);
l = next;
}
}
/*
** Garbage collection functions.
*/
static void remove_from_list (GCnode *l) {
while (l) {
GCnode *next = l->next;
while (next && !next->marked)
next = l->next = next->next;
l = next;
}
}
TaggedString *luaS_collector (void) {
TaggedString *frees = NULL;
int i;
remove_from_list(&(L->rootglobal));
for (i=0; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == NULL) continue;
if (t->head.marked == 1)
t->head.marked = 0;
else if (!t->head.marked) {
t->head.next = (GCnode *)frees;
frees = t;
tb->hash[j] = &EMPTY;
}
}
}
return frees;
}
TaggedString *luaS_collectudata (void) {
TaggedString *frees = NULL;
int i;
L->rootglobal.next = NULL; /* empty list of globals */
for (i=NUM_HASHSTR; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == NULL || t == &EMPTY)
continue;
LUA_ASSERT(t->constindex == -1, "must be userdata");
t->head.next = (GCnode *)frees;
frees = t;
tb->hash[j] = &EMPTY;
}
}
return frees;
}
void luaS_freeall (void) {
int i;
for (i=0; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == &EMPTY) continue;
luaM_free(t);
}
luaM_free(tb->hash);
}
luaM_free(L->string_root);
}
void luaS_rawsetglobal (TaggedString *ts, TObject *newval) {
ts->u.s.globalval = *newval;
if (ts->head.next == (GCnode *)ts) { /* is not in list? */
ts->head.next = L->rootglobal.next;
L->rootglobal.next = (GCnode *)ts;
}
}
char *luaS_travsymbol (int (*fn)(TObject *)) {
TaggedString *g;
for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next)
if (fn(&g->u.s.globalval))
return g->str;
return NULL;
}
int luaS_globaldefined (char *name) {
TaggedString *ts = luaS_new(name);
return ts->u.s.globalval.ttype != LUA_T_NIL;
}

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lstring.h,v 1.6 1997/12/01 20:31:25 roberto Exp roberto $ ** $Id: lstring.h,v 1.23 2000/10/26 12:47:05 roberto Exp roberto $
** String table (keep all strings handled by Lua) ** String table (keep all strings handled by Lua)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -9,20 +9,29 @@
#include "lobject.h" #include "lobject.h"
#include "lstate.h"
void luaS_init (void); /*
TaggedString *luaS_createudata (void *udata, int tag); ** any TString with mark>=FIXMARK is never collected.
TaggedString *luaS_collector (void); ** Marks>=RESERVEDMARK are used to identify reserved words.
void luaS_free (TaggedString *l); */
TaggedString *luaS_newlstr (char *str, long l); #define FIXMARK 2
TaggedString *luaS_new (char *str); #define RESERVEDMARK 3
TaggedString *luaS_newfixedstring (char *str);
void luaS_rawsetglobal (TaggedString *ts, TObject *newval);
char *luaS_travsymbol (int (*fn)(TObject *)); #define sizestring(l) ((long)sizeof(TString) + \
int luaS_globaldefined (char *name); ((long)(l+1)-TSPACK)*(long)sizeof(char))
TaggedString *luaS_collectudata (void);
void luaS_freeall (void);
void luaS_init (lua_State *L);
void luaS_resize (lua_State *L, stringtable *tb, int newsize);
TString *luaS_newudata (lua_State *L, size_t s, void *udata);
TString *luaS_createudata (lua_State *L, void *udata, int tag);
void luaS_freeall (lua_State *L);
TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
TString *luaS_new (lua_State *L, const char *str);
TString *luaS_newfixed (lua_State *L, const char *str);
#endif #endif

654
lstrlib.c
View File

@@ -1,112 +1,111 @@
/* /*
** $Id: lstrlib.c,v 1.27 1999/02/25 19:13:56 roberto Exp roberto $ ** $Id: lstrlib.c,v 1.55 2000/10/20 16:39:03 roberto Exp roberto $
** Standard library for strings and pattern-matching ** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include <ctype.h> #include <ctype.h>
#include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "lauxlib.h"
#include "lua.h" #include "lua.h"
#include "lauxlib.h"
#include "lualib.h" #include "lualib.h"
static void addnchar (char *s, int n) static int str_len (lua_State *L) {
{ size_t l;
char *b = luaL_openspace(n); luaL_check_lstr(L, 1, &l);
memcpy(b, s, n); lua_pushnumber(L, l);
luaL_addsize(n); return 1;
} }
static void str_len (void) static long posrelat (long pos, size_t len) {
{
long l;
luaL_check_lstr(1, &l);
lua_pushnumber(l);
}
static void closeandpush (void) {
lua_pushlstring(luaL_buffer(), luaL_getsize());
}
static long posrelat (long pos, long len) {
/* relative string position: negative means back from end */ /* relative string position: negative means back from end */
return (pos>=0) ? pos : len+pos+1; return (pos>=0) ? pos : (long)len+pos+1;
} }
static void str_sub (void) { static int str_sub (lua_State *L) {
long l; size_t l;
char *s = luaL_check_lstr(1, &l); const char *s = luaL_check_lstr(L, 1, &l);
long start = posrelat(luaL_check_long(2), l); long start = posrelat(luaL_check_long(L, 2), l);
long end = posrelat(luaL_opt_long(3, -1), l); long end = posrelat(luaL_opt_long(L, 3, -1), l);
if (start < 1) start = 1; if (start < 1) start = 1;
if (end > l) end = l; if (end > (long)l) end = l;
if (start <= end) if (start <= end)
lua_pushlstring(s+start-1, end-start+1); lua_pushlstring(L, s+start-1, end-start+1);
else lua_pushstring(""); else lua_pushstring(L, "");
return 1;
} }
static void str_lower (void) { static int str_lower (lua_State *L) {
long l; size_t l;
int i; size_t i;
char *s = luaL_check_lstr(1, &l); luaL_Buffer b;
luaL_resetbuffer(); const char *s = luaL_check_lstr(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++) for (i=0; i<l; i++)
luaL_addchar(tolower((unsigned char)(s[i]))); luaL_putchar(&b, tolower((unsigned char)(s[i])));
closeandpush(); luaL_pushresult(&b);
return 1;
} }
static void str_upper (void) { static int str_upper (lua_State *L) {
long l; size_t l;
int i; size_t i;
char *s = luaL_check_lstr(1, &l); luaL_Buffer b;
luaL_resetbuffer(); const char *s = luaL_check_lstr(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++) for (i=0; i<l; i++)
luaL_addchar(toupper((unsigned char)(s[i]))); luaL_putchar(&b, toupper((unsigned char)(s[i])));
closeandpush(); luaL_pushresult(&b);
return 1;
} }
static void str_rep (void) static int str_rep (lua_State *L) {
{ size_t l;
long l; luaL_Buffer b;
char *s = luaL_check_lstr(1, &l); const char *s = luaL_check_lstr(L, 1, &l);
int n = luaL_check_int(2); int n = luaL_check_int(L, 2);
luaL_resetbuffer(); luaL_buffinit(L, &b);
while (n-- > 0) while (n-- > 0)
addnchar(s, l); luaL_addlstring(&b, s, l);
closeandpush(); luaL_pushresult(&b);
return 1;
} }
static void str_byte (void) { static int str_byte (lua_State *L) {
long l; size_t l;
char *s = luaL_check_lstr(1, &l); const char *s = luaL_check_lstr(L, 1, &l);
long pos = posrelat(luaL_opt_long(2, 1), l); long pos = posrelat(luaL_opt_long(L, 2, 1), l);
luaL_arg_check(0<pos && pos<=l, 2, "out of range"); luaL_arg_check(L, 0<pos && (size_t)pos<=l, 2, "out of range");
lua_pushnumber((unsigned char)s[pos-1]); lua_pushnumber(L, (unsigned char)s[pos-1]);
return 1;
} }
static void str_char (void) { static int str_char (lua_State *L) {
int i = 0; int n = lua_gettop(L); /* number of arguments */
luaL_resetbuffer(); int i;
while (lua_getparam(++i) != LUA_NOOBJECT) { luaL_Buffer b;
double c = luaL_check_number(i); luaL_buffinit(L, &b);
luaL_arg_check((unsigned char)c == c, i, "invalid value"); for (i=1; i<=n; i++) {
luaL_addchar((unsigned char)c); int c = luaL_check_int(L, i);
luaL_arg_check(L, (unsigned char)c == c, i, "invalid value");
luaL_putchar(&b, (unsigned char)c);
} }
closeandpush(); luaL_pushresult(&b);
return 1;
} }
@@ -117,55 +116,61 @@ static void str_char (void) {
** ======================================================= ** =======================================================
*/ */
#define MAX_CAPT 9 #ifndef MAX_CAPTURES
#define MAX_CAPTURES 32 /* arbitrary limit */
#endif
struct Capture { struct Capture {
char *src_end; /* end ('\0') of source string */ const char *src_end; /* end ('\0') of source string */
int level; /* total number of captures (finished or unfinished) */ int level; /* total number of captures (finished or unfinished) */
struct { struct {
char *init; const char *init;
int len; /* -1 signals unfinished capture */ long len; /* -1 signals unfinished capture */
} capture[MAX_CAPT]; } capture[MAX_CAPTURES];
}; };
#define ESC '%' #define ESC '%'
#define SPECIALS "^$*?.([%-" #define SPECIALS "^$*+?.([%-"
static void push_captures (struct Capture *cap) { static int check_capture (lua_State *L, int l, struct Capture *cap) {
int i;
for (i=0; i<cap->level; i++) {
int l = cap->capture[i].len;
if (l == -1) lua_error("unfinished capture");
lua_pushlstring(cap->capture[i].init, l);
}
}
static int check_cap (int l, struct Capture *cap) {
l -= '1'; l -= '1';
if (!(0 <= l && l < cap->level && cap->capture[l].len != -1)) if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
lua_error("invalid capture index"); lua_error(L, "invalid capture index");
return l; return l;
} }
static int capture_to_close (struct Capture *cap) { static int capture_to_close (lua_State *L, struct Capture *cap) {
int level = cap->level; int level = cap->level;
for (level--; level>=0; level--) for (level--; level>=0; level--)
if (cap->capture[level].len == -1) return level; if (cap->capture[level].len == -1) return level;
lua_error("invalid pattern capture"); lua_error(L, "invalid pattern capture");
return 0; /* to avoid warnings */ return 0; /* to avoid warnings */
} }
static char *bracket_end (char *p) { const char *luaI_classend (lua_State *L, const char *p) {
return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']'); switch (*p++) {
case ESC:
if (*p == '\0') lua_error(L, "malformed pattern (ends with `%')");
return p+1;
case '[':
if (*p == '^') p++;
do { /* look for a ']' */
if (*p == '\0') lua_error(L, "malformed pattern (missing `]')");
if (*(p++) == ESC && *p != '\0') p++; /* skip escapes (e.g. '%]') */
} while (*p != ']');
return p+1;
default:
return p;
}
} }
static int matchclass (int c, int cl) { static int match_class (int c, int cl) {
int res; int res;
switch (tolower(cl)) { switch (tolower(cl)) {
case 'a' : res = isalpha(c); break; case 'a' : res = isalpha(c); break;
@@ -184,48 +189,57 @@ static int matchclass (int c, int cl) {
} }
int luaI_singlematch (int c, char *p, char **ep) {
static int matchbracketclass (int c, const char *p, const char *endclass) {
int sig = 1;
if (*(p+1) == '^') {
sig = 0;
p++; /* skip the '^' */
}
while (++p < endclass) {
if (*p == ESC) {
p++;
if (match_class(c, (unsigned char)*p))
return sig;
}
else if ((*(p+1) == '-') && (p+2 < endclass)) {
p+=2;
if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
return sig;
}
else if ((int)(unsigned char)*p == c) return sig;
}
return !sig;
}
int luaI_singlematch (int c, const char *p, const char *ep) {
switch (*p) { switch (*p) {
case '.': /* matches any char */ case '.': /* matches any char */
*ep = p+1;
return 1; return 1;
case '\0': /* end of pattern; matches nothing */
*ep = p;
return 0;
case ESC: case ESC:
if (*(++p) == '\0') return match_class(c, (unsigned char)*(p+1));
luaL_verror("incorrect pattern (ends with `%c')", ESC); case '[':
*ep = p+1; return matchbracketclass(c, p, ep-1);
return matchclass(c, (unsigned char)*p);
case '[': {
char *end = bracket_end(p+1);
int sig = *(p+1) == '^' ? (p++, 0) : 1;
if (end == NULL) lua_error("incorrect pattern (missing `]')");
*ep = end+1;
while (++p < end) {
if (*p == ESC) {
if (((p+1) < end) && matchclass(c, (unsigned char)*++p))
return sig;
}
else if ((*(p+1) == '-') && (p+2 < end)) {
p+=2;
if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
return sig;
}
else if ((unsigned char)*p == c) return sig;
}
return !sig;
}
default: default:
*ep = p+1;
return ((unsigned char)*p == c); return ((unsigned char)*p == c);
} }
} }
static char *matchbalance (char *s, int b, int e, struct Capture *cap) { static const char *match (lua_State *L, const char *s, const char *p,
if (*s != b) return NULL; struct Capture *cap);
static const char *matchbalance (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
if (*p == 0 || *(p+1) == 0)
lua_error(L, "unbalanced pattern");
if (*s != *p) return NULL;
else { else {
int b = *p;
int e = *(p+1);
int cont = 1; int cont = 1;
while (++s < cap->src_end) { while (++s < cap->src_end) {
if (*s == e) { if (*s == e) {
@@ -238,241 +252,299 @@ static char *matchbalance (char *s, int b, int e, struct Capture *cap) {
} }
static char *matchitem (char *s, char *p, struct Capture *cap, char **ep) { static const char *max_expand (lua_State *L, const char *s, const char *p,
if (*p == ESC) { const char *ep, struct Capture *cap) {
p++; long i = 0; /* counts maximum expand for item */
if (isdigit((unsigned char)*p)) { /* capture */ while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
int l = check_cap(*p, cap); i++;
int len = cap->capture[l].len; /* keeps trying to match with the maximum repetitions */
*ep = p+1; while (i>=0) {
if (cap->src_end-s >= len && memcmp(cap->capture[l].init, s, len) == 0) const char *res = match(L, (s+i), ep+1, cap);
return s+len; if (res) return res;
else return NULL; i--; /* else didn't match; reduce 1 repetition to try again */
}
else if (*p == 'b') { /* balanced string */
p++;
if (*p == 0 || *(p+1) == 0)
lua_error("unbalanced pattern");
*ep = p+2;
return matchbalance(s, *p, *(p+1), cap);
}
else p--; /* and go through */
} }
/* "luaI_singlematch" sets "ep" (so must be called even at the end of "s" */ return NULL;
return (luaI_singlematch((unsigned char)*s, p, ep) && s<cap->src_end) ?
s+1 : NULL;
} }
static char *match (char *s, char *p, struct Capture *cap) { static const char *min_expand (lua_State *L, const char *s, const char *p,
const char *ep, struct Capture *cap) {
for (;;) {
const char *res = match(L, s, ep+1, cap);
if (res != NULL)
return res;
else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
s++; /* try with one more repetition */
else return NULL;
}
}
static const char *start_capture (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
const char *res;
int level = cap->level;
if (level >= MAX_CAPTURES) lua_error(L, "too many captures");
cap->capture[level].init = s;
cap->capture[level].len = -1;
cap->level = level+1;
if ((res=match(L, s, p+1, cap)) == NULL) /* match failed? */
cap->level--; /* undo capture */
return res;
}
static const char *end_capture (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
int l = capture_to_close(L, cap);
const char *res;
cap->capture[l].len = s - cap->capture[l].init; /* close capture */
if ((res = match(L, s, p+1, cap)) == NULL) /* match failed? */
cap->capture[l].len = -1; /* undo capture */
return res;
}
static const char *match_capture (lua_State *L, const char *s, int level,
struct Capture *cap) {
int l = check_capture(L, level, cap);
size_t len = cap->capture[l].len;
if ((size_t)(cap->src_end-s) >= len &&
memcmp(cap->capture[l].init, s, len) == 0)
return s+len;
else return NULL;
}
static const char *match (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
init: /* using goto's to optimize tail recursion */ init: /* using goto's to optimize tail recursion */
switch (*p) { switch (*p) {
case '(': { /* start capture */ case '(': /* start capture */
char *res; return start_capture(L, s, p, cap);
if (cap->level >= MAX_CAPT) lua_error("too many captures"); case ')': /* end capture */
cap->capture[cap->level].init = s; return end_capture(L, s, p, cap);
cap->capture[cap->level].len = -1; case ESC: /* may be %[0-9] or %b */
cap->level++; if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
if ((res=match(s, p+1, cap)) == NULL) /* match failed? */ s = match_capture(L, s, *(p+1), cap);
cap->level--; /* undo capture */ if (s == NULL) return NULL;
return res; p+=2; goto init; /* else return match(L, s, p+2, cap) */
} }
case ')': { /* end capture */ else if (*(p+1) == 'b') { /* balanced string? */
int l = capture_to_close(cap); s = matchbalance(L, s, p+2, cap);
char *res; if (s == NULL) return NULL;
cap->capture[l].len = s - cap->capture[l].init; /* close capture */ p+=4; goto init; /* else return match(L, s, p+4, cap); */
if ((res = match(s, p+1, cap)) == NULL) /* match failed? */ }
cap->capture[l].len = -1; /* undo capture */ else goto dflt; /* case default */
return res; case '\0': /* end of pattern */
} return s; /* match succeeded */
case '\0': case '$': /* (possibly) end of pattern */ case '$':
if (*p == 0 || (*(p+1) == 0 && s == cap->src_end)) if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
return s; return (s == cap->src_end) ? s : NULL; /* check end of string */
/* else go through */ else goto dflt;
default: { /* it is a pattern item */ default: dflt: { /* it is a pattern item */
char *ep; /* will point to what is next */ const char *ep = luaI_classend(L, p); /* points to what is next */
char *s1 = matchitem(s, p, cap, &ep); int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
switch (*ep) { switch (*ep) {
case '*': { /* repetition */
char *res;
if (s1 && s1>s && ((res=match(s1, p, cap)) != NULL))
return res;
p=ep+1; goto init; /* else return match(s, ep+1, cap); */
}
case '?': { /* optional */ case '?': { /* optional */
char *res; const char *res;
if (s1 && ((res=match(s1, ep+1, cap)) != NULL)) if (m && ((res=match(L, s+1, ep+1, cap)) != NULL))
return res; return res;
p=ep+1; goto init; /* else return match(s, ep+1, cap); */ p=ep+1; goto init; /* else return match(L, s, ep+1, cap); */
}
case '-': { /* repetition */
char *res;
if ((res = match(s, ep+1, cap)) != NULL)
return res;
else if (s1 && s1>s) {
s = s1;
goto init; /* return match(s1, p, cap); */
}
else
return NULL;
} }
case '*': /* 0 or more repetitions */
return max_expand(L, s, p, ep, cap);
case '+': /* 1 or more repetitions */
return (m ? max_expand(L, s+1, p, ep, cap) : NULL);
case '-': /* 0 or more repetitions (minimum) */
return min_expand(L, s, p, ep, cap);
default: default:
if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */ if (!m) return NULL;
else return NULL; s++; p=ep; goto init; /* else return match(L, s+1, ep, cap); */
} }
} }
} }
} }
static void str_find (void) {
long l; static const char *lmemfind (const char *s1, size_t l1,
char *s = luaL_check_lstr(1, &l); const char *s2, size_t l2) {
char *p = luaL_check_string(2); if (l2 == 0) return s1; /* empty strings are everywhere */
long init = posrelat(luaL_opt_long(3, 1), l) - 1; else if (l2 > l1) return NULL; /* avoids a negative `l1' */
else {
const char *init; /* to search for a `*s2' inside `s1' */
l2--; /* 1st char will be checked by `memchr' */
l1 = l1-l2; /* `s2' cannot be found after that */
while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct `l1' and `s1' to try again */
l1 -= init-s1;
s1 = init;
}
}
return NULL; /* not found */
}
}
static int push_captures (lua_State *L, struct Capture *cap) {
int i;
luaL_checkstack(L, cap->level, "too many captures");
for (i=0; i<cap->level; i++) {
int l = cap->capture[i].len;
if (l == -1) lua_error(L, "unfinished capture");
lua_pushlstring(L, cap->capture[i].init, l);
}
return cap->level; /* number of strings pushed */
}
static int str_find (lua_State *L) {
size_t l1, l2;
const char *s = luaL_check_lstr(L, 1, &l1);
const char *p = luaL_check_lstr(L, 2, &l2);
long init = posrelat(luaL_opt_long(L, 3, 1), l1) - 1;
struct Capture cap; struct Capture cap;
luaL_arg_check(0 <= init && init <= l, 3, "out of range"); luaL_arg_check(L, 0 <= init && (size_t)init <= l1, 3, "out of range");
if (lua_getparam(4) != LUA_NOOBJECT || if (lua_gettop(L) > 3 || /* extra argument? */
strpbrk(p, SPECIALS) == NULL) { /* no special characters? */ strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
char *s2 = strstr(s+init, p); const char *s2 = lmemfind(s+init, l1-init, p, l2);
if (s2) { if (s2) {
lua_pushnumber(s2-s+1); lua_pushnumber(L, s2-s+1);
lua_pushnumber(s2-s+strlen(p)); lua_pushnumber(L, s2-s+l2);
return; return 2;
} }
} }
else { else {
int anchor = (*p == '^') ? (p++, 1) : 0; int anchor = (*p == '^') ? (p++, 1) : 0;
char *s1=s+init; const char *s1=s+init;
cap.src_end = s+l; cap.src_end = s+l1;
do { do {
char *res; const char *res;
cap.level = 0; cap.level = 0;
if ((res=match(s1, p, &cap)) != NULL) { if ((res=match(L, s1, p, &cap)) != NULL) {
lua_pushnumber(s1-s+1); /* start */ lua_pushnumber(L, s1-s+1); /* start */
lua_pushnumber(res-s); /* end */ lua_pushnumber(L, res-s); /* end */
push_captures(&cap); return push_captures(L, &cap) + 2;
return;
} }
} while (s1++<cap.src_end && !anchor); } while (s1++<cap.src_end && !anchor);
} }
lua_pushnil(); /* if arrives here, it didn't find */ lua_pushnil(L); /* not found */
return 1;
} }
static void add_s (lua_Object newp, struct Capture *cap) { static void add_s (lua_State *L, luaL_Buffer *b, struct Capture *cap) {
if (lua_isstring(newp)) { if (lua_isstring(L, 3)) {
char *news = lua_getstring(newp); const char *news = lua_tostring(L, 3);
int l = lua_strlen(newp); size_t l = lua_strlen(L, 3);
int i; size_t i;
for (i=0; i<l; i++) { for (i=0; i<l; i++) {
if (news[i] != ESC) if (news[i] != ESC)
luaL_addchar(news[i]); luaL_putchar(b, news[i]);
else { else {
i++; /* skip ESC */ i++; /* skip ESC */
if (!isdigit((unsigned char)news[i])) if (!isdigit((unsigned char)news[i]))
luaL_addchar(news[i]); luaL_putchar(b, news[i]);
else { else {
int level = check_cap(news[i], cap); int level = check_capture(L, news[i], cap);
addnchar(cap->capture[level].init, cap->capture[level].len); luaL_addlstring(b, cap->capture[level].init, cap->capture[level].len);
} }
} }
} }
} }
else { /* is a function */ else { /* is a function */
lua_Object res; int n;
int status; lua_pushvalue(L, 3);
int oldbuff; n = push_captures(L, cap);
lua_beginblock(); lua_rawcall(L, n, 1);
push_captures(cap); if (lua_isstring(L, -1))
/* function may use buffer, so save it and create a new one */ luaL_addvalue(b); /* add return to accumulated result */
oldbuff = luaL_newbuffer(0); else
status = lua_callfunction(newp); lua_pop(L, 1); /* function result is not a string: pop it */
/* restore old buffer */
luaL_oldbuffer(oldbuff);
if (status != 0) {
lua_endblock();
lua_error(NULL);
}
res = lua_getresult(1);
if (lua_isstring(res))
addnchar(lua_getstring(res), lua_strlen(res));
lua_endblock();
} }
} }
static void str_gsub (void) { static int str_gsub (lua_State *L) {
long srcl; size_t srcl;
char *src = luaL_check_lstr(1, &srcl); const char *src = luaL_check_lstr(L, 1, &srcl);
char *p = luaL_check_string(2); const char *p = luaL_check_string(L, 2);
lua_Object newp = lua_getparam(3); int max_s = luaL_opt_int(L, 4, srcl+1);
int max_s = luaL_opt_int(4, srcl+1);
int anchor = (*p == '^') ? (p++, 1) : 0; int anchor = (*p == '^') ? (p++, 1) : 0;
int n = 0; int n = 0;
struct Capture cap; struct Capture cap;
luaL_arg_check(lua_isstring(newp) || lua_isfunction(newp), 3, luaL_Buffer b;
"string or function expected"); luaL_arg_check(L,
luaL_resetbuffer(); lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
3, "string or function expected");
luaL_buffinit(L, &b);
cap.src_end = src+srcl; cap.src_end = src+srcl;
while (n < max_s) { while (n < max_s) {
char *e; const char *e;
cap.level = 0; cap.level = 0;
e = match(src, p, &cap); e = match(L, src, p, &cap);
if (e) { if (e) {
n++; n++;
add_s(newp, &cap); add_s(L, &b, &cap);
} }
if (e && e>src) /* non empty match? */ if (e && e>src) /* non empty match? */
src = e; /* skip it */ src = e; /* skip it */
else if (src < cap.src_end) else if (src < cap.src_end)
luaL_addchar(*src++); luaL_putchar(&b, *src++);
else break; else break;
if (anchor) break; if (anchor) break;
} }
addnchar(src, cap.src_end-src); luaL_addlstring(&b, src, cap.src_end-src);
closeandpush(); luaL_pushresult(&b);
lua_pushnumber(n); /* number of substitutions */ lua_pushnumber(L, n); /* number of substitutions */
return 2;
} }
/* }====================================================== */ /* }====================================================== */
static void luaI_addquoted (int arg) { static void luaI_addquoted (lua_State *L, luaL_Buffer *b, int arg) {
long l; size_t l;
char *s = luaL_check_lstr(arg, &l); const char *s = luaL_check_lstr(L, arg, &l);
luaL_addchar('"'); luaL_putchar(b, '"');
while (l--) { while (l--) {
switch (*s) { switch (*s) {
case '"': case '\\': case '\n': case '"': case '\\': case '\n':
luaL_addchar('\\'); luaL_putchar(b, '\\');
luaL_addchar(*s); luaL_putchar(b, *s);
break; break;
case '\0': addnchar("\\000", 4); break; case '\0': luaL_addlstring(b, "\\000", 4); break;
default: luaL_addchar(*s); default: luaL_putchar(b, *s);
} }
s++; s++;
} }
luaL_addchar('"'); luaL_putchar(b, '"');
} }
/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
#define MAX_ITEM 512
/* maximum size of each format specification (such as '%-099.99d') */ /* maximum size of each format specification (such as '%-099.99d') */
#define MAX_FORMAT 20 #define MAX_FORMAT 20
static void str_format (void) { static int str_format (lua_State *L) {
int arg = 1; int arg = 1;
char *strfrmt = luaL_check_string(arg); const char *strfrmt = luaL_check_string(L, arg);
luaL_resetbuffer(); luaL_Buffer b;
luaL_buffinit(L, &b);
while (*strfrmt) { while (*strfrmt) {
if (*strfrmt != '%') if (*strfrmt != '%')
luaL_addchar(*strfrmt++); luaL_putchar(&b, *strfrmt++);
else if (*++strfrmt == '%') else if (*++strfrmt == '%')
luaL_addchar(*strfrmt++); /* %% */ luaL_putchar(&b, *strfrmt++); /* %% */
else { /* format item */ else { /* format item */
struct Capture cap; struct Capture cap;
char form[MAX_FORMAT]; /* to store the format ('%...') */ char form[MAX_FORMAT]; /* to store the format ('%...') */
char *buff; /* to store the formatted item */ char buff[MAX_ITEM]; /* to store the formatted item */
char *initf = strfrmt; const char *initf = strfrmt;
form[0] = '%'; form[0] = '%';
if (isdigit((unsigned char)*initf) && *(initf+1) == '$') { if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
arg = *initf - '0'; arg = *initf - '0';
@@ -481,33 +553,33 @@ static void str_format (void) {
arg++; arg++;
cap.src_end = strfrmt+strlen(strfrmt)+1; cap.src_end = strfrmt+strlen(strfrmt)+1;
cap.level = 0; cap.level = 0;
strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap); strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */ if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
strfrmt-initf > MAX_FORMAT-2) strfrmt-initf > MAX_FORMAT-2)
lua_error("invalid format (width or precision too long)"); lua_error(L, "invalid format (width or precision too long)");
strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */ strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
form[strfrmt-initf+2] = 0; form[strfrmt-initf+2] = 0;
buff = luaL_openspace(512); /* 512 > soid luaI_addquot99.99f', -1e308) */
switch (*strfrmt++) { switch (*strfrmt++) {
case 'c': case 'd': case 'i': case 'c': case 'd': case 'i':
sprintf(buff, form, luaL_check_int(arg)); sprintf(buff, form, luaL_check_int(L, arg));
break; break;
case 'o': case 'u': case 'x': case 'X': case 'o': case 'u': case 'x': case 'X':
sprintf(buff, form, (unsigned int)luaL_check_number(arg)); sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
break; break;
case 'e': case 'E': case 'f': case 'g': case 'G': case 'e': case 'E': case 'f': case 'g': case 'G':
sprintf(buff, form, luaL_check_number(arg)); sprintf(buff, form, luaL_check_number(L, arg));
break; break;
case 'q': case 'q':
luaI_addquoted(arg); luaI_addquoted(L, &b, arg);
continue; /* skip the "addsize" at the end */ continue; /* skip the "addsize" at the end */
case 's': { case 's': {
long l; size_t l;
char *s = luaL_check_lstr(arg, &l); const char *s = luaL_check_lstr(L, arg, &l);
if (cap.capture[1].len == 0 && l >= 100) { if (cap.capture[1].len == 0 && l >= 100) {
/* no precision and string is too big to be formatted; /* no precision and string is too long to be formatted;
keep original string */ keep original string */
addnchar(s, l); lua_pushvalue(L, arg);
luaL_addvalue(&b);
continue; /* skip the "addsize" at the end */ continue; /* skip the "addsize" at the end */
} }
else { else {
@@ -516,16 +588,17 @@ static void str_format (void) {
} }
} }
default: /* also treat cases 'pnLlh' */ default: /* also treat cases 'pnLlh' */
lua_error("invalid option in `format'"); lua_error(L, "invalid option in `format'");
} }
luaL_addsize(strlen(buff)); luaL_addlstring(&b, buff, strlen(buff));
} }
} }
closeandpush(); /* push the result */ luaL_pushresult(&b);
return 1;
} }
static struct luaL_reg strlib[] = { static const struct luaL_reg strlib[] = {
{"strlen", str_len}, {"strlen", str_len},
{"strsub", str_sub}, {"strsub", str_sub},
{"strlower", str_lower}, {"strlower", str_lower},
@@ -543,7 +616,6 @@ static struct luaL_reg strlib[] = {
/* /*
** Open string library ** Open string library
*/ */
void strlib_open (void) LUALIB_API void lua_strlibopen (lua_State *L) {
{ luaL_openl(L, strlib);
luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
} }

353
ltable.c
View File

@@ -1,176 +1,303 @@
/* /*
** $Id: ltable.c,v 1.20 1999/01/25 17:41:19 roberto Exp roberto $ ** $Id: ltable.c,v 1.57 2000/10/05 12:14:08 roberto Exp roberto $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include <stdlib.h>
#include "lauxlib.h" /*
** Implementation of tables (aka arrays, objects, or hash tables);
** uses a mix of chained scatter table with Brent's variation.
** A main invariant of these tables is that, if an element is not
** in its main position (i.e. the `original' position that its hash gives
** to it), then the colliding element is in its own main position.
** In other words, there are collisions only when two elements have the
** same main position (i.e. the same hash values for that table size).
** Because of that, the load factor of these tables can be 100% without
** performance penalties.
*/
#include "lua.h"
#include "lmem.h" #include "lmem.h"
#include "lobject.h" #include "lobject.h"
#include "lstate.h" #include "lstate.h"
#include "lstring.h"
#include "ltable.h" #include "ltable.h"
#include "lua.h"
#define gcsize(n) (1+(n/16)) #define gcsize(L, n) (sizeof(Hash)+(n)*sizeof(Node))
#define nuse(t) ((t)->nuse)
#define nodevector(t) ((t)->node)
#define TagDefault LUA_T_ARRAY;
static long int hashindex (TObject *ref) { #define TagDefault LUA_TTABLE
long int h;
switch (ttype(ref)) {
case LUA_T_NUMBER:
h = (long int)nvalue(ref); /*
** returns the `main' position of an element in a table (that is, the index
** of its hash value)
*/
Node *luaH_mainposition (const Hash *t, const TObject *key) {
unsigned long h;
switch (ttype(key)) {
case LUA_TNUMBER:
h = (unsigned long)(long)nvalue(key);
break; break;
case LUA_T_STRING: case LUA_T_USERDATA: case LUA_TSTRING:
h = (IntPoint)tsvalue(ref); h = tsvalue(key)->u.s.hash;
break; break;
case LUA_T_ARRAY: case LUA_TUSERDATA:
h = (IntPoint)avalue(ref); h = IntPoint(tsvalue(key));
break; break;
case LUA_T_PROTO: case LUA_TTABLE:
h = (IntPoint)tfvalue(ref); h = IntPoint(hvalue(key));
break; break;
case LUA_T_CPROTO: case LUA_TFUNCTION:
h = (IntPoint)fvalue(ref); h = IntPoint(clvalue(key));
break;
case LUA_T_CLOSURE:
h = (IntPoint)clvalue(ref);
break; break;
default: default:
lua_error("unexpected type to index table"); return NULL; /* invalid key */
h = 0; /* to avoid warnings */
} }
return (h >= 0 ? h : -(h+1)); LUA_ASSERT(h%(unsigned int)t->size == (h&((unsigned int)t->size-1)),
"a&(x-1) == a%x, for x power of 2");
return &t->node[h&(t->size-1)];
} }
Node *luaH_present (Hash *t, TObject *key) { static const TObject *luaH_getany (lua_State *L, const Hash *t,
int tsize = nhash(t); const TObject *key) {
long int h = hashindex(key); Node *n = luaH_mainposition(t, key);
int h1 = h%tsize; if (!n)
Node *n = node(t, h1); lua_error(L, "table index is nil");
/* keep looking until an entry with "ref" equal to key or nil */ else do {
while ((ttype(ref(n)) == ttype(key)) ? !luaO_equalval(key, ref(n)) if (luaO_equalObj(key, &n->key))
: ttype(ref(n)) != LUA_T_NIL) { return &n->val;
h1 += (h&(tsize-2)) + 1; /* double hashing */ n = n->next;
if (h1 >= tsize) h1 -= tsize; } while (n);
n = node(t, h1); return &luaO_nilobject; /* key not found */
}
return n;
} }
void luaH_free (Hash *frees) { /* specialized version for numbers */
while (frees) { const TObject *luaH_getnum (const Hash *t, Number key) {
Hash *next = (Hash *)frees->head.next; Node *n = &t->node[(unsigned long)(long)key&(t->size-1)];
L->nblocks -= gcsize(frees->nhash); do {
luaM_free(nodevector(frees)); if (ttype(&n->key) == LUA_TNUMBER && nvalue(&n->key) == key)
luaM_free(frees); return &n->val;
frees = next; n = n->next;
} while (n);
return &luaO_nilobject; /* key not found */
}
/* specialized version for strings */
const TObject *luaH_getstr (const Hash *t, TString *key) {
Node *n = &t->node[key->u.s.hash&(t->size-1)];
do {
if (ttype(&n->key) == LUA_TSTRING && tsvalue(&n->key) == key)
return &n->val;
n = n->next;
} while (n);
return &luaO_nilobject; /* key not found */
}
const TObject *luaH_get (lua_State *L, const Hash *t, const TObject *key) {
switch (ttype(key)) {
case LUA_TNUMBER: return luaH_getnum(t, nvalue(key));
case LUA_TSTRING: return luaH_getstr(t, tsvalue(key));
default: return luaH_getany(L, t, key);
} }
} }
static Node *hashnodecreate (int nhash) { Node *luaH_next (lua_State *L, const Hash *t, const TObject *key) {
Node *v = luaM_newvector(nhash, Node);
int i; int i;
for (i=0; i<nhash; i++) if (ttype(key) == LUA_TNIL)
ttype(ref(&v[i])) = ttype(val(&v[i])) = LUA_T_NIL; i = 0; /* first iteration */
return v; else {
const TObject *v = luaH_get(L, t, key);
if (v == &luaO_nilobject)
lua_error(L, "invalid key for `next'");
i = (int)(((const char *)v -
(const char *)(&t->node[0].val)) / sizeof(Node)) + 1;
}
for (; i<t->size; i++) {
Node *n = node(t, i);
if (ttype(val(n)) != LUA_TNIL)
return n;
}
return NULL; /* no more elements */
} }
Hash *luaH_new (int nhash) { /*
Hash *t = luaM_new(Hash); ** try to remove a key without value from a table. To avoid problems with
nhash = luaO_redimension(nhash*3/2); ** hash, change `key' for a number with the same hash.
nodevector(t) = hashnodecreate(nhash); */
nhash(t) = nhash; void luaH_remove (Hash *t, TObject *key) {
nuse(t) = 0; if (ttype(key) == LUA_TNUMBER ||
(ttype(key) == LUA_TSTRING && tsvalue(key)->len <= 30))
return; /* do not remove numbers nor small strings */
else {
/* try to find a number `n' with the same hash as `key' */
Node *mp = luaH_mainposition(t, key);
int n = mp - &t->node[0];
/* make sure `n' is not in `t' */
while (luaH_getnum(t, n) != &luaO_nilobject) {
if (n >= MAX_INT - t->size)
return; /* give up; (to avoid overflow) */
n += t->size;
}
ttype(key) = LUA_TNUMBER;
nvalue(key) = n;
LUA_ASSERT(luaH_mainposition(t, key) == mp, "cannot change hash");
}
}
static void setnodevector (lua_State *L, Hash *t, lint32 size) {
int i;
if (size > MAX_INT)
lua_error(L, "table overflow");
t->node = luaM_newvector(L, size, Node);
for (i=0; i<(int)size; i++) {
ttype(&t->node[i].key) = ttype(&t->node[i].val) = LUA_TNIL;
t->node[i].next = NULL;
}
L->nblocks += gcsize(L, size) - gcsize(L, t->size);
t->size = size;
t->firstfree = &t->node[size-1]; /* first free position to be used */
}
Hash *luaH_new (lua_State *L, int size) {
Hash *t = luaM_new(L, Hash);
t->htag = TagDefault; t->htag = TagDefault;
luaO_insertlist(&(L->roottable), (GCnode *)t); t->next = L->roottable;
L->nblocks += gcsize(nhash); L->roottable = t;
t->mark = t;
t->size = 0;
L->nblocks += gcsize(L, 0);
t->node = NULL;
setnodevector(L, t, luaO_power2(size));
return t; return t;
} }
static int newsize (Hash *t) { void luaH_free (lua_State *L, Hash *t) {
L->nblocks -= gcsize(L, t->size);
luaM_free(L, t->node);
luaM_free(L, t);
}
static int numuse (const Hash *t) {
Node *v = t->node; Node *v = t->node;
int size = nhash(t); int size = t->size;
int realuse = 0; int realuse = 0;
int i; int i;
for (i=0; i<size; i++) { for (i=0; i<size; i++) {
if (ttype(val(v+i)) != LUA_T_NIL) if (ttype(&v[i].val) != LUA_TNIL)
realuse++; realuse++;
} }
return luaO_redimension((realuse+1)*2); /* +1 is the new element */ return realuse;
} }
static void rehash (Hash *t) { static void rehash (lua_State *L, Hash *t) {
int nold = nhash(t); int oldsize = t->size;
Node *vold = nodevector(t); Node *nold = t->node;
int nnew = newsize(t); int nelems = numuse(t);
int i; int i;
nodevector(t) = hashnodecreate(nnew); LUA_ASSERT(nelems<=oldsize, "wrong count");
nhash(t) = nnew; if (nelems >= oldsize-oldsize/4) /* using more than 3/4? */
nuse(t) = 0; setnodevector(L, t, (lint32)oldsize*2);
for (i=0; i<nold; i++) { else if (nelems <= oldsize/4 && /* less than 1/4? */
Node *n = vold+i; oldsize > MINPOWER2)
if (ttype(val(n)) != LUA_T_NIL) { setnodevector(L, t, oldsize/2);
*luaH_present(t, ref(n)) = *n; /* copy old node to new hash */ else
nuse(t)++; setnodevector(L, t, oldsize);
for (i=0; i<oldsize; i++) {
Node *old = nold+i;
if (ttype(&old->val) != LUA_TNIL)
*luaH_set(L, t, &old->key) = old->val;
}
luaM_free(L, nold); /* free old array */
}
/*
** inserts a key into a hash table; first, check whether key is
** already present; if not, check whether key's main position is free;
** if not, check whether colliding node is in its main position or not;
** if it is not, move colliding node to an empty place and put new key
** in its main position; otherwise (colliding node is in its main position),
** new key goes to an empty position.
*/
TObject *luaH_set (lua_State *L, Hash *t, const TObject *key) {
Node *mp = luaH_mainposition(t, key);
Node *n = mp;
if (!mp)
lua_error(L, "table index is nil");
do { /* check whether `key' is somewhere in the chain */
if (luaO_equalObj(key, &n->key))
return &n->val; /* that's all */
else n = n->next;
} while (n);
/* `key' not found; must insert it */
if (ttype(&mp->key) != LUA_TNIL) { /* main position is not free? */
Node *othern; /* main position of colliding node */
n = t->firstfree; /* get a free place */
/* is colliding node out of its main position? (can only happens if
its position is after "firstfree") */
if (mp > n && (othern=luaH_mainposition(t, &mp->key)) != mp) {
/* yes; move colliding node into free position */
while (othern->next != mp) othern = othern->next; /* find previous */
othern->next = n; /* redo the chain with `n' in place of `mp' */
*n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
mp->next = NULL; /* now `mp' is free */
}
else { /* colliding node is in its own main position */
/* new node will go into free position */
n->next = mp->next; /* chain new position */
mp->next = n;
mp = n;
} }
} }
L->nblocks += gcsize(nnew)-gcsize(nold); mp->key = *key;
luaM_free(vold); for (;;) { /* correct `firstfree' */
} if (ttype(&t->firstfree->key) == LUA_TNIL)
return &mp->val; /* OK; table still has a free place */
else if (t->firstfree == t->node) break; /* cannot decrement from here */
void luaH_set (Hash *t, TObject *ref, TObject *val) { else (t->firstfree)--;
Node *n = luaH_present(t, ref);
if (ttype(ref(n)) != LUA_T_NIL)
*val(n) = *val;
else {
TObject buff = *val; /* rehash may invalidate this address */
if ((long)nuse(t)*3L > (long)nhash(t)*2L) {
rehash(t);
n = luaH_present(t, ref);
}
nuse(t)++;
*ref(n) = *ref;
*val(n) = buff;
} }
rehash(L, t); /* no more free places */
return luaH_set(L, t, key); /* `rehash' invalidates this insertion */
} }
int luaH_pos (Hash *t, TObject *r) { TObject *luaH_setint (lua_State *L, Hash *t, int key) {
Node *n = luaH_present(t, r);
luaL_arg_check(ttype(val(n)) != LUA_T_NIL, 2, "key not found");
return n-(t->node);
}
void luaH_setint (Hash *t, int ref, TObject *val) {
TObject index; TObject index;
ttype(&index) = LUA_T_NUMBER; ttype(&index) = LUA_TNUMBER;
nvalue(&index) = ref; nvalue(&index) = key;
luaH_set(t, &index, val); return luaH_set(L, t, &index);
} }
TObject *luaH_getint (Hash *t, int ref) { void luaH_setstrnum (lua_State *L, Hash *t, TString *key, Number val) {
TObject index; TObject *value, index;
ttype(&index) = LUA_T_NUMBER; ttype(&index) = LUA_TSTRING;
nvalue(&index) = ref; tsvalue(&index) = key;
return luaH_get(t, &index); value = luaH_set(L, t, &index);
ttype(value) = LUA_TNUMBER;
nvalue(value) = val;
}
const TObject *luaH_getglobal (lua_State *L, const char *name) {
return luaH_getstr(L->gt, luaS_new(L, name));
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltable.h,v 1.10 1999/01/25 17:40:10 roberto Exp roberto $ ** $Id: ltable.h,v 1.23 2000/06/06 16:31:41 roberto Exp roberto $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -10,21 +10,25 @@
#include "lobject.h" #include "lobject.h"
#define node(t,i) (&(t)->node[i]) #define node(t,i) (&(t)->node[i])
#define ref(n) (&(n)->ref) #define key(n) (&(n)->key)
#define val(n) (&(n)->val) #define val(n) (&(n)->val)
#define nhash(t) ((t)->nhash)
#define luaH_get(t,ref) (val(luaH_present((t), (ref)))) Hash *luaH_new (lua_State *L, int nhash);
#define luaH_move(t,from,to) (luaH_setint(t, to, luaH_getint(t, from))) void luaH_free (lua_State *L, Hash *t);
const TObject *luaH_get (lua_State *L, const Hash *t, const TObject *key);
const TObject *luaH_getnum (const Hash *t, Number key);
const TObject *luaH_getstr (const Hash *t, TString *key);
void luaH_remove (Hash *t, TObject *key);
TObject *luaH_set (lua_State *L, Hash *t, const TObject *key);
Node * luaH_next (lua_State *L, const Hash *t, const TObject *r);
TObject *luaH_setint (lua_State *L, Hash *t, int key);
void luaH_setstrnum (lua_State *L, Hash *t, TString *key, Number val);
unsigned long luaH_hash (lua_State *L, const TObject *key);
const TObject *luaH_getglobal (lua_State *L, const char *name);
Hash *luaH_new (int nhash); /* exported only for debugging */
void luaH_free (Hash *frees); Node *luaH_mainposition (const Hash *t, const TObject *key);
Node *luaH_present (Hash *t, TObject *key);
void luaH_set (Hash *t, TObject *ref, TObject *val);
int luaH_pos (Hash *t, TObject *r);
void luaH_setint (Hash *t, int ref, TObject *val);
TObject *luaH_getint (Hash *t, int ref);
#endif #endif

543
ltests.c Normal file
View File

@@ -0,0 +1,543 @@
/*
** $Id: ltests.c,v 1.53 2000/10/30 16:29:59 roberto Exp roberto $
** Internal Module for Debugging of the Lua Implementation
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "lauxlib.h"
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "luadebug.h"
#include "lualib.h"
void luaB_opentests (lua_State *L);
/*
** The whole module only makes sense with LUA_DEBUG on
*/
#ifdef LUA_DEBUG
static void setnameval (lua_State *L, const char *name, int val) {
lua_pushstring(L, name);
lua_pushnumber(L, val);
lua_settable(L, -3);
}
/*
** {======================================================
** Disassembler
** =======================================================
*/
static const char *const instrname[NUM_OPCODES] = {
"END", "RETURN", "CALL", "TAILCALL", "PUSHNIL", "POP", "PUSHINT",
"PUSHSTRING", "PUSHNUM", "PUSHNEGNUM", "PUSHUPVALUE", "GETLOCAL",
"GETGLOBAL", "GETTABLE", "GETDOTTED", "GETINDEXED", "PUSHSELF",
"CREATETABLE", "SETLOCAL", "SETGLOBAL", "SETTABLE", "SETLIST", "SETMAP",
"ADD", "ADDI", "SUB", "MULT", "DIV", "POW", "CONCAT", "MINUS", "NOT",
"JMPNE", "JMPEQ", "JMPLT", "JMPLE", "JMPGT", "JMPGE", "JMPT", "JMPF",
"JMPONT", "JMPONF", "JMP", "PUSHNILJMP", "FORPREP", "FORLOOP", "LFORPREP",
"LFORLOOP", "CLOSURE"
};
static int pushop (lua_State *L, Proto *p, int pc) {
char buff[100];
Instruction i = p->code[pc];
OpCode o = GET_OPCODE(i);
const char *name = instrname[o];
sprintf(buff, "%5d - ", luaG_getline(p->lineinfo, pc, 1, NULL));
switch ((enum Mode)luaK_opproperties[o].mode) {
case iO:
sprintf(buff+8, "%-12s", name);
break;
case iU:
sprintf(buff+8, "%-12s%4u", name, GETARG_U(i));
break;
case iS:
sprintf(buff+8, "%-12s%4d", name, GETARG_S(i));
break;
case iAB:
sprintf(buff+8, "%-12s%4d %4d", name, GETARG_A(i), GETARG_B(i));
break;
}
lua_pushstring(L, buff);
return (o != OP_END);
}
static int listcode (lua_State *L) {
int pc;
Proto *p;
int res;
luaL_arg_check(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = clvalue(luaA_index(L, 1))->f.l;
lua_newtable(L);
setnameval(L, "maxstack", p->maxstacksize);
setnameval(L, "numparams", p->numparams);
pc = 0;
do {
lua_pushnumber(L, pc+1);
res = pushop(L, p, pc++);
lua_settable(L, -3);
} while (res);
return 1;
}
static int liststrings (lua_State *L) {
Proto *p;
int i;
luaL_arg_check(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = clvalue(luaA_index(L, 1))->f.l;
lua_newtable(L);
for (i=0; i<p->nkstr; i++) {
lua_pushnumber(L, i+1);
lua_pushstring(L, p->kstr[i]->str);
lua_settable(L, -3);
}
return 1;
}
static int listlocals (lua_State *L) {
Proto *p;
int pc = luaL_check_int(L, 2) - 1;
int i = 0;
const char *name;
luaL_arg_check(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = clvalue(luaA_index(L, 1))->f.l;
while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)
lua_pushstring(L, name);
return i-1;
}
/* }====================================================== */
static int get_limits (lua_State *L) {
lua_newtable(L);
setnameval(L, "BITS_INT", BITS_INT);
setnameval(L, "LFPF", LFIELDS_PER_FLUSH);
setnameval(L, "MAXARG_A", MAXARG_A);
setnameval(L, "MAXARG_B", MAXARG_B);
setnameval(L, "MAXARG_S", MAXARG_S);
setnameval(L, "MAXARG_U", MAXARG_U);
setnameval(L, "MAXLOCALS", MAXLOCALS);
setnameval(L, "MAXPARAMS", MAXPARAMS);
setnameval(L, "MAXSTACK", MAXSTACK);
setnameval(L, "MAXUPVALUES", MAXUPVALUES);
setnameval(L, "MAXVARSLH", MAXVARSLH);
setnameval(L, "RFPF", RFIELDS_PER_FLUSH);
setnameval(L, "SIZE_A", SIZE_A);
setnameval(L, "SIZE_B", SIZE_B);
setnameval(L, "SIZE_OP", SIZE_OP);
setnameval(L, "SIZE_U", SIZE_U);
return 1;
}
static int mem_query (lua_State *L) {
if (lua_isnull(L, 1)) {
lua_pushnumber(L, memdebug_total);
lua_pushnumber(L, memdebug_numblocks);
lua_pushnumber(L, memdebug_maxmem);
return 3;
}
else {
memdebug_memlimit = luaL_check_int(L, 1);
return 0;
}
}
static int hash_query (lua_State *L) {
if (lua_isnull(L, 2)) {
luaL_arg_check(L, lua_tag(L, 1) == LUA_TSTRING, 1, "string expected");
lua_pushnumber(L, tsvalue(luaA_index(L, 1))->u.s.hash);
}
else {
Hash *t;
luaL_checktype(L, 2, LUA_TTABLE);
t = hvalue(luaA_index(L, 2));
lua_pushnumber(L, luaH_mainposition(t, luaA_index(L, 1)) - t->node);
}
return 1;
}
static int table_query (lua_State *L) {
const Hash *t;
int i = luaL_opt_int(L, 2, -1);
luaL_checktype(L, 1, LUA_TTABLE);
t = hvalue(luaA_index(L, 1));
if (i == -1) {
lua_pushnumber(L, t->size);
lua_pushnumber(L, t->firstfree - t->node);
return 2;
}
else if (i < t->size) {
luaA_pushobject(L, &t->node[i].key);
luaA_pushobject(L, &t->node[i].val);
if (t->node[i].next) {
lua_pushnumber(L, t->node[i].next - t->node);
return 3;
}
else
return 2;
}
return 0;
}
static int string_query (lua_State *L) {
stringtable *tb = (*luaL_check_string(L, 1) == 's') ? &L->strt : &L->udt;
int s = luaL_opt_int(L, 2, 0) - 1;
if (s==-1) {
lua_pushnumber(L ,tb->nuse);
lua_pushnumber(L ,tb->size);
return 2;
}
else if (s < tb->size) {
TString *ts;
int n = 0;
for (ts = tb->hash[s]; ts; ts = ts->nexthash) {
ttype(L->top) = LUA_TSTRING;
tsvalue(L->top) = ts;
incr_top;
n++;
}
return n;
}
return 0;
}
static int tref (lua_State *L) {
luaL_checkany(L, 1);
lua_pushvalue(L, 1);
lua_pushnumber(L, lua_ref(L, luaL_opt_int(L, 2, 1)));
return 1;
}
static int getref (lua_State *L) {
if (lua_getref(L, luaL_check_int(L, 1)))
return 1;
else
return 0;
}
static int unref (lua_State *L) {
lua_unref(L, luaL_check_int(L, 1));
return 0;
}
static int newuserdata (lua_State *L) {
if (lua_isnumber(L, 2))
lua_pushusertag(L, (void *)luaL_check_int(L, 1), luaL_check_int(L, 2));
else
lua_newuserdata(L, luaL_check_int(L, 1));
return 1;
}
static int udataval (lua_State *L) {
luaL_checktype(L, 1, LUA_TUSERDATA);
lua_pushnumber(L, (int)lua_touserdata(L, 1));
return 1;
}
static int newstate (lua_State *L) {
lua_State *L1 = lua_open(luaL_check_int(L, 1));
if (L1)
lua_pushuserdata(L, L1);
else
lua_pushnil(L);
return 1;
}
static int loadlib (lua_State *L) {
lua_State *L1 = (lua_State *)lua_touserdata(L, 1);
switch (*luaL_check_string(L, 2)) {
case 'm': lua_mathlibopen(L1); break;
case 's': lua_strlibopen(L1); break;
case 'i': lua_iolibopen(L1); break;
case 'd': lua_dblibopen(L1); break;
case 'b': lua_baselibopen(L1); break;
default: luaL_argerror(L, 2, "invalid option");
}
return 0;
}
static int closestate (lua_State *L) {
luaL_checktype(L, 1, LUA_TUSERDATA);
lua_close((lua_State *)lua_touserdata(L, 1));
return 0;
}
static int doremote (lua_State *L) {
lua_State *L1;
const char *code = luaL_check_string(L, 2);
int status;
luaL_checktype(L, 1, LUA_TUSERDATA);
L1 = (lua_State *)lua_touserdata(L, 1);
status = lua_dostring(L1, code);
if (status != 0) {
lua_pushnil(L);
lua_pushnumber(L, status);
return 2;
}
else {
int i = 0;
while (!lua_isnull(L1, ++i))
lua_pushstring(L, lua_tostring(L1, i));
return i-1;
}
}
static int settagmethod (lua_State *L) {
int tag = luaL_check_int(L, 1);
const char *event = luaL_check_string(L, 2);
luaL_checkany(L, 3);
lua_gettagmethod(L, tag, event);
lua_pushvalue(L, 3);
lua_settagmethod(L, tag, event);
return 1;
}
static int pushbool (lua_State *L, int b) {
if (b) lua_pushnumber(L, 1);
else lua_pushnil(L);
return 1;
}
static int equal (lua_State *L) {
return pushbool(L, lua_equal(L, 1, 2));
}
/*
** {======================================================
** function to test the API with C. It interprets a kind of "assembler"
** language with calls to the API, so the test can be driven by Lua code
** =======================================================
*/
static const char *const delimits = " \t\n,;";
static void skip (const char **pc) {
while (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
}
static int getnum (lua_State *L, const char **pc) {
int res = 0;
int sig = 1;
skip(pc);
if (**pc == '.') {
res = (int)lua_tonumber(L, -1);
lua_pop(L, 1);
(*pc)++;
return res;
}
else if (**pc == '-') {
sig = -1;
(*pc)++;
}
while (isdigit(**pc)) res = res*10 + (*(*pc)++) - '0';
return sig*res;
}
static const char *getname (char *buff, const char **pc) {
int i = 0;
skip(pc);
while (**pc != '\0' && !strchr(delimits, **pc))
buff[i++] = *(*pc)++;
buff[i] = '\0';
return buff;
}
#define EQ(s1) (strcmp(s1, inst) == 0)
#define getnum ((getnum)(L, &pc))
#define getname ((getname)(buff, &pc))
static int testC (lua_State *L) {
char buff[30];
const char *pc = luaL_check_string(L, 1);
for (;;) {
const char *inst = getname;
if EQ("") return 0;
else if EQ("isnumber") {
lua_pushnumber(L, lua_isnumber(L, getnum));
}
else if EQ("isstring") {
lua_pushnumber(L, lua_isstring(L, getnum));
}
else if EQ("istable") {
lua_pushnumber(L, lua_istable(L, getnum));
}
else if EQ("iscfunction") {
lua_pushnumber(L, lua_iscfunction(L, getnum));
}
else if EQ("isfunction") {
lua_pushnumber(L, lua_isfunction(L, getnum));
}
else if EQ("isuserdata") {
lua_pushnumber(L, lua_isuserdata(L, getnum));
}
else if EQ("isnil") {
lua_pushnumber(L, lua_isnil(L, getnum));
}
else if EQ("isnull") {
lua_pushnumber(L, lua_isnull(L, getnum));
}
else if EQ("tonumber") {
lua_pushnumber(L, lua_tonumber(L, getnum));
}
else if EQ("tostring") {
lua_pushstring(L, lua_tostring(L, getnum));
}
else if EQ("tonumber") {
lua_pushnumber(L, lua_tonumber(L, getnum));
}
else if EQ("strlen") {
lua_pushnumber(L, lua_strlen(L, getnum));
}
else if EQ("tocfunction") {
lua_pushcfunction(L, lua_tocfunction(L, getnum));
}
else if EQ("return") {
return getnum;
}
else if EQ("gettop") {
lua_pushnumber(L, lua_gettop(L));
}
else if EQ("settop") {
lua_settop(L, getnum);
}
else if EQ("pop") {
lua_pop(L, getnum);
}
else if EQ("pushnum") {
lua_pushnumber(L, getnum);
}
else if EQ("pushvalue") {
lua_pushvalue(L, getnum);
}
else if EQ("remove") {
lua_remove(L, getnum);
}
else if EQ("insert") {
lua_insert(L, getnum);
}
else if EQ("gettable") {
lua_gettable(L, getnum);
}
else if EQ("settable") {
lua_settable(L, getnum);
}
else if EQ("next") {
lua_next(L, -2);
}
else if EQ("concat") {
lua_concat(L, getnum);
}
else if EQ("rawcall") {
int narg = getnum;
int nres = getnum;
lua_rawcall(L, narg, nres);
}
else if EQ("call") {
int narg = getnum;
int nres = getnum;
lua_call(L, narg, nres);
}
else if EQ("dostring") {
lua_dostring(L, luaL_check_string(L, getnum));
}
else if EQ("settagmethod") {
int tag = getnum;
const char *event = getname;
lua_settagmethod(L, tag, event);
}
else if EQ("gettagmethod") {
int tag = getnum;
const char *event = getname;
lua_gettagmethod(L, tag, event);
}
else if EQ("type") {
lua_pushstring(L, lua_typename(L, lua_type(L, getnum)));
}
else luaL_verror(L, "unknown instruction %.30s", buff);
}
return 0;
}
/* }====================================================== */
static const struct luaL_reg tests_funcs[] = {
{"hash", hash_query},
{"limits", get_limits},
{"listcode", listcode},
{"liststrings", liststrings},
{"listlocals", listlocals},
{"loadlib", loadlib},
{"querystr", string_query},
{"querytab", table_query},
{"testC", testC},
{"ref", tref},
{"getref", getref},
{"unref", unref},
{"newuserdata", newuserdata},
{"udataval", udataval},
{"newstate", newstate},
{"closestate", closestate},
{"doremote", doremote},
{"settagmethod", settagmethod},
{"equal", equal},
{"totalmem", mem_query}
};
void luaB_opentests (lua_State *L) {
lua_newtable(L);
lua_getglobals(L);
lua_pushvalue(L, -2);
lua_setglobals(L);
luaL_openl(L, tests_funcs); /* open functions inside new table */
lua_setglobals(L); /* restore old table of globals */
lua_setglobal(L, "T"); /* set new table as global T */
}
#endif

270
ltm.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltm.c,v 1.23 1999/02/25 19:13:56 roberto Exp roberto $ ** $Id: ltm.c,v 1.55 2000/10/20 16:39:03 roberto Exp roberto $
** Tag methods ** Tag methods
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -8,240 +8,156 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "lauxlib.h" #include "lua.h"
#include "ldo.h"
#include "lmem.h" #include "lmem.h"
#include "lobject.h" #include "lobject.h"
#include "lstate.h" #include "lstate.h"
#include "ltm.h" #include "ltm.h"
char *luaT_eventname[] = { /* ORDER IM */ const char *const luaT_eventname[] = { /* ORDER TM */
"gettable", "settable", "index", "getglobal", "setglobal", "add", "gettable", "settable", "index", "getglobal", "setglobal", "add", "sub",
"sub", "mul", "div", "pow", "unm", "lt", "le", "gt", "ge", "mul", "div", "pow", "unm", "lt", "concat", "gc", "function",
"concat", "gc", "function", NULL "le", "gt", "ge", /* deprecated options!! */
NULL
}; };
static int luaI_checkevent (char *name, char *list[]) { static int findevent (const char *name) {
int e = luaL_findstring(name, list); int i;
for (i=0; luaT_eventname[i]; i++)
if (strcmp(luaT_eventname[i], name) == 0)
return i;
return -1; /* name not found */
}
static int luaI_checkevent (lua_State *L, const char *name, int t) {
int e = findevent(name);
if (e >= TM_N)
luaO_verror(L, "event `%.50s' is deprecated", name);
if (e == TM_GC && t == LUA_TTABLE)
luaO_verror(L, "event `gc' for tables is deprecated");
if (e < 0) if (e < 0)
luaL_verror("`%.50s' is not a valid event name", name); luaO_verror(L, "`%.50s' is not a valid event name", name);
return e; return e;
} }
/* events in LUA_T_NIL are all allowed, since this is used as a /* events in LUA_TNIL are all allowed, since this is used as a
* 'placeholder' for "default" fallbacks * 'placeholder' for "default" fallbacks
*/ */
static char luaT_validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */ /* ORDER LUA_T, ORDER TM */
{1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_T_USERDATA */ static const char luaT_validevents[NUM_TAGS][TM_N] = {
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_NUMBER */ {1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_TUSERDATA */
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_STRING */ {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, /* LUA_TNIL */
{0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, /* LUA_T_ARRAY */ {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}, /* LUA_TNUMBER */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* LUA_T_PROTO */ {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_TSTRING */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* LUA_T_CPROTO */ {0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_TTABLE */
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* LUA_T_NIL */ {1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0} /* LUA_TFUNCTION */
}; };
static int luaT_validevent (int t, int e) { /* ORDER LUA_T */ int luaT_validevent (int t, int e) { /* ORDER LUA_T */
return (t < LUA_T_NIL) ? 1 : luaT_validevents[-t][e]; return (t >= NUM_TAGS) ? 1 : luaT_validevents[t][e];
} }
static void init_entry (int tag) { static void init_entry (lua_State *L, int tag) {
int i; int i;
for (i=0; i<IM_N; i++) for (i=0; i<TM_N; i++)
ttype(luaT_getim(tag, i)) = LUA_T_NIL; luaT_gettm(L, tag, i) = NULL;
L->TMtable[tag].collected = NULL;
} }
void luaT_init (void) { void luaT_init (lua_State *L) {
int t; int t;
L->last_tag = -(NUM_TAGS-1); luaM_growvector(L, L->TMtable, 0, NUM_TAGS, struct TM, "", MAX_INT);
luaM_growvector(L->IMtable, 0, NUM_TAGS, struct IM, arrEM, MAX_INT); L->nblocks += NUM_TAGS*sizeof(struct TM);
for (t=L->last_tag; t<=0; t++) L->last_tag = NUM_TAGS-1;
init_entry(t); for (t=0; t<=L->last_tag; t++)
init_entry(L, t);
} }
int lua_newtag (void) { LUA_API int lua_newtag (lua_State *L) {
--L->last_tag; luaM_growvector(L, L->TMtable, L->last_tag, 1, struct TM,
luaM_growvector(L->IMtable, -(L->last_tag), 1, struct IM, arrEM, MAX_INT); "tag table overflow", MAX_INT);
init_entry(L->last_tag); L->nblocks += sizeof(struct TM);
L->last_tag++;
init_entry(L, L->last_tag);
return L->last_tag; return L->last_tag;
} }
static void checktag (int tag) { static void checktag (lua_State *L, int tag) {
if (!(L->last_tag <= tag && tag <= 0)) if (!(0 <= tag && tag <= L->last_tag))
luaL_verror("%d is not a valid tag", tag); luaO_verror(L, "%d is not a valid tag", tag);
} }
void luaT_realtag (int tag) { void luaT_realtag (lua_State *L, int tag) {
if (!(L->last_tag <= tag && tag < LUA_T_NIL)) if (!validtag(tag))
luaL_verror("tag %d was not created by `newtag'", tag); luaO_verror(L, "tag %d was not created by `newtag'", tag);
} }
int lua_copytagmethods (int tagto, int tagfrom) { LUA_API int lua_copytagmethods (lua_State *L, int tagto, int tagfrom) {
int e; int e;
checktag(tagto); checktag(L, tagto);
checktag(tagfrom); checktag(L, tagfrom);
for (e=0; e<IM_N; e++) { for (e=0; e<TM_N; e++) {
if (luaT_validevent(tagto, e)) if (luaT_validevent(tagto, e))
*luaT_getim(tagto, e) = *luaT_getim(tagfrom, e); luaT_gettm(L, tagto, e) = luaT_gettm(L, tagfrom, e);
} }
return tagto; return tagto;
} }
int luaT_effectivetag (TObject *o) { int luaT_tag (const TObject *o) {
int t; int t = ttype(o);
switch (t = ttype(o)) { switch (t) {
case LUA_T_ARRAY: case LUA_TUSERDATA: return tsvalue(o)->u.d.tag;
return o->value.a->htag; case LUA_TTABLE: return hvalue(o)->htag;
case LUA_T_USERDATA: { default: return t;
int tag = o->value.ts->u.d.tag;
return (tag >= 0) ? LUA_T_USERDATA : tag;
}
case LUA_T_CLOSURE:
return o->value.cl->consts[0].ttype;
#ifdef DEBUG
case LUA_T_PMARK: case LUA_T_CMARK:
case LUA_T_CLMARK: case LUA_T_LINE:
LUA_INTERNALERROR("invalid type");
#endif
default:
return t;
} }
} }
TObject *luaT_gettagmethod (int t, char *event) { LUA_API void lua_gettagmethod (lua_State *L, int t, const char *event) {
int e = luaI_checkevent(event, luaT_eventname);
checktag(t);
if (luaT_validevent(t, e))
return luaT_getim(t,e);
else
return &luaO_nilobject;
}
void luaT_settagmethod (int t, char *event, TObject *func) {
TObject temp = *func;
int e = luaI_checkevent(event, luaT_eventname);
checktag(t);
if (!luaT_validevent(t, e))
luaL_verror("cannot change tag method `%.20s' for type `%.20s'%.20s",
luaT_eventname[e], luaO_typenames[-t],
(t == LUA_T_ARRAY || t == LUA_T_USERDATA) ? " with default tag"
: "");
*func = *luaT_getim(t,e);
*luaT_getim(t, e) = temp;
}
char *luaT_travtagmethods (int (*fn)(TObject *)) { /* ORDER IM */
int e; int e;
for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) { e = luaI_checkevent(L, event, t);
int t; checktag(L, t);
for (t=0; t>=L->last_tag; t--) if (luaT_validevent(t, e) && luaT_gettm(L, t, e)) {
if (fn(luaT_getim(t,e))) clvalue(L->top) = luaT_gettm(L, t, e);
return luaT_eventname[e]; ttype(L->top) = LUA_TFUNCTION;
} }
return NULL;
}
/*
* ===================================================================
* compatibility with old fallback system
*/
#ifdef LUA_COMPAT2_5
#include "lapi.h"
#include "lstring.h"
static void errorFB (void)
{
lua_Object o = lua_getparam(1);
if (lua_isstring(o))
fprintf(stderr, "lua: %s\n", lua_getstring(o));
else else
fprintf(stderr, "lua: unknown error\n"); ttype(L->top) = LUA_TNIL;
incr_top;
} }
static void nilFB (void) { } LUA_API void lua_settagmethod (lua_State *L, int t, const char *event) {
int e = luaI_checkevent(L, event, t);
checktag(L, t);
static void typeFB (void) { if (!luaT_validevent(t, e))
lua_error("unexpected type"); luaO_verror(L, "cannot change `%.20s' tag method for type `%.20s'%.20s",
} luaT_eventname[e], luaO_typenames[t],
(t == LUA_TTABLE || t == LUA_TUSERDATA) ?
" with default tag" : "");
static void fillvalids (IMS e, TObject *func) { switch (ttype(L->top - 1)) {
int t; case LUA_TNIL:
for (t=LUA_T_NIL; t<=LUA_T_USERDATA; t++) luaT_gettm(L, t, e) = NULL;
if (luaT_validevent(t, e))
*luaT_getim(t, e) = *func;
}
void luaT_setfallback (void) {
static char *oldnames [] = {"error", "getglobal", "arith", "order", NULL};
TObject oldfunc;
lua_CFunction replace;
char *name = luaL_check_string(1);
lua_Object func = lua_getparam(2);
luaL_arg_check(lua_isfunction(func), 2, "function expected");
switch (luaL_findstring(name, oldnames)) {
case 0: { /* old error fallback */
TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval);
oldfunc = *em;
*em = *luaA_Address(func);
replace = errorFB;
break; break;
} case LUA_TFUNCTION:
case 1: /* old getglobal fallback */ luaT_gettm(L, t, e) = clvalue(L->top - 1);
oldfunc = *luaT_getim(LUA_T_NIL, IM_GETGLOBAL);
*luaT_getim(LUA_T_NIL, IM_GETGLOBAL) = *luaA_Address(func);
replace = nilFB;
break; break;
case 2: { /* old arith fallback */ default:
int i; lua_error(L, "tag method must be a function (or nil)");
oldfunc = *luaT_getim(LUA_T_NUMBER, IM_POW);
for (i=IM_ADD; i<=IM_UNM; i++) /* ORDER IM */
fillvalids(i, luaA_Address(func));
replace = typeFB;
break;
}
case 3: { /* old order fallback */
int i;
oldfunc = *luaT_getim(LUA_T_NIL, IM_LT);
for (i=IM_LT; i<=IM_GE; i++) /* ORDER IM */
fillvalids(i, luaA_Address(func));
replace = typeFB;
break;
}
default: {
int e;
if ((e = luaL_findstring(name, luaT_eventname)) >= 0) {
oldfunc = *luaT_getim(LUA_T_NIL, e);
fillvalids(e, luaA_Address(func));
replace = (e == IM_GC || e == IM_INDEX) ? nilFB : typeFB;
}
else {
luaL_verror("`%.50s' is not a valid fallback name", name);
replace = NULL; /* to avoid warnings */
}
}
} }
if (oldfunc.ttype != LUA_T_NIL) L->top--;
luaA_pushobject(&oldfunc);
else
lua_pushcfunction(replace);
} }
#endif

69
ltm.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: ltm.h,v 1.4 1997/11/26 18:53:45 roberto Exp roberto $ ** $Id: ltm.h,v 1.17 2000/10/05 12:14:08 roberto Exp roberto $
** Tag methods ** Tag methods
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -13,50 +13,47 @@
/* /*
* WARNING: if you change the order of this enumeration, * WARNING: if you change the order of this enumeration,
* grep "ORDER IM" * grep "ORDER TM"
*/ */
typedef enum { typedef enum {
IM_GETTABLE = 0, TM_GETTABLE = 0,
IM_SETTABLE, TM_SETTABLE,
IM_INDEX, TM_INDEX,
IM_GETGLOBAL, TM_GETGLOBAL,
IM_SETGLOBAL, TM_SETGLOBAL,
IM_ADD, TM_ADD,
IM_SUB, TM_SUB,
IM_MUL, TM_MUL,
IM_DIV, TM_DIV,
IM_POW, TM_POW,
IM_UNM, TM_UNM,
IM_LT, TM_LT,
IM_LE, TM_CONCAT,
IM_GT, TM_GC,
IM_GE, TM_FUNCTION,
IM_CONCAT, TM_N /* number of elements in the enum */
IM_GC, } TMS;
IM_FUNCTION
} IMS;
#define IM_N 18
struct IM { struct TM {
TObject int_method[IM_N]; Closure *method[TM_N];
TString *collected; /* list of garbage-collected udata with this tag */
}; };
#define luaT_getim(tag,event) (&L->IMtable[-(tag)].int_method[event]) #define luaT_gettm(L,tag,event) (L->TMtable[tag].method[event])
#define luaT_getimbyObj(o,e) (luaT_getim(luaT_effectivetag(o),(e))) #define luaT_gettmbyObj(L,o,e) (luaT_gettm((L),luaT_tag(o),(e)))
extern char *luaT_eventname[];
void luaT_init (void); #define validtag(t) (NUM_TAGS <= (t) && (t) <= L->last_tag)
void luaT_realtag (int tag);
int luaT_effectivetag (TObject *o); extern const char *const luaT_eventname[];
void luaT_settagmethod (int t, char *event, TObject *func);
TObject *luaT_gettagmethod (int t, char *event);
char *luaT_travtagmethods (int (*fn)(TObject *)); void luaT_init (lua_State *L);
void luaT_realtag (lua_State *L, int tag);
int luaT_tag (const TObject *o);
int luaT_validevent (int t, int e); /* used by compatibility module */
void luaT_setfallback (void); /* only if LUA_COMPAT2_5 */
#endif #endif

323
lua.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lua.c,v 1.18 1999/01/26 11:50:58 roberto Exp roberto $ ** $Id: lua.c,v 1.54 2000/10/17 13:36:24 roberto Exp roberto $
** Lua stand-alone interpreter ** Lua stand-alone interpreter
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,30 +11,51 @@
#include <string.h> #include <string.h>
#include "lua.h" #include "lua.h"
#include "luadebug.h" #include "luadebug.h"
#include "lualib.h" #include "lualib.h"
#ifndef OLD_ANSI static lua_State *L = NULL;
#include <locale.h>
#else
#define setlocale(a,b) 0 #ifndef PROMPT
#define PROMPT "> "
#endif #endif
#ifdef _POSIX_SOURCE #ifdef _POSIX_SOURCE
#include <unistd.h> #include <unistd.h>
#else #else
#define isatty(x) (x==0) /* assume stdin is a tty */ static int isatty (int x) { return x==0; } /* assume stdin is a tty */
#endif #endif
/*
** global options
*/
struct Options {
int toclose;
int stacksize;
};
typedef void (*handler)(int); /* type for signal actions */ typedef void (*handler)(int); /* type for signal actions */
static void laction (int i); static void laction (int i);
static lua_LHFunction old_linehook = NULL; static lua_Hook old_linehook = NULL;
static lua_CHFunction old_callhook = NULL; static lua_Hook old_callhook = NULL;
static void userinit (void) {
lua_baselibopen(L);
lua_iolibopen(L);
lua_strlibopen(L);
lua_mathlibopen(L);
lua_dblibopen(L);
/* add your libraries here */
}
static handler lreset (void) { static handler lreset (void) {
@@ -43,64 +64,125 @@ static handler lreset (void) {
static void lstop (void) { static void lstop (void) {
lua_setlinehook(old_linehook); lua_setlinehook(L, old_linehook);
lua_setcallhook(old_callhook); lua_setcallhook(L, old_callhook);
lreset(); lreset();
lua_error("interrupted!"); lua_error(L, "interrupted!");
} }
static void laction (int i) { static void laction (int i) {
old_linehook = lua_setlinehook((lua_LHFunction)lstop); (void)i; /* to avoid warnings */
old_callhook = lua_setcallhook((lua_CHFunction)lstop); signal(SIGINT, SIG_DFL); /* if another SIGINT happens before lstop,
terminate process (default action) */
old_linehook = lua_setlinehook(L, (lua_Hook)lstop);
old_callhook = lua_setcallhook(L, (lua_Hook)lstop);
} }
static int ldo (int (*f)(char *), char *name) { static int ldo (int (*f)(lua_State *l, const char *), const char *name) {
int res; int res;
handler h = lreset(); handler h = lreset();
res = f(name); /* dostring | dofile */ int top = lua_gettop(L);
res = f(L, name); /* dostring | dofile */
lua_settop(L, top); /* remove eventual results */
signal(SIGINT, h); /* restore old action */ signal(SIGINT, h); /* restore old action */
/* Lua gives no message in such cases, so lua.c provides one */
if (res == LUA_ERRMEM) {
fprintf(stderr, "lua: memory allocation error\n");
}
else if (res == LUA_ERRERR)
fprintf(stderr, "lua: error in error message\n");
return res; return res;
} }
static void print_message (void) { static void print_message (void) {
fprintf(stderr, fprintf(stderr,
"Lua: command line options:\n" "usage: lua [options]. Available options are:\n"
" -v print version information\n" " - execute stdin as a file\n"
" -d turn debug on\n" " -c close Lua when exiting\n"
" -e stat dostring `stat'\n" " -e stat execute string `stat'\n"
" -q interactive mode without prompt\n" " -f name execute file `name' with remaining arguments in table `arg'\n"
" -i interactive mode with prompt\n" " -i enter interactive mode with prompt\n"
" - executes stdin as a file\n" " -q enter interactive mode without prompt\n"
" a=b sets global `a' with string `b'\n" " -sNUM set stack size to NUM (must be the first option)\n"
" name dofile `name'\n\n"); " -v print version information\n"
" a=b set global `a' to string `b'\n"
" name execute file `name'\n"
);
}
static void print_version (void) {
printf("%.80s %.80s\n", LUA_VERSION, LUA_COPYRIGHT);
} }
static void assign (char *arg) { static void assign (char *arg) {
if (strlen(arg) >= 500) char *eq = strchr(arg, '=');
fprintf(stderr, "lua: shell argument too long"); *eq = '\0'; /* spilt `arg' in two strings (name & value) */
else { lua_pushstring(L, eq+1);
char buffer[500]; lua_setglobal(L, arg);
char *eq = strchr(arg, '=');
lua_pushstring(eq+1);
strncpy(buffer, arg, eq-arg);
buffer[eq-arg] = 0;
lua_setglobal(buffer);
}
} }
static void manual_input (int prompt) { static void getargs (char *argv[]) {
int i;
lua_newtable(L);
for (i=0; argv[i]; i++) {
/* arg[i] = argv[i] */
lua_pushnumber(L, i);
lua_pushstring(L, argv[i]);
lua_settable(L, -3);
}
/* arg.n = maximum index in table `arg' */
lua_pushstring(L, "n");
lua_pushnumber(L, i-1);
lua_settable(L, -3);
}
static int l_getargs (lua_State *l) {
char **argv = (char **)lua_touserdata(l, -1);
getargs(argv);
return 1;
}
static int file_input (const char *argv) {
int result = ldo(lua_dofile, argv);
if (result) {
if (result == LUA_ERRFILE) {
fprintf(stderr, "lua: cannot execute file ");
perror(argv);
}
return EXIT_FAILURE;
}
else
return EXIT_SUCCESS;
}
/* maximum length of an input string */
#ifndef MAXINPUT
#define MAXINPUT BUFSIZ
#endif
static void manual_input (int version, int prompt) {
int cont = 1; int cont = 1;
if (version) print_version();
while (cont) { while (cont) {
char buffer[BUFSIZ]; char buffer[MAXINPUT];
int i = 0; int i = 0;
lua_beginblock(); if (prompt) {
if (prompt) const char *s;
printf("%s", lua_getstring(lua_getglobal("_PROMPT"))); lua_getglobal(L, "_PROMPT");
s = lua_tostring(L, -1);
if (!s) s = PROMPT;
fputs(s, stdout);
lua_pop(L, 1); /* remove global */
}
for(;;) { for(;;) {
int c = getchar(); int c = getchar();
if (c == EOF) { if (c == EOF) {
@@ -112,82 +194,129 @@ static void manual_input (int prompt) {
buffer[i-1] = '\n'; buffer[i-1] = '\n';
else break; else break;
} }
else if (i >= BUFSIZ-1) { else if (i >= MAXINPUT-1) {
fprintf(stderr, "lua: argument line too long\n"); fprintf(stderr, "lua: input line too long\n");
break; break;
} }
else buffer[i++] = (char)c; else buffer[i++] = (char)c;
} }
buffer[i] = '\0'; buffer[i] = '\0';
ldo(lua_dostring, buffer); ldo(lua_dostring, buffer);
lua_endblock(); lua_settop(L, 0); /* remove eventual results */
} }
printf("\n"); printf("\n");
} }
int main (int argc, char *argv[]) static int handle_argv (char *argv[], struct Options *opt) {
{ if (opt->stacksize > 0) argv++; /* skip option `-s' (if present) */
int i; if (*argv == NULL) { /* no more arguments? */
lua_open();
lua_pushstring("> "); lua_setglobal("_PROMPT");
setlocale(LC_ALL, "");
lua_userinit();
if (argc < 2) { /* no arguments? */
if (isatty(0)) { if (isatty(0)) {
printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT); manual_input(1, 1);
manual_input(1);
} }
else else
ldo(lua_dofile, NULL); /* executes stdin as a file */ ldo(lua_dofile, NULL); /* executes stdin as a file */
} }
else for (i=1; i<argc; i++) { else { /* other arguments; loop over them */
if (argv[i][0] == '-') { /* option? */ int i;
switch (argv[i][1]) { for (i = 0; argv[i] != NULL; i++) {
case 0: if (argv[i][0] != '-') { /* not an option? */
ldo(lua_dofile, NULL); /* executes stdin as a file */ if (strchr(argv[i], '='))
break; assign(argv[i]);
case 'i': else
manual_input(1); if (file_input(argv[i]) != EXIT_SUCCESS)
break; return EXIT_FAILURE; /* stop if file fails */
case 'q': }
manual_input(0); else switch (argv[i][1]) { /* option */
break; case 0: {
case 'd': ldo(lua_dofile, NULL); /* executes stdin as a file */
lua_setdebug(1); break;
break; }
case 'v': case 'i': {
printf("%s %s\n(written by %s)\n\n", manual_input(0, 1);
LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS); break;
break; }
case 'e': case 'q': {
i++; manual_input(0, 0);
if (ldo(lua_dostring, argv[i]) != 0) { break;
fprintf(stderr, "lua: error running argument `%s'\n", argv[i]); }
return 1; case 'c': {
} opt->toclose = 1;
break; break;
default: }
print_message(); case 'v': {
exit(1); print_version();
} break;
} }
else if (strchr(argv[i], '=')) case 'e': {
assign(argv[i]); i++;
else { if (argv[i] == NULL) {
int result = ldo(lua_dofile, argv[i]); print_message();
if (result) { return EXIT_FAILURE;
if (result == 2) { }
fprintf(stderr, "lua: cannot execute file "); if (ldo(lua_dostring, argv[i]) != 0) {
perror(argv[i]); fprintf(stderr, "lua: error running argument `%.99s'\n", argv[i]);
return EXIT_FAILURE;
}
break;
}
case 'f': {
i++;
if (argv[i] == NULL) {
print_message();
return EXIT_FAILURE;
}
getargs(argv+i); /* collect remaining arguments */
lua_setglobal(L, "arg");
return file_input(argv[i]); /* stop scanning arguments */
}
case 's': {
fprintf(stderr, "lua: stack size (`-s') must be the first option\n");
return EXIT_FAILURE;
}
default: {
print_message();
return EXIT_FAILURE;
}
} }
exit(1);
}
} }
} }
#ifdef DEBUG return EXIT_SUCCESS;
lua_close(); }
#endif
return 0;
static void getstacksize (int argc, char *argv[], struct Options *opt) {
if (argc >= 2 && argv[1][0] == '-' && argv[1][1] == 's') {
int stacksize = atoi(&argv[1][2]);
if (stacksize <= 0) {
fprintf(stderr, "lua: invalid stack size ('%.20s')\n", &argv[1][2]);
exit(EXIT_FAILURE);
}
opt->stacksize = stacksize;
}
else
opt->stacksize = 0; /* no stack size */
}
static void register_getargs (char *argv[]) {
lua_pushuserdata(L, argv);
lua_pushcclosure(L, l_getargs, 1);
lua_setglobal(L, "getargs");
}
int main (int argc, char *argv[]) {
struct Options opt;
int status;
opt.toclose = 0;
getstacksize(argc, argv, &opt); /* handle option `-s' */
L = lua_open(opt.stacksize); /* create state */
userinit(); /* open libraries */
register_getargs(argv); /* create `getargs' function */
status = handle_argv(argv+1, &opt);
if (opt.toclose)
lua_close(L);
return status;
} }

285
lua.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lua.h,v 1.30 1999/02/25 19:13:56 roberto Exp roberto $ ** $Id: lua.h,v 1.78 2000/10/30 12:38:50 roberto Exp roberto $
** Lua - An Extensible Extension Language ** Lua - An Extensible Extension Language
** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil ** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil
** e-mail: lua@tecgraf.puc-rio.br ** e-mail: lua@tecgraf.puc-rio.br
@@ -11,154 +11,208 @@
#ifndef lua_h #ifndef lua_h
#define lua_h #define lua_h
#define LUA_VERSION "Lua 3.2 (beta)"
#define LUA_COPYRIGHT "Copyright (C) 1994-1999 TeCGraf, PUC-Rio" /* definition of `size_t' */
#include <stddef.h>
/* mark for all API functions */
#ifndef LUA_API
#define LUA_API extern
#endif
#define LUA_VERSION "Lua 4.0"
#define LUA_COPYRIGHT "Copyright (C) 1994-2000 TeCGraf, PUC-Rio"
#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo" #define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
#define LUA_NOOBJECT 0 /* name of global variable with error handler */
#define LUA_ERRORMESSAGE "_ERRORMESSAGE"
/* pre-defined references */
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
#define LUA_REFREGISTRY 0
/* pre-defined tags */
#define LUA_ANYTAG (-1)
#define LUA_NOTAG (-2)
/* option for multiple returns in lua_call */
#define LUA_MULTRET (-1)
/* minimum stack available for a C function */
#define LUA_MINSTACK 20
/* error codes for lua_do* */
#define LUA_ERRRUN 1
#define LUA_ERRFILE 2
#define LUA_ERRSYNTAX 3
#define LUA_ERRMEM 4
#define LUA_ERRERR 5
#define LUA_ANYTAG (-1)
typedef struct lua_State lua_State; typedef struct lua_State lua_State;
extern lua_State *lua_state;
typedef void (*lua_CFunction) (void); typedef int (*lua_CFunction) (lua_State *L);
typedef unsigned int lua_Object;
void lua_open (void); /*
void lua_close (void); ** types returned by `lua_type'
lua_State *lua_setstate (lua_State *st); */
#define LUA_TNONE (-1)
lua_Object lua_settagmethod (int tag, char *event); /* In: new method */ #define LUA_TUSERDATA 0
lua_Object lua_gettagmethod (int tag, char *event); #define LUA_TNIL 1
#define LUA_TNUMBER 2
int lua_newtag (void); #define LUA_TSTRING 3
int lua_copytagmethods (int tagto, int tagfrom); #define LUA_TTABLE 4
void lua_settag (int tag); /* In: object */ #define LUA_TFUNCTION 5
void lua_error (char *s);
int lua_dofile (char *filename); /* Out: returns */
int lua_dostring (char *string); /* Out: returns */
int lua_dobuffer (char *buff, int size, char *name);
/* Out: returns */
int lua_callfunction (lua_Object f);
/* In: parameters; Out: returns */
void lua_beginblock (void);
void lua_endblock (void);
lua_Object lua_lua2C (int number);
#define lua_getparam(_) lua_lua2C(_)
#define lua_getresult(_) lua_lua2C(_)
int lua_isnil (lua_Object object);
int lua_istable (lua_Object object);
int lua_isuserdata (lua_Object object);
int lua_iscfunction (lua_Object object);
int lua_isnumber (lua_Object object);
int lua_isstring (lua_Object object);
int lua_isfunction (lua_Object object);
double lua_getnumber (lua_Object object);
char *lua_getstring (lua_Object object);
long lua_strlen (lua_Object object);
lua_CFunction lua_getcfunction (lua_Object object);
void *lua_getuserdata (lua_Object object);
void lua_pushnil (void);
void lua_pushnumber (double n);
void lua_pushlstring (char *s, long len);
void lua_pushstring (char *s);
void lua_pushcclosure (lua_CFunction fn, int n);
void lua_pushusertag (void *u, int tag);
void lua_pushobject (lua_Object object);
lua_Object lua_pop (void); /*
** state manipulation
lua_Object lua_getglobal (char *name); */
lua_Object lua_rawgetglobal (char *name); LUA_API lua_State *lua_open (int stacksize);
void lua_setglobal (char *name); /* In: value */ LUA_API void lua_close (lua_State *L);
void lua_rawsetglobal (char *name); /* In: value */
void lua_settable (void); /* In: table, index, value */
void lua_rawsettable (void); /* In: table, index, value */
lua_Object lua_gettable (void); /* In: table, index */
lua_Object lua_rawgettable (void); /* In: table, index */
int lua_tag (lua_Object object);
char *lua_nextvar (char *varname); /* Out: value */
int lua_next (lua_Object o, int i);
/* Out: ref, value */
int lua_ref (int lock); /* In: value */
lua_Object lua_getref (int ref);
void lua_unref (int ref);
lua_Object lua_createtable (void);
long lua_collectgarbage (long limit);
/* =============================================================== */ /*
/* some useful macros/functions */ ** basic stack manipulation
*/
LUA_API int lua_gettop (lua_State *L);
LUA_API void lua_settop (lua_State *L, int index);
LUA_API void lua_pushvalue (lua_State *L, int index);
LUA_API void lua_remove (lua_State *L, int index);
LUA_API void lua_insert (lua_State *L, int index);
LUA_API int lua_stackspace (lua_State *L);
#define lua_call(name) lua_callfunction(lua_getglobal(name))
#define lua_pushref(ref) lua_pushobject(lua_getref(ref)) /*
** access functions (stack -> C)
#define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
#define lua_pushuserdata(u) lua_pushusertag(u, 0)
#define lua_pushcfunction(f) lua_pushcclosure(f, 0)
#define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))
lua_Object lua_seterrormethod (void); /* In: new method */
/* ==========================================================================
** for compatibility with old versions. Avoid using these macros/functions
** If your program does need any of these, define LUA_COMPAT2_5
*/ */
LUA_API int lua_type (lua_State *L, int index);
LUA_API const char *lua_typename (lua_State *L, int t);
LUA_API int lua_isnumber (lua_State *L, int index);
LUA_API int lua_isstring (lua_State *L, int index);
LUA_API int lua_iscfunction (lua_State *L, int index);
LUA_API int lua_tag (lua_State *L, int index);
#ifdef LUA_COMPAT2_5 LUA_API int lua_equal (lua_State *L, int index1, int index2);
LUA_API int lua_lessthan (lua_State *L, int index1, int index2);
LUA_API double lua_tonumber (lua_State *L, int index);
LUA_API const char *lua_tostring (lua_State *L, int index);
LUA_API size_t lua_strlen (lua_State *L, int index);
LUA_API lua_CFunction lua_tocfunction (lua_State *L, int index);
LUA_API void *lua_touserdata (lua_State *L, int index);
LUA_API const void *lua_topointer (lua_State *L, int index);
lua_Object lua_setfallback (char *event, lua_CFunction fallback); /*
** push functions (C -> stack)
*/
LUA_API void lua_pushnil (lua_State *L);
LUA_API void lua_pushnumber (lua_State *L, double n);
LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len);
LUA_API void lua_pushstring (lua_State *L, const char *s);
LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
LUA_API void lua_pushusertag (lua_State *L, void *u, int tag);
#define lua_storeglobal lua_setglobal
#define lua_type lua_tag
#define lua_lockobject(o) lua_refobject(o,1) /*
#define lua_lock() lua_ref(1) ** get functions (Lua -> stack)
#define lua_getlocked lua_getref */
#define lua_pushlocked lua_pushref LUA_API void lua_getglobal (lua_State *L, const char *name);
#define lua_unlock lua_unref LUA_API void lua_gettable (lua_State *L, int index);
LUA_API void lua_rawget (lua_State *L, int index);
LUA_API void lua_rawgeti (lua_State *L, int index, int n);
LUA_API void lua_getglobals (lua_State *L);
LUA_API void lua_gettagmethod (lua_State *L, int tag, const char *event);
LUA_API int lua_getref (lua_State *L, int ref);
LUA_API void lua_newtable (lua_State *L);
#define lua_pushliteral(o) lua_pushstring(o)
#define lua_getindexed(o,n) (lua_pushobject(o), lua_pushnumber(n), lua_gettable()) /*
#define lua_getfield(o,f) (lua_pushobject(o), lua_pushstring(f), lua_gettable()) ** set functions (stack -> Lua)
*/
LUA_API void lua_setglobal (lua_State *L, const char *name);
LUA_API void lua_settable (lua_State *L, int index);
LUA_API void lua_rawset (lua_State *L, int index);
LUA_API void lua_rawseti (lua_State *L, int index, int n);
LUA_API void lua_setglobals (lua_State *L);
LUA_API void lua_settagmethod (lua_State *L, int tag, const char *event);
LUA_API int lua_ref (lua_State *L, int lock);
#define lua_copystring(o) (strdup(lua_getstring(o)))
#define lua_getsubscript lua_gettable /*
#define lua_storesubscript lua_settable ** "do" functions (run Lua code)
*/
LUA_API int lua_call (lua_State *L, int nargs, int nresults);
LUA_API void lua_rawcall (lua_State *L, int nargs, int nresults);
LUA_API int lua_dofile (lua_State *L, const char *filename);
LUA_API int lua_dostring (lua_State *L, const char *str);
LUA_API int lua_dobuffer (lua_State *L, const char *buff, size_t size, const char *name);
#endif /*
** Garbage-collection functions
*/
LUA_API int lua_getgcthreshold (lua_State *L);
LUA_API int lua_getgccount (lua_State *L);
LUA_API void lua_setgcthreshold (lua_State *L, int newthreshold);
/*
** miscellaneous functions
*/
LUA_API int lua_newtag (lua_State *L);
LUA_API int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
LUA_API void lua_settag (lua_State *L, int tag);
LUA_API void lua_error (lua_State *L, const char *s);
LUA_API void lua_unref (lua_State *L, int ref);
LUA_API int lua_next (lua_State *L, int index);
LUA_API int lua_getn (lua_State *L, int index);
LUA_API void lua_concat (lua_State *L, int n);
LUA_API void *lua_newuserdata (lua_State *L, size_t size);
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#define lua_pop(L,n) lua_settop(L, -(n)-1)
#define lua_register(L,n,f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
#define lua_pushuserdata(L,u) lua_pushusertag(L, u, 0)
#define lua_pushcfunction(L,f) lua_pushcclosure(L, f, 0)
#define lua_clonetag(L,t) lua_copytagmethods(L, lua_newtag(L), (t))
#define lua_isfunction(L,n) (lua_type(L,n) == LUA_TFUNCTION)
#define lua_istable(L,n) (lua_type(L,n) == LUA_TTABLE)
#define lua_isuserdata(L,n) (lua_type(L,n) == LUA_TUSERDATA)
#define lua_isnil(L,n) (lua_type(L,n) == LUA_TNIL)
#define lua_isnull(L,n) (lua_type(L,n) == LUA_TNONE)
#define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY)
#endif #endif
/****************************************************************************** /******************************************************************************
* Copyright (c) 1994-1999 TeCGraf, PUC-Rio. All rights reserved. * Copyright (C) 1994-2000 TeCGraf, PUC-Rio. All rights reserved.
* *
* Permission is hereby granted, without written agreement and without license * Permission is hereby granted, without written agreement and without license
* or royalty fees, to use, copy, modify, and distribute this software and its * or royalty fees, to use, copy, modify, and distribute this software and its
@@ -191,3 +245,4 @@ lua_Object lua_setfallback (char *event, lua_CFunction fallback);
* *
* This implementation contains no third-party code. * This implementation contains no third-party code.
******************************************************************************/ ******************************************************************************/

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: luadebug.h,v 1.5 1999/02/04 17:47:59 roberto Exp roberto $ ** $Id: luadebug.h,v 1.16 2000/10/20 16:39:03 roberto Exp roberto $
** Debugging API ** Debugging API
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -11,24 +11,36 @@
#include "lua.h" #include "lua.h"
typedef lua_Object lua_Function; typedef struct lua_Debug lua_Debug; /* activation record */
typedef struct lua_Localvar lua_Localvar;
typedef void (*lua_LHFunction) (int line); typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
lua_Function lua_stackedfunction (int level);
void lua_funcinfo (lua_Object func, char **source, int *linedefined);
int lua_currentline (lua_Function func);
char *lua_getobjname (lua_Object o, char **name);
lua_Object lua_getlocal (lua_Function func, int local_number, char **name); LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar);
int lua_setlocal (lua_Function func, int local_number); LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
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);
int lua_nups (lua_Function func); LUA_API lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
LUA_API lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
lua_LHFunction lua_setlinehook (lua_LHFunction func);
lua_CHFunction lua_setcallhook (lua_CHFunction func); #define LUA_IDSIZE 60
int lua_setdebug (int debug);
struct lua_Debug {
const char *event; /* `call', `return' */
int currentline; /* (l) */
const char *name; /* (n) */
const char *namewhat; /* (n) `global', `tag method', `local', `field' */
int nups; /* (u) number of upvalues */
int linedefined; /* (S) */
const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
const char *source; /* (S) */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */
struct lua_TObject *_func; /* active function */
};
#endif #endif

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lualib.h,v 1.4 1998/06/19 16:14:09 roberto Exp roberto $ ** $Id: lualib.h,v 1.13 2000/10/20 16:39:03 roberto Exp roberto $
** Lua standard libraries ** Lua standard libraries
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -10,26 +10,25 @@
#include "lua.h" #include "lua.h"
void lua_iolibopen (void);
void lua_strlibopen (void); #ifndef LUALIB_API
void lua_mathlibopen (void); #define LUALIB_API extern
void lua_dblibopen (void); #endif
void lua_userinit (void); #define LUA_ALERT "_ALERT"
LUALIB_API void lua_baselibopen (lua_State *L);
/* To keep compatibility with old versions */ LUALIB_API void lua_iolibopen (lua_State *L);
LUALIB_API void lua_strlibopen (lua_State *L);
#define iolib_open lua_iolibopen LUALIB_API void lua_mathlibopen (lua_State *L);
#define strlib_open lua_strlibopen LUALIB_API void lua_dblibopen (lua_State *L);
#define mathlib_open lua_mathlibopen
/* Auxiliary functions (private) */ /* Auxiliary functions (private) */
int luaI_singlematch (int c, char *p, char **ep); const char *luaI_classend (lua_State *L, const char *p);
int luaI_singlematch (int c, const char *p, const char *ep);
#endif #endif

312
lundump.c
View File

@@ -1,234 +1,244 @@
/* /*
** $Id: lundump.c,v 1.18 1999/04/09 03:10:40 lhf Exp lhf $ ** $Id: lundump.c,v 1.33 2000/10/31 16:57:23 lhf Exp $
** load bytecodes from files ** load bytecodes from files
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "lauxlib.h"
#include "lfunc.h" #include "lfunc.h"
#include "lmem.h" #include "lmem.h"
#include "lopcodes.h" #include "lopcodes.h"
#include "lstring.h" #include "lstring.h"
#include "lundump.h" #include "lundump.h"
#define LoadBlock(b,size,Z) ezread(Z,b,size) #define LoadByte ezgetc
#if LUAC_NATIVE static const char* ZNAME (ZIO* Z)
#define doLoadNumber(x,Z) LoadBlock(&x,sizeof(x),Z)
#else
#define doLoadNumber(x,Z) x=LoadNumber(Z)
#endif
static void unexpectedEOZ (ZIO* Z)
{ {
luaL_verror("unexpected end of file in %s",zname(Z)); const char* s=zname(Z);
return (*s=='@') ? s+1 : s;
} }
static int ezgetc (ZIO* Z) static void unexpectedEOZ (lua_State* L, ZIO* Z)
{
luaO_verror(L,"unexpected end of file in `%.99s'",ZNAME(Z));
}
static int ezgetc (lua_State* L, ZIO* Z)
{ {
int c=zgetc(Z); int c=zgetc(Z);
if (c==EOZ) unexpectedEOZ(Z); if (c==EOZ) unexpectedEOZ(L,Z);
return c; return c;
} }
static void ezread (ZIO* Z, void* b, int n) static void ezread (lua_State* L, ZIO* Z, void* b, int n)
{ {
int r=zread(Z,b,n); int r=zread(Z,b,n);
if (r!=0) unexpectedEOZ(Z); if (r!=0) unexpectedEOZ(L,Z);
} }
static unsigned int LoadWord (ZIO* Z) static void LoadBlock (lua_State* L, void* b, size_t size, ZIO* Z, int swap)
{ {
unsigned int hi=ezgetc(Z); if (swap)
unsigned int lo=ezgetc(Z); {
return (hi<<8)|lo; char *p=(char *) b+size-1;
} int n=size;
while (n--) *p--=(char)ezgetc(L,Z);
static unsigned long LoadLong (ZIO* Z) }
{
unsigned long hi=LoadWord(Z);
unsigned long lo=LoadWord(Z);
return (hi<<16)|lo;
}
static real LoadNumber (ZIO* Z)
{
char b[256];
int size=ezgetc(Z);
LoadBlock(b,size,Z);
b[size]=0;
if (b[0]=='-')
return -luaO_str2d(b+1);
else else
return luaO_str2d(b); ezread(L,Z,b,size);
} }
static int LoadInt (ZIO* Z, char* message) static void LoadVector (lua_State* L, void* b, int m, size_t size, ZIO* Z, int swap)
{ {
unsigned long l=LoadLong(Z); if (swap)
unsigned int i=l; {
if (i!=l) luaL_verror(message,l,zname(Z)); char *q=(char *) b;
return i; while (m--)
{
char *p=q+size-1;
int n=size;
while (n--) *p--=(char)ezgetc(L,Z);
q+=size;
}
}
else
ezread(L,Z,b,m*size);
} }
#define PAD 5 /* two word operands plus opcode */ static int LoadInt (lua_State* L, ZIO* Z, int swap)
static Byte* LoadCode (ZIO* Z)
{ {
int size=LoadInt(Z,"code too long (%ld bytes) in %s"); int x;
Byte* b=luaM_malloc(size+PAD); LoadBlock(L,&x,sizeof(x),Z,swap);
LoadBlock(b,size,Z); return x;
if (b[size-1]!=ENDCODE) luaL_verror("bad code in %s",zname(Z));
memset(b+size,ENDCODE,PAD); /* pad code for safety */
return b;
} }
static TaggedString* LoadTString (ZIO* Z) static size_t LoadSize (lua_State* L, ZIO* Z, int swap)
{ {
long size=LoadLong(Z); size_t x;
LoadBlock(L,&x,sizeof(x),Z,swap);
return x;
}
static Number LoadNumber (lua_State* L, ZIO* Z, int swap)
{
Number x;
LoadBlock(L,&x,sizeof(x),Z,swap);
return x;
}
static TString* LoadString (lua_State* L, ZIO* Z, int swap)
{
size_t size=LoadSize(L,Z,swap);
if (size==0) if (size==0)
return NULL; return NULL;
else else
{ {
char* s=luaL_openspace(size); char* s=luaO_openspace(L,size);
LoadBlock(s,size,Z); LoadBlock(L,s,size,Z,0);
return luaS_newlstr(s,size-1); return luaS_newlstr(L,s,size-1); /* remove trailing '\0' */
} }
} }
static void LoadLocals (TProtoFunc* tf, ZIO* Z) static void LoadCode (lua_State* L, Proto* tf, ZIO* Z, int swap)
{ {
int i,n=LoadInt(Z,"too many locals (%ld) in %s"); int size=LoadInt(L,Z,swap);
if (n==0) return; tf->code=luaM_newvector(L,size,Instruction);
tf->locvars=luaM_newvector(n+1,LocVar); LoadVector(L,tf->code,size,sizeof(*tf->code),Z,swap);
if (tf->code[size-1]!=OP_END) luaO_verror(L,"bad code in `%.99s'",ZNAME(Z));
luaF_protook(L,tf,size);
}
static void LoadLocals (lua_State* L, Proto* tf, ZIO* Z, int swap)
{
int i,n;
tf->nlocvars=n=LoadInt(L,Z,swap);
tf->locvars=luaM_newvector(L,n,LocVar);
for (i=0; i<n; i++) for (i=0; i<n; i++)
{ {
tf->locvars[i].line=LoadInt(Z,"too many lines (%ld) in %s"); tf->locvars[i].varname=LoadString(L,Z,swap);
tf->locvars[i].varname=LoadTString(Z); tf->locvars[i].startpc=LoadInt(L,Z,swap);
tf->locvars[i].endpc=LoadInt(L,Z,swap);
} }
tf->locvars[i].line=-1; /* flag end of vector */
tf->locvars[i].varname=NULL;
} }
static TProtoFunc* LoadFunction (ZIO* Z); static void LoadLines (lua_State* L, Proto* tf, ZIO* Z, int swap)
static void LoadConstants (TProtoFunc* tf, ZIO* Z)
{ {
int i,n=LoadInt(Z,"too many constants (%ld) in %s"); int n;
tf->nconsts=n; tf->nlineinfo=n=LoadInt(L,Z,swap);
if (n==0) return; tf->lineinfo=luaM_newvector(L,n,int);
tf->consts=luaM_newvector(n,TObject); LoadVector(L,tf->lineinfo,n,sizeof(*tf->lineinfo),Z,swap);
}
static Proto* LoadFunction (lua_State* L, ZIO* Z, int swap);
static void LoadConstants (lua_State* L, Proto* tf, ZIO* Z, int swap)
{
int i,n;
tf->nkstr=n=LoadInt(L,Z,swap);
tf->kstr=luaM_newvector(L,n,TString*);
for (i=0; i<n; i++) for (i=0; i<n; i++)
{ tf->kstr[i]=LoadString(L,Z,swap);
TObject* o=tf->consts+i; tf->nknum=n=LoadInt(L,Z,swap);
ttype(o)=-ezgetc(Z); /* ttype(o) is negative - ORDER LUA_T */ tf->knum=luaM_newvector(L,n,Number);
switch (ttype(o)) LoadVector(L,tf->knum,n,sizeof(*tf->knum),Z,swap);
{ tf->nkproto=n=LoadInt(L,Z,swap);
case LUA_T_NUMBER: tf->kproto=luaM_newvector(L,n,Proto*);
doLoadNumber(nvalue(o),Z); for (i=0; i<n; i++)
break; tf->kproto[i]=LoadFunction(L,Z,swap);
case LUA_T_STRING:
tsvalue(o)=LoadTString(Z);
break;
case LUA_T_PROTO:
tfvalue(o)=LoadFunction(Z);
break;
case LUA_T_NIL:
break;
default: /* cannot happen */
luaU_badconstant("load",i,o,tf);
break;
}
}
} }
static TProtoFunc* LoadFunction (ZIO* Z) static Proto* LoadFunction (lua_State* L, ZIO* Z, int swap)
{ {
TProtoFunc* tf=luaF_newproto(); Proto* tf=luaF_newproto(L);
tf->lineDefined=LoadInt(Z,"lineDefined too large (%ld) in %s"); tf->source=LoadString(L,Z,swap);
tf->source=LoadTString(Z); tf->lineDefined=LoadInt(L,Z,swap);
if (tf->source==NULL) tf->source=luaS_new(zname(Z)); tf->numparams=LoadInt(L,Z,swap);
tf->code=LoadCode(Z); tf->is_vararg=LoadByte(L,Z);
LoadLocals(tf,Z); tf->maxstacksize=LoadInt(L,Z,swap);
LoadConstants(tf,Z); LoadLocals(L,tf,Z,swap);
LoadLines(L,tf,Z,swap);
LoadConstants(L,tf,Z,swap);
LoadCode(L,tf,Z,swap);
return tf; return tf;
} }
static void LoadSignature (ZIO* Z) static void LoadSignature (lua_State* L, ZIO* Z)
{ {
char* s=SIGNATURE; const char* s=SIGNATURE;
while (*s!=0 && ezgetc(Z)==*s) while (*s!=0 && ezgetc(L,Z)==*s)
++s; ++s;
if (*s!=0) luaL_verror("bad signature in %s",zname(Z)); if (*s!=0) luaO_verror(L,"bad signature in `%.99s'",ZNAME(Z));
} }
static void LoadHeader (ZIO* Z) static void TestSize (lua_State* L, int s, const char* what, ZIO* Z)
{ {
int version,sizeofR; int r=ezgetc(L,Z);
LoadSignature(Z); if (r!=s)
version=ezgetc(Z); luaO_verror(L,"virtual machine mismatch in `%.99s':\n"
" %.20s is %d but read %d",ZNAME(Z),what,s,r);
}
#define TESTSIZE(s) TestSize(L,s,#s,Z)
#define V(v) v/16,v%16
static int LoadHeader (lua_State* L, ZIO* Z)
{
int version,swap;
Number f=0,tf=TEST_NUMBER;
LoadSignature(L,Z);
version=ezgetc(L,Z);
if (version>VERSION) if (version>VERSION)
luaL_verror( luaO_verror(L,"`%.99s' too new:\n"
"%s too new: version=0x%02x; expected at most 0x%02x", " read version %d.%d; expected at most %d.%d",
zname(Z),version,VERSION); ZNAME(Z),V(version),V(VERSION));
if (version<VERSION0) /* check last major change */ if (version<VERSION0) /* check last major change */
luaL_verror( luaO_verror(L,"`%.99s' too old:\n"
"%s too old: version=0x%02x; expected at least 0x%02x", " read version %d.%d; expected at least %d.%d",
zname(Z),version,VERSION0); ZNAME(Z),V(version),V(VERSION));
sizeofR=ezgetc(Z); /* test number representation */ swap=(luaU_endianess()!=ezgetc(L,Z)); /* need to swap bytes? */
#if LUAC_NATIVE TESTSIZE(sizeof(int));
if (sizeofR==0) TESTSIZE(sizeof(size_t));
luaL_verror("cannot read numbers in %s: " TESTSIZE(sizeof(Instruction));
"support for decimal format not enabled", TESTSIZE(SIZE_INSTRUCTION);
zname(Z)); TESTSIZE(SIZE_OP);
if (sizeofR!=sizeof(real)) TESTSIZE(SIZE_B);
luaL_verror("unknown number size in %s: read %d; expected %d", TESTSIZE(sizeof(Number));
zname(Z),sizeofR,sizeof(real)); f=LoadNumber(L,Z,swap);
else if ((long)f!=(long)tf) /* disregard errors in last bit of fraction */
{ luaO_verror(L,"unknown number format in `%.99s':\n"
real f=-TEST_NUMBER,tf=TEST_NUMBER; " read " NUMBER_FMT "; expected " NUMBER_FMT, ZNAME(Z),f,tf);
doLoadNumber(f,Z); return swap;
if (f!=tf)
luaL_verror("unknown number representation in %s: "
"read " NUMBER_FMT "; expected " NUMBER_FMT,
zname(Z),f,tf);
}
#else
if (sizeofR!=0)
luaL_verror("cannot read numbers in %s: "
"support for native format not enabled",
zname(Z));
#endif
} }
static TProtoFunc* LoadChunk (ZIO* Z) static Proto* LoadChunk (lua_State* L, ZIO* Z)
{ {
LoadHeader(Z); return LoadFunction(L,Z,LoadHeader(L,Z));
return LoadFunction(Z);
} }
/* /*
** load one chunk from a file or buffer ** load one chunk from a file or buffer
** return main if ok and NULL at EOF ** return main if ok and NULL at EOF
*/ */
TProtoFunc* luaU_undump1 (ZIO* Z) Proto* luaU_undump (lua_State* L, ZIO* Z)
{ {
Proto* tf=NULL;
int c=zgetc(Z); int c=zgetc(Z);
if (c==ID_CHUNK) if (c==ID_CHUNK)
return LoadChunk(Z); tf=LoadChunk(L,Z);
else if (c!=EOZ) c=zgetc(Z);
luaL_verror("%s is not a Lua binary file",zname(Z)); if (c!=EOZ)
return NULL; luaO_verror(L,"`%.99s' apparently contains more than one chunk",ZNAME(Z));
return tf;
} }
/* /*
* handle constants that cannot happen ** find byte order
*/ */
void luaU_badconstant (char* s, int i, TObject* o, TProtoFunc* tf) int luaU_endianess (void)
{ {
int t=ttype(o); int x=1;
char* name= (t>0 || t<LUA_T_LINE) ? "?" : luaO_typenames[-t]; return *(char*)&x;
luaL_verror("cannot %s constant #%d: type=%d [%s]" IN,s,i,t,name,INLOC);
} }

View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lundump.h,v 1.13 1999/03/29 16:16:18 lhf Exp lhf $ ** $Id: lundump.h,v 1.21 2000/10/31 16:57:23 lhf Exp $
** load pre-compiled Lua chunks ** load pre-compiled Lua chunks
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -10,39 +10,26 @@
#include "lobject.h" #include "lobject.h"
#include "lzio.h" #include "lzio.h"
TProtoFunc* luaU_undump1 (ZIO* Z); /* load one chunk */ /* load one chunk */
void luaU_badconstant (char* s, int i, TObject* o, TProtoFunc* tf); Proto* luaU_undump (lua_State* L, ZIO* Z);
/* handle cases that cannot happen */
/* find byte order */
int luaU_endianess (void);
/* definitions for headers of binary files */ /* definitions for headers of binary files */
#define VERSION 0x32 /* last format change was in 3.2 */ #define VERSION 0x40 /* last format change was in 4.0 */
#define VERSION0 0x32 /* last major change was in 3.2 */ #define VERSION0 0x40 /* last major change was in 4.0 */
#define ID_CHUNK 27 /* binary files start with ESC... */ #define ID_CHUNK 27 /* binary files start with ESC... */
#define SIGNATURE "Lua" /* ...followed by this signature */ #define SIGNATURE "Lua" /* ...followed by this signature */
/* formats for error messages */ /* formats for error messages */
#define SOURCE "<%s:%d>" #define SOURCE_FMT "<%d:%.99s>"
#define IN " in %p " SOURCE #define SOURCE tf->lineDefined,tf->source->str
#define INLOC tf,tf->source->str,tf->lineDefined #define IN_FMT " in %p " SOURCE_FMT
#define IN tf,SOURCE
/* format for numbers in listings and error messages */ /* a multiple of PI for testing native format */
#ifndef NUMBER_FMT
#define NUMBER_FMT "%.16g" /* LUA_NUMBER */
#endif
/* LUA_NUMBER
* by default, numbers are stored in precompiled chunks as decimal strings.
* this is completely portable and fast enough for most applications.
* if you want to use this default, do nothing.
* if you want additional speed at the expense of portability, move the line
* below out of this comment.
#define LUAC_NATIVE
*/
#ifdef LUAC_NATIVE
/* a multiple of PI for testing number representation */
/* multiplying by 1E8 gives non-trivial integer values */ /* multiplying by 1E8 gives non-trivial integer values */
#define TEST_NUMBER 3.14159265358979323846E8 #define TEST_NUMBER 3.14159265358979323846E8
#endif
#endif #endif

1086
lvm.c

File diff suppressed because it is too large Load Diff

28
lvm.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lvm.h,v 1.7 1998/12/30 17:26:49 roberto Exp roberto $ ** $Id: lvm.h,v 1.26 2000/09/05 19:33:32 roberto Exp roberto $
** Lua virtual machine ** Lua virtual machine
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -13,22 +13,20 @@
#include "ltm.h" #include "ltm.h"
#define tonumber(o) ((ttype(o) != LUA_T_NUMBER) && (luaV_tonumber(o) != 0)) #define tonumber(o) ((ttype(o) != LUA_TNUMBER) && (luaV_tonumber(o) != 0))
#define tostring(o) ((ttype(o) != LUA_T_STRING) && (luaV_tostring(o) != 0)) #define tostring(L,o) ((ttype(o) != LUA_TSTRING) && (luaV_tostring(L, o) != 0))
void luaV_pack (StkId firstel, int nvararg, TObject *tab);
int luaV_tonumber (TObject *obj); int luaV_tonumber (TObject *obj);
int luaV_tostring (TObject *obj); int luaV_tostring (lua_State *L, TObject *obj);
void luaV_setn (Hash *t, int val); const TObject *luaV_gettable (lua_State *L, StkId t);
void luaV_gettable (void); void luaV_settable (lua_State *L, StkId t, StkId key);
void luaV_settable (TObject *t); const TObject *luaV_getglobal (lua_State *L, TString *s);
void luaV_rawsettable (TObject *t); void luaV_setglobal (lua_State *L, TString *s);
void luaV_getglobal (TaggedString *ts); StkId luaV_execute (lua_State *L, const Closure *cl, StkId base);
void luaV_setglobal (TaggedString *ts); void luaV_Cclosure (lua_State *L, lua_CFunction c, int nelems);
StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base); void luaV_Lclosure (lua_State *L, Proto *l, int nelems);
void luaV_closure (int nelems); int luaV_lessthan (lua_State *L, const TObject *l, const TObject *r, StkId top);
void luaV_comparison (lua_Type ttype_less, lua_Type ttype_equal, void luaV_strconc (lua_State *L, int total, StkId top);
lua_Type ttype_great, IMS op);
#endif #endif

68
lzio.c
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lzio.c,v 1.6 1999/03/04 14:49:18 roberto Exp roberto $ ** $Id: lzio.c,v 1.12 2000/05/24 13:54:49 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
*/ */
@@ -9,6 +9,8 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "lua.h"
#include "lzio.h" #include "lzio.h"
@@ -16,62 +18,60 @@
/* ----------------------------------------------------- memory buffers --- */ /* ----------------------------------------------------- memory buffers --- */
static int zmfilbuf (ZIO* z) { static int zmfilbuf (ZIO* z) {
return EOZ; (void)z; /* to avoid warnings */
return EOZ;
} }
ZIO* zmopen (ZIO* z, char* b, int size, char *name) ZIO* zmopen (ZIO* z, const char* b, size_t size, const char *name) {
{ if (b==NULL) return NULL;
if (b==NULL) return NULL; z->n = size;
z->n=size; z->p = (const unsigned char *)b;
z->p= (unsigned char *)b; z->filbuf = zmfilbuf;
z->filbuf=zmfilbuf; z->u = NULL;
z->u=NULL; z->name = name;
z->name=name; return z;
return z;
} }
/* ------------------------------------------------------------ strings --- */ /* ------------------------------------------------------------ strings --- */
ZIO* zsopen (ZIO* z, char* s, char *name) ZIO* zsopen (ZIO* z, const char* s, const char *name) {
{ if (s==NULL) return NULL;
if (s==NULL) return NULL; return zmopen(z, s, strlen(s), name);
return zmopen(z,s,strlen(s),name);
} }
/* -------------------------------------------------------------- FILEs --- */ /* -------------------------------------------------------------- FILEs --- */
static int zffilbuf (ZIO* z) { static int zffilbuf (ZIO* z) {
int n; size_t n;
if (feof((FILE *)z->u)) return EOZ; if (feof((FILE *)z->u)) return EOZ;
n=fread(z->buffer,1,ZBSIZE,z->u); n = fread(z->buffer, 1, ZBSIZE, (FILE *)z->u);
if (n==0) return EOZ; if (n==0) return EOZ;
z->n=n-1; z->n = n-1;
z->p=z->buffer; z->p = z->buffer;
return *(z->p++); return *(z->p++);
} }
ZIO* zFopen (ZIO* z, FILE* f, char *name) ZIO* zFopen (ZIO* z, FILE* f, const char *name) {
{ if (f==NULL) return NULL;
if (f==NULL) return NULL; z->n = 0;
z->n=0; z->p = z->buffer;
z->p=z->buffer; z->filbuf = zffilbuf;
z->filbuf=zffilbuf; z->u = f;
z->u=f; z->name = name;
z->name=name; return z;
return z;
} }
/* --------------------------------------------------------------- read --- */ /* --------------------------------------------------------------- read --- */
int zread (ZIO *z, void *b, int n) { size_t zread (ZIO *z, void *b, size_t n) {
while (n) { while (n) {
int m; size_t m;
if (z->n == 0) { if (z->n == 0) {
if (z->filbuf(z) == EOZ) if (z->filbuf(z) == EOZ)
return n; /* return number of missing bytes */ return n; /* return number of missing bytes */
zungetc(z); /* put result from 'filbuf' in the buffer */ zungetc(z); /* put result from `filbuf' in the buffer */
} }
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);

27
lzio.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: lzio.h,v 1.3 1997/12/22 20:57:18 roberto Exp roberto $ ** $Id: lzio.h,v 1.6 2000/05/24 13:54:49 roberto Exp roberto $
** Buffered streams ** Buffered streams
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@@ -22,28 +22,31 @@
typedef struct zio ZIO; typedef struct zio ZIO;
ZIO* zFopen (ZIO* z, FILE* f, char *name); /* open FILEs */ ZIO* zFopen (ZIO* z, FILE* f, const char *name); /* open FILEs */
ZIO* zsopen (ZIO* z, char* s, char *name); /* string */ ZIO* zsopen (ZIO* z, const char* s, const char *name); /* string */
ZIO* zmopen (ZIO* z, char* b, int size, char *name); /* memory */ ZIO* zmopen (ZIO* z, const char* b, size_t size, const char *name); /* memory */
int zread (ZIO* z, void* b, int n); /* read next n bytes */ size_t zread (ZIO* z, void* b, size_t n); /* read next n bytes */
#define zgetc(z) (--(z)->n>=0 ? ((int)*(z)->p++): (z)->filbuf(z)) #define zgetc(z) (((z)->n--)>0 ? ((int)*(z)->p++): (z)->filbuf(z))
#define zungetc(z) (++(z)->n,--(z)->p) #define zungetc(z) (++(z)->n,--(z)->p)
#define zname(z) ((z)->name) #define zname(z) ((z)->name)
/* --------- Private Part ------------------ */ /* --------- Private Part ------------------ */
#ifndef ZBSIZE
#define ZBSIZE 256 /* buffer size */ #define ZBSIZE 256 /* buffer size */
#endif
struct zio { struct zio {
int n; /* bytes still unread */ size_t n; /* bytes still unread */
unsigned char* p; /* current position in buffer */ const unsigned char* p; /* current position in buffer */
int (*filbuf)(ZIO* z); int (*filbuf)(ZIO* z);
void* u; /* additional data */ void* u; /* additional data */
char *name; const char *name;
unsigned char buffer[ZBSIZE]; /* buffer */ unsigned char buffer[ZBSIZE]; /* buffer */
}; };

140
makefile
View File

@@ -1,5 +1,5 @@
# #
## $Id: makefile,v 1.18 1999/02/23 15:01:29 roberto Exp roberto $ ## $Id: makefile,v 1.29 2000/10/30 17:50:00 roberto Exp roberto $
## Makefile ## Makefile
## See Copyright Notice in lua.h ## See Copyright Notice in lua.h
# #
@@ -15,20 +15,34 @@
# facilities (e.g. strerror, locale.h, memmove). SunOS does not comply; # facilities (e.g. strerror, locale.h, memmove). SunOS does not comply;
# so, add "-DOLD_ANSI" on SunOS # so, add "-DOLD_ANSI" on SunOS
# #
# define LUA_COMPAT2_5 if yous system does need to be compatible with
# version 2.5 (or older)
#
# define LUA_NUM_TYPE if you need numbers to be different from double # define LUA_NUM_TYPE if you need numbers to be different from double
# (for instance, -DLUA_NUM_TYPE=float) # (for instance, -DLUA_NUM_TYPE=float)
# you may need to adapat the code, too.
# #
# define LUA_COMPAT_READPATTERN if you need read patterns
# (only for compatibility with previous versions)
# define LUA_COMPAT_ARGRET for compatibility in the way function results
# are passed as arguments
# define LUA_DEPRECATEDFUNCS to include obsolete functions
CONFIG = -DPOPEN -D_POSIX_SOURCE CONFIG = -DPOPEN -D_POSIX_SOURCE
#CONFIG = -DLUA_COMPAT2_5 -DOLD_ANSI -DDEBUG #CONFIG = -DOLD_ANSI -DLUA_DEBUG -DLUA_COMPAT_READPATTERN -DLUA_COMPAT_ARGRET
# -DLUA_DEPRECATEDFUNCS
# Compilation parameters # Compilation parameters
CC = gcc CC = gcc
CWARNS = -Wall -Wmissing-prototypes -Wshadow -pedantic -Wpointer-arith -Wcast-align -Waggregate-return CWARNS = -Wall -W -pedantic \
-Waggregate-return \
-Wcast-align \
-Wmissing-prototypes \
-Wnested-externs \
-Wpointer-arith \
-Wshadow \
-Wwrite-strings
# -Wcast-qual
# -Wtraditional
CFLAGS = $(CONFIG) $(CWARNS) -ansi -O2 CFLAGS = $(CONFIG) $(CWARNS) -ansi -O2
@@ -42,31 +56,32 @@ ARFLAGS = rvl
# Aplication modules # Aplication modules
LUAOBJS = \ LUAOBJS = \
lapi.o \
lauxlib.o \
lbuffer.o \
lbuiltin.o \
ldo.o \
lfunc.o \
lgc.o \
llex.o \
lmem.o \
lobject.o \
lparser.o \
lstate.o \ lstate.o \
lapi.o \
lmem.o \
lstring.o \ lstring.o \
ltable.o \ ltable.o \
ltm.o \ ltm.o \
lvm.o \ lvm.o \
ldo.o \
lobject.o \
lfunc.o \
lgc.o \
lcode.o \
lparser.o \
llex.o \
lundump.o \ lundump.o \
lzio.o lzio.o \
ldebug.o \
ltests.o
LIBOBJS = \ LIBOBJS = \
lauxlib.o \
lbaselib.o \
liolib.o \ liolib.o \
lmathlib.o \ lmathlib.o \
lstrlib.o \ lstrlib.o \
ldblib.o \ ldblib.o
linit.o
lua : lua.o liblua.a liblualib.a lua : lua.o liblua.a liblualib.a
@@ -86,9 +101,7 @@ liblua.so.1.0 : lua.o
clear : clear :
rcsclean rcsclean
rm -f *.o rm -f *.o *.a
rm -f
co $(CO_OPTIONS) lua.h lualib.h luadebug.h
%.h : RCS/%.h,v %.h : RCS/%.h,v
@@ -98,43 +111,50 @@ clear :
co $(CO_OPTIONS) $@ co $(CO_OPTIONS) $@
lapi.o: lapi.c lapi.h lua.h lobject.h lauxlib.h ldo.h lstate.h \ lapi.o: lapi.c lua.h lapi.h lobject.h llimits.h ldo.h lstate.h \
luadebug.h lfunc.h lgc.h lmem.h lstring.h ltable.h ltm.h lvm.h luadebug.h lfunc.h lgc.h lmem.h lstring.h ltable.h ltm.h lvm.h
lauxlib.o: lauxlib.c lauxlib.h lua.h luadebug.h lauxlib.o: lauxlib.c lua.h lauxlib.h luadebug.h
lbuffer.o: lbuffer.c lauxlib.h lua.h lmem.h lstate.h lobject.h \ lbaselib.o: lbaselib.c lua.h lauxlib.h luadebug.h lualib.h
lcode.o: lcode.c /usr/include/stdlib.h lua.h lcode.h llex.h lobject.h \
llimits.h lzio.h lopcodes.h lparser.h ldo.h lstate.h luadebug.h \
lmem.h
ldblib.o: ldblib.c lua.h lauxlib.h luadebug.h lualib.h
ldebug.o: ldebug.c lua.h lapi.h lobject.h llimits.h lcode.h llex.h \
lzio.h lopcodes.h lparser.h ldebug.h lstate.h luadebug.h ldo.h \
lfunc.h lstring.h ltable.h ltm.h
ldo.o: ldo.c lua.h ldebug.h lstate.h lobject.h llimits.h luadebug.h \
ldo.h lgc.h lmem.h lparser.h lzio.h lstring.h ltable.h ltm.h \
lundump.h lvm.h
lfunc.o: lfunc.c lua.h lfunc.h lobject.h llimits.h lmem.h lstate.h \
luadebug.h luadebug.h
lbuiltin.o: lbuiltin.c lapi.h lua.h lobject.h lauxlib.h lbuiltin.h \ lgc.o: lgc.c lua.h ldo.h lobject.h llimits.h lstate.h luadebug.h \
ldo.h lstate.h luadebug.h lfunc.h lmem.h lstring.h ltable.h ltm.h \ lfunc.h lgc.h lmem.h lstring.h ltable.h ltm.h
lundump.h lzio.h lvm.h liolib.o: liolib.c lua.h lauxlib.h luadebug.h lualib.h
ldblib.o: ldblib.c lauxlib.h lua.h luadebug.h lualib.h llex.o: llex.c lua.h llex.h lobject.h llimits.h lzio.h lmem.h \
ldo.o: ldo.c ldo.h lobject.h lua.h lstate.h luadebug.h lfunc.h lgc.h \ lparser.h lstate.h luadebug.h lstring.h ltable.h
lmem.h lparser.h lzio.h lstring.h ltm.h lundump.h lvm.h lmathlib.o: lmathlib.c lua.h lauxlib.h lualib.h
lfunc.o: lfunc.c lfunc.h lobject.h lua.h lmem.h lstate.h luadebug.h lmem.o: lmem.c lua.h ldo.h lobject.h llimits.h lstate.h luadebug.h \
lgc.o: lgc.c ldo.h lobject.h lua.h lstate.h luadebug.h lfunc.h lgc.h \ lmem.h
lmem.h lstring.h ltable.h ltm.h lobject.o: lobject.c lua.h lmem.h llimits.h lobject.h lstate.h \
linit.o: linit.c lua.h lualib.h luadebug.h
liolib.o: liolib.c lauxlib.h lua.h luadebug.h lualib.h lparser.o: lparser.c lua.h lcode.h llex.h lobject.h llimits.h lzio.h \
llex.o: llex.c lauxlib.h lua.h llex.h lobject.h lzio.h lmem.h \ lopcodes.h lparser.h lfunc.h lmem.h lstate.h luadebug.h lstring.h
lparser.h lstate.h luadebug.h lstring.h lstate.o: lstate.c lua.h ldo.h lobject.h llimits.h lstate.h luadebug.h \
lmathlib.o: lmathlib.c lauxlib.h lua.h lualib.h lgc.h llex.h lzio.h lmem.h lstring.h ltable.h ltm.h
lmem.o: lmem.c lmem.h lstate.h lobject.h lua.h luadebug.h lstring.o: lstring.c lua.h lmem.h llimits.h lobject.h lstate.h \
lobject.o: lobject.c lobject.h lua.h luadebug.h lstring.h
lparser.o: lparser.c lauxlib.h lua.h ldo.h lobject.h lstate.h \ lstrlib.o: lstrlib.c lua.h lauxlib.h lualib.h
luadebug.h lfunc.h llex.h lzio.h lmem.h lopcodes.h lparser.h \ ltable.o: ltable.c lua.h lmem.h llimits.h lobject.h lstate.h \
lstring.h luadebug.h lstring.h ltable.h
lstate.o: lstate.c lbuiltin.h ldo.h lobject.h lua.h lstate.h \ ltests.o: ltests.c lua.h lapi.h lobject.h llimits.h lauxlib.h lcode.h \
luadebug.h lfunc.h lgc.h llex.h lzio.h lmem.h lstring.h ltable.h \ llex.h lzio.h lopcodes.h lparser.h ldebug.h lstate.h luadebug.h ldo.h \
ltm.h lfunc.h lmem.h lstring.h ltable.h lualib.h
lstring.o: lstring.c lmem.h lobject.h lua.h lstate.h luadebug.h \ ltm.o: ltm.c lua.h ldo.h lobject.h llimits.h lstate.h luadebug.h \
lstring.h lmem.h ltm.h
lstrlib.o: lstrlib.c lauxlib.h lua.h lualib.h
ltable.o: ltable.c lauxlib.h lua.h lmem.h lobject.h lstate.h \
luadebug.h ltable.h
ltm.o: ltm.c lauxlib.h lua.h lmem.h lobject.h lstate.h luadebug.h \
ltm.h
lua.o: lua.c lua.h luadebug.h lualib.h lua.o: lua.c lua.h luadebug.h lualib.h
lundump.o: lundump.c lauxlib.h lua.h lfunc.h lobject.h lmem.h \ lundump.o: lundump.c lfunc.h lobject.h llimits.h lua.h lmem.h \
lstring.h lundump.h lzio.h lopcodes.h lstring.h lstate.h luadebug.h lundump.h lzio.h
lvm.o: lvm.c lauxlib.h lua.h ldo.h lobject.h lstate.h luadebug.h \ lvm.o: lvm.c lua.h lapi.h lobject.h llimits.h ldebug.h lstate.h \
lfunc.h lgc.h lmem.h lopcodes.h lstring.h ltable.h ltm.h lvm.h luadebug.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h ltm.h \
lzio.o: lzio.c lzio.h lvm.h
lzio.o: lzio.c lua.h lzio.h

4493
manual.tex

File diff suppressed because it is too large Load Diff