Compare commits

..

179 Commits
v2.1 ... v2.4

Author SHA1 Message Date
Roberto Ierusalimschy
a7ca46405d unused "#include". 1996-05-06 13:59:00 -03:00
Roberto Ierusalimschy
0e2297afaa update of dependencies from "#include"s. 1996-05-06 11:38:40 -03:00
Roberto Ierusalimschy
0a1891f6a0 new version. 1996-05-06 11:32:59 -03:00
Roberto Ierusalimschy
1936a9e53b tables may grow bigger than words. 1996-05-06 11:30:27 -03:00
Roberto Ierusalimschy
820ec63bdf as strings are no more duplicated, "nextvar" can use "pushstring". 1996-05-06 11:29:35 -03:00
Roberto Ierusalimschy
01ea523b80 small corrections. 1996-05-03 17:10:59 -03:00
Roberto Ierusalimschy
88cf0836fc "isatty" is POSIX, but not ANSI. 1996-05-03 14:27:03 -03:00
Roberto Ierusalimschy
3ec9ee0d0f new function "luaI_openlib" to help open libs. 1996-04-30 18:13:55 -03:00
Roberto Ierusalimschy
21c9ebf4a9 new algotithm to adjust garbage collection: it tries to adapt gc calls
so that it collects half of the total objects when it is called.
1996-04-29 15:53:53 -03:00
Roberto Ierusalimschy
4fb77c4308 no more "lua_Reference"; new return value for "append";
documentation of "exit" (it was not in the manual).
1996-04-29 15:50:08 -03:00
Roberto Ierusalimschy
bced00ab9e lua_Reference is int, so say so. 1996-04-25 11:10:00 -03:00
Roberto Ierusalimschy
25116a3065 "malloc.h" is not ansi. 1996-04-25 11:01:27 -03:00
Roberto Ierusalimschy
eadbb9cff4 "stat" is not ansi. 1996-04-23 09:43:07 -03:00
Roberto Ierusalimschy
42b947296b "fileno" is not ansi. 1996-04-23 09:43:07 -03:00
Roberto Ierusalimschy
f37e65d1cb "exit" has an optional parameter of status. 1996-04-22 16:28:37 -03:00
Roberto Ierusalimschy
0ef5cf2289 lock mechanism seperseded by the REFERENCE mechanism. 1996-04-22 15:00:37 -03:00
Roberto Ierusalimschy
fed9408ab5 page size "letter". 1996-04-01 11:36:35 -03:00
Roberto Ierusalimschy
ce23901f04 smaller limit to stack size (otherwise C stack can finish first) 1996-03-22 16:12:15 -03:00
Roberto Ierusalimschy
df1ee1fb1c small "abstraction" 1996-03-22 14:57:24 -03:00
Roberto Ierusalimschy
f1d0276684 small bug in strfind. 1996-03-21 19:18:08 -03:00
Roberto Ierusalimschy
7ecc2ea597 new version 1996-03-21 18:30:29 -03:00
Roberto Ierusalimschy
7a35f23c16 a simplification about memory error messages. 1996-03-21 15:55:02 -03:00
Roberto Ierusalimschy
9284742a11 better control when growing arrays. 1996-03-21 13:33:47 -03:00
Roberto Ierusalimschy
9704ff4cb1 hook variables are global, no more "lua_set...hook" functions. 1996-03-20 15:44:02 -03:00
Roberto Ierusalimschy
e3c0ce9a69 dofile accepts pre-compiled chunks.
lua_is... do coercion.
small correction: = versus ==.
1996-03-19 19:39:07 -03:00
Roberto Ierusalimschy
85b76bcc01 functions "lua_is..." consider coercions.
small change when calling call hook.
1996-03-19 19:28:37 -03:00
Roberto Ierusalimschy
a275d9a25b functions "lua_is..." consider coercions. 1996-03-19 19:28:37 -03:00
Roberto Ierusalimschy
7e0be1fbde unused "#include" 1996-03-19 13:50:24 -03:00
Roberto Ierusalimschy
54ba642cc3 new module "undump.o" 1996-03-15 15:22:09 -03:00
Roberto Ierusalimschy
8826eb7918 small correction 1996-03-15 15:21:58 -03:00
Roberto Ierusalimschy
e701a86385 "openfile" now returns the file 1996-03-15 10:13:13 -03:00
Roberto Ierusalimschy
3e1f731826 integration with undump (execution of pre-compiled chuncks) 1996-03-15 10:13:13 -03:00
Roberto Ierusalimschy
f86c1367db new functions "rename" and "tmpname".
new option 'q' for function "format".
new example, about vararg.
1996-03-14 14:45:01 -03:00
Luiz Henrique de Figueiredo
58fd8aa851 added cast instead of union [lazy?] 1996-03-14 14:31:15 -03:00
Roberto Ierusalimschy
3226ac2da8 "lua_ntable" and "lua_nconstant" are public (undump.c uses them). 1996-03-14 12:57:19 -03:00
Roberto Ierusalimschy
3e9daa7416 creation of strings must call garbage collector. 1996-03-14 12:56:26 -03:00
Roberto Ierusalimschy
7236df875a new function "luaI_buffer". 1996-03-14 12:55:49 -03:00
Roberto Ierusalimschy
675e608325 new functions "rename" and "tmpname". 1996-03-14 12:55:18 -03:00
Roberto Ierusalimschy
1dc0e82aeb "freefunc" now is public. 1996-03-14 12:54:20 -03:00
Roberto Ierusalimschy
c2eb02aaf6 both "write" and "format" need "addquoted". 1996-03-14 12:53:09 -03:00
Roberto Ierusalimschy
2fee7e42c9 new option 'q' in function "format". 1996-03-14 12:52:35 -03:00
Roberto Ierusalimschy
281db390e8 no more "ugly" programs.
no more comments with '#'.
1996-03-14 12:17:28 -03:00
Luiz Henrique de Figueiredo
df8cf53cc9 removed tf->marked=0; 1996-03-12 17:00:40 -03:00
Roberto Ierusalimschy
40306b10db small corrections. 1996-03-12 12:56:03 -03:00
Luiz Henrique de Figueiredo
5eff5d3eac moved some includes from undump.h
LoadString now uses luaI_buffer
added LoadNewString
needs tf->marked=0
luaI_undump now returns int and aborts if luaI_dorun fails
1996-03-11 19:01:46 -03:00
Luiz Henrique de Figueiredo
8ad8426c43 moved some includes to undump.c
luaI_undump now returns int
1996-03-11 18:59:41 -03:00
Luiz Henrique de Figueiredo
3cab7cd025 undump.c is now a module
panic is now lua_error
 included swap.c
 tries float permutation earlier
 new functions: luaI_undump1 and luaI_undump
1996-03-08 18:44:12 -03:00
Luiz Henrique de Figueiredo
bb26efbbec definitions for lua decompiler
undump is now a module
1996-03-08 18:43:21 -03:00
Roberto Ierusalimschy
5c0e5fd36d details. 1996-03-08 09:04:04 -03:00
Roberto Ierusalimschy
621322a305 "PrintCode" now is defined in luac. 1996-03-08 09:02:37 -03:00
Luiz Henrique de Figueiredo
e33a3b8e0d now loads size as two words 1996-03-06 18:40:10 -03:00
Luiz Henrique de Figueiredo
9a6cccb08c removed support for local vars 1996-03-06 13:01:08 -03:00
Roberto Ierusalimschy
b58225e93b unused declaration removed. 1996-03-06 10:11:23 -03:00
Luiz Henrique de Figueiredo
852b919465 now swaps bytes (but need to make it more robust) 1996-03-05 22:41:18 -03:00
Roberto Ierusalimschy
ef94999647 parse.o was included twice in lua.a 1996-03-05 12:57:53 -03:00
Roberto Ierusalimschy
6f30fa98d8 small change to avoid error on "lua_pushstring(NULL)". 1996-03-04 11:46:35 -03:00
Roberto Ierusalimschy
74102bd716 small corrections. 1996-03-04 10:29:10 -03:00
Roberto Ierusalimschy
8d82aa821a small correction (about types) 1996-03-01 13:54:00 -03:00
Luiz Henrique de Figueiredo
cec1ffb80b uses ID_* constants
simplified signature checking
loads local vars
1996-03-01 00:43:50 -03:00
Luiz Henrique de Figueiredo
870967ca77 headers for Main and others are different 1996-02-28 20:10:46 -03:00
Roberto Ierusalimschy
66fc0f554a using double to read numbers. 1996-02-26 19:35:51 -03:00
Roberto Ierusalimschy
d6e4c29733 fixed strings (not collectable) don't need to be inserted in the constant table. 1996-02-26 18:00:27 -03:00
Luiz Henrique de Figueiredo
3e42969979 main always reads "luac.out" 1996-02-26 16:44:17 -03:00
Roberto Ierusalimschy
712ac505e0 small correction 1996-02-26 14:07:49 -03:00
Roberto Ierusalimschy
f935d3397e check if jump is bigger than 2^16. 1996-02-26 14:07:20 -03:00
Roberto Ierusalimschy
30dd3a2dbc small changes (preparing for new module of pre-compilation) 1996-02-26 14:06:39 -03:00
Luiz Henrique de Figueiredo
b04f88d581 functions now linked into a list headed by main 1996-02-24 13:44:28 -03:00
Luiz Henrique de Figueiredo
b3c10c8c41 fix to PUSHFUNCTION now correctly at tf->marked 1996-02-24 00:46:57 -03:00
Luiz Henrique de Figueiredo
5c1bd89a1c added fix to PUSHFUNCTION and support for main function 1996-02-23 19:00:26 -03:00
Luiz Henrique de Figueiredo
15f3ab09eb load bytecodes from files 1996-02-23 16:04:38 -03:00
Roberto Ierusalimschy
c7e834f424 function "write_quoted" rewritten more clearly. 1996-02-22 17:56:33 -03:00
Roberto Ierusalimschy
8c1a9899d4 functions "luaI_free" and "luaI_realloc" (or macro "growvector") may be
called with NULL.
1996-02-22 17:34:33 -03:00
Roberto Ierusalimschy
05caf09a36 list of incompatibilities with version 2.2.
new macro \Version.
1996-02-16 10:12:12 -03:00
Roberto Ierusalimschy
168a865e60 more appropriate error message for "date" 1996-02-16 10:10:14 -03:00
Roberto Ierusalimschy
15c17c24fa small improvements 1996-02-14 16:11:09 -03:00
Roberto Ierusalimschy
45cf24485d useless #include. 1996-02-14 15:25:04 -03:00
Roberto Ierusalimschy
c56e2b2e30 new version 1996-02-14 10:40:26 -03:00
Roberto Ierusalimschy
d1608c597e reserved words are stored in main string table; "marked" field is
used to indicate its type.
Table initializations centralized by "tree.c".
1996-02-14 10:35:51 -03:00
Roberto Ierusalimschy
0f4903a5d7 new header "lex.h". 1996-02-13 14:30:39 -03:00
Roberto Ierusalimschy
772f25d3dd new header for lex.c 1996-02-13 14:30:39 -03:00
Roberto Ierusalimschy
f1a1eda7c5 old trick in "strsub" does not work with new hash table for strings. 1996-02-12 15:34:44 -03:00
Roberto Ierusalimschy
41259bff31 BIG CHANGE: new data structure for constants, strings and globals, using
an array of hash tables for all them.
1996-02-12 15:32:40 -03:00
Roberto Ierusalimschy
afaa98a666 no more "lua_pushliteral". 1996-02-12 15:32:09 -03:00
Roberto Ierusalimschy
73be918285 a backslash followed by a newline allows the newline to go into
a string.
1996-02-09 17:35:23 -02:00
Roberto Ierusalimschy
ca412214cb new function "date", replaces old "date" and "time". 1996-02-09 17:02:30 -02:00
Roberto Ierusalimschy
801722825d "lua_check_number" accepts strings convertible to numbers. 1996-02-09 17:00:23 -02:00
Roberto Ierusalimschy
3abc25fa54 new functions "random" and "randomseed". 1996-02-09 15:21:27 -02:00
Roberto Ierusalimschy
f4d67761f1 new section describing the debug interface. 1996-02-09 14:37:58 -02:00
Roberto Ierusalimschy
369c5fe3c0 lock mechanism more robust; nil is pseudo-locked under index -1. 1996-02-08 17:08:34 -02:00
Roberto Ierusalimschy
7918c6cf11 small bug 1996-02-08 16:14:17 -02:00
Roberto Ierusalimschy
826d70fcba new type lua_Function for activation records 1996-02-08 15:03:20 -02:00
Roberto Ierusalimschy
bbb23048e3 correction of dependencies (include's). 1996-02-07 16:14:38 -02:00
Roberto Ierusalimschy
5a3a1fe458 debug interface functions to manipulated local variables:
"lua_getlocal" and "lua_setlocal".
1996-02-07 16:10:27 -02:00
Roberto Ierusalimschy
56fb06b6f5 "lua_debug" now is exported through debug interface (luadebug.h) 1996-02-07 12:14:40 -02:00
Roberto Ierusalimschy
995a9f7188 no more "Bool" type 1996-02-07 12:13:17 -02:00
Roberto Ierusalimschy
a0ef046ef1 elimination of unused declarations (left from old modifications) 1996-02-06 14:18:21 -02:00
Roberto Ierusalimschy
5fa51fc426 new option "q" in function "write", to write literal strings. 1996-02-05 19:32:19 -02:00
Roberto Ierusalimschy
15057aa0a4 new examples showing data structures and object-oriented programming.
generic improvements and corrections.
1996-02-05 12:52:47 -02:00
Roberto Ierusalimschy
1431b52e76 improve of compiling error messages. 1996-02-05 11:26:01 -02:00
Roberto Ierusalimschy
98fe770cab small bug 1996-02-04 14:59:12 -02:00
Roberto Ierusalimschy
43382ce5a2 new fallback "getglobal". 1996-01-30 13:25:23 -02:00
Roberto Ierusalimschy
abfebf1e21 new example showing how to build modules. 1996-01-30 13:24:49 -02:00
Roberto Ierusalimschy
b1c02c7f00 new fallback "getglobal".
modifications to generate an index (not automatically yet).
1996-01-30 10:55:10 -02:00
Roberto Ierusalimschy
84df3ac267 new functions "tostring", "assert", and "format". 1996-01-29 15:08:23 -02:00
Roberto Ierusalimschy
55a70c9719 "read('s')" was "eating" delimiter. 1996-01-29 14:40:09 -02:00
Roberto Ierusalimschy
0d50b87aa4 lua_table now has references to global variable names (TreeNode's). 1996-01-26 16:03:19 -02:00
Roberto Ierusalimschy
19290a8e92 "dofile" issues an error when called with non string arguments, and
runs stdin when called without arguments.
1996-01-26 14:52:47 -02:00
Roberto Ierusalimschy
d845963349 "setglobal" and "getglobal" moved to inout.c, as it concentrates pre-defined
library.
new function "assert".
1996-01-26 12:05:28 -02:00
Roberto Ierusalimschy
8dae4657a1 "setglobal" and "getglobal" moved to inout.c, as it concentrates pre-defined
library.
1996-01-26 12:04:32 -02:00
Roberto Ierusalimschy
ca7be1cfeb elimination of function "int2str", as it can be replaced by "format('%c', .)" 1996-01-26 10:11:28 -02:00
Roberto Ierusalimschy
445872a6e2 "dofile" does not issue a warning when unable to open the file,
but only returns an error code.
1996-01-23 16:43:07 -02:00
Roberto Ierusalimschy
3681d025ac new function "assert" 1996-01-23 16:39:45 -02:00
Roberto Ierusalimschy
2998049f51 local variable stack needs only the name of the variable (TreeNode);
this way is simpler and faster than old way.
1996-01-23 15:50:29 -02:00
Roberto Ierusalimschy
24ccc7c038 correction of some order dependencies in debug code. 1996-01-22 16:39:37 -02:00
Roberto Ierusalimschy
be48c4d91e add_char now is global.
time returns week-day.
1996-01-22 15:46:55 -02:00
Roberto Ierusalimschy
a19f9056f3 new function "tostring". 1996-01-22 15:40:00 -02:00
Roberto Ierusalimschy
5b71ab780c add_char now is global.
new function format.
1996-01-22 15:38:57 -02:00
Roberto Ierusalimschy
481bafd581 add_char now is global. 1996-01-22 15:38:57 -02:00
Roberto Ierusalimschy
e74b250d71 memory overflow tries a garbage collection; if it fails then exit the
program.
1996-01-22 12:15:13 -02:00
Roberto Ierusalimschy
cd54c95ee1 bug: "read" with format MUST read given number of chars (if file ends
before that reports an error, returning nil).
"readuntil" can be called with nil or no parameters to read until EOF.
1996-01-12 15:00:30 -02:00
Roberto Ierusalimschy
bf006eeaf5 "getobjectname" got a "lua_" prefix. 1996-01-09 18:23:19 -02:00
Roberto Ierusalimschy
b2afc410fa hooks for line change and function calls; first version. 1996-01-09 18:22:44 -02:00
Roberto Ierusalimschy
19cfa32393 correction of dependencies from "luadebug.h". 1996-01-09 18:22:08 -02:00
Roberto Ierusalimschy
27ae8432b6 names generated by yacc (starting with "yy") are changed to start with
"luaY_", to avoid name clashes with hosts using yacc.
1995-12-21 14:14:04 -02:00
Roberto Ierusalimschy
415ee250b5 bug: luaI_findconstantbyname may change the value of lua_constant. 1995-12-18 14:47:29 -02:00
Roberto Ierusalimschy
f188e1000b useless "#include math.h" 1995-11-16 18:46:24 -02:00
Roberto Ierusalimschy
07d64e78b6 reference manual 1995-11-16 18:46:02 -02:00
Roberto Ierusalimschy
fa649fbc26 new distribution 1995-11-13 13:36:52 -02:00
Roberto Ierusalimschy
0c3e0fd95d "read" must return 'nil' on EOF. 1995-11-10 16:32:59 -02:00
Roberto Ierusalimschy
3bb6443131 changes to improve portability 1995-11-10 15:56:06 -02:00
Roberto Ierusalimschy
f57afd6e32 re-implementation of functions "write" and "read" 1995-11-10 15:55:48 -02:00
Roberto Ierusalimschy
5f664a4516 error functions are shared by all libraries 1995-11-10 15:54:31 -02:00
Roberto Ierusalimschy
87fe07c0d4 little improvement 1995-11-10 12:12:02 -02:00
Roberto Ierusalimschy
f9a9bd77e4 print_stack now gets a parameter (file to print);
small changes.
1995-11-03 13:43:50 -02:00
Roberto Ierusalimschy
63b8a6fd20 "getobjname" checks first fallbacks (so, if a function is global and
a fallback, it is reported as a fallback).
1995-11-03 13:30:50 -02:00
Roberto Ierusalimschy
024f2374ab "AUTHORS" separated from COPYRIGHT. 1995-10-31 15:05:35 -02:00
Roberto Ierusalimschy
9d9f9c48ff local variables may appear inside blocks in main code. 1995-10-26 15:02:50 -02:00
Roberto Ierusalimschy
15d48576ea functions now may be declared with any "var" as a name;
therefore they do not have a "baptism" name.
Changes in debug API to acomodate that.
1995-10-26 12:21:56 -02:00
Roberto Ierusalimschy
39b071f7b1 new syntax for function declarations: "function a.x () ... "
new semantics for function declarations: function f () is valid only
at run-time.
1995-10-25 12:33:25 -02:00
Roberto Ierusalimschy
9efc257d9d new method to keep debug line information: current line is stored on the
Lua stack, just below (new) base, with tag LUA_T_LINE.
SETLINE opcodes are generated by lex.
1995-10-25 11:05:51 -02:00
Roberto Ierusalimschy
fa71304e54 "dofile" now accepts NULL as parameter, to run stdin. 1995-10-23 11:54:11 -02:00
Roberto Ierusalimschy
b5745d11cd uses "isatty" to check if executes stdin line by line or as a file. 1995-10-23 11:54:11 -02:00
Roberto Ierusalimschy
ebcf546a55 small changes in the format of debug information. 1995-10-23 11:53:48 -02:00
Roberto Ierusalimschy
2b45f8967c small bug 1995-10-17 16:16:58 -02:00
Roberto Ierusalimschy
a66404aca6 function "setfallback" now gives an error if called with wrong parameters. 1995-10-17 12:30:05 -02:00
Roberto Ierusalimschy
d80659759b new module luadebug.h. 1995-10-17 12:12:45 -02:00
Roberto Ierusalimschy
d24253d92f module to declare API for debuging. 1995-10-17 12:12:45 -02:00
Roberto Ierusalimschy
2cffb08a5c new style for debug information about functions: no more SETFUNCTION
opcodes. When a function is called, its entry in the stack is marked with
LUA_T_(C)MARK, so function 'luaD_stackedfunction' can find it if
needed.
Functions now have their file names in the headers, so there is no need
of 'addfile' and the like.
1995-10-17 09:58:41 -02:00
Roberto Ierusalimschy
15f40fddca 'nextvar' now traverses the symbol array, instead of the constant tree. 1995-10-17 09:53:53 -02:00
Roberto Ierusalimschy
970995c3f2 'luaI_travfallbacks' now can look for a fallback. 1995-10-17 09:52:38 -02:00
Roberto Ierusalimschy
b17c76817d new function "luaI_findconstantbyname". 1995-10-13 12:16:25 -03:00
Roberto Ierusalimschy
b074306267 bug. "fgets" reads n-1 chars. 1995-10-11 17:50:56 -03:00
Roberto Ierusalimschy
3c75b75516 new module "func", for GC of functions,
and new "defines" for configuration setup.
1995-10-09 15:51:49 -03:00
Roberto Ierusalimschy
36a7fda014 bug: stack overflow error must leave space on the stack for error function. 1995-10-09 15:45:59 -03:00
Roberto Ierusalimschy
1bb3fb73cc fallback table now has number of parameters and results of each
fallback. This information is used by opcode.c, when calling a fallback.
1995-10-09 10:14:29 -03:00
Roberto Ierusalimschy
7e01348658 "docall" now assumes that called function is always on the stack, just
below "base". That gives more regularity for the stack shape, and
prevents fallbacks of being garbage collected if they are redefined
during execution.
1995-10-09 10:10:20 -03:00
Roberto Ierusalimschy
28b3017baf lua function "type" now returns the string "function" both for lua
functions and c functions.
1995-10-09 10:06:20 -03:00
Roberto Ierusalimschy
ae808860ae new functions: "ascii" and "int2str",
small "re-engineering" on parameter checking.
1995-10-09 09:49:21 -03:00
Roberto Ierusalimschy
a47e8c7dd0 small "re-engineering" on parameter checking.
correction of function "atan2".
1995-10-09 09:48:38 -03:00
Roberto Ierusalimschy
79ce619876 new command line options: -v to print Copyright message, and
- to read stdin.
1995-10-06 11:11:40 -03:00
Roberto Ierusalimschy
233f0b0cc7 definitions for Copyright and version notices 1995-10-06 11:11:10 -03:00
Roberto Ierusalimschy
025589f772 nova forma de comentarios: de '#' ate' fim de linha (para uso de lua
como shell)
1995-10-06 10:10:53 -03:00
Roberto Ierusalimschy
68f337dfa6 Garbage collection of functions + header structure for functions 1995-10-04 14:13:02 -03:00
Roberto Ierusalimschy
f132ac03bc Module to manipulate function headers. 1995-10-04 11:20:26 -03:00
Roberto Ierusalimschy
ec785a1d65 new option for "writeto" and "readfrom", to allow piped I/O on
machines that support it.
1995-10-04 10:53:10 -03:00
Roberto Ierusalimschy
e0621e6115 new function "atan2". 1995-10-04 10:52:09 -03:00
Roberto Ierusalimschy
38411aa102 small correction to avoid problems with DOS/Windows 1995-10-03 15:06:10 -03:00
Roberto Ierusalimschy
3ec4f4eb86 small corrections to avoid warnings. 1995-10-02 14:03:33 -03:00
Roberto Ierusalimschy
367139c6d9 buffer for literals now grows dynamically, allowing big programs between [[ and ]]. 1995-09-15 17:48:26 -03:00
Roberto Ierusalimschy
457bac94ce small corrections to avoid uninitialized global variables. 1995-09-15 17:47:53 -03:00
Roberto Ierusalimschy
bcf46ee83b new syntax for strings: [[ ... ]]. Still in tests,
since the code does not check buffer overflow.
1995-07-06 14:47:08 -03:00
Roberto Ierusalimschy
97b2fd1ba1 syntax for {...;...} is more flexible now. 1995-06-08 16:47:28 -03:00
Waldemar Celes
e13753e2fb Ajustar limites para garbage collection. 1995-05-16 16:23:55 -03:00
Roberto Ierusalimschy
ec79f25286 new lua function "getstack"; new interface to function luaI_reportbug. 1995-05-16 14:23:58 -03:00
Roberto Ierusalimschy
18ea2eff80 calls to "lua_reportbug" changed to "lua_error", since
"lua_reportbug" is only an internal function to build debug information
1995-05-02 15:43:03 -03:00
Waldemar Celes
8156604823 run-time stack now is controled at run time, instead of
compilation time.
1995-04-11 14:56:30 -03:00
Roberto Ierusalimschy
36b6fdda83 function "type" now returns a second result: the tag of the type,
so lua can discriminate different kinds of user data.
1995-03-17 17:42:20 -03:00
Waldemar Celes
3c67d2595b error message buffer got a bigger size 1995-03-17 17:27:11 -03:00
Roberto Ierusalimschy
2043a0ca30 adjust checks if stack has enough space 1995-02-10 10:51:29 -02:00
32 changed files with 4918 additions and 2065 deletions

View File

@@ -3,7 +3,7 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_fallback="$Id: fallback.c,v 1.10 1994/12/20 21:20:36 roberto Exp $"; char *rcs_fallback="$Id: fallback.c,v 1.24 1996/04/22 18:00:37 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@@ -11,8 +11,8 @@ char *rcs_fallback="$Id: fallback.c,v 1.10 1994/12/20 21:20:36 roberto Exp $";
#include "mem.h" #include "mem.h"
#include "fallback.h" #include "fallback.h"
#include "opcode.h" #include "opcode.h"
#include "inout.h"
#include "lua.h" #include "lua.h"
#include "table.h"
static void errorFB (void); static void errorFB (void);
@@ -29,15 +29,18 @@ static void funcFB (void);
** Warning: This list must be in the same order as the #define's ** Warning: This list must be in the same order as the #define's
*/ */
struct FB luaI_fallBacks[] = { struct FB luaI_fallBacks[] = {
{"error", {LUA_T_CFUNCTION, errorFB}}, {"error", {LUA_T_CFUNCTION, {errorFB}}, 1, 0},
{"index", {LUA_T_CFUNCTION, indexFB}}, {"index", {LUA_T_CFUNCTION, {indexFB}}, 2, 1},
{"gettable", {LUA_T_CFUNCTION, gettableFB}}, {"gettable", {LUA_T_CFUNCTION, {gettableFB}}, 2, 1},
{"arith", {LUA_T_CFUNCTION, arithFB}}, {"arith", {LUA_T_CFUNCTION, {arithFB}}, 3, 1},
{"order", {LUA_T_CFUNCTION, orderFB}}, {"order", {LUA_T_CFUNCTION, {orderFB}}, 3, 1},
{"concat", {LUA_T_CFUNCTION, concatFB}}, {"concat", {LUA_T_CFUNCTION, {concatFB}}, 2, 1},
{"settable", {LUA_T_CFUNCTION, gettableFB}}, {"settable", {LUA_T_CFUNCTION, {gettableFB}}, 3, 0},
{"gc", {LUA_T_CFUNCTION, GDFB}}, {"gc", {LUA_T_CFUNCTION, {GDFB}}, 1, 0},
{"function", {LUA_T_CFUNCTION, funcFB}} {"function", {LUA_T_CFUNCTION, {funcFB}}, -1, -1},
/* no fixed number of params or results */
{"getglobal", {LUA_T_CFUNCTION, {indexFB}}, 1, 1}
/* same default behavior of index FB */
}; };
#define N_FB (sizeof(luaI_fallBacks)/sizeof(struct FB)) #define N_FB (sizeof(luaI_fallBacks)/sizeof(struct FB))
@@ -47,11 +50,8 @@ void luaI_setfallback (void)
int i; int i;
char *name = lua_getstring(lua_getparam(1)); char *name = lua_getstring(lua_getparam(1));
lua_Object func = lua_getparam(2); lua_Object func = lua_getparam(2);
if (name == NULL || !(lua_isfunction(func) || lua_iscfunction(func))) if (name == NULL || !lua_isfunction(func))
{ lua_error("incorrect argument to function `setfallback'");
lua_pushnil();
return;
}
for (i=0; i<N_FB; i++) for (i=0; i<N_FB; i++)
{ {
if (strcmp(luaI_fallBacks[i].kind, name) == 0) if (strcmp(luaI_fallBacks[i].kind, name) == 0)
@@ -62,7 +62,7 @@ void luaI_setfallback (void)
} }
} }
/* name not found */ /* name not found */
lua_pushnil(); lua_error("incorrect argument to function `setfallback'");
} }
@@ -84,88 +84,108 @@ static void indexFB (void)
static void gettableFB (void) static void gettableFB (void)
{ {
lua_reportbug("indexed expression not a table"); lua_error("indexed expression not a table");
} }
static void arithFB (void) static void arithFB (void)
{ {
lua_reportbug("unexpected type at conversion to number"); lua_error("unexpected type at conversion to number");
} }
static void concatFB (void) static void concatFB (void)
{ {
lua_reportbug("unexpected type at conversion to string"); lua_error("unexpected type at conversion to string");
} }
static void orderFB (void) static void orderFB (void)
{ {
lua_reportbug("unexpected type at comparison"); lua_error("unexpected type at comparison");
} }
static void GDFB (void) { } static void GDFB (void) { }
static void funcFB (void) static void funcFB (void)
{ {
lua_reportbug("call expression not a function"); lua_error("call expression not a function");
} }
/* /*
** Lock routines ** Reference routines
*/ */
static Object *lockArray = NULL; static struct ref {
static Word lockSize = 0; Object o;
enum {LOCK, HOLD, FREE, COLLECTED} status;
} *refArray = NULL;
static int refSize = 0;
int luaI_lock (Object *object) int luaI_ref (Object *object, int lock)
{ {
Word i; int i;
Word oldSize; int oldSize;
if (tag(object) == LUA_T_NIL) if (tag(object) == LUA_T_NIL)
return -1; return -1; /* special ref for nil */
for (i=0; i<lockSize; i++) for (i=0; i<refSize; i++)
if (tag(&lockArray[i]) == LUA_T_NIL) if (refArray[i].status == FREE)
{ goto found;
lockArray[i] = *object;
return i;
}
/* no more empty spaces */ /* no more empty spaces */
oldSize = lockSize; oldSize = refSize;
if (lockArray == NULL) refSize = growvector(&refArray, refSize, struct ref, refEM, MAX_WORD);
{ for (i=oldSize; i<refSize; i++)
lockSize = 10; refArray[i].status = FREE;
lockArray = newvector(lockSize, Object); i = oldSize;
} found:
refArray[i].o = *object;
refArray[i].status = lock ? LOCK : HOLD;
return i;
}
void lua_unref (int ref)
{
if (ref >= 0 && ref < refSize)
refArray[ref].status = FREE;
}
Object *luaI_getref (int ref)
{
static Object nul = {LUA_T_NIL, {0}};
if (ref == -1)
return &nul;
if (ref >= 0 && ref < refSize &&
(refArray[ref].status == LOCK || refArray[ref].status == HOLD))
return &refArray[ref].o;
else else
{ return NULL;
lockSize = 3*oldSize/2 + 5;
lockArray = growvector(lockArray, lockSize, Object);
}
for (i=oldSize; i<lockSize; i++)
tag(&lockArray[i]) = LUA_T_NIL;
lockArray[oldSize] = *object;
return oldSize;
} }
void lua_unlock (int ref) void luaI_travlock (int (*fn)(Object *))
{ {
tag(&lockArray[ref]) = LUA_T_NIL; int i;
for (i=0; i<refSize; i++)
if (refArray[i].status == LOCK)
fn(&refArray[i].o);
} }
Object *luaI_getlocked (int ref) void luaI_invalidaterefs (void)
{ {
return &lockArray[ref]; int i;
for (i=0; i<refSize; i++)
if (refArray[i].status == HOLD && !luaI_ismarked(&refArray[i].o))
refArray[i].status = COLLECTED;
} }
char *luaI_travfallbacks (int (*fn)(Object *))
void luaI_travlock (void (*fn)(Object *))
{ {
Word i; int i;
for (i=0; i<lockSize; i++) for (i=0; i<N_FB; i++)
fn(&lockArray[i]); if (fn(&luaI_fallBacks[i].function))
return luaI_fallBacks[i].kind;
return NULL;
} }

View File

@@ -1,15 +1,18 @@
/* /*
** $Id: fallback.h,v 1.6 1994/11/21 13:30:15 roberto Exp roberto $ ** $Id: fallback.h,v 1.12 1996/04/22 18:00:37 roberto Exp roberto $
*/ */
#ifndef fallback_h #ifndef fallback_h
#define fallback_h #define fallback_h
#include "lua.h"
#include "opcode.h" #include "opcode.h"
extern struct FB { extern struct FB {
char *kind; char *kind;
Object function; Object function;
int nParams;
int nResults;
} luaI_fallBacks[]; } luaI_fallBacks[];
#define FB_ERROR 0 #define FB_ERROR 0
@@ -21,11 +24,14 @@ extern struct FB {
#define FB_SETTABLE 6 #define FB_SETTABLE 6
#define FB_GC 7 #define FB_GC 7
#define FB_FUNCTION 8 #define FB_FUNCTION 8
#define FB_GETGLOBAL 9
void luaI_setfallback (void); void luaI_setfallback (void);
int luaI_lock (Object *object); int luaI_ref (Object *object, int lock);
Object *luaI_getlocked (int ref); Object *luaI_getref (int ref);
void luaI_travlock (void (*fn)(Object *)); void luaI_travlock (int (*fn)(Object *));
void luaI_invalidaterefs (void);
char *luaI_travfallbacks (int (*fn)(Object *));
#endif #endif

156
func.c Normal file
View File

@@ -0,0 +1,156 @@
#include <stdlib.h>
#include "luadebug.h"
#include "table.h"
#include "mem.h"
#include "func.h"
#include "opcode.h"
static TFunc *function_root = NULL;
static LocVar *currvars = NULL;
static int numcurrvars = 0;
static int maxcurrvars = 0;
/*
** Initialize TFunc struct
*/
void luaI_initTFunc (TFunc *f)
{
f->next = NULL;
f->marked = 0;
f->size = 0;
f->code = NULL;
f->lineDefined = 0;
f->fileName = NULL;
f->locvars = NULL;
}
/*
** Insert function in list for GC
*/
void luaI_insertfunction (TFunc *f)
{
lua_pack();
f->next = function_root;
function_root = f;
f->marked = 0;
}
/*
** Free function
*/
void luaI_freefunc (TFunc *f)
{
luaI_free (f->code);
luaI_free (f->locvars);
luaI_free (f);
}
/*
** Garbage collection function.
** This function traverse the function list freeing unindexed functions
*/
Long luaI_funccollector (void)
{
TFunc *curr = function_root;
TFunc *prev = NULL;
Long counter = 0;
while (curr)
{
TFunc *next = curr->next;
if (!curr->marked)
{
if (prev == NULL)
function_root = next;
else
prev->next = next;
luaI_freefunc (curr);
++counter;
}
else
{
curr->marked = 0;
prev = curr;
}
curr = next;
}
return counter;
}
void lua_funcinfo (lua_Object func, char **filename, int *linedefined)
{
Object *f = luaI_Address(func);
if (f->tag == LUA_T_MARK || f->tag == LUA_T_FUNCTION)
{
*filename = f->value.tf->fileName;
*linedefined = f->value.tf->lineDefined;
}
else if (f->tag == LUA_T_CMARK || f->tag == LUA_T_CFUNCTION)
{
*filename = "(C)";
*linedefined = -1;
}
}
/*
** Stores information to know that variable has been declared in given line
*/
void luaI_registerlocalvar (TaggedString *varname, int line)
{
if (numcurrvars >= maxcurrvars)
maxcurrvars = growvector(&currvars, maxcurrvars, LocVar, "", MAX_WORD);
currvars[numcurrvars].varname = varname;
currvars[numcurrvars].line = line;
numcurrvars++;
}
/*
** Stores information to know that variable has been out of scope in given line
*/
void luaI_unregisterlocalvar (int line)
{
luaI_registerlocalvar(NULL, line);
}
/*
** Copies "currvars" into a new area and store it in function header.
** The values (varname = NULL, line = -1) signal the end of vector.
*/
void luaI_closelocalvars (TFunc *func)
{
func->locvars = newvector (numcurrvars+1, LocVar);
memcpy (func->locvars, currvars, numcurrvars*sizeof(LocVar));
func->locvars[numcurrvars].varname = NULL;
func->locvars[numcurrvars].line = -1;
numcurrvars = 0; /* prepares for next function */
}
/*
** Look for n-esim local variable at line "line" in function "func".
** Returns NULL if not found.
*/
char *luaI_getlocalname (TFunc *func, int local_number, int line)
{
int count = 0;
char *varname = NULL;
LocVar *lv = func->locvars;
if (lv == NULL)
return NULL;
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;
}

44
func.h Normal file
View File

@@ -0,0 +1,44 @@
/*
** $Id: func.h,v 1.7 1996/03/08 12:04:04 roberto Exp roberto $
*/
#ifndef func_h
#define func_h
#include "types.h"
#include "lua.h"
#include "tree.h"
typedef struct LocVar
{
TaggedString *varname; /* NULL signals end of scope */
int line;
} LocVar;
/*
** Function Headers
*/
typedef struct TFunc
{
struct TFunc *next;
int marked;
int size;
Byte *code;
int lineDefined;
char *fileName;
LocVar *locvars;
} TFunc;
Long luaI_funccollector (void);
void luaI_insertfunction (TFunc *f);
void luaI_initTFunc (TFunc *f);
void luaI_freefunc (TFunc *f);
void luaI_registerlocalvar (TaggedString *varname, int line);
void luaI_unregisterlocalvar (int line);
void luaI_closelocalvars (TFunc *func);
char *luaI_getlocalname (TFunc *func, int local_number, int line);
#endif

77
hash.c
View File

@@ -3,18 +3,15 @@
** hash manager for lua ** hash manager for lua
*/ */
char *rcs_hash="$Id: hash.c,v 2.23 1995/01/12 14:19:04 roberto Exp $"; char *rcs_hash="$Id: hash.c,v 2.29 1996/02/14 18:25:04 roberto Exp roberto $";
#include <string.h>
#include "mem.h" #include "mem.h"
#include "opcode.h" #include "opcode.h"
#include "hash.h" #include "hash.h"
#include "inout.h"
#include "table.h" #include "table.h"
#include "lua.h" #include "lua.h"
#define streq(s1,s2) (s1 == s2 || (*(s1) == *(s2) && strcmp(s1,s2)==0))
#define nhash(t) ((t)->nhash) #define nhash(t) ((t)->nhash)
#define nuse(t) ((t)->nuse) #define nuse(t) ((t)->nuse)
@@ -25,22 +22,22 @@ char *rcs_hash="$Id: hash.c,v 2.23 1995/01/12 14:19:04 roberto Exp $";
#define val(n) (&(n)->val) #define val(n) (&(n)->val)
#define REHASH_LIMIT 0.70 /* avoid more than this % full */ #define REHASH_LIMIT 0.70 /* avoid more than this % full */
static Hash *listhead = NULL; static Hash *listhead = NULL;
/* hash dimensions values */ /* hash dimensions values */
static Word dimensions[] = static Long dimensions[] =
{3, 5, 7, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, {3L, 5L, 7L, 11L, 23L, 47L, 97L, 197L, 397L, 797L, 1597L, 3203L, 6421L,
12853, 25717, 51437, 65521, 0}; /* 65521 == last prime < MAX_WORD */ 12853L, 25717L, 51437L, 102811L, 205619L, 411233L, 822433L,
1644817L, 3289613L, 6579211L, 13158023L, MAX_INT};
static Word redimension (Word nhash) int luaI_redimension (int nhash)
{ {
Word i; int i;
for (i=0; dimensions[i]!=0; i++) for (i=0; dimensions[i]<MAX_INT; i++)
{ {
if (dimensions[i] > nhash) if (dimensions[i] > nhash)
return dimensions[i]; return dimensions[i];
@@ -49,29 +46,19 @@ static Word redimension (Word nhash)
return 0; /* to avoid warnings */ return 0; /* to avoid warnings */
} }
static Word hashindex (Hash *t, Object *ref) /* hash function */ static int hashindex (Hash *t, Object *ref) /* hash function */
{ {
switch (tag(ref)) switch (tag(ref))
{ {
case LUA_T_NIL: case LUA_T_NIL:
lua_reportbug ("unexpected type to index table"); lua_error ("unexpected type to index table");
return -1; /* UNREACHEABLE */ return -1; /* UNREACHEABLE */
case LUA_T_NUMBER: case LUA_T_NUMBER:
return (((Word)nvalue(ref))%nhash(t)); return (((int)nvalue(ref))%nhash(t));
case LUA_T_STRING: case LUA_T_STRING:
{ return (int)((tsvalue(ref)->hash)%nhash(t)); /* make it a valid index */
unsigned long h = tsvalue(ref)->hash;
if (h == 0)
{
char *name = svalue(ref);
while (*name)
h = ((h<<5)-h)^(unsigned char)*(name++);
tsvalue(ref)->hash = h;
}
return (Word)h%nhash(t); /* make it a valid index */
}
case LUA_T_FUNCTION: case LUA_T_FUNCTION:
return (((IntPoint)bvalue(ref))%nhash(t)); return (((IntPoint)ref->value.tf)%nhash(t));
case LUA_T_CFUNCTION: case LUA_T_CFUNCTION:
return (((IntPoint)fvalue(ref))%nhash(t)); return (((IntPoint)fvalue(ref))%nhash(t));
case LUA_T_ARRAY: case LUA_T_ARRAY:
@@ -81,24 +68,24 @@ static Word hashindex (Hash *t, Object *ref) /* hash function */
} }
} }
Bool lua_equalObj (Object *t1, Object *t2) int lua_equalObj (Object *t1, Object *t2)
{ {
if (tag(t1) != tag(t2)) return 0; if (tag(t1) != tag(t2)) return 0;
switch (tag(t1)) switch (tag(t1))
{ {
case LUA_T_NIL: return 1; case LUA_T_NIL: return 1;
case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2); case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2);
case LUA_T_STRING: return streq(svalue(t1), svalue(t2)); case LUA_T_STRING: return svalue(t1) == svalue(t2);
case LUA_T_ARRAY: return avalue(t1) == avalue(t2); case LUA_T_ARRAY: return avalue(t1) == avalue(t2);
case LUA_T_FUNCTION: return bvalue(t1) == bvalue(t2); case LUA_T_FUNCTION: return t1->value.tf == t2->value.tf;
case LUA_T_CFUNCTION: return fvalue(t1) == fvalue(t2); case LUA_T_CFUNCTION: return fvalue(t1) == fvalue(t2);
default: return uvalue(t1) == uvalue(t2); default: return uvalue(t1) == uvalue(t2);
} }
} }
static Word present (Hash *t, Object *ref) static int present (Hash *t, Object *ref)
{ {
Word h = hashindex(t, ref); int h = hashindex(t, ref);
while (tag(ref(node(t, h))) != LUA_T_NIL) while (tag(ref(node(t, h))) != LUA_T_NIL)
{ {
if (lua_equalObj(ref, ref(node(t, h)))) if (lua_equalObj(ref, ref(node(t, h))))
@@ -112,9 +99,9 @@ static Word present (Hash *t, Object *ref)
/* /*
** Alloc a vector node ** Alloc a vector node
*/ */
static Node *hashnodecreate (Word nhash) static Node *hashnodecreate (int nhash)
{ {
Word i; int i;
Node *v = newvector (nhash, Node); Node *v = newvector (nhash, Node);
for (i=0; i<nhash; i++) for (i=0; i<nhash; i++)
tag(ref(&v[i])) = LUA_T_NIL; tag(ref(&v[i])) = LUA_T_NIL;
@@ -124,10 +111,10 @@ static Node *hashnodecreate (Word nhash)
/* /*
** Create a new hash. Return the hash pointer or NULL on error. ** Create a new hash. Return the hash pointer or NULL on error.
*/ */
static Hash *hashcreate (Word nhash) static Hash *hashcreate (int nhash)
{ {
Hash *t = new(Hash); Hash *t = new(Hash);
nhash = redimension((Word)((float)nhash/REHASH_LIMIT)); nhash = luaI_redimension((int)((float)nhash/REHASH_LIMIT));
nodevector(t) = hashnodecreate(nhash); nodevector(t) = hashnodecreate(nhash);
nhash(t) = nhash; nhash(t) = nhash;
nuse(t) = 0; nuse(t) = 0;
@@ -152,7 +139,7 @@ void lua_hashmark (Hash *h)
{ {
if (markarray(h) == 0) if (markarray(h) == 0)
{ {
Word i; int i;
markarray(h) = 1; markarray(h) = 1;
for (i=0; i<nhash(h); i++) for (i=0; i<nhash(h); i++)
{ {
@@ -219,7 +206,7 @@ Long lua_hashcollector (void)
** executes garbage collection if the number of arrays created ** executes garbage collection if the number of arrays created
** exceed a pre-defined range. ** exceed a pre-defined range.
*/ */
Hash *lua_createarray (Word nhash) Hash *lua_createarray (int nhash)
{ {
Hash *array; Hash *array;
lua_pack(); lua_pack();
@@ -235,10 +222,10 @@ Hash *lua_createarray (Word nhash)
*/ */
static void rehash (Hash *t) static void rehash (Hash *t)
{ {
Word i; int i;
Word nold = nhash(t); int nold = nhash(t);
Node *vold = nodevector(t); Node *vold = nodevector(t);
nhash(t) = redimension(nhash(t)); nhash(t) = luaI_redimension(nhash(t));
nodevector(t) = hashnodecreate(nhash(t)); nodevector(t) = hashnodecreate(nhash(t));
for (i=0; i<nold; i++) for (i=0; i<nold; i++)
{ {
@@ -255,7 +242,7 @@ static void rehash (Hash *t)
*/ */
Object *lua_hashget (Hash *t, Object *ref) Object *lua_hashget (Hash *t, Object *ref)
{ {
Word h = present(t, ref); int h = present(t, ref);
if (tag(ref(node(t, h))) != LUA_T_NIL) return val(node(t, h)); if (tag(ref(node(t, h))) != LUA_T_NIL) return val(node(t, h));
else return NULL; else return NULL;
} }
@@ -267,7 +254,7 @@ Object *lua_hashget (Hash *t, Object *ref)
*/ */
Object *lua_hashdefine (Hash *t, Object *ref) Object *lua_hashdefine (Hash *t, Object *ref)
{ {
Word h; int h;
Node *n; Node *n;
h = present(t, ref); h = present(t, ref);
n = node(t, h); n = node(t, h);
@@ -293,7 +280,7 @@ Object *lua_hashdefine (Hash *t, Object *ref)
** in the hash. ** in the hash.
** This function pushs the element value and its reference to the stack. ** This function pushs the element value and its reference to the stack.
*/ */
static void hashnext (Hash *t, Word i) static void hashnext (Hash *t, int i)
{ {
if (i >= nhash(t)) if (i >= nhash(t))
{ {
@@ -330,7 +317,7 @@ void lua_next (void)
} }
else else
{ {
Word h = present (t, luaI_Address(r)); int h = present (t, luaI_Address(r));
hashnext(t, h+1); hashnext(t, h+1);
} }
} }

15
hash.h
View File

@@ -1,14 +1,14 @@
/* /*
** hash.h ** hash.h
** hash manager for lua ** hash manager for lua
** Luiz Henrique de Figueiredo - 17 Aug 90 ** $Id: hash.h,v 2.11 1996/03/08 12:04:04 roberto Exp roberto $
** $Id: hash.h,v 2.7 1994/12/20 21:20:36 roberto Exp roberto $
*/ */
#ifndef hash_h #ifndef hash_h
#define hash_h #define hash_h
#include "types.h" #include "types.h"
#include "opcode.h"
typedef struct node typedef struct node
{ {
@@ -19,15 +19,16 @@ typedef struct node
typedef struct Hash typedef struct Hash
{ {
struct Hash *next; struct Hash *next;
char mark;
Word nhash;
Word nuse;
Node *node; Node *node;
int nhash;
int nuse;
char mark;
} Hash; } Hash;
Bool lua_equalObj (Object *t1, Object *t2); int lua_equalObj (Object *t1, Object *t2);
Hash *lua_createarray (Word nhash); int luaI_redimension (int nhash);
Hash *lua_createarray (int nhash);
void lua_hashmark (Hash *h); void lua_hashmark (Hash *h);
Long lua_hashcollector (void); Long lua_hashcollector (void);
Object *lua_hashget (Hash *t, Object *ref); Object *lua_hashget (Hash *t, Object *ref);

240
inout.c
View File

@@ -5,42 +5,24 @@
** Also provides some predefined lua functions. ** Also provides some predefined lua functions.
*/ */
char *rcs_inout="$Id: inout.c,v 2.15 1994/12/16 15:55:04 roberto Exp roberto $"; char *rcs_inout="$Id: inout.c,v 2.35 1996/03/19 16:50:24 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mem.h" #include "lex.h"
#include "opcode.h" #include "opcode.h"
#include "hash.h"
#include "inout.h" #include "inout.h"
#include "table.h" #include "table.h"
#include "tree.h" #include "tree.h"
#include "lua.h" #include "lua.h"
#include "mem.h"
/* Exported variables */ /* Exported variables */
Word lua_linenumber; Word lua_linenumber;
Bool lua_debug; char *lua_parsedfile;
Word lua_debugline = 0;
/* Internal variables */
#ifndef MAXFUNCSTACK
#define MAXFUNCSTACK 100
#endif
typedef struct FuncStackNode {
struct FuncStackNode *next;
char *file;
Word function;
Word line;
} FuncStackNode;
static FuncStackNode *funcStack = NULL;
static Word nfuncstack=0;
static FILE *fp; static FILE *fp;
static char *st; static char *st;
@@ -62,20 +44,23 @@ static int stringinput (void)
/* /*
** Function to open a file to be input unit. ** Function to open a file to be input unit.
** Return 0 on success or error message on error. ** Return the file.
*/ */
char *lua_openfile (char *fn) FILE *lua_openfile (char *fn)
{ {
lua_linenumber = 1;
lua_setinput (fileinput); lua_setinput (fileinput);
fp = fopen (fn, "r"); if (fn == NULL)
if (fp == NULL)
{ {
static char buff[32]; fp = stdin;
sprintf(buff, "unable to open file %.10s", fn); fn = "(stdin)";
return buff;
} }
return lua_addfile (fn); else
fp = fopen (fn, "r");
if (fp == NULL)
return NULL;
lua_linenumber = 1;
lua_parsedfile = luaI_createfixedstring(fn)->str;
return fp;
} }
/* /*
@@ -83,9 +68,8 @@ char *lua_openfile (char *fn)
*/ */
void lua_closefile (void) void lua_closefile (void)
{ {
if (fp != NULL) if (fp != NULL && fp != stdin)
{ {
lua_delfile();
fclose (fp); fclose (fp);
fp = NULL; fp = NULL;
} }
@@ -94,16 +78,12 @@ void lua_closefile (void)
/* /*
** Function to open a string to be input unit ** Function to open a string to be input unit
*/ */
char *lua_openstring (char *s) void lua_openstring (char *s)
{ {
lua_linenumber = 1;
lua_setinput (stringinput); lua_setinput (stringinput);
st = s; st = s;
{ lua_linenumber = 1;
char sn[64]; lua_parsedfile = luaI_createfixedstring("(string)")->str;
sprintf (sn, "String: %10.10s...", s);
return lua_addfile (sn);
}
} }
/* /*
@@ -111,75 +91,6 @@ char *lua_openstring (char *s)
*/ */
void lua_closestring (void) void lua_closestring (void)
{ {
lua_delfile();
}
/*
** Called to execute SETFUNCTION opcode, this function pushs a function into
** function stack.
*/
void lua_pushfunction (char *file, Word function)
{
FuncStackNode *newNode;
if (nfuncstack++ >= MAXFUNCSTACK)
{
lua_reportbug("function stack overflow");
}
newNode = new(FuncStackNode);
newNode->function = function;
newNode->file = file;
newNode->line= lua_debugline;
newNode->next = funcStack;
funcStack = newNode;
}
/*
** Called to execute RESET opcode, this function pops a function from
** function stack.
*/
void lua_popfunction (void)
{
FuncStackNode *temp = funcStack;
if (temp == NULL) return;
--nfuncstack;
lua_debugline = temp->line;
funcStack = temp->next;
luaI_free(temp);
}
/*
** Report bug building a message and sending it to lua_error function.
*/
void lua_reportbug (char *s)
{
char msg[MAXFUNCSTACK*80];
strcpy (msg, s);
if (lua_debugline != 0)
{
if (funcStack)
{
FuncStackNode *func = funcStack;
int line = lua_debugline;
sprintf (strchr(msg,0), "\n\tactive stack:\n");
do
{
sprintf (strchr(msg,0),
"\t-> function \"%s\" at file \"%s\":%u\n",
lua_constant[func->function]->str, func->file, line);
line = func->line;
func = func->next;
lua_popfunction();
} while (func);
}
else
{
sprintf (strchr(msg,0),
"\n\tin statement begining at line %u of file \"%s\"",
lua_debugline, lua_filename());
}
}
lua_error (msg);
} }
@@ -201,33 +112,57 @@ void lua_internaldostring (void)
void lua_internaldofile (void) void lua_internaldofile (void)
{ {
lua_Object obj = lua_getparam (1); lua_Object obj = lua_getparam (1);
if (lua_isstring(obj) && !lua_dofile(lua_getstring(obj))) char *fname = NULL;
if (lua_isstring(obj))
fname = lua_getstring(obj);
else if (obj != LUA_NOOBJECT)
lua_error("invalid argument to function `dofile'");
/* else fname = NULL */
if (!lua_dofile(fname))
lua_pushnumber(1); lua_pushnumber(1);
else else
lua_pushnil(); lua_pushnil();
} }
/*
** Internal function: print object values static char *tostring (lua_Object obj)
*/
void lua_print (void)
{ {
int i=1; char *buff = luaI_buffer(20);
lua_Object obj; if (lua_isstring(obj)) /* get strings and numbers */
while ((obj=lua_getparam (i++)) != LUA_NOOBJECT) return lua_getstring(obj);
{ else switch(lua_type(obj))
if (lua_isnumber(obj)) printf("%g\n",lua_getnumber(obj)); {
else if (lua_isstring(obj)) printf("%s\n",lua_getstring(obj)); case LUA_T_FUNCTION:
else if (lua_isfunction(obj)) printf("function: %p\n",bvalue(luaI_Address(obj))); sprintf(buff, "function: %p", (luaI_Address(obj))->value.tf);
else if (lua_iscfunction(obj)) printf("cfunction: %p\n",lua_getcfunction(obj) break;
); case LUA_T_CFUNCTION:
else if (lua_isuserdata(obj)) printf("userdata: %p\n",lua_getuserdata(obj)); sprintf(buff, "cfunction: %p", lua_getcfunction(obj));
else if (lua_istable(obj)) printf("table: %p\n",avalue(luaI_Address(obj))); break;
else if (lua_isnil(obj)) printf("nil\n"); case LUA_T_ARRAY:
else printf("invalid value to print\n"); sprintf(buff, "table: %p", avalue(luaI_Address(obj)));
} break;
case LUA_T_NIL:
sprintf(buff, "nil");
break;
default:
sprintf(buff, "userdata: %p", lua_getuserdata(obj));
break;
}
return buff;
} }
void luaI_tostring (void)
{
lua_pushstring(tostring(lua_getparam(1)));
}
void luaI_print (void)
{
int i = 1;
lua_Object obj;
while ((obj = lua_getparam(i++)) != LUA_NOOBJECT)
printf("%s\n", tostring(obj));
}
/* /*
** Internal function: return an object type. ** Internal function: return an object type.
@@ -235,9 +170,11 @@ void lua_print (void)
void luaI_type (void) void luaI_type (void)
{ {
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
int t;
if (o == LUA_NOOBJECT) if (o == LUA_NOOBJECT)
lua_error("no parameter to function 'type'"); lua_error("no parameter to function 'type'");
switch (lua_type(o)) t = lua_type(o);
switch (t)
{ {
case LUA_T_NIL : case LUA_T_NIL :
lua_pushliteral("nil"); lua_pushliteral("nil");
@@ -252,15 +189,14 @@ void luaI_type (void)
lua_pushliteral("table"); lua_pushliteral("table");
break; break;
case LUA_T_FUNCTION : case LUA_T_FUNCTION :
lua_pushliteral("function");
break;
case LUA_T_CFUNCTION : case LUA_T_CFUNCTION :
lua_pushliteral("cfunction"); lua_pushliteral("function");
break; break;
default : default :
lua_pushliteral("userdata"); lua_pushliteral("userdata");
break; break;
} }
lua_pushnumber(t);
} }
/* /*
@@ -270,16 +206,7 @@ void lua_obj2number (void)
{ {
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
if (lua_isnumber(o)) if (lua_isnumber(o))
lua_pushobject(o); lua_pushnumber(lua_getnumber(o));
else if (lua_isstring(o))
{
char c;
float f;
if (sscanf(lua_getstring(o),"%f %c",&f,&c) == 1)
lua_pushnumber(f);
else
lua_pushnil();
}
else else
lua_pushnil(); lua_pushnil();
} }
@@ -289,6 +216,31 @@ void luaI_error (void)
{ {
char *s = lua_getstring(lua_getparam(1)); char *s = lua_getstring(lua_getparam(1));
if (s == NULL) s = "(no message)"; if (s == NULL) s = "(no message)";
lua_reportbug(s); lua_error(s);
} }
void luaI_assert (void)
{
lua_Object p = lua_getparam(1);
if (p == LUA_NOOBJECT || lua_isnil(p))
lua_error("assertion failed!");
}
void luaI_setglobal (void)
{
lua_Object name = lua_getparam(1);
lua_Object value = lua_getparam(2);
if (!lua_isstring(name))
lua_error("incorrect argument to function `setglobal'");
lua_pushobject(value);
lua_storeglobal(lua_getstring(name));
lua_pushobject(value); /* return given value */
}
void luaI_getglobal (void)
{
lua_Object name = lua_getparam(1);
if (!lua_isstring(name))
lua_error("incorrect argument to function `getglobal'");
lua_pushobject(lua_getglobal(lua_getstring(name)));
}

19
inout.h
View File

@@ -1,5 +1,5 @@
/* /*
** $Id: inout.h,v 1.6 1994/11/21 21:41:09 roberto Stab roberto $ ** $Id: inout.h,v 1.14 1996/03/15 13:13:13 roberto Exp roberto $
*/ */
@@ -7,24 +7,27 @@
#define inout_h #define inout_h
#include "types.h" #include "types.h"
#include <stdio.h>
extern Word lua_linenumber; extern Word lua_linenumber;
extern Bool lua_debug;
extern Word lua_debugline; extern Word lua_debugline;
extern char *lua_parsedfile;
char *lua_openfile (char *fn); FILE *lua_openfile (char *fn);
void lua_closefile (void); void lua_closefile (void);
char *lua_openstring (char *s); void lua_openstring (char *s);
void lua_closestring (void); void lua_closestring (void);
void lua_pushfunction (char *file, Word function);
void lua_popfunction (void);
void lua_reportbug (char *s);
void lua_internaldofile (void); void lua_internaldofile (void);
void lua_internaldostring (void); void lua_internaldostring (void);
void lua_print (void); void luaI_tostring (void);
void luaI_print (void);
void luaI_type (void); void luaI_type (void);
void lua_obj2number (void); void lua_obj2number (void);
void luaI_error (void); void luaI_error (void);
void luaI_assert (void);
void luaI_setglobal (void);
void luaI_getglobal (void);
#endif #endif

825
iolib.c
View File

@@ -3,62 +3,86 @@
** Input/output library to LUA ** Input/output library to LUA
*/ */
char *rcs_iolib="$Id: iolib.c,v 1.20 1995/02/02 18:54:58 roberto Exp roberto $"; char *rcs_iolib="$Id: iolib.c,v 1.43 1996/04/30 21:13:55 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <stdlib.h> #include <stdlib.h>
#include <errno.h>
#include "lua.h" #include "lua.h"
#include "luadebug.h"
#include "lualib.h" #include "lualib.h"
static FILE *in=stdin, *out=stdout; static FILE *in=stdin, *out=stdout;
#ifdef POPEN
FILE *popen();
int pclose();
#else
#define popen(x,y) NULL /* that is, popen always fails */
#define pclose(x) (-1)
#endif
static void pushresult (int i)
{
if (i)
lua_pushnumber (1);
else
lua_pushnil();
}
static void closeread (void)
{
if (in != stdin)
{
if (pclose(in) == -1)
fclose(in);
in = stdin;
}
}
static void closewrite (void)
{
if (out != stdout)
{
if (pclose(out) == -1)
fclose(out);
out = stdout;
}
}
/* /*
** Open a file to read. ** Open a file to read.
** LUA interface: ** LUA interface:
** status = readfrom (filename) ** status = readfrom (filename)
** where: ** where:
** status = 1 -> success ** status = 1 -> success
** status = 0 -> error ** status = nil -> error
*/ */
static void io_readfrom (void) static void io_readfrom (void)
{ {
lua_Object o = lua_getparam (1); if (lua_getparam (1) == LUA_NOOBJECT)
if (o == LUA_NOOBJECT) /* restore standart input */ { /* restore standart input */
{ closeread();
if (in != stdin)
{
fclose (in);
in = stdin;
}
lua_pushnumber (1); lua_pushnumber (1);
} }
else else
{ {
if (!lua_isstring (o)) char *s = lua_check_string(1, "readfrom");
{ FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
lua_error ("incorrect argument to function 'readfrom`");
lua_pushnumber (0);
}
else
{
FILE *fp = fopen (lua_getstring(o),"r");
if (fp == NULL) if (fp == NULL)
{ lua_pushnil();
lua_pushnumber (0);
}
else else
{ {
if (in != stdin) fclose (in); closeread();
in = fp; in = fp;
lua_pushnumber (1); lua_pushnumber (1);
} }
}
} }
} }
@@ -69,41 +93,27 @@ static void io_readfrom (void)
** status = writeto (filename) ** status = writeto (filename)
** where: ** where:
** status = 1 -> success ** status = 1 -> success
** status = 0 -> error ** status = nil -> error
*/ */
static void io_writeto (void) static void io_writeto (void)
{ {
lua_Object o = lua_getparam (1); if (lua_getparam (1) == LUA_NOOBJECT) /* restore standart output */
if (o == LUA_NOOBJECT) /* restore standart output */
{ {
if (out != stdout) closewrite();
{
fclose (out);
out = stdout;
}
lua_pushnumber (1); lua_pushnumber (1);
} }
else else
{ {
if (!lua_isstring (o)) char *s = lua_check_string(1, "writeto");
{ FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
lua_error ("incorrect argument to function 'writeto`");
lua_pushnumber (0);
}
else
{
FILE *fp = fopen (lua_getstring(o),"w");
if (fp == NULL) if (fp == NULL)
{ lua_pushnil();
lua_pushnumber (0);
}
else else
{ {
if (out != stdout) fclose (out); closewrite();
out = fp; out = fp;
lua_pushnumber (1); lua_pushnumber (1);
} }
}
} }
} }
@@ -113,52 +123,62 @@ static void io_writeto (void)
** LUA interface: ** LUA interface:
** status = appendto (filename) ** status = appendto (filename)
** where: ** where:
** status = 2 -> success (already exist) ** status = 1 -> success
** status = 1 -> success (new file) ** status = nil -> error
** status = 0 -> error
*/ */
static void io_appendto (void) static void io_appendto (void)
{ {
lua_Object o = lua_getparam (1); char *s = lua_check_string(1, "appendto");
if (o == LUA_NOOBJECT) /* restore standart output */ FILE *fp = fopen (s, "a");
{ if (fp == NULL)
if (out != stdout) lua_pushnil();
{
fclose (out);
out = stdout;
}
lua_pushnumber (1);
}
else else
{ {
if (!lua_isstring (o)) if (out != stdout) fclose (out);
{ out = fp;
lua_error ("incorrect argument to function 'appendto`"); lua_pushnumber(1);
lua_pushnumber (0);
}
else
{
int r;
FILE *fp;
struct stat st;
if (stat(lua_getstring(o), &st) == -1) r = 1;
else r = 2;
fp = fopen (lua_getstring(o),"a");
if (fp == NULL)
{
lua_pushnumber (0);
}
else
{
if (out != stdout) fclose (out);
out = fp;
lua_pushnumber (r);
}
}
} }
} }
static char getformat (char *f, int *just, int *m, int *n)
{
int t;
switch (*f++)
{
case 'q': case 'Q':
case 's': case 'S':
case 'i': case 'I':
t = tolower(*(f-1));
break;
case 'f': case 'F': case 'g': case 'G': case 'e': case 'E':
t = 'f';
break;
default:
t = 0; /* to avoid compiler warnings */
lua_arg_error("read/write (format)");
}
*just = (*f == '<' || *f == '>' || *f == '|') ? *f++ : '>';
if (isdigit(*f))
{
*m = 0;
while (isdigit(*f))
*m = *m*10 + (*f++ - '0');
}
else
*m = -1;
if (*f == '.')
{
f++; /* skip point */
*n = 0;
while (isdigit(*f))
*n = *n*10 + (*f++ - '0');
}
else
*n = -1;
return t;
}
/* /*
** Read a variable. On error put nil on stack. ** Read a variable. On error put nil on stack.
@@ -174,138 +194,112 @@ static void io_appendto (void)
** Estes especificadores podem vir seguidos de numero que representa ** Estes especificadores podem vir seguidos de numero que representa
** o numero de campos a serem lidos. ** o numero de campos a serem lidos.
*/ */
static void io_read (void)
static int read_until_char (int del)
{
int c;
while((c = fgetc(in)) != EOF && c != del)
luaI_addchar(c);
return c;
}
static void read_until_blank (void)
{
int c;
while((c = fgetc(in)) != EOF && !isspace(c))
luaI_addchar(c);
if (c != EOF) ungetc(c,in);
}
static void read_m (int m)
{
int c;
while (m-- && (c = fgetc(in)) != EOF)
luaI_addchar(c);
}
static void read_free (void)
{ {
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT || !lua_isstring(o)) /* free format */
{
int c; int c;
char s[256];
while (isspace(c=fgetc(in))) while (isspace(c=fgetc(in)))
; ;
if (c == '\"') if (c == EOF)
{ {
int n=0;
while((c = fgetc(in)) != '\"')
{
if (c == EOF)
{
lua_pushnil ();
return;
}
s[n++] = c;
}
s[n] = 0;
}
else if (c == '\'')
{
int n=0;
while((c = fgetc(in)) != '\'')
{
if (c == EOF)
{
lua_pushnil ();
return;
}
s[n++] = c;
}
s[n] = 0;
}
else
{
double d;
ungetc (c, in);
if (fscanf (in, "%s", s) != 1)
{
lua_pushnil ();
return;
}
if (sscanf(s, "%lf %*c", &d) == 1)
{
lua_pushnumber (d);
return;
}
}
lua_pushstring (s);
return;
}
else /* formatted */
{
char *e = lua_getstring(o);
char t;
int m=0;
while (isspace(*e)) e++;
t = *e++;
while (isdigit(*e))
m = m*10 + (*e++ - '0');
if (m > 0)
{
char f[80];
char s[256];
sprintf (f, "%%%ds", m);
if (fgets (s, m, in) == NULL)
{
lua_pushnil(); lua_pushnil();
return; return;
} }
else if (c == '\"' || c == '\'')
{ { /* string */
if (s[strlen(s)-1] == '\n') c = read_until_char(c);
s[strlen(s)-1] = 0; if (c == EOF)
} lua_pushnil();
switch (tolower(t)) else
{ lua_pushstring(luaI_addchar(0));
case 'i':
{
long int l;
sscanf (s, "%ld", &l);
lua_pushnumber(l);
}
break;
case 'f': case 'g': case 'e':
{
float fl;
sscanf (s, "%f", &fl);
lua_pushnumber(fl);
}
break;
default:
lua_pushstring(s);
break;
}
} }
else else
{ {
switch (tolower(t)) double d;
{ char dummy;
case 'i': char *s;
{ luaI_addchar(c);
long int l; read_until_blank();
if (fscanf (in, "%ld", &l) == EOF) s = luaI_addchar(0);
lua_pushnil(); if (sscanf(s, "%lf %c", &d, &dummy) == 1)
else lua_pushnumber(l); lua_pushnumber(d);
} else
break; lua_pushstring(s);
case 'f': case 'g': case 'e': }
{ }
float f;
if (fscanf (in, "%f", &f) == EOF) static void io_read (void)
lua_pushnil(); {
else lua_pushnumber(f); lua_Object o = lua_getparam (1);
} luaI_addchar(0); /* initialize buffer */
break; if (o == LUA_NOOBJECT) /* free format */
default: read_free();
{ else /* formatted */
char s[256]; {
if (fscanf (in, "%s", s) == EOF) int m, dummy1, dummy2;
lua_pushnil(); switch (getformat(lua_check_string(1, "read"), &dummy1, &m, &dummy2))
else lua_pushstring(s); {
} case 's':
break; {
} char *s;
if (m < 0)
read_until_blank();
else
read_m(m);
s = luaI_addchar(0);
if ((m >= 0 && strlen(s) == m) || (m < 0 && strlen(s) > 0))
lua_pushstring(s);
else
lua_pushnil();
break;
}
case 'i': /* can read as float, since it makes no difference to Lua */
case 'f':
{
double d;
int result;
if (m < 0)
result = fscanf(in, "%lf", &d);
else
{
read_m(m);
result = sscanf(luaI_addchar(0), "%lf", &d);
}
if (result == 1)
lua_pushnumber(d);
else
lua_pushnil();
break;
}
default:
lua_arg_error("read (format)");
}
} }
}
} }
@@ -314,33 +308,19 @@ static void io_read (void)
*/ */
static void io_readuntil (void) static void io_readuntil (void)
{ {
int n=255,m=0; int del, c;
int c,d; lua_Object p = lua_getparam(1);
char *s; luaI_addchar(0); /* initialize buffer */
lua_Object lo = lua_getparam(1); if (p == LUA_NOOBJECT || lua_isnil(p))
if (!lua_isstring(lo)) del = EOF;
d = EOF;
else else
d = *lua_getstring(lo); del = *lua_check_string(1, "readuntil");
c = read_until_char(del);
s = (char *)malloc(n+1);
while((c = fgetc(in)) != EOF && c != d)
{
if (m==n)
{
n *= 2;
s = (char *)realloc(s, n+1);
}
s[m++] = c;
}
if (c != EOF) ungetc(c,in); if (c != EOF) ungetc(c,in);
s[m] = 0; lua_pushstring(luaI_addchar(0));
lua_pushstring(s);
free(s);
} }
/* /*
** Write a variable. On error put 0 on stack, otherwise put 1. ** Write a variable. On error put 0 on stack, otherwise put 1.
** LUA interface: ** LUA interface:
@@ -367,106 +347,111 @@ static void io_readuntil (void)
** inteiros -> numero minimo de digitos ** inteiros -> numero minimo de digitos
** string -> nao se aplica ** string -> nao se aplica
*/ */
static char *buildformat (char *e, lua_Object o)
{
static char buffer[2048];
static char f[80];
char *string = &buffer[255];
char *fstart=e, *fspace, *send;
char t, j='r';
int m=0, n=-1, l;
while (isspace(*e)) e++;
fspace = e;
t = *e++;
if (*e == '<' || *e == '|' || *e == '>') j = *e++;
while (isdigit(*e))
m = m*10 + (*e++ - '0');
if (*e == '.') e++; /* skip point */
while (isdigit(*e))
if (n < 0) n = (*e++ - '0');
else n = n*10 + (*e++ - '0');
sprintf(f,"%%"); static int write_fill (int n, int c)
if (j == '<' || j == '|') sprintf(strchr(f,0),"-"); {
if (m > 0) sprintf(strchr(f,0),"%d", m); while (n--)
if (n >= 0) sprintf(strchr(f,0),".%d", n); if (fputc(c, out) == EOF)
switch (t) return 0;
{ return 1;
case 'i': case 'I': t = 'd';
sprintf(strchr(f,0), "%c", t);
sprintf (string, f, (long int)lua_getnumber(o));
break;
case 'f': case 'g': case 'e': case 'G': case 'E':
sprintf(strchr(f,0), "%c", t);
sprintf (string, f, (float)lua_getnumber(o));
break;
case 'F': t = 'f';
sprintf(strchr(f,0), "%c", t);
sprintf (string, f, (float)lua_getnumber(o));
break;
case 's': case 'S': t = 's';
sprintf(strchr(f,0), "%c", t);
sprintf (string, f, lua_getstring(o));
break;
default: return "";
}
l = strlen(string);
send = string+l;
if (m!=0 && l>m)
{
int i;
for (i=0; i<m; i++)
string[i] = '*';
string[i] = 0;
}
else if (m!=0 && j=='|')
{
int k;
int i=l-1;
while (isspace(string[i]) || string[i]==0) i--;
string -= (m-i)/2;
for(k=0; k<(m-i)/2; k++)
string[k] = ' ';
}
/* add space characteres */
while (fspace != fstart)
{
string--;
fspace--;
*string = *fspace;
}
while (isspace(*e)) *send++ = *e++;
*send = 0;
return string;
} }
static int write_string (char *s, int just, int m)
{
int status;
int l = strlen(s);
int pre; /* number of blanks before string */
if (m < 0) m = l;
else if (l > m)
{
write_fill(m, '*');
return 0;
}
pre = (just == '<') ? 0 : (just == '>') ? m-l : (m-l)/2;
status = write_fill(pre, ' ');
status = status && fprintf(out, "%s", s) >= 0;
status = status && write_fill(m-(l+pre), ' ');
return status;
}
static int write_quoted (int just, int m)
{
luaI_addchar(0);
luaI_addquoted(lua_check_string(1, "write"));
return write_string(luaI_addchar(0), just, m);
}
static int write_float (int just, int m, int n)
{
char buffer[100];
lua_Object p = lua_getparam(1);
float number;
if (!lua_isnumber(p)) return 0;
number = lua_getnumber(p);
if (n >= 0)
sprintf(buffer, "%.*f", n, number);
else
sprintf(buffer, "%g", number);
return write_string(buffer, just, m);
}
static int write_int (int just, int m, int n)
{
char buffer[100];
lua_Object p = lua_getparam(1);
int number;
if (!lua_isnumber(p)) return 0;
number = (int)lua_getnumber(p);
if (n >= 0)
sprintf(buffer, "%.*d", n, number);
else
sprintf(buffer, "%d", number);
return write_string(buffer, just, m);
}
static void io_write (void) static void io_write (void)
{ {
lua_Object o1 = lua_getparam (1); int status = 0;
lua_Object o2 = lua_getparam (2); if (lua_getparam (2) == LUA_NOOBJECT) /* free format */
if (o1 == LUA_NOOBJECT) /* new line */ {
{ lua_Object o1 = lua_getparam(1);
fprintf (out, "\n"); int t = lua_type(o1);
lua_pushnumber(1); if (t == LUA_T_NUMBER)
} status = fprintf (out, "%g", lua_getnumber(o1)) >= 0;
else if (o2 == LUA_NOOBJECT) /* free format */ else if (t == LUA_T_STRING)
{ status = fprintf (out, "%s", lua_getstring(o1)) >= 0;
int status=0;
if (lua_isnumber(o1))
status = fprintf (out, "%g", lua_getnumber(o1));
else if (lua_isstring(o1))
status = fprintf (out, "%s", lua_getstring(o1));
lua_pushnumber(status);
}
else /* formated */
{
if (!lua_isstring(o2))
{
lua_error ("incorrect format to function `write'");
lua_pushnumber(0);
return;
} }
lua_pushnumber(fprintf (out, "%s", buildformat(lua_getstring(o2),o1))); else /* formated */
} {
int just, m, n;
switch (getformat(lua_check_string(2, "write"), &just, &m, &n))
{
case 's':
{
lua_Object p = lua_getparam(1);
if (lua_isstring(p))
status = write_string(lua_getstring(p), just, m);
else
status = 0;
break;
}
case 'q':
status = write_quoted(just, m);
break;
case 'f':
status = write_float(just, m, n);
break;
case 'i':
status = write_int(just, m, n);
break;
}
}
if (status)
lua_pushnumber(status);
else
lua_pushnil();
} }
/* /*
@@ -475,95 +460,62 @@ static void io_write (void)
*/ */
static void io_execute (void) static void io_execute (void)
{ {
lua_Object o = lua_getparam (1); lua_pushnumber(system(lua_check_string(1, "execute")));
if (o == LUA_NOOBJECT || !lua_isstring (o))
{
lua_error ("incorrect argument to function 'execute`");
lua_pushnumber (0);
}
else
{
int res = system(lua_getstring(o));
lua_pushnumber (res);
}
return;
} }
/* /*
** Remove a file. ** Remove a file. On error return nil.
** On error put 0 on stack, otherwise put 1.
*/ */
static void io_remove (void) static void io_remove (void)
{ {
lua_Object o = lua_getparam (1); pushresult(remove(lua_check_string(1, "remove")) == 0);
if (o == LUA_NOOBJECT || !lua_isstring (o)) }
{
lua_error ("incorrect argument to function 'execute`"); static void io_rename (void)
lua_pushnumber (0); {
} char *f1 = lua_check_string(1, "rename");
else char *f2 = lua_check_string(2, "rename");
{ pushresult(rename(f1, f2) == 0);
if (remove(lua_getstring(o)) == 0) }
lua_pushnumber (1);
else static void io_tmpname (void)
lua_pushnumber (0); {
} lua_pushstring(tmpnam(NULL));
return; }
static void io_errorno (void)
{
/* lua_pushstring(strerror(errno));*/
} }
/* /*
** To get a environment variables ** To get a environment variable
*/ */
static void io_getenv (void) static void io_getenv (void)
{ {
lua_Object s = lua_getparam(1); char *env = getenv(lua_check_string(1, "getenv"));
if (!lua_isstring(s)) lua_pushstring(env); /* if NULL push nil */
lua_pushnil();
else
{
char *env = getenv(lua_getstring(s));
if (env == NULL) lua_pushnil();
else lua_pushstring(env);
}
} }
/* /*
** Return time: hour, min, sec ** Return user formatted time stamp
*/
static void io_time (void)
{
time_t t;
struct tm *s;
time(&t);
s = localtime(&t);
lua_pushnumber(s->tm_hour);
lua_pushnumber(s->tm_min);
lua_pushnumber(s->tm_sec);
}
/*
** Return date: dd, mm, yyyy
*/ */
static void io_date (void) static void io_date (void)
{ {
time_t t; time_t t;
struct tm *s; struct tm *tm;
char *s;
time(&t); char b[BUFSIZ];
s = localtime(&t); if (lua_getparam(1) == LUA_NOOBJECT)
lua_pushnumber(s->tm_mday); s = "%c";
lua_pushnumber(s->tm_mon+1); else
lua_pushnumber(s->tm_year+1900); s = lua_check_string(1, "date");
} time(&t); tm = localtime(&t);
if (strftime(b,sizeof(b),s,tm))
/* lua_pushstring(b);
** Beep else
*/ lua_error("invalid `date' format");
static void io_beep (void)
{
printf("\a");
} }
/* /*
@@ -572,9 +524,8 @@ static void io_beep (void)
static void io_exit (void) static void io_exit (void)
{ {
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
if (lua_isstring(o)) int code = lua_isnumber(o) ? (int)lua_getnumber(o) : 1;
printf("%s\n", lua_getstring(o)); exit(code);
exit(1);
} }
/* /*
@@ -587,29 +538,81 @@ static void io_debug (void)
{ {
char buffer[250]; char buffer[250];
fprintf(stderr, "lua_debug> "); fprintf(stderr, "lua_debug> ");
if (gets(buffer) == 0) return; if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
if (strcmp(buffer, "cont") == 0) return; if (strcmp(buffer, "cont") == 0) return;
lua_dostring(buffer); lua_dostring(buffer);
} }
} }
/*
** Open io library static void lua_printstack (FILE *f)
*/ {
int level = 0;
lua_Object func;
fprintf(f, "Active Stack:\n");
while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT)
{
char *name;
int currentline;
fprintf(f, "\t");
switch (*lua_getobjname(func, &name))
{
case 'g':
fprintf(f, "function %s", name);
break;
case 'f':
fprintf(f, "`%s' fallback", name);
break;
default:
{
char *filename;
int linedefined;
lua_funcinfo(func, &filename, &linedefined);
if (linedefined == 0)
fprintf(f, "main of %s", filename);
else if (linedefined < 0)
fprintf(f, "%s", filename);
else
fprintf(f, "function (%s:%d)", filename, linedefined);
}
}
if ((currentline = lua_currentline(func)) > 0)
fprintf(f, " at line %d", currentline);
fprintf(f, "\n");
}
}
static void errorfb (void)
{
lua_Object o = lua_getparam(1);
char *s = lua_isstring(o) ? lua_getstring(o) : "(no messsage)";
fprintf(stderr, "lua: %s\n", s);
lua_printstack(stderr);
}
static struct lua_reg iolib[] = {
{"readfrom", io_readfrom},
{"writeto", io_writeto},
{"appendto", io_appendto},
{"read", io_read},
{"readuntil",io_readuntil},
{"write", io_write},
{"execute", io_execute},
{"remove", io_remove},
{"rename", io_rename},
{"tmpname", io_tmpname},
{"ioerror", io_errorno},
{"getenv", io_getenv},
{"date", io_date},
{"exit", io_exit},
{"debug", io_debug},
{"print_stack", errorfb}
};
void iolib_open (void) void iolib_open (void)
{ {
lua_register ("readfrom", io_readfrom); luaI_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
lua_register ("writeto", io_writeto); lua_setfallback("error", errorfb);
lua_register ("appendto", io_appendto);
lua_register ("read", io_read);
lua_register ("readuntil",io_readuntil);
lua_register ("write", io_write);
lua_register ("execute", io_execute);
lua_register ("remove", io_remove);
lua_register ("getenv", io_getenv);
lua_register ("time", io_time);
lua_register ("date", io_date);
lua_register ("beep", io_beep);
lua_register ("exit", io_exit);
lua_register ("debug", io_debug);
} }

171
lex.c
View File

@@ -1,27 +1,26 @@
char *rcs_lex = "$Id: lex.c,v 2.13 1994/12/20 21:20:36 roberto Exp celes $"; char *rcs_lex = "$Id: lex.c,v 2.31 1996/03/19 16:50:24 roberto Exp roberto $";
#include <ctype.h> #include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include "mem.h"
#include "tree.h" #include "tree.h"
#include "table.h" #include "table.h"
#include "opcode.h" #include "lex.h"
#include "inout.h" #include "inout.h"
#include "luadebug.h"
#include "parser.h" #include "parser.h"
#include "ugly.h"
#define lua_strcmp(a,b) (a[0]<b[0]?(-1):(a[0]>b[0]?(1):strcmp(a,b))) #define MINBUFF 260
#define next() { current = input(); } #define next() { current = input(); }
#define save(x) { *yytextLast++ = (x); } #define save(x) { *yytextLast++ = (x); }
#define save_and_next() { save(current); next(); } #define save_and_next() { save(current); next(); }
static int current; static int current;
static char yytext[256]; static char *yytext = NULL;
static int textsize = 0;
static char *yytextLast; static char *yytextLast;
static Input input; static Input input;
@@ -30,6 +29,11 @@ void lua_setinput (Input fn)
{ {
current = ' '; current = ' ';
input = fn; input = fn;
if (yytext == NULL)
{
textsize = MINBUFF;
yytext = newvector(textsize, char);
}
} }
char *lua_lasttext (void) char *lua_lasttext (void)
@@ -39,7 +43,6 @@ char *lua_lasttext (void)
} }
/* The reserved words must be listed in lexicographic order */
static struct static struct
{ {
char *name; char *name;
@@ -66,41 +69,85 @@ static struct
#define RESERVEDSIZE (sizeof(reserved)/sizeof(reserved[0])) #define RESERVEDSIZE (sizeof(reserved)/sizeof(reserved[0]))
static int findReserved (char *name) void luaI_addReserved (void)
{ {
int l = 0; int i;
int h = RESERVEDSIZE - 1; for (i=0; i<RESERVEDSIZE; i++)
while (l <= h)
{ {
int m = (l+h)/2; TaggedString *ts = lua_createstring(reserved[i].name);
int comp = lua_strcmp(name, reserved[m].name); ts->marked = reserved[i].token; /* reserved word (always > 255) */
if (comp < 0)
h = m-1;
else if (comp == 0)
return reserved[m].token;
else
l = m+1;
} }
return 0;
} }
int yylex (void) static void growtext (void)
{ {
float a; int size = yytextLast - yytext;
textsize = growvector(&yytext, textsize, char, lexEM, MAX_WORD);
yytextLast = yytext + size;
}
static int read_long_string (void)
{
int cont = 0;
int spaceleft = textsize - (yytextLast - yytext);
while (1)
{
if (spaceleft <= 2) /* may read more than 1 char in one cicle */
{
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
switch (current)
{
case EOF:
case 0:
return WRONGTOKEN;
case '[':
save_and_next(); spaceleft--;
if (current == '[')
{
cont++;
save_and_next(); spaceleft--;
}
continue;
case ']':
save_and_next(); spaceleft--;
if (current == ']')
{
if (cont == 0) return STRING;
cont--;
save_and_next(); spaceleft--;
}
continue;
case '\n':
lua_linenumber++; /* goes through */
default:
save_and_next(); spaceleft--;
}
}
}
int luaY_lex (void)
{
double a;
static int linelasttoken = 0;
if (lua_debug)
luaI_codedebugline(linelasttoken);
linelasttoken = lua_linenumber;
while (1) while (1)
{ {
yytextLast = yytext; yytextLast = yytext;
#if 0
fprintf(stderr,"'%c' %d\n",current,current);
#endif
switch (current) switch (current)
{ {
case EOF: case EOF:
case 0: case 0:
return 0; return 0;
case '\n': lua_linenumber++; case '\n': linelasttoken = ++lua_linenumber;
case ' ': case ' ':
case '\r': /* CR: to avoid problems with DOS/Windows */
case '\t': case '\t':
next(); next();
continue; continue;
@@ -110,14 +157,14 @@ int yylex (void)
while (isalnum(current) || current == '_') while (isalnum(current) || current == '_')
save_and_next(); save_and_next();
*yytextLast = 0; *yytextLast = 0;
if (lua_strcmp(yytext, "debug") == 0) if (strcmp(yytext, "debug") == 0)
{ {
yylval.vInt = 1; luaY_lval.vInt = 1;
return DEBUG; return DEBUG;
} }
else if (lua_strcmp(yytext, "nodebug") == 0) else if (strcmp(yytext, "nodebug") == 0)
{ {
yylval.vInt = 0; luaY_lval.vInt = 0;
return DEBUG; return DEBUG;
} }
return WRONGTOKEN; return WRONGTOKEN;
@@ -128,6 +175,20 @@ int yylex (void)
do { next(); } while (current != '\n' && current != 0); do { next(); } while (current != '\n' && current != 0);
continue; continue;
case '[':
save_and_next();
if (current != '[') return '[';
else
{
save_and_next(); /* pass the second '[' */
if (read_long_string() == WRONGTOKEN)
return WRONGTOKEN;
save_and_next(); /* pass the second ']' */
*(yytextLast-2) = 0; /* erases ']]' */
luaY_lval.vWord = luaI_findconstantbyname(yytext+2);
return STRING;
}
case '=': case '=':
save_and_next(); save_and_next();
if (current != '=') return '='; if (current != '=') return '=';
@@ -152,9 +213,16 @@ int yylex (void)
case '\'': case '\'':
{ {
int del = current; int del = current;
int spaceleft = textsize - (yytextLast - yytext);
next(); /* skip the delimiter */ next(); /* skip the delimiter */
while (current != del) while (current != del)
{ {
if (spaceleft <= 2) /* may read more than 1 char in one cicle */
{
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
spaceleft--;
switch (current) switch (current)
{ {
case EOF: case EOF:
@@ -168,6 +236,7 @@ int yylex (void)
case 'n': save('\n'); next(); break; case 'n': save('\n'); next(); break;
case 't': save('\t'); next(); break; case 't': save('\t'); next(); break;
case 'r': save('\r'); next(); break; case 'r': save('\r'); next(); break;
case '\n': lua_linenumber++; /* goes through */
default : save(current); next(); break; default : save(current); next(); break;
} }
break; break;
@@ -177,7 +246,7 @@ int yylex (void)
} }
next(); /* skip the delimiter */ next(); /* skip the delimiter */
*yytextLast = 0; *yytextLast = 0;
yylval.vWord = luaI_findconstant(lua_constcreate(yytext)); luaY_lval.vWord = luaI_findconstantbyname(yytext);
return STRING; return STRING;
} }
@@ -195,12 +264,14 @@ int yylex (void)
case 'Z': case 'Z':
case '_': case '_':
{ {
Word res; TaggedString *ts;
do { save_and_next(); } while (isalnum(current) || current == '_'); do { save_and_next(); } while (isalnum(current) || current == '_');
*yytextLast = 0; *yytextLast = 0;
res = findReserved(yytext); ts = lua_createstring(yytext);
if (res) return res; if (ts->marked > 2)
yylval.pNode = lua_constcreate(yytext); return ts->marked; /* reserved word */
luaY_lval.pTStr = ts;
ts->marked = 2; /* avoid GC */
return NAME; return NAME;
} }
@@ -219,48 +290,32 @@ int yylex (void)
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':
a=0.0; a=0.0;
do { a=10*a+current-'0'; save_and_next(); } while (isdigit(current)); do { a=10.0*a+(current-'0'); save_and_next(); } while (isdigit(current));
if (current == '.') save_and_next(); if (current == '.') save_and_next();
fraction: fraction:
{ float da=0.1; { double da=0.1;
while (isdigit(current)) while (isdigit(current))
{a+=(current-'0')*da; da/=10.0; save_and_next()}; {a+=(current-'0')*da; da/=10.0; save_and_next()};
if (current == 'e' || current == 'E') if (current == 'e' || current == 'E')
{ {
int e=0; int e=0;
int neg; int neg;
float ea; double ea;
save_and_next(); save_and_next();
neg=(current=='-'); neg=(current=='-');
if (current == '+' || current == '-') save_and_next(); if (current == '+' || current == '-') save_and_next();
if (!isdigit(current)) return WRONGTOKEN; if (!isdigit(current)) return WRONGTOKEN;
do { e=10*e+current-'0'; save_and_next(); } while (isdigit(current)); do { e=10.0*e+(current-'0'); save_and_next(); } while (isdigit(current));
for (ea=neg?0.1:10.0; e>0; e>>=1) for (ea=neg?0.1:10.0; e>0; e>>=1)
{ {
if (e & 1) a*=ea; if (e & 1) a*=ea;
ea*=ea; ea*=ea;
} }
} }
yylval.vFloat = a; luaY_lval.vFloat = a;
return NUMBER; return NUMBER;
} }
case U_and: case U_do: case U_else: case U_elseif: case U_end:
case U_function: case U_if: case U_local: case U_nil: case U_not:
case U_or: case U_repeat: case U_return: case U_then:
case U_until: case U_while:
{
int old = current;
next();
return reserved[old-U_and].token;
}
case U_eq: next(); return EQ;
case U_le: next(); return LE;
case U_ge: next(); return GE;
case U_ne: next(); return NE;
case U_sc: next(); return CONC;
default: /* also end of file */ default: /* also end of file */
{ {
save_and_next(); save_and_next();

19
lex.h Normal file
View File

@@ -0,0 +1,19 @@
/*
** lex.h
** TecCGraf - PUC-Rio
** $Id: lex.h,v 1.1 1996/02/13 17:30:39 roberto Exp roberto $
*/
#ifndef lex_h
#define lex_h
typedef int (*Input) (void);
void lua_setinput (Input fn);
char *lua_lasttext (void);
int luaY_lex (void);
void luaI_addReserved (void);
#endif

42
lua.c
View File

@@ -3,7 +3,7 @@
** Linguagem para Usuarios de Aplicacao ** Linguagem para Usuarios de Aplicacao
*/ */
char *rcs_lua="$Id: lua.c,v 1.3 1994/12/14 19:58:20 celes Exp $"; char *rcs_lua="$Id: lua.c,v 1.9 1996/04/23 12:43:07 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@@ -14,6 +14,16 @@ char *rcs_lua="$Id: lua.c,v 1.3 1994/12/14 19:58:20 celes Exp $";
static int lua_argc; static int lua_argc;
static char **lua_argv; static char **lua_argv;
#ifdef POSIX
/*
** although this function is POSIX, there is no standard header file that
** defines it
*/
int isatty (int fd);
#else
#define isatty(x) (x==0) /* assume stdin is a tty */
#endif
/* /*
%F Allow Lua code to access argv strings. %F Allow Lua code to access argv strings.
%i Receive from Lua the argument number (starting with 1). %i Receive from Lua the argument number (starting with 1).
@@ -33,6 +43,19 @@ static void lua_getargv (void)
} }
static void manual_input (void)
{
if (isatty(0))
{
char buffer[250];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
lua_dostring(buffer);
}
else
lua_dofile(NULL); /* executes stdin as a file */
}
int main (int argc, char *argv[]) int main (int argc, char *argv[])
{ {
int i; int i;
@@ -44,28 +67,31 @@ int main (int argc, char *argv[])
lua_register("argv", lua_getargv); lua_register("argv", lua_getargv);
if (argc < 2) if (argc < 2)
{ manual_input();
char buffer[250];
while (gets(buffer) != 0)
result = lua_dostring(buffer);
}
else else
{ {
for (i=1; i<argc; i++) for (i=1; i<argc; i++)
{
if (strcmp(argv[i], "--") == 0) if (strcmp(argv[i], "--") == 0)
{ {
lua_argc = argc-i-1; lua_argc = argc-i-1;
lua_argv = argv+i; lua_argv = argv+i;
break; break;
} }
}
for (i=1; i<argc; i++) for (i=1; i<argc; i++)
{ {
if (strcmp(argv[i], "--") == 0) if (strcmp(argv[i], "--") == 0)
break; break;
else if (strcmp(argv[i], "-") == 0)
manual_input();
else if (strcmp(argv[i], "-v") == 0)
printf("%s %s\n(written by %s)\n\n",
LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS);
else else
{
result = lua_dofile (argv[i]); result = lua_dofile (argv[i]);
if (result)
fprintf(stderr, "lua: error trying to run file %s\n", argv[i]);
}
} }
} }
return result; return result;

46
lua.h
View File

@@ -2,13 +2,18 @@
** LUA - Linguagem para Usuarios de Aplicacao ** LUA - Linguagem para Usuarios de Aplicacao
** Grupo de Tecnologia em Computacao Grafica ** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: lua.h,v 3.15 1995/01/18 20:15:05 celes Exp celes $ ** $Id: lua.h,v 3.27 1996/04/25 14:10:00 roberto Exp roberto $
*/ */
#ifndef lua_h #ifndef lua_h
#define lua_h #define lua_h
#define LUA_VERSION "Lua 2.4"
#define LUA_COPYRIGHT "Copyright (C) 1994, 1995 TeCGraf"
#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
/* Private Part */ /* Private Part */
typedef enum typedef enum
@@ -19,6 +24,9 @@ typedef enum
LUA_T_ARRAY = -4, LUA_T_ARRAY = -4,
LUA_T_FUNCTION = -5, LUA_T_FUNCTION = -5,
LUA_T_CFUNCTION= -6, LUA_T_CFUNCTION= -6,
LUA_T_MARK = -7,
LUA_T_CMARK = -8,
LUA_T_LINE = -9,
LUA_T_USERDATA = 0 LUA_T_USERDATA = 0
} lua_Type; } lua_Type;
@@ -44,6 +52,14 @@ void lua_endblock (void);
lua_Object lua_getparam (int number); lua_Object lua_getparam (int number);
#define lua_getresult(_) lua_getparam(_) #define lua_getresult(_) lua_getparam(_)
#define lua_isnil(_) (lua_type(_)==LUA_T_NIL)
#define lua_istable(_) (lua_type(_)==LUA_T_ARRAY)
#define lua_isuserdata(_) (lua_type(_)>=LUA_T_USERDATA)
#define lua_iscfunction(_) (lua_type(_)==LUA_T_CFUNCTION)
int lua_isnumber (lua_Object object);
int lua_isstring (lua_Object object);
int lua_isfunction (lua_Object object);
float lua_getnumber (lua_Object object); float lua_getnumber (lua_Object object);
char *lua_getstring (lua_Object object); char *lua_getstring (lua_Object object);
lua_CFunction lua_getcfunction (lua_Object object); lua_CFunction lua_getcfunction (lua_Object object);
@@ -52,7 +68,6 @@ void *lua_getuserdata (lua_Object object);
void lua_pushnil (void); void lua_pushnil (void);
void lua_pushnumber (float n); void lua_pushnumber (float n);
void lua_pushstring (char *s); void lua_pushstring (char *s);
void lua_pushliteral (char *s);
void lua_pushcfunction (lua_CFunction fn); void lua_pushcfunction (lua_CFunction fn);
void lua_pushusertag (void *u, int tag); void lua_pushusertag (void *u, int tag);
void lua_pushobject (lua_Object object); void lua_pushobject (lua_Object object);
@@ -65,32 +80,33 @@ lua_Object lua_getsubscript (void);
int lua_type (lua_Object object); int lua_type (lua_Object object);
int lua_lock (void);
lua_Object lua_getlocked (int ref); int lua_ref (int lock);
void lua_pushlocked (int ref); lua_Object lua_getref (int ref);
void lua_unlock (int ref); void lua_pushref (int ref);
void lua_unref (int ref);
lua_Object lua_createtable (void); lua_Object lua_createtable (void);
/* some useful macros */ /* some useful macros */
#define lua_lockobject(o) (lua_pushobject(o), lua_lock()) #define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
#define lua_register(n,f) (lua_pushcfunction(f), lua_storeglobal(n)) #define lua_register(n,f) (lua_pushcfunction(f), lua_storeglobal(n))
#define lua_pushuserdata(u) lua_pushusertag(u, LUA_T_USERDATA) #define lua_pushuserdata(u) lua_pushusertag(u, LUA_T_USERDATA)
#define lua_isnil(_) (lua_type(_)==LUA_T_NIL)
#define lua_isnumber(_) (lua_type(_)==LUA_T_NUMBER)
#define lua_isstring(_) (lua_type(_)==LUA_T_STRING)
#define lua_istable(_) (lua_type(_)==LUA_T_ARRAY)
#define lua_isfunction(_) (lua_type(_)==LUA_T_FUNCTION)
#define lua_iscfunction(_) (lua_type(_)==LUA_T_CFUNCTION)
#define lua_isuserdata(_) (lua_type(_)>=LUA_T_USERDATA)
/* for compatibility with old versions. Avoid using these macros */
/* for lua 1.1 compatibility. Avoid using these macros */ #define lua_lockobject(o) lua_refobject(o,1)
#define lua_lock() lua_ref(1)
#define lua_getlocked lua_getref
#define lua_pushlocked lua_pushref
#define lua_unlock lua_unref
#define lua_pushliteral(o) lua_pushstring(o)
#define lua_getindexed(o,n) (lua_pushobject(o), lua_pushnumber(n), lua_getsubscript()) #define lua_getindexed(o,n) (lua_pushobject(o), lua_pushnumber(n), lua_getsubscript())
#define lua_getfield(o,f) (lua_pushobject(o), lua_pushliteral(f), lua_getsubscript()) #define lua_getfield(o,f) (lua_pushobject(o), lua_pushliteral(f), lua_getsubscript())

676
lua.stx
View File

@@ -1,18 +1,20 @@
%{ %{
char *rcs_luastx = "$Id: lua.stx,v 3.16 1994/12/27 20:41:11 celes Exp roberto $"; char *rcs_luastx = "$Id: lua.stx,v 3.35 1996/03/08 12:02:37 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "luadebug.h"
#include "mem.h" #include "mem.h"
#include "lex.h"
#include "opcode.h" #include "opcode.h"
#include "hash.h" #include "hash.h"
#include "inout.h" #include "inout.h"
#include "tree.h" #include "tree.h"
#include "table.h" #include "table.h"
#include "lua.h" #include "lua.h"
#include "func.h"
/* to avoid warnings generated by yacc */ /* to avoid warnings generated by yacc */
int yyparse (void); int yyparse (void);
@@ -29,39 +31,46 @@ int yyparse (void);
#endif #endif
static int maxcode; static int maxcode;
static int maxmain; static int maxmain;
static Long maxcurr; /* to allow maxcurr *= 2 without overflow */ static int maxcurr;
static Byte *funcCode = NULL; static Byte *funcCode = NULL;
static Byte **initcode; static Byte **initcode;
static Byte *basepc; static Byte *basepc;
static int maincode; static int maincode;
static int pc; static int pc;
#define MAXVAR 32 #define MAXVAR 32
static Long varbuffer[MAXVAR]; /* variables in an assignment list; static Long varbuffer[MAXVAR]; /* variables in an assignment list;
it's long to store negative Word values */ it's long to store negative Word values */
static int nvarbuffer=0; /* number of variables at a list */ static int nvarbuffer=0; /* number of variables at a list */
static Word localvar[STACKGAP]; /* store local variable names */ #define MAXLOCALS 32
static TaggedString *localvar[MAXLOCALS]; /* store local variable names */
static int nlocalvar=0; /* number of local variables */ static int nlocalvar=0; /* number of local variables */
#define MAXFIELDS FIELDS_PER_FLUSH*2 #define MAXFIELDS FIELDS_PER_FLUSH*2
static Word fields[MAXFIELDS]; /* fieldnames to be flushed */ static Word fields[MAXFIELDS]; /* fieldnames to be flushed */
static int nfields=0; static int nfields=0;
int lua_debug = 0;
/* Internal functions */ /* Internal functions */
static void yyerror (char *s)
{
char msg[256];
char *token = lua_lasttext();
if (token[0] == 0)
token = "<eof>";
sprintf (msg,"%s; last token read: \"%s\" at line %d in file `%s'",
s, token, lua_linenumber, lua_parsedfile);
lua_error (msg);
}
static void code_byte (Byte c) static void code_byte (Byte c)
{ {
if (pc>maxcurr-2) /* 1 byte free to code HALT of main code */ if (pc>maxcurr-2) /* 1 byte free to code HALT of main code */
{ maxcurr = growvector(&basepc, maxcurr, Byte, codeEM, MAX_INT);
if (maxcurr >= MAX_INT)
lua_error("code size overflow");
maxcurr *= 2;
if (maxcurr >= MAX_INT)
maxcurr = MAX_INT;
basepc = growvector(basepc, maxcurr, Byte);
}
basepc[pc++] = c; basepc[pc++] = c;
} }
@@ -83,30 +92,32 @@ static void code_float (float n)
code_byte(code.m.c4); code_byte(code.m.c4);
} }
static void code_code (Byte *b) static void code_code (TFunc *tf)
{ {
CodeCode code; CodeCode code;
code.b = b; code.tf = tf;
code_byte(code.m.c1); code_byte(code.m.c1);
code_byte(code.m.c2); code_byte(code.m.c2);
code_byte(code.m.c3); code_byte(code.m.c3);
code_byte(code.m.c4); code_byte(code.m.c4);
} }
static void code_word_at (Byte *p, Word n) static void code_word_at (Byte *p, int n)
{ {
CodeWord code; CodeWord code;
code.w = n; if ((Word)n != n)
yyerror("block too big");
code.w = (Word)n;
*p++ = code.m.c1; *p++ = code.m.c1;
*p++ = code.m.c2; *p++ = code.m.c2;
} }
static void push_field (Word name) static void push_field (Word name)
{ {
if (nfields < STACKGAP-1) if (nfields < MAXFIELDS)
fields[nfields++] = name; fields[nfields++] = name;
else else
lua_error ("too many fields in a constructor"); yyerror ("too many fields in nested constructors");
} }
static void flush_record (int n) static void flush_record (int n)
@@ -131,24 +142,32 @@ static void flush_list (int m, int n)
code_byte(m); code_byte(m);
} }
else else
lua_error ("list constructor too long"); yyerror ("list constructor too long");
code_byte(n); code_byte(n);
} }
static void add_nlocalvar (int n) static void store_localvar (TaggedString *name, int n)
{ {
if (MAX_TEMPS+nlocalvar+MAXVAR+n < STACKGAP) if (nlocalvar+n < MAXLOCALS)
nlocalvar += n; localvar[nlocalvar+n] = name;
else else
lua_error ("too many local variables"); yyerror ("too many local variables");
if (lua_debug)
luaI_registerlocalvar(name, lua_linenumber);
} }
static void incr_nvarbuffer (void) static void add_localvar (TaggedString *name)
{ {
if (nvarbuffer < MAXVAR-1) store_localvar(name, 0);
nvarbuffer++; nlocalvar++;
}
static void add_varbuffer (Long var)
{
if (nvarbuffer < MAXVAR)
varbuffer[nvarbuffer++] = var;
else else
lua_error ("variable buffer overflow"); yyerror ("variable buffer overflow");
} }
static void code_number (float f) static void code_number (float f)
@@ -178,7 +197,7 @@ static void code_number (float f)
/* /*
** Search a local name and if find return its index. If do not find return -1 ** Search a local name and if find return its index. If do not find return -1
*/ */
static int lua_localname (Word n) static int lua_localname (TaggedString *n)
{ {
int i; int i;
for (i=nlocalvar-1; i >= 0; i--) for (i=nlocalvar-1; i >= 0; i--)
@@ -225,26 +244,35 @@ static void lua_codeadjust (int n)
} }
} }
static void init_function (TreeNode *func) static void change2main (void)
{ {
if (funcCode == NULL) /* first function */ /* (re)store main values */
{ pc=maincode; basepc=*initcode; maxcurr=maxmain;
funcCode = newvector(CODE_BLOCK, Byte); nlocalvar=0;
maxcode = CODE_BLOCK; }
}
pc=0; basepc=funcCode; maxcurr=maxcode; static void savemain (void)
nlocalvar=0; {
if (lua_debug) /* save main values */
maincode=pc; *initcode=basepc; maxmain=maxcurr;
}
static void init_func (void)
{
if (funcCode == NULL) /* first function */
{ {
code_byte(SETFUNCTION); funcCode = newvector(CODE_BLOCK, Byte);
code_code((Byte *)luaI_strdup(lua_file[lua_nfile-1])); maxcode = CODE_BLOCK;
code_word(luaI_findconstant(func));
} }
savemain(); /* save main values */
/* set func values */
pc=0; basepc=funcCode; maxcurr=maxcode;
nlocalvar = 0;
luaI_codedebugline(lua_linenumber);
} }
static void codereturn (void) static void codereturn (void)
{ {
if (lua_debug) code_byte(RESET);
if (nlocalvar == 0) if (nlocalvar == 0)
code_byte(RETCODE0); code_byte(RETCODE0);
else else
@@ -254,49 +282,71 @@ static void codereturn (void)
} }
} }
static void codedebugline (void) void luaI_codedebugline (int line)
{ {
if (lua_debug) static int lastline = 0;
if (lua_debug && line != lastline)
{ {
code_byte(SETLINE); code_byte(SETLINE);
code_word(lua_linenumber); code_word(line);
lastline = line;
} }
} }
static void adjust_mult_assign (int vars, int exps, int temps) static int adjust_functioncall (Long exp, int i)
{ {
if (exps < 0) if (exp <= 0)
return -exp; /* exp is -list length */
else
{ {
int r = vars - (-exps-1); int temp = basepc[exp];
if (r >= 0) basepc[exp] = i;
code_byte(r); return temp+i;
}
}
static void adjust_mult_assign (int vars, Long exps, int temps)
{
if (exps > 0)
{ /* must correct function call */
int diff = vars - basepc[exps];
if (diff >= 0)
adjust_functioncall(exps, diff);
else else
{ {
code_byte(0); adjust_functioncall(exps, 0);
lua_codeadjust(temps); lua_codeadjust(temps);
} }
} }
else if (vars != exps) else if (vars != -exps)
lua_codeadjust(temps); lua_codeadjust(temps);
} }
static void storesinglevar (Long v)
{
if (v > 0) /* global var */
{
code_byte(STOREGLOBAL);
code_word(v-1);
}
else if (v < 0) /* local var */
{
int number = (-v) - 1;
if (number < 10) code_byte(STORELOCAL0 + number);
else
{
code_byte(STORELOCAL);
code_byte(number);
}
}
else
code_byte(STOREINDEXED0);
}
static void lua_codestore (int i) static void lua_codestore (int i)
{ {
if (varbuffer[i] > 0) /* global var */ if (varbuffer[i] != 0) /* global or local var */
{ storesinglevar(varbuffer[i]);
code_byte(STOREGLOBAL);
code_word(varbuffer[i]-1);
}
else if (varbuffer[i] < 0) /* local var */
{
int number = (-varbuffer[i]) - 1;
if (number < 10) code_byte(STORELOCAL0 + number);
else
{
code_byte(STORELOCAL);
code_byte(number);
}
}
else /* indexed var */ else /* indexed var */
{ {
int j; int j;
@@ -332,26 +382,21 @@ static void codeIf (Long thenAdd, Long elseAdd)
code_word_at(basepc+thenAdd+1,elseinit-(thenAdd+sizeof(Word)+1)); code_word_at(basepc+thenAdd+1,elseinit-(thenAdd+sizeof(Word)+1));
} }
static void yyerror (char *s)
{
static char msg[256];
sprintf (msg,"%s near \"%s\" at line %d in file \"%s\"",
s, lua_lasttext (), lua_linenumber, lua_filename());
lua_error (msg);
}
/* /*
** Parse LUA code. ** Parse LUA code.
*/ */
void lua_parse (Byte **code) void lua_parse (TFunc *tf)
{ {
initcode = code; initcode = &(tf->code);
*initcode = newvector(CODE_BLOCK, Byte); *initcode = newvector(CODE_BLOCK, Byte);
maincode = 0; maincode = 0;
maxmain = CODE_BLOCK; maxmain = CODE_BLOCK;
change2main();
if (yyparse ()) lua_error("parse error"); if (yyparse ()) lua_error("parse error");
savemain();
(*initcode)[maincode++] = RETCODE0; (*initcode)[maincode++] = RETCODE0;
tf->size = maincode;
#if LISTING #if LISTING
{ static void PrintCode (Byte *c, Byte *end); { static void PrintCode (Byte *c, Byte *end);
PrintCode(*initcode,*initcode+maincode); } PrintCode(*initcode,*initcode+maincode); }
@@ -369,8 +414,8 @@ void lua_parse (Byte **code)
char *pChar; char *pChar;
Word vWord; Word vWord;
Long vLong; Long vLong;
Byte *pByte; TFunc *pFunc;
TreeNode *pNode; TaggedString *pTStr;
} }
%start functionlist %start functionlist
@@ -383,16 +428,21 @@ void lua_parse (Byte **code)
%token FUNCTION %token FUNCTION
%token <vFloat> NUMBER %token <vFloat> NUMBER
%token <vWord> STRING %token <vWord> STRING
%token <pNode> NAME %token <pTStr> NAME
%token <vInt> DEBUG %token <vInt> DEBUG
%type <vLong> PrepJump %type <vLong> PrepJump
%type <vInt> expr, exprlist, exprlist1, varlist1, funcParams, funcvalue %type <vLong> exprlist, exprlist1 /* if > 0, points to function return
counter (which has list length); if <= 0, -list lenght */
%type <vLong> functioncall, expr /* if != 0, points to function return
counter */
%type <vInt> varlist1, funcParams, funcvalue
%type <vInt> fieldlist, localdeclist, decinit %type <vInt> fieldlist, localdeclist, decinit
%type <vInt> ffieldlist1 %type <vInt> ffieldlist, ffieldlist1, semicolonpart
%type <vInt> lfieldlist1 %type <vInt> lfieldlist, lfieldlist1
%type <vLong> var, singlevar %type <vInt> parlist
%type <pByte> body %type <vLong> var, singlevar, funcname
%type <pFunc> body
%left AND OR %left AND OR
%left EQ NE '>' '<' LE GE %left EQ NE '>' '<' LE GE
@@ -407,62 +457,51 @@ void lua_parse (Byte **code)
functionlist : /* empty */ functionlist : /* empty */
| functionlist | functionlist globalstat
{
pc=maincode; basepc=*initcode; maxcurr=maxmain;
nlocalvar=0;
}
stat sc
{
maincode=pc; *initcode=basepc; maxmain=maxcurr;
}
| functionlist function | functionlist function
| functionlist method
| functionlist setdebug
; ;
function : FUNCTION NAME globalstat : stat sc
{ | setdebug
init_function($2); ;
}
body function : FUNCTION funcname body
{ {
Word func = luaI_findsymbol($2); code_byte(PUSHFUNCTION);
s_tag(func) = LUA_T_FUNCTION; code_code($3);
s_bvalue(func) = $4; storesinglevar($2);
} }
; ;
method : FUNCTION NAME ':' NAME funcname : var { $$ =$1; init_func(); }
{ | varexp ':' NAME
init_function($4); {
localvar[nlocalvar]=luaI_findsymbolbyname("self"); code_byte(PUSHSTRING);
add_nlocalvar(1); code_word(luaI_findconstant($3));
} $$ = 0; /* indexed variable */
body init_func();
{ add_localvar(luaI_createfixedstring("self"));
/* assign function to table field */ }
pc=maincode; basepc=*initcode; maxcurr=maxmain; ;
nlocalvar=0;
lua_pushvar(luaI_findsymbol($2)+1);
code_byte(PUSHSTRING);
code_word(luaI_findconstant($4));
code_byte(PUSHFUNCTION);
code_code($6);
code_byte(STOREINDEXED0);
maincode=pc; *initcode=basepc; maxmain=maxcurr;
}
;
body : '(' parlist ')' block END body : '(' parlist ')' block END
{ {
codereturn(); codereturn();
$$ = newvector(pc, Byte); $$ = new(TFunc);
memcpy($$, basepc, pc*sizeof(Byte)); luaI_initTFunc($$);
$$->size = pc;
$$->code = newvector(pc, Byte);
$$->fileName = lua_parsedfile;
$$->lineDefined = $2;
memcpy($$->code, basepc, pc*sizeof(Byte));
if (lua_debug)
luaI_closelocalvars($$);
/* save func values */
funcCode = basepc; maxcode=maxcurr; funcCode = basepc; maxcode=maxcurr;
#if LISTING #if LISTING
PrintCode(funcCode,funcCode+pc); PrintCode(funcCode,funcCode+pc);
#endif #endif
change2main(); /* change back to main code */
} }
; ;
@@ -472,11 +511,7 @@ statlist : /* empty */
sc : /* empty */ | ';' ; sc : /* empty */ | ';' ;
stat : { codedebugline(); } stat1 ; stat : IF expr1 THEN PrepJump block PrepJump elsepart END
cond : { codedebugline(); } expr1 ;
stat1 : IF expr1 THEN PrepJump block PrepJump elsepart END
{ codeIf($4, $6); } { codeIf($4, $6); }
| WHILE {$<vLong>$=pc;} expr1 DO PrepJump block PrepJump END | WHILE {$<vLong>$=pc;} expr1 DO PrepJump block PrepJump END
@@ -487,7 +522,7 @@ stat1 : IF expr1 THEN PrepJump block PrepJump elsepart END
code_word_at(basepc+$7+1, pc - ($<vLong>2)); code_word_at(basepc+$7+1, pc - ($<vLong>2));
} }
| REPEAT {$<vLong>$=pc;} block UNTIL cond PrepJump | REPEAT {$<vLong>$=pc;} block UNTIL expr1 PrepJump
{ {
basepc[$6] = IFFUPJMP; basepc[$6] = IFFUPJMP;
code_word_at(basepc+$6+1, pc - ($<vLong>2)); code_word_at(basepc+$6+1, pc - ($<vLong>2));
@@ -504,16 +539,16 @@ stat1 : IF expr1 THEN PrepJump block PrepJump elsepart END
lua_codeadjust (0); lua_codeadjust (0);
} }
} }
| functioncall { code_byte(0); } | functioncall
| LOCAL localdeclist decinit | LOCAL localdeclist decinit
{ add_nlocalvar($2); { nlocalvar += $2;
adjust_mult_assign($2, $3, 0); adjust_mult_assign($2, $3, 0);
} }
; ;
elsepart : /* empty */ elsepart : /* empty */
| ELSE block | ELSE block
| ELSEIF cond THEN PrepJump block PrepJump elsepart | ELSEIF expr1 THEN PrepJump block PrepJump elsepart
{ codeIf($4, $6); } { codeIf($4, $6); }
; ;
@@ -521,16 +556,20 @@ block : {$<vInt>$ = nlocalvar;} statlist ret
{ {
if (nlocalvar != $<vInt>1) if (nlocalvar != $<vInt>1)
{ {
nlocalvar = $<vInt>1; if (lua_debug)
for (; nlocalvar > $<vInt>1; nlocalvar--)
luaI_unregisterlocalvar(lua_linenumber);
else
nlocalvar = $<vInt>1;
lua_codeadjust (0); lua_codeadjust (0);
} }
} }
; ;
ret : /* empty */ ret : /* empty */
| RETURN { codedebugline(); } exprlist sc | RETURN exprlist sc
{ {
if ($3 < 0) code_byte(MULT_RET); adjust_functioncall($2, MULT_RET);
codereturn(); codereturn();
} }
; ;
@@ -542,46 +581,46 @@ PrepJump : /* empty */
code_word (0); code_word (0);
} }
expr1 : expr { if ($1 == 0) code_byte(1); } expr1 : expr { adjust_functioncall($1, 1); }
; ;
expr : '(' expr ')' { $$ = $2; } expr : '(' expr ')' { $$ = $2; }
| expr1 EQ expr1 { code_byte(EQOP); $$ = 1; } | expr1 EQ expr1 { code_byte(EQOP); $$ = 0; }
| expr1 '<' expr1 { code_byte(LTOP); $$ = 1; } | expr1 '<' expr1 { code_byte(LTOP); $$ = 0; }
| expr1 '>' expr1 { code_byte(GTOP); $$ = 1; } | expr1 '>' expr1 { code_byte(GTOP); $$ = 0; }
| expr1 NE expr1 { code_byte(EQOP); code_byte(NOTOP); $$ = 1; } | expr1 NE expr1 { code_byte(EQOP); code_byte(NOTOP); $$ = 0; }
| expr1 LE expr1 { code_byte(LEOP); $$ = 1; } | expr1 LE expr1 { code_byte(LEOP); $$ = 0; }
| expr1 GE expr1 { code_byte(GEOP); $$ = 1; } | expr1 GE expr1 { code_byte(GEOP); $$ = 0; }
| expr1 '+' expr1 { code_byte(ADDOP); $$ = 1; } | expr1 '+' expr1 { code_byte(ADDOP); $$ = 0; }
| expr1 '-' expr1 { code_byte(SUBOP); $$ = 1; } | expr1 '-' expr1 { code_byte(SUBOP); $$ = 0; }
| expr1 '*' expr1 { code_byte(MULTOP); $$ = 1; } | expr1 '*' expr1 { code_byte(MULTOP); $$ = 0; }
| expr1 '/' expr1 { code_byte(DIVOP); $$ = 1; } | expr1 '/' expr1 { code_byte(DIVOP); $$ = 0; }
| expr1 '^' expr1 { code_byte(POWOP); $$ = 1; } | expr1 '^' expr1 { code_byte(POWOP); $$ = 0; }
| expr1 CONC expr1 { code_byte(CONCOP); $$ = 1; } | expr1 CONC expr1 { code_byte(CONCOP); $$ = 0; }
| '-' expr1 %prec UNARY { code_byte(MINUSOP); $$ = 1;} | '-' expr1 %prec UNARY { code_byte(MINUSOP); $$ = 0;}
| table { $$ = 1; } | table { $$ = 0; }
| varexp { $$ = 1;} | varexp { $$ = 0;}
| NUMBER { code_number($1); $$ = 1; } | NUMBER { code_number($1); $$ = 0; }
| STRING | STRING
{ {
code_byte(PUSHSTRING); code_byte(PUSHSTRING);
code_word($1); code_word($1);
$$ = 1; $$ = 0;
} }
| NIL {code_byte(PUSHNIL); $$ = 1; } | NIL {code_byte(PUSHNIL); $$ = 0; }
| functioncall { $$ = 0; } | functioncall { $$ = $1; }
| NOT expr1 { code_byte(NOTOP); $$ = 1;} | NOT expr1 { code_byte(NOTOP); $$ = 0;}
| expr1 AND PrepJump {code_byte(POP); } expr1 | expr1 AND PrepJump {code_byte(POP); } expr1
{ {
basepc[$3] = ONFJMP; basepc[$3] = ONFJMP;
code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1)); code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1));
$$ = 1; $$ = 0;
} }
| expr1 OR PrepJump {code_byte(POP); } expr1 | expr1 OR PrepJump {code_byte(POP); } expr1
{ {
basepc[$3] = ONTJMP; basepc[$3] = ONTJMP;
code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1)); code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1));
$$ = 1; $$ = 0;
} }
; ;
@@ -597,7 +636,12 @@ table :
; ;
functioncall : funcvalue funcParams functioncall : funcvalue funcParams
{ code_byte(CALLFUNC); code_byte($1+$2); } {
code_byte(CALLFUNC);
code_byte($1+$2);
$$ = pc;
code_byte(0); /* may be modified by other rules */
}
; ;
funcvalue : varexp { $$ = 0; } funcvalue : varexp { $$ = 0; }
@@ -610,7 +654,7 @@ funcvalue : varexp { $$ = 0; }
; ;
funcParams : '(' exprlist ')' funcParams : '(' exprlist ')'
{ if ($2<0) { code_byte(1); $$ = -$2; } else $$ = $2; } { $$ = adjust_functioncall($2, 1); }
| table { $$ = 1; } | table { $$ = 1; }
; ;
@@ -618,45 +662,48 @@ exprlist : /* empty */ { $$ = 0; }
| exprlist1 { $$ = $1; } | exprlist1 { $$ = $1; }
; ;
exprlist1 : expr { if ($1 == 0) $$ = -1; else $$ = 1; } exprlist1 : expr { if ($1 != 0) $$ = $1; else $$ = -1; }
| exprlist1 ',' { if ($1 < 0) code_byte(1); } expr | exprlist1 ',' { $<vLong>$ = adjust_functioncall($1, 1); } expr
{ {
int r = $1 < 0 ? -$1 : $1; if ($4 == 0) $$ = -($<vLong>3 + 1); /* -length */
$$ = ($4 == 0) ? -(r+1) : r+1; else
{
adjust_functioncall($4, $<vLong>3);
$$ = $4;
}
} }
; ;
parlist : /* empty */ { lua_codeadjust(0); } parlist : /* empty */ { lua_codeadjust(0); $$ = lua_linenumber; }
| parlist1 { lua_codeadjust(0); } | parlist1 { lua_codeadjust(0); $$ = lua_linenumber; }
; ;
parlist1 : NAME parlist1 : NAME { add_localvar($1); }
{ | parlist1 ',' NAME { add_localvar($3); }
localvar[nlocalvar]=luaI_findsymbol($1);
add_nlocalvar(1);
}
| parlist1 ',' NAME
{
localvar[nlocalvar]=luaI_findsymbol($3);
add_nlocalvar(1);
}
; ;
fieldlist : /* empty */ { $$ = 0; } fieldlist : lfieldlist
| lfieldlist1 lastcomma { flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); }
{ $$ = $1; flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); } semicolonpart
{ $$ = $1+$3; }
| ffieldlist1 lastcomma | ffieldlist1 lastcomma
{ $$ = $1; flush_record($1%FIELDS_PER_FLUSH); } { $$ = $1; flush_record($1%FIELDS_PER_FLUSH); }
| lfieldlist1 ';'
{ flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); }
ffieldlist1 lastcomma
{ $$ = $1+$4; flush_record($4%FIELDS_PER_FLUSH); }
; ;
semicolonpart : /* empty */
{ $$ = 0; }
| ';' ffieldlist
{ $$ = $2; flush_record($2%FIELDS_PER_FLUSH); }
;
lastcomma : /* empty */ lastcomma : /* empty */
| ',' | ','
; ;
ffieldlist : /* empty */ { $$ = 0; }
| ffieldlist1 lastcomma { $$ = $1; }
;
ffieldlist1 : ffield {$$=1;} ffieldlist1 : ffield {$$=1;}
| ffieldlist1 ',' ffield | ffieldlist1 ',' ffield
{ {
@@ -671,6 +718,10 @@ ffield : NAME '=' expr1
} }
; ;
lfieldlist : /* empty */ { $$ = 0; }
| lfieldlist1 lastcomma { $$ = $1; }
;
lfieldlist1 : expr1 {$$=1;} lfieldlist1 : expr1 {$$=1;}
| lfieldlist1 ',' expr1 | lfieldlist1 ',' expr1
{ {
@@ -683,12 +734,12 @@ lfieldlist1 : expr1 {$$=1;}
varlist1 : var varlist1 : var
{ {
nvarbuffer = 0; nvarbuffer = 0;
varbuffer[nvarbuffer] = $1; incr_nvarbuffer(); add_varbuffer($1);
$$ = ($1 == 0) ? 1 : 0; $$ = ($1 == 0) ? 1 : 0;
} }
| varlist1 ',' var | varlist1 ',' var
{ {
varbuffer[nvarbuffer] = $3; incr_nvarbuffer(); add_varbuffer($3);
$$ = ($3 == 0) ? $1 + 1 : $1; $$ = ($3 == 0) ? $1 + 1 : $1;
} }
; ;
@@ -708,10 +759,9 @@ var : singlevar { $$ = $1; }
singlevar : NAME singlevar : NAME
{ {
Word s = luaI_findsymbol($1); int local = lua_localname($1);
int local = lua_localname (s);
if (local == -1) /* global var */ if (local == -1) /* global var */
$$ = s + 1; /* return positive value */ $$ = luaI_findsymbol($1)+1; /* return positive value */
else else
$$ = -(local+1); /* return negative value */ $$ = -(local+1); /* return negative value */
} }
@@ -720,10 +770,10 @@ singlevar : NAME
varexp : var { lua_pushvar($1); } varexp : var { lua_pushvar($1); }
; ;
localdeclist : NAME {localvar[nlocalvar]=luaI_findsymbol($1); $$ = 1;} localdeclist : NAME {store_localvar($1, 0); $$ = 1;}
| localdeclist ',' NAME | localdeclist ',' NAME
{ {
localvar[nlocalvar+$1]=luaI_findsymbol($3); store_localvar($3, $1);
$$ = $1+1; $$ = $1+1;
} }
; ;
@@ -732,243 +782,7 @@ decinit : /* empty */ { $$ = 0; }
| '=' exprlist1 { $$ = $2; } | '=' exprlist1 { $$ = $2; }
; ;
setdebug : DEBUG {lua_debug = $1;} setdebug : DEBUG { lua_debug = $1; }
;
%% %%
#if LISTING
static void PrintCode (Byte *code, Byte *end)
{
Byte *p = code;
printf ("\n\nCODE\n");
while (p != end)
{
switch ((OpCode)*p)
{
case PUSHNIL: printf ("%d PUSHNIL\n", (p++)-code); break;
case PUSH0: case PUSH1: case PUSH2:
printf ("%d PUSH%c\n", p-code, *p-PUSH0+'0');
p++;
break;
case PUSHBYTE:
printf ("%d PUSHBYTE %d\n", p-code, *(++p));
p++;
break;
case PUSHWORD:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d PUSHWORD %d\n", n, c.w);
}
break;
case PUSHFLOAT:
{
CodeFloat c;
int n = p-code;
p++;
get_float(c,p);
printf ("%d PUSHFLOAT %f\n", n, c.f);
}
break;
case PUSHSTRING:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d PUSHSTRING %d\n", n, c.w);
}
break;
case PUSHFUNCTION:
{
CodeCode c;
int n = p-code;
p++;
get_code(c,p);
printf ("%d PUSHFUNCTION %p\n", n, c.b);
}
break;
case PUSHLOCAL0: case PUSHLOCAL1: case PUSHLOCAL2: case PUSHLOCAL3:
case PUSHLOCAL4: case PUSHLOCAL5: case PUSHLOCAL6: case PUSHLOCAL7:
case PUSHLOCAL8: case PUSHLOCAL9:
printf ("%d PUSHLOCAL%c\n", p-code, *p-PUSHLOCAL0+'0');
p++;
break;
case PUSHLOCAL: printf ("%d PUSHLOCAL %d\n", p-code, *(++p));
p++;
break;
case PUSHGLOBAL:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d PUSHGLOBAL %d\n", n, c.w);
}
break;
case PUSHINDEXED: printf ("%d PUSHINDEXED\n", (p++)-code); break;
case STORELOCAL0: case STORELOCAL1: case STORELOCAL2: case STORELOCAL3:
case STORELOCAL4: case STORELOCAL5: case STORELOCAL6: case STORELOCAL7:
case STORELOCAL8: case STORELOCAL9:
printf ("%d STORELOCAL%c\n", p-code, *p-STORELOCAL0+'0');
p++;
break;
case STORELOCAL:
printf ("%d STORELOCAL %d\n", p-code, *(++p));
p++;
break;
case STOREGLOBAL:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d STOREGLOBAL %d\n", n, c.w);
}
break;
case PUSHSELF:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d PUSHSELF %d\n", n, c.w);
}
break;
case STOREINDEXED0: printf ("%d STOREINDEXED0\n", (p++)-code); break;
case STOREINDEXED: printf ("%d STOREINDEXED %d\n", p-code, *(++p));
p++;
break;
case STORELIST0:
printf("%d STORELIST0 %d\n", p-code, *(++p));
p++;
break;
case STORELIST:
printf("%d STORELIST %d %d\n", p-code, *(p+1), *(p+2));
p+=3;
break;
case STORERECORD:
printf("%d STORERECORD %d\n", p-code, *(++p));
p += *p*sizeof(Word) + 1;
break;
case ADJUST0: printf ("%d ADJUST0\n", (p++)-code); break;
case ADJUST:
printf ("%d ADJUST %d\n", p-code, *(++p));
p++;
break;
case CREATEARRAY:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d CREATEARRAY %d\n", n, c.w);
break;
}
case EQOP: printf ("%d EQOP\n", (p++)-code); break;
case LTOP: printf ("%d LTOP\n", (p++)-code); break;
case LEOP: printf ("%d LEOP\n", (p++)-code); break;
case ADDOP: printf ("%d ADDOP\n", (p++)-code); break;
case SUBOP: printf ("%d SUBOP\n", (p++)-code); break;
case MULTOP: printf ("%d MULTOP\n", (p++)-code); break;
case DIVOP: printf ("%d DIVOP\n", (p++)-code); break;
case POWOP: printf ("%d POWOP\n", (p++)-code); break;
case CONCOP: printf ("%d CONCOP\n", (p++)-code); break;
case MINUSOP: printf ("%d MINUSOP\n", (p++)-code); break;
case NOTOP: printf ("%d NOTOP\n", (p++)-code); break;
case ONTJMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d ONTJMP %d\n", n, c.w);
}
break;
case ONFJMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d ONFJMP %d\n", n, c.w);
}
break;
case JMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d JMP %d\n", n, c.w);
}
break;
case UPJMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d UPJMP %d\n", n, c.w);
}
break;
case IFFJMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d IFFJMP %d\n", n, c.w);
}
break;
case IFFUPJMP:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d IFFUPJMP %d\n", n, c.w);
}
break;
case POP: printf ("%d POP\n", (p++)-code); break;
case CALLFUNC:
printf ("%d CALLFUNC %d %d\n", p-code, *(p+1), *(p+2));
p+=3;
break;
case RETCODE0: printf ("%d RETCODE0\n", (p++)-code); break;
case RETCODE:
printf ("%d RETCODE %d\n", p-code, *(++p));
p++;
break;
case SETFUNCTION:
{
CodeCode c1;
CodeWord c2;
int n = p-code;
p++;
get_code(c1,p);
get_word(c2,p);
printf ("%d SETFUNCTION %s %d\n", n, (char *)c1.b, c2.w);
}
break;
case SETLINE:
{
CodeWord c;
int n = p-code;
p++;
get_word(c,p);
printf ("%d SETLINE %d\n", n, c.w);
}
break;
case RESET: printf ("%d RESET\n", (p++)-code); break;
default: printf ("%d Cannot happen: code %d\n", (p++)-code, *(p-1)); break;
}
}
}
#endif

31
luadebug.h Normal file
View File

@@ -0,0 +1,31 @@
/*
** LUA - Linguagem para Usuarios de Aplicacao
** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio
** $Id: luadebug.h,v 1.5 1996/02/08 17:03:20 roberto Exp roberto $
*/
#ifndef luadebug_h
#define luadebug_h
#include "lua.h"
typedef lua_Object lua_Function;
typedef void (*lua_LHFunction) (int line);
typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
lua_Function lua_stackedfunction (int level);
void lua_funcinfo (lua_Object func, char **filename, 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);
int lua_setlocal (lua_Function func, int local_number);
extern lua_LHFunction lua_linehook;
extern lua_CHFunction lua_callhook;
extern int lua_debug;
#endif

View File

@@ -2,15 +2,32 @@
** Libraries to be used in LUA programs ** Libraries to be used in LUA programs
** Grupo de Tecnologia em Computacao Grafica ** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: lualib.h,v 1.2 1994/08/24 15:29:02 celes Stab roberto $ ** $Id: lualib.h,v 1.7 1996/03/14 15:53:09 roberto Exp roberto $
*/ */
#ifndef lualib_h #ifndef lualib_h
#define lualib_h #define lualib_h
#include "lua.h"
void iolib_open (void); void iolib_open (void);
void strlib_open (void); void strlib_open (void);
void mathlib_open (void); void mathlib_open (void);
/* auxiliar functions (private) */
struct lua_reg {
char *name;
lua_CFunction func;
};
void luaI_openlib (struct lua_reg *l, int n);
void lua_arg_error(char *funcname);
char *lua_check_string (int numArg, char *funcname);
double lua_check_number (int numArg, char *funcname);
char *luaI_addchar (int c);
void luaI_addquoted (char *s);
#endif #endif

View File

@@ -3,18 +3,24 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_mem = "$Id: mem.c,v 1.4 1995/01/13 22:11:12 roberto Exp roberto $"; char *rcs_mem = "$Id: mem.c,v 1.11 1996/03/21 18:54:29 roberto Exp roberto $";
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "mem.h" #include "mem.h"
#include "lua.h" #include "lua.h"
#define mem_error() lua_error(memEM)
void luaI_free (void *block) void luaI_free (void *block)
{ {
*((int *)block) = -1; /* to catch errors */ if (block)
free(block); {
*((int *)block) = -1; /* to catch errors */
free(block);
}
} }
@@ -22,23 +28,40 @@ void *luaI_malloc (unsigned long size)
{ {
void *block = malloc((size_t)size); void *block = malloc((size_t)size);
if (block == NULL) if (block == NULL)
lua_error("not enough memory"); mem_error();
return block; return block;
} }
void *luaI_realloc (void *oldblock, unsigned long size) void *luaI_realloc (void *oldblock, unsigned long size)
{ {
void *block = realloc(oldblock, (size_t)size); void *block = oldblock ? realloc(oldblock, (size_t)size) :
malloc((size_t)size);
if (block == NULL) if (block == NULL)
lua_error("not enough memory"); mem_error();
return block; return block;
} }
char *luaI_strdup (char *str) int luaI_growvector (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit)
{ {
char *newstr = luaI_malloc(strlen(str)+1); if (nelems >= limit)
strcpy(newstr, str); lua_error(errormsg);
return newstr; nelems = (nelems == 0) ? 20 : nelems*2;
if (nelems > limit)
nelems = limit;
*block = luaI_realloc(*block, nelems*size);
return (int) nelems;
} }
void* luaI_buffer (unsigned long size)
{
static unsigned long buffsize = 0;
static char* buffer = NULL;
if (size > buffsize)
buffer = luaI_realloc(buffer, buffsize=size);
return buffer;
}

View File

@@ -1,7 +1,7 @@
/* /*
** mem.c ** mem.c
** memory manager for lua ** memory manager for lua
** $Id: mem.h,v 1.1 1994/11/16 17:38:08 roberto Stab roberto $ ** $Id: mem.h,v 1.6 1996/03/21 18:54:29 roberto Exp roberto $
*/ */
#ifndef mem_h #ifndef mem_h
@@ -11,15 +11,29 @@
#define NULL 0 #define NULL 0
#endif #endif
/* memory error messages */
#define codeEM "code size overflow"
#define symbolEM "symbol table overflow"
#define constantEM "constant table overflow"
#define stackEM "stack size overflow"
#define lexEM "lex buffer overflow"
#define refEM "reference table overflow"
#define tableEM "table overflow"
#define memEM "not enough memory"
void luaI_free (void *block); void luaI_free (void *block);
void *luaI_malloc (unsigned long size); void *luaI_malloc (unsigned long size);
void *luaI_realloc (void *oldblock, unsigned long size); void *luaI_realloc (void *oldblock, unsigned long size);
void *luaI_buffer (unsigned long size);
char *luaI_strdup (char *str); int luaI_growvector (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit);
#define new(s) ((s *)luaI_malloc(sizeof(s))) #define new(s) ((s *)luaI_malloc(sizeof(s)))
#define newvector(n,s) ((s *)luaI_malloc((n)*sizeof(s))) #define newvector(n,s) ((s *)luaI_malloc((n)*sizeof(s)))
#define growvector(old,n,s) ((s *)luaI_realloc(old,(n)*sizeof(s))) #define growvector(old,n,s,e,l) \
(luaI_growvector((void**)old,n,sizeof(s),e,l))
#endif #endif

100
makefile
View File

@@ -1,7 +1,13 @@
# $Id: makefile,v 1.12 1995/02/02 19:02:03 roberto Exp $ # $Id: makefile,v 1.25 1996/05/06 14:38:40 roberto Exp $
#configuration
# define (undefine) POPEN if your system (does not) support piped I/O
# define (undefine) POSIX if your system is (not) POSIX compliant
CONFIG = -DPOPEN -DPOSIX
# Compilation parameters # Compilation parameters
CC = gcc CC = gcc
CFLAGS = -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2 CFLAGS = $(CONFIG) -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2
#CC = acc #CC = acc
#CFLAGS = -fast -I/usr/5include #CFLAGS = -fast -I/usr/5include
@@ -10,30 +16,29 @@ AR = ar
ARFLAGS = rvl ARFLAGS = rvl
# Aplication modules # Aplication modules
LUAMOD = \ LUAOBJS = \
parser \ parser.o \
lex \ lex.o \
opcode \ opcode.o \
hash \ hash.o \
table \ table.o \
inout \ inout.o \
tree \ tree.o \
fallback\ fallback.o \
mem mem.o \
func.o \
undump.o
LIBMOD = \ LIBOBJS = \
iolib \ iolib.o \
strlib \ mathlib.o \
mathlib strlib.o
LUAOBJS = $(LUAMOD:%=%.o)
LIBOBJS = $(LIBMOD:%=%.o)
lua : lua.o lua.a lualib.a lua : lua.o lua.a lualib.a
$(CC) $(CFLAGS) -o $@ lua.c lua.a lualib.a -lm $(CC) $(CFLAGS) -o $@ lua.o lua.a lualib.a -lm
lua.a : parser.c $(LUAOBJS) lua.a : $(LUAOBJS)
$(AR) $(ARFLAGS) $@ $? $(AR) $(ARFLAGS) $@ $?
ranlib lua.a ranlib lua.a
@@ -44,35 +49,44 @@ lualib.a : $(LIBOBJS)
liblua.so.1.0 : lua.o liblua.so.1.0 : lua.o
ld -o liblua.so.1.0 $(LUAOBJS) ld -o liblua.so.1.0 $(LUAOBJS)
%.o : %.c #y.tab.c y.tab.h : lua.stx
$(CC) $(CFLAGS) -c -o $@ $< # yacc++ -d lua.stx
#parser.c : y.tab.c
# sed -e 's/yy/luaY_/g' -e 's/malloc\.h/stdlib\.h/g' y.tab.c > parser.c
parser.c : lua.stx #parser.h : y.tab.h
yacc++ -d lua.stx ; mv -f y.tab.c parser.c ; mv -f y.tab.h parser.h # sed -e 's/yy/luaY_/g' y.tab.h > parser.h
clear : clear :
rcsclean rcsclean
rm -f *.o rm -f *.o
rm -f parser.c parser.h rm -f parser.c parser.h y.tab.c y.tab.h
co lua.h lualib.h co lua.h lualib.h luadebug.h
% : RCS/%,v
co $@
fallback.o : fallback.c mem.h fallback.h opcode.h lua.h types.h tree.h inout.h #% : RCS/%,v
hash.o : hash.c mem.h opcode.h lua.h types.h tree.h hash.h inout.h table.h # co $@
inout.o : inout.c mem.h opcode.h lua.h types.h tree.h hash.h inout.h table.h
iolib.o : iolib.c mem.h lua.h lualib.h
lex.o : lex.c tree.h types.h table.h opcode.h lua.h inout.h parser.h ugly.h fallback.o : fallback.c mem.h fallback.h lua.h opcode.h types.h tree.h func.h \
table.h
func.o : func.c luadebug.h lua.h table.h tree.h types.h opcode.h func.h mem.h
hash.o : hash.c mem.h opcode.h lua.h types.h tree.h func.h hash.h table.h
inout.o : inout.c lex.h opcode.h lua.h types.h tree.h func.h inout.h table.h \
mem.h
iolib.o : iolib.c lua.h luadebug.h lualib.h
lex.o : lex.c mem.h tree.h types.h table.h opcode.h lua.h func.h lex.h inout.h \
luadebug.h parser.h
lua.o : lua.c lua.h lualib.h lua.o : lua.c lua.h lualib.h
mathlib.o : mathlib.c lualib.h lua.h mathlib.o : mathlib.c lualib.h lua.h
mem.o : mem.c mem.h lua.h mem.o : mem.c mem.h lua.h table.h tree.h types.h opcode.h func.h
opcode.o : opcode.c mem.h opcode.h lua.h types.h tree.h hash.h inout.h table.h \ opcode.o : opcode.c luadebug.h lua.h mem.h opcode.h types.h tree.h func.h hash.h \
fallback.h inout.h table.h fallback.h undump.h
strlib.o : strlib.c mem.h lua.h lualib.h parser.o : parser.c luadebug.h lua.h mem.h lex.h opcode.h types.h tree.h func.h \
table.o : table.c mem.h opcode.h lua.h types.h tree.h hash.h inout.h table.h \ hash.h inout.h table.h
fallback.h strlib.o : strlib.c lua.h lualib.h
tree.o : tree.c mem.h lua.h tree.h types.h table.h opcode.h table.o : table.c mem.h opcode.h lua.h types.h tree.h func.h hash.h table.h \
parser.o : parser.c mem.h opcode.h lua.h types.h tree.h hash.h inout.h table.h inout.h fallback.h luadebug.h
tree.o : tree.c mem.h lua.h tree.h types.h lex.h hash.h opcode.h func.h table.h
undump.o : undump.c opcode.h lua.h types.h tree.h func.h mem.h table.h undump.h

2165
manual.tex Normal file

File diff suppressed because it is too large Load Diff

233
mathlib.c
View File

@@ -3,27 +3,23 @@
** Mathematics library to LUA ** Mathematics library to LUA
*/ */
char *rcs_mathlib="$Id: mathlib.c,v 1.8 1995/01/04 18:49:54 roberto Exp $"; char *rcs_mathlib="$Id: mathlib.c,v 1.16 1996/04/25 14:10:00 roberto Exp roberto $";
#include <stdio.h> /* NULL */ #include <stdlib.h>
#include <math.h> #include <math.h>
#include "lualib.h" #include "lualib.h"
#include "lua.h" #include "lua.h"
#ifndef PI
#define PI 3.14159265358979323846 #define PI 3.14159265358979323846
#endif
#define TODEGREE(a) ((a)*180.0/PI) #define TODEGREE(a) ((a)*180.0/PI)
#define TORAD(a) ((a)*PI/180.0) #define TORAD(a) ((a)*PI/180.0)
static void math_abs (void) static void math_abs (void)
{ {
double d; double d = lua_check_number(1, "abs");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `abs'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `abs'");
d = lua_getnumber(o);
if (d < 0) d = -d; if (d < 0) d = -d;
lua_pushnumber (d); lua_pushnumber (d);
} }
@@ -31,13 +27,7 @@ static void math_abs (void)
static void math_sin (void) static void math_sin (void)
{ {
double d; double d = lua_check_number(1, "sin");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `sin'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `sin'");
d = lua_getnumber(o);
lua_pushnumber (sin(TORAD(d))); lua_pushnumber (sin(TORAD(d)));
} }
@@ -45,13 +35,7 @@ static void math_sin (void)
static void math_cos (void) static void math_cos (void)
{ {
double d; double d = lua_check_number(1, "cos");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `cos'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `cos'");
d = lua_getnumber(o);
lua_pushnumber (cos(TORAD(d))); lua_pushnumber (cos(TORAD(d)));
} }
@@ -59,104 +43,64 @@ static void math_cos (void)
static void math_tan (void) static void math_tan (void)
{ {
double d; double d = lua_check_number(1, "tan");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `tan'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `tan'");
d = lua_getnumber(o);
lua_pushnumber (tan(TORAD(d))); lua_pushnumber (tan(TORAD(d)));
} }
static void math_asin (void) static void math_asin (void)
{ {
double d; double d = lua_check_number(1, "asin");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `asin'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `asin'");
d = lua_getnumber(o);
lua_pushnumber (TODEGREE(asin(d))); lua_pushnumber (TODEGREE(asin(d)));
} }
static void math_acos (void) static void math_acos (void)
{ {
double d; double d = lua_check_number(1, "acos");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `acos'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `acos'");
d = lua_getnumber(o);
lua_pushnumber (TODEGREE(acos(d))); lua_pushnumber (TODEGREE(acos(d)));
} }
static void math_atan (void) static void math_atan (void)
{ {
double d; double d = lua_check_number(1, "atan");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `atan'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `atan'");
d = lua_getnumber(o);
lua_pushnumber (TODEGREE(atan(d))); lua_pushnumber (TODEGREE(atan(d)));
} }
static void math_atan2 (void)
{
double d1 = lua_check_number(1, "atan2");
double d2 = lua_check_number(2, "atan2");
lua_pushnumber (TODEGREE(atan2(d1, d2)));
}
static void math_ceil (void) static void math_ceil (void)
{ {
double d; double d = lua_check_number(1, "ceil");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `ceil'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `ceil'");
d = lua_getnumber(o);
lua_pushnumber (ceil(d)); lua_pushnumber (ceil(d));
} }
static void math_floor (void) static void math_floor (void)
{ {
double d; double d = lua_check_number(1, "floor");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `floor'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `floor'");
d = lua_getnumber(o);
lua_pushnumber (floor(d)); lua_pushnumber (floor(d));
} }
static void math_mod (void) static void math_mod (void)
{ {
int d1, d2; int d1 = (int)lua_check_number(1, "mod");
lua_Object o1 = lua_getparam (1); int d2 = (int)lua_check_number(2, "mod");
lua_Object o2 = lua_getparam (2);
if (!lua_isnumber(o1) || !lua_isnumber(o2))
lua_error ("incorrect arguments to function `mod'");
d1 = (int) lua_getnumber(o1);
d2 = (int) lua_getnumber(o2);
lua_pushnumber (d1%d2); lua_pushnumber (d1%d2);
} }
static void math_sqrt (void) static void math_sqrt (void)
{ {
double d; double d = lua_check_number(1, "sqrt");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `sqrt'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `sqrt'");
d = lua_getnumber(o);
lua_pushnumber (sqrt(d)); lua_pushnumber (sqrt(d));
} }
@@ -169,7 +113,7 @@ static void math_pow (void)
lua_Object op = lua_getparam(3); lua_Object op = lua_getparam(3);
if (!lua_isnumber(o1) || !lua_isnumber(o2) || *(lua_getstring(op)) != 'p') if (!lua_isnumber(o1) || !lua_isnumber(o2) || *(lua_getstring(op)) != 'p')
{ {
lua_Object old = lua_getlocked(old_pow); lua_Object old = lua_getref(old_pow);
lua_pushobject(o1); lua_pushobject(o1);
lua_pushobject(o2); lua_pushobject(o2);
lua_pushobject(op); lua_pushobject(op);
@@ -187,129 +131,100 @@ static void math_pow (void)
static void math_min (void) static void math_min (void)
{ {
int i=1; int i=1;
double d, dmin; double dmin = lua_check_number(i, "min");
lua_Object o; while (lua_getparam(++i) != LUA_NOOBJECT)
if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
lua_error ("too few arguments to function `min'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `min'");
dmin = lua_getnumber (o);
while ((o = lua_getparam(i++)) != LUA_NOOBJECT)
{ {
if (!lua_isnumber(o)) double d = lua_check_number(i, "min");
lua_error ("incorrect arguments to function `min'");
d = lua_getnumber (o);
if (d < dmin) dmin = d; if (d < dmin) dmin = d;
} }
lua_pushnumber (dmin); lua_pushnumber (dmin);
} }
static void math_max (void) static void math_max (void)
{ {
int i=1; int i=1;
double d, dmax; double dmax = lua_check_number(i, "max");
lua_Object o; while (lua_getparam(++i) != LUA_NOOBJECT)
if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
lua_error ("too few arguments to function `max'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `max'");
dmax = lua_getnumber (o);
while ((o = lua_getparam(i++)) != LUA_NOOBJECT)
{ {
if (!lua_isnumber(o)) double d = lua_check_number(i, "max");
lua_error ("incorrect arguments to function `max'");
d = lua_getnumber (o);
if (d > dmax) dmax = d; if (d > dmax) dmax = d;
} }
lua_pushnumber (dmax); lua_pushnumber (dmax);
} }
static void math_log (void) static void math_log (void)
{ {
double d; double d = lua_check_number(1, "log");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `log'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `log'");
d = lua_getnumber(o);
lua_pushnumber (log(d)); lua_pushnumber (log(d));
} }
static void math_log10 (void) static void math_log10 (void)
{ {
double d; double d = lua_check_number(1, "log10");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `log10'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `log10'");
d = lua_getnumber(o);
lua_pushnumber (log10(d)); lua_pushnumber (log10(d));
} }
static void math_exp (void) static void math_exp (void)
{ {
double d; double d = lua_check_number(1, "exp");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `exp'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `exp'");
d = lua_getnumber(o);
lua_pushnumber (exp(d)); lua_pushnumber (exp(d));
} }
static void math_deg (void) static void math_deg (void)
{ {
float d; float d = lua_check_number(1, "deg");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `deg'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `deg'");
d = lua_getnumber(o);
lua_pushnumber (d*180./PI); lua_pushnumber (d*180./PI);
} }
static void math_rad (void) static void math_rad (void)
{ {
float d; float d = lua_check_number(1, "rad");
lua_Object o = lua_getparam (1);
if (o == LUA_NOOBJECT)
lua_error ("too few arguments to function `rad'");
if (!lua_isnumber(o))
lua_error ("incorrect arguments to function `rad'");
d = lua_getnumber(o);
lua_pushnumber (d/180.*PI); lua_pushnumber (d/180.*PI);
} }
static void math_random (void)
{
lua_pushnumber((double)(rand()%RAND_MAX) / (double)RAND_MAX);
}
static void math_randomseed (void)
{
srand(lua_check_number(1, "randomseed"));
}
static struct lua_reg mathlib[] = {
{"abs", math_abs},
{"sin", math_sin},
{"cos", math_cos},
{"tan", math_tan},
{"asin", math_asin},
{"acos", math_acos},
{"atan", math_atan},
{"atan2", math_atan2},
{"ceil", math_ceil},
{"floor", math_floor},
{"mod", math_mod},
{"sqrt", math_sqrt},
{"min", math_min},
{"max", math_max},
{"log", math_log},
{"log10", math_log10},
{"exp", math_exp},
{"deg", math_deg},
{"rad", math_rad},
{"random", math_random},
{"randomseed", math_randomseed}
};
/* /*
** Open math library ** Open math library
*/ */
void mathlib_open (void) void mathlib_open (void)
{ {
lua_register ("abs", math_abs); luaI_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));
lua_register ("sin", math_sin); old_pow = lua_refobject(lua_setfallback("arith", math_pow), 1);
lua_register ("cos", math_cos);
lua_register ("tan", math_tan);
lua_register ("asin", math_asin);
lua_register ("acos", math_acos);
lua_register ("atan", math_atan);
lua_register ("ceil", math_ceil);
lua_register ("floor", math_floor);
lua_register ("mod", math_mod);
lua_register ("sqrt", math_sqrt);
lua_register ("min", math_min);
lua_register ("max", math_max);
lua_register ("log", math_log);
lua_register ("log10", math_log10);
lua_register ("exp", math_exp);
lua_register ("deg", math_deg);
lua_register ("rad", math_rad);
old_pow = lua_lockobject(lua_setfallback("arith", math_pow));
} }

637
opcode.c

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/* /*
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: opcode.h,v 3.9 1994/11/23 14:31:11 roberto Stab $ ** $Id: opcode.h,v 3.19 1996/03/06 13:11:23 roberto Exp $
*/ */
#ifndef opcode_h #ifndef opcode_h
@@ -9,19 +9,11 @@
#include "lua.h" #include "lua.h"
#include "types.h" #include "types.h"
#include "tree.h" #include "tree.h"
#include "func.h"
#ifndef STACKGAP
#define STACKGAP 128
#endif
#ifndef real
#define real float
#endif
#define FIELDS_PER_FLUSH 40 #define FIELDS_PER_FLUSH 40
#define MAX_TEMPS 20
typedef enum typedef enum
{ {
@@ -73,25 +65,21 @@ typedef enum
CALLFUNC, CALLFUNC,
RETCODE0, RETCODE0,
RETCODE, RETCODE,
SETFUNCTION, SETLINE
SETLINE,
RESET
} OpCode; } OpCode;
#define MULT_RET 255 #define MULT_RET 255
typedef void (*Cfunction) (void);
typedef int (*Input) (void);
typedef union typedef union
{ {
Cfunction f; lua_CFunction f;
real n; real n;
TaggedString *ts; TaggedString *ts;
Byte *b; TFunc *tf;
struct Hash *a; struct Hash *a;
void *u; void *u;
int i;
} Value; } Value;
typedef struct Object typedef struct Object
@@ -100,17 +88,12 @@ typedef struct Object
Value value; Value value;
} Object; } Object;
typedef struct
{
Object object;
} Symbol;
/* Macros to access structure members */ /* Macros to access structure members */
#define tag(o) ((o)->tag) #define tag(o) ((o)->tag)
#define nvalue(o) ((o)->value.n) #define nvalue(o) ((o)->value.n)
#define svalue(o) ((o)->value.ts->str) #define svalue(o) ((o)->value.ts->str)
#define tsvalue(o) ((o)->value.ts) #define tsvalue(o) ((o)->value.ts)
#define bvalue(o) ((o)->value.b)
#define avalue(o) ((o)->value.a) #define avalue(o) ((o)->value.a)
#define fvalue(o) ((o)->value.f) #define fvalue(o) ((o)->value.f)
#define uvalue(o) ((o)->value.u) #define uvalue(o) ((o)->value.u)
@@ -120,21 +103,20 @@ typedef struct
#define s_tag(i) (tag(&s_object(i))) #define s_tag(i) (tag(&s_object(i)))
#define s_nvalue(i) (nvalue(&s_object(i))) #define s_nvalue(i) (nvalue(&s_object(i)))
#define s_svalue(i) (svalue(&s_object(i))) #define s_svalue(i) (svalue(&s_object(i)))
#define s_bvalue(i) (bvalue(&s_object(i)))
#define s_avalue(i) (avalue(&s_object(i))) #define s_avalue(i) (avalue(&s_object(i)))
#define s_fvalue(i) (fvalue(&s_object(i))) #define s_fvalue(i) (fvalue(&s_object(i)))
#define s_uvalue(i) (uvalue(&s_object(i))) #define s_uvalue(i) (uvalue(&s_object(i)))
typedef union typedef union
{ {
struct {char c1; char c2;} m; struct {Byte c1; Byte c2;} m;
Word w; Word w;
} CodeWord; } CodeWord;
#define get_word(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;} #define get_word(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;}
typedef union typedef union
{ {
struct {char c1; char c2; char c3; char c4;} m; struct {Byte c1; Byte c2; Byte c3; Byte c4;} m;
float f; float f;
} CodeFloat; } CodeFloat;
#define get_float(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\ #define get_float(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\
@@ -142,23 +124,20 @@ typedef union
typedef union typedef union
{ {
struct {char c1; char c2; char c3; char c4;} m; struct {Byte c1; Byte c2; Byte c3; Byte c4;} m;
Byte *b; TFunc *tf;
} CodeCode; } CodeCode;
#define get_code(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\ #define get_code(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\
code.m.c3 = *pc++; code.m.c4 = *pc++;} code.m.c3 = *pc++; code.m.c4 = *pc++;}
/* Exported functions */ /* Exported functions */
char *lua_strdup (char *l); void lua_parse (TFunc *tf); /* from "lua.stx" module */
void luaI_codedebugline (int line); /* from "lua.stx" module */
void lua_setinput (Input fn); /* from "lex.c" module */ void lua_travstack (int (*fn)(Object *));
char *lua_lasttext (void); /* from "lex.c" module */
int yylex (void); /* from "lex.c" module */
void lua_parse (Byte **code); /* from "lua.stx" module */
void lua_travstack (void (*fn)(Object *));
Object *luaI_Address (lua_Object o); Object *luaI_Address (lua_Object o);
void luaI_pushobject (Object *o); void luaI_pushobject (Object *o);
void luaI_gcFB (Object *o); void luaI_gcFB (Object *o);
int luaI_dorun (TFunc *tf);
#endif #endif

275
strlib.c
View File

@@ -3,24 +3,71 @@
** String library to LUA ** String library to LUA
*/ */
char *rcs_strlib="$Id: strlib.c,v 1.11 1995/02/02 20:05:37 roberto Exp roberto $"; char *rcs_strlib="$Id: strlib.c,v 1.22 1996/03/22 17:57:24 roberto Exp roberto $";
#include <string.h> #include <string.h>
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
#include <limits.h>
#include "lua.h" #include "lua.h"
#include "lualib.h" #include "lualib.h"
static char *newstring (lua_Object o) void lua_arg_error(char *funcname)
{ {
char *s = lua_getstring(o); char buff[100];
char *ns = (char *)malloc(strlen(s)+1); sprintf(buff, "incorrect arguments to function `%s'", funcname);
if (ns == 0) lua_error(buff);
lua_error("not enough memory for new string"); }
strcpy(ns, s);
return ns; char *lua_check_string (int numArg, char *funcname)
{
lua_Object o = lua_getparam(numArg);
if (!lua_isstring(o))
lua_arg_error(funcname);
return lua_getstring(o);
}
double lua_check_number (int numArg, char *funcname)
{
lua_Object o = lua_getparam(numArg);
if (!lua_isnumber(o))
lua_arg_error(funcname);
return lua_getnumber(o);
}
static int lua_opt_number (int numArg, int def, char *funcname)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
(int)lua_check_number(numArg, funcname);
}
char *luaI_addchar (int c)
{
static char *buff = NULL;
static int max = 0;
static int n = 0;
if (n >= max)
{
if (max == 0)
{
max = 100;
buff = (char *)malloc(max);
}
else
{
max *= 2;
buff = (char *)realloc(buff, max);
}
if (buff == NULL)
lua_error("memory overflow");
}
buff[n++] = c;
if (c == 0)
n = 0; /* prepare for next string */
return buff;
} }
@@ -31,34 +78,14 @@ static char *newstring (lua_Object o)
*/ */
static void str_find (void) static void str_find (void)
{ {
char *s1, *s2, *f; char *s1 = lua_check_string(1, "strfind");
int init; char *s2 = lua_check_string(2, "strfind");
lua_Object o1 = lua_getparam (1); int init = lua_opt_number(3, 1, "strfind") - 1;
lua_Object o2 = lua_getparam (2); char *f = (init>=0 && init<=strlen(s1)) ? strstr(s1+init,s2) : NULL;
lua_Object o3 = lua_getparam (3);
lua_Object o4 = lua_getparam (4);
if (!lua_isstring(o1) || !lua_isstring(o2))
lua_error ("incorrect arguments to function `strfind'");
if (o3 == LUA_NOOBJECT)
init = 0;
else if (lua_isnumber(o3))
init = lua_getnumber(o3)-1;
else
{
lua_error ("incorrect arguments to function `strfind'");
return; /* to avoid warnings */
}
s1 = lua_getstring(o1);
s2 = lua_getstring(o2);
f = strstr(s1+init,s2);
if (f != NULL) if (f != NULL)
{ {
int pos = f-s1+1; int pos = f-s1+1;
if (o4 == LUA_NOOBJECT) if (lua_opt_number(4, INT_MAX, "strfind") >= pos+strlen(s2)-1)
lua_pushnumber (pos);
else if (!lua_isnumber(o4))
lua_error ("incorrect arguments to function `strfind'");
else if ((int)lua_getnumber(o4) >= pos+strlen(s2)-1)
lua_pushnumber (pos); lua_pushnumber (pos);
else else
lua_pushnil(); lua_pushnil();
@@ -74,10 +101,8 @@ static void str_find (void)
*/ */
static void str_len (void) static void str_len (void)
{ {
lua_Object o = lua_getparam (1); char *s = lua_check_string(1, "strlen");
if (!lua_isstring(o)) lua_pushnumber(strlen(s));
lua_error ("incorrect arguments to function `strlen'");
lua_pushnumber(strlen(lua_getstring(o)));
} }
@@ -88,26 +113,18 @@ static void str_len (void)
*/ */
static void str_sub (void) static void str_sub (void)
{ {
int start, end; char *s = lua_check_string(1, "strsub");
char *s; int start = (int)lua_check_number(2, "strsub");
lua_Object o1 = lua_getparam (1); int end = lua_opt_number(3, strlen(s), "strsub");
lua_Object o2 = lua_getparam (2);
lua_Object o3 = lua_getparam (3);
if (!lua_isstring(o1) || !lua_isnumber(o2))
lua_error ("incorrect arguments to function `strsub'");
if (o3 != LUA_NOOBJECT && !lua_isnumber(o3))
lua_error ("incorrect third argument to function `strsub'");
s = newstring(o1);
start = lua_getnumber (o2);
end = o3 == LUA_NOOBJECT ? strlen(s) : lua_getnumber (o3);
if (end < start || start < 1 || end > strlen(s)) if (end < start || start < 1 || end > strlen(s))
lua_pushliteral(""); lua_pushliteral("");
else else
{ {
s[end] = 0; luaI_addchar(0);
lua_pushstring (&s[start-1]); while (start <= end)
luaI_addchar(s[start++ - 1]);
lua_pushstring (luaI_addchar(0));
} }
free(s);
} }
/* /*
@@ -117,19 +134,12 @@ static void str_sub (void)
*/ */
static void str_lower (void) static void str_lower (void)
{ {
char *s, *c; char *s = lua_check_string(1, "strlower");
lua_Object o = lua_getparam (1); luaI_addchar(0);
if (!lua_isstring(o)) while (*s)
lua_error ("incorrect arguments to function `strlower'"); luaI_addchar(tolower(*s++));
c = s = newstring(o); lua_pushstring(luaI_addchar(0));
while (*c != 0) }
{
*c = tolower(*c);
c++;
}
lua_pushstring(s);
free(s);
}
/* /*
@@ -139,19 +149,122 @@ static void str_lower (void)
*/ */
static void str_upper (void) static void str_upper (void)
{ {
char *s, *c; char *s = lua_check_string(1, "strupper");
lua_Object o = lua_getparam (1); luaI_addchar(0);
if (!lua_isstring(o)) while (*s)
lua_error ("incorrect arguments to function `strlower'"); luaI_addchar(toupper(*s++));
c = s = newstring(o); lua_pushstring(luaI_addchar(0));
while (*c != 0) }
{
*c = toupper(*c); /*
c++; ** get ascii value of a character in a string
} */
lua_pushstring(s); static void str_ascii (void)
free(s); {
} char *s = lua_check_string(1, "ascii");
int pos = lua_opt_number(2, 1, "ascii") - 1;
if (pos<0 || pos>=strlen(s))
lua_arg_error("ascii");
lua_pushnumber(s[pos]);
}
void luaI_addquoted (char *s)
{
luaI_addchar('"');
for (; *s; s++)
{
if (*s == '"' || *s == '\\' || *s == '\n')
luaI_addchar('\\');
luaI_addchar(*s);
}
luaI_addchar('"');
}
#define MAX_CONVERTION 2000
#define MAX_FORMAT 50
static void str_format (void)
{
int arg = 1;
char *strfrmt = lua_check_string(arg++, "format");
luaI_addchar(0); /* initialize */
while (*strfrmt)
{
if (*strfrmt != '%')
luaI_addchar(*strfrmt++);
else if (*++strfrmt == '%')
luaI_addchar(*strfrmt++); /* %% */
else
{ /* format item */
char form[MAX_FORMAT]; /* store the format ('%...') */
char buff[MAX_CONVERTION]; /* store the formated value */
int size = 0;
int i = 0;
form[i++] = '%';
form[i] = *strfrmt++;
while (!isalpha(form[i]))
{
if (isdigit(form[i]))
{
size = size*10 + form[i]-'0';
if (size >= MAX_CONVERTION)
lua_error("format size/precision too long in function `format'");
}
else if (form[i] == '.')
size = 0; /* re-start */
if (++i >= MAX_FORMAT)
lua_error("bad format in function `format'");
form[i] = *strfrmt++;
}
form[i+1] = 0; /* ends string */
switch (form[i])
{
case 'q':
luaI_addquoted(lua_check_string(arg++, "format"));
buff[0] = '\0'; /* addchar already done */
break;
case 's':
{
char *s = lua_check_string(arg++, "format");
if (strlen(s) >= MAX_CONVERTION)
lua_error("string argument too long in function `format'");
sprintf(buff, form, s);
break;
}
case 'c': case 'd': case 'i': case 'o':
case 'u': case 'x': case 'X':
sprintf(buff, form, (int)lua_check_number(arg++, "format"));
break;
case 'e': case 'E': case 'f': case 'g':
sprintf(buff, form, lua_check_number(arg++, "format"));
break;
default: /* also treat cases 'pnLlh' */
lua_error("invalid format option in function `format'");
}
for (i=0; buff[i]; i++) /* move formated value to result */
luaI_addchar(buff[i]);
}
}
lua_pushstring(luaI_addchar(0)); /* push the result */
}
void luaI_openlib (struct lua_reg *l, int n)
{
int i;
for (i=0; i<n; i++)
lua_register(l[i].name, l[i].func);
}
static struct lua_reg strlib[] = {
{"strfind", str_find},
{"strlen", str_len},
{"strsub", str_sub},
{"strlower", str_lower},
{"strupper", str_upper},
{"ascii", str_ascii},
{"format", str_format}
};
/* /*
@@ -159,9 +272,5 @@ static void str_upper (void)
*/ */
void strlib_open (void) void strlib_open (void)
{ {
lua_register ("strfind", str_find); luaI_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
lua_register ("strlen", str_len);
lua_register ("strsub", str_sub);
lua_register ("strlower", str_lower);
lua_register ("strupper", str_upper);
} }

280
table.c
View File

@@ -3,83 +3,82 @@
** Module to control static tables ** Module to control static tables
*/ */
char *rcs_table="$Id: table.c,v 2.27 1995/01/13 22:11:12 roberto Exp celes $"; char *rcs_table="$Id: table.c,v 2.53 1996/04/29 18:53:53 roberto Exp roberto $";
#include <string.h>
#include "mem.h" #include "mem.h"
#include "opcode.h" #include "opcode.h"
#include "tree.h" #include "tree.h"
#include "hash.h" #include "hash.h"
#include "inout.h"
#include "table.h" #include "table.h"
#include "inout.h"
#include "lua.h" #include "lua.h"
#include "fallback.h" #include "fallback.h"
#include "luadebug.h"
#define BUFFER_BLOCK 256 #define BUFFER_BLOCK 256
Symbol *lua_table; Symbol *lua_table = NULL;
static Word lua_ntable = 0; Word lua_ntable = 0;
static Long lua_maxsymbol = 0; static Long lua_maxsymbol = 0;
TaggedString **lua_constant; TaggedString **lua_constant = NULL;
static Word lua_nconstant = 0; Word lua_nconstant = 0;
static Long lua_maxconstant = 0; static Long lua_maxconstant = 0;
#define GARBAGE_BLOCK 50
#define MAXFILE 20
char *lua_file[MAXFILE];
int lua_nfile;
#define GARBAGE_BLOCK 256
#define MIN_GARBAGE_BLOCK 10
static void lua_nextvar (void); static void lua_nextvar (void);
static void setglobal (void);
static void getglobal (void);
/* /*
** Initialise symbol table with internal functions ** Internal functions
*/ */
static void lua_initsymbol (void) static struct {
char *name;
lua_CFunction func;
} int_funcs[] = {
{"assert", luaI_assert},
{"dofile", lua_internaldofile},
{"dostring", lua_internaldostring},
{"error", luaI_error},
{"getglobal", luaI_getglobal},
{"next", lua_next},
{"nextvar", lua_nextvar},
{"print", luaI_print},
{"setfallback", luaI_setfallback},
{"setglobal", luaI_setglobal},
{"tonumber", lua_obj2number},
{"tostring", luaI_tostring},
{"type", luaI_type}
};
#define INTFUNCSIZE (sizeof(int_funcs)/sizeof(int_funcs[0]))
void luaI_initsymbol (void)
{ {
Word n; int i;
lua_maxsymbol = BUFFER_BLOCK; lua_maxsymbol = BUFFER_BLOCK;
lua_table = newvector(lua_maxsymbol, Symbol); lua_table = newvector(lua_maxsymbol, Symbol);
n = luaI_findsymbolbyname("next"); for (i=0; i<INTFUNCSIZE; i++)
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_next; {
n = luaI_findsymbolbyname("dofile"); Word n = luaI_findsymbolbyname(int_funcs[i].name);
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_internaldofile; s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = int_funcs[i].func;
n = luaI_findsymbolbyname("setglobal"); }
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = setglobal;
n = luaI_findsymbolbyname("getglobal");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = getglobal;
n = luaI_findsymbolbyname("nextvar");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_nextvar;
n = luaI_findsymbolbyname("type");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = luaI_type;
n = luaI_findsymbolbyname("tonumber");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_obj2number;
n = luaI_findsymbolbyname("print");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_print;
n = luaI_findsymbolbyname("dostring");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = lua_internaldostring;
n = luaI_findsymbolbyname("setfallback");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = luaI_setfallback;
n = luaI_findsymbolbyname("error");
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = luaI_error;
} }
/* /*
** Initialise constant table with pre-defined constants ** Initialise constant table with pre-defined constants
*/ */
void lua_initconstant (void) void luaI_initconstant (void)
{ {
lua_maxconstant = BUFFER_BLOCK; lua_maxconstant = BUFFER_BLOCK;
lua_constant = newvector(lua_maxconstant, TaggedString *); lua_constant = newvector(lua_maxconstant, TaggedString *);
/* pre-register mem error messages, to avoid loop when error arises */
luaI_findconstantbyname(tableEM);
luaI_findconstantbyname(memEM);
} }
@@ -87,22 +86,15 @@ void lua_initconstant (void)
** Given a name, search it at symbol table and return its index. If not ** Given a name, search it at symbol table and return its index. If not
** found, allocate it. ** found, allocate it.
*/ */
Word luaI_findsymbol (TreeNode *t) Word luaI_findsymbol (TaggedString *t)
{ {
if (lua_table == NULL)
lua_initsymbol();
if (t->varindex == NOT_USED) if (t->varindex == NOT_USED)
{ {
if (lua_ntable == lua_maxsymbol) if (lua_ntable == lua_maxsymbol)
{ lua_maxsymbol = growvector(&lua_table, lua_maxsymbol, Symbol,
if (lua_maxsymbol >= MAX_WORD) symbolEM, MAX_WORD);
lua_error("symbol table overflow");
lua_maxsymbol *= 2;
if (lua_maxsymbol >= MAX_WORD)
lua_maxsymbol = MAX_WORD;
lua_table = growvector(lua_table, lua_maxsymbol, Symbol);
}
t->varindex = lua_ntable; t->varindex = lua_ntable;
lua_table[lua_ntable].varname = t;
s_tag(lua_ntable) = LUA_T_NIL; s_tag(lua_ntable) = LUA_T_NIL;
lua_ntable++; lua_ntable++;
} }
@@ -112,58 +104,87 @@ Word luaI_findsymbol (TreeNode *t)
Word luaI_findsymbolbyname (char *name) Word luaI_findsymbolbyname (char *name)
{ {
return luaI_findsymbol(lua_constcreate(name)); return luaI_findsymbol(luaI_createfixedstring(name));
} }
/* /*
** Given a name, search it at constant table and return its index. If not ** Given a tree node, check it is has a correspondent constant index. If not,
** found, allocate it. ** allocate it.
** On error, return -1.
*/ */
Word luaI_findconstant (TreeNode *t) Word luaI_findconstant (TaggedString *t)
{ {
if (lua_constant == NULL)
lua_initconstant();
if (t->constindex == NOT_USED) if (t->constindex == NOT_USED)
{ {
if (lua_nconstant == lua_maxconstant) if (lua_nconstant == lua_maxconstant)
{ lua_maxconstant = growvector(&lua_constant, lua_maxconstant, TaggedString *,
if (lua_maxconstant >= MAX_WORD) constantEM, MAX_WORD);
lua_error("constant table overflow");
lua_maxconstant *= 2;
if (lua_maxconstant >= MAX_WORD)
lua_maxconstant = MAX_WORD;
lua_constant = growvector(lua_constant, lua_maxconstant, TaggedString *);
}
t->constindex = lua_nconstant; t->constindex = lua_nconstant;
lua_constant[lua_nconstant] = &(t->ts); lua_constant[lua_nconstant] = t;
lua_nconstant++; lua_nconstant++;
} }
return t->constindex; return t->constindex;
} }
Word luaI_findconstantbyname (char *name)
{
return luaI_findconstant(luaI_createfixedstring(name));
}
TaggedString *luaI_createfixedstring (char *name)
{
TaggedString *ts = lua_createstring(name);
if (!ts->marked)
ts->marked = 2; /* avoid GC */
return ts;
}
/* /*
** Traverse symbol table objects ** Traverse symbol table objects
*/ */
void lua_travsymbol (void (*fn)(Object *)) static char *lua_travsymbol (int (*fn)(Object *))
{ {
Word i; Word i;
for (i=0; i<lua_ntable; i++) for (i=0; i<lua_ntable; i++)
fn(&s_object(i)); if (fn(&s_object(i)))
return lua_table[i].varname->str;
return NULL;
} }
/* /*
** Mark an object if it is a string or a unmarked array. ** Mark an object if it is a string or a unmarked array.
*/ */
void lua_markobject (Object *o) int lua_markobject (Object *o)
{ {/* if already marked, does not change mark value */
if (tag(o) == LUA_T_STRING && !tsvalue(o)->marked) if (tag(o) == LUA_T_STRING && !tsvalue(o)->marked)
tsvalue(o)->marked = 1; tsvalue(o)->marked = 1;
else if (tag(o) == LUA_T_ARRAY) else if (tag(o) == LUA_T_ARRAY)
lua_hashmark (avalue(o)); lua_hashmark (avalue(o));
else if ((o->tag == LUA_T_FUNCTION || o->tag == LUA_T_MARK)
&& !o->value.tf->marked)
o->value.tf->marked = 1;
return 0;
}
/*
* returns 0 if the object is going to be (garbage) collected
*/
int luaI_ismarked (Object *o)
{
switch (o->tag)
{
case LUA_T_STRING:
return o->value.ts->marked;
case LUA_T_FUNCTION:
return o->value.tf->marked;
case LUA_T_ARRAY:
return o->value.a->mark;
default: /* nil, number, cfunction, or user data */
return 1;
}
} }
@@ -171,107 +192,88 @@ void lua_markobject (Object *o)
** Garbage collection. ** Garbage collection.
** Delete all unused strings and arrays. ** Delete all unused strings and arrays.
*/ */
void lua_pack (void) Long luaI_collectgarbage (void)
{ {
static Long block = GARBAGE_BLOCK; /* when garbage collector will be called */
static Long nentity = 0; /* counter of new entities (strings and arrays) */
Long recovered = 0; Long recovered = 0;
if (nentity++ < block) return;
lua_travstack(lua_markobject); /* mark stack objects */ lua_travstack(lua_markobject); /* mark stack objects */
lua_travsymbol(lua_markobject); /* mark symbol table objects */ lua_travsymbol(lua_markobject); /* mark symbol table objects */
luaI_travlock(lua_markobject); /* mark locked objects */ luaI_travlock(lua_markobject); /* mark locked objects */
luaI_travfallbacks(lua_markobject); /* mark fallbacks */
luaI_invalidaterefs();
recovered += lua_strcollector(); recovered += lua_strcollector();
recovered += lua_hashcollector(); recovered += lua_hashcollector();
nentity = 0; /* reset counter */ recovered += luaI_funccollector();
block=(16*block-7*recovered)/12; /* adapt block size */ return recovered;
if (block < MIN_GARBAGE_BLOCK) block = MIN_GARBAGE_BLOCK;
} }
void lua_pack (void)
/*
** Add a file name at file table, checking overflow. This function also set
** the external variable "lua_filename" with the function filename set.
** Return 0 on success or error message on error.
*/
char *lua_addfile (char *fn)
{ {
if (lua_nfile >= MAXFILE) static unsigned long block = GARBAGE_BLOCK;
return "too many files"; static unsigned long nentity = 0; /* total of strings, arrays, etc */
if ((lua_file[lua_nfile++] = luaI_strdup (fn)) == NULL) unsigned long recovered = 0;
return "not enough memory"; if (nentity++ < block) return;
return NULL; recovered = luaI_collectgarbage();
} block = block*2*(1.0 - (float)recovered/nentity);
nentity -= recovered;
}
/*
** Delete a file from file stack
*/
int lua_delfile (void)
{
luaI_free(lua_file[--lua_nfile]);
return 1;
}
/*
** Return the last file name set.
*/
char *lua_filename (void)
{
return lua_file[lua_nfile-1];
}
/* /*
** Internal function: return next global variable ** Internal function: return next global variable
*/ */
static void lua_nextvar (void) static void lua_nextvar (void)
{ {
char *varname; Word next;
TreeNode *next;
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
if (o == LUA_NOOBJECT) if (o == LUA_NOOBJECT)
lua_reportbug("too few arguments to function `nextvar'"); lua_error("too few arguments to function `nextvar'");
if (lua_getparam(2) != LUA_NOOBJECT) if (lua_getparam(2) != LUA_NOOBJECT)
lua_reportbug("too many arguments to function `nextvar'"); lua_error("too many arguments to function `nextvar'");
if (lua_isnil(o)) if (lua_isnil(o))
varname = NULL; next = 0;
else if (!lua_isstring(o)) else if (!lua_isstring(o))
{ {
lua_reportbug("incorrect argument to function `nextvar'"); lua_error("incorrect argument to function `nextvar'");
return; /* to avoid warnings */ return; /* to avoid warnings */
} }
else else
varname = lua_getstring(o); next = luaI_findsymbolbyname(lua_getstring(o)) + 1;
next = lua_varnext(varname); while (next < lua_ntable && s_tag(next) == LUA_T_NIL) next++;
if (next == NULL) if (next >= lua_ntable)
{ {
lua_pushnil(); lua_pushnil();
lua_pushnil(); lua_pushnil();
} }
else else
{ {
Object name; lua_pushstring(lua_table[next].varname->str);
tag(&name) = LUA_T_STRING; luaI_pushobject(&s_object(next));
tsvalue(&name) = &(next->ts);
luaI_pushobject(&name);
luaI_pushobject(&s_object(next->varindex));
} }
} }
static void setglobal (void) static Object *functofind;
static int checkfunc (Object *o)
{ {
lua_Object name = lua_getparam(1); if (o->tag == LUA_T_FUNCTION)
lua_Object value = lua_getparam(2); return
if (!lua_isstring(name)) ((functofind->tag == LUA_T_FUNCTION || functofind->tag == LUA_T_MARK)
lua_reportbug("incorrect argument to function `setglobal'"); && (functofind->value.tf == o->value.tf));
lua_pushobject(value); if (o->tag == LUA_T_CFUNCTION)
lua_storeglobal(lua_getstring(name)); return
((functofind->tag == LUA_T_CFUNCTION || functofind->tag == LUA_T_CMARK)
&& (functofind->value.f == o->value.f));
return 0;
} }
static void getglobal (void) char *lua_getobjname (lua_Object o, char **name)
{ { /* try to find a name for given function */
lua_Object name = lua_getparam(1); functofind = luaI_Address(o);
if (!lua_isstring(name)) if ((*name = luaI_travfallbacks(checkfunc)) != NULL)
lua_reportbug("incorrect argument to function `getglobal'"); return "fallback";
lua_pushobject(lua_getglobal(lua_getstring(name))); else if ((*name = lua_travsymbol(checkfunc)) != NULL)
return "global";
else return "";
} }

33
table.h
View File

@@ -1,7 +1,7 @@
/* /*
** Module to control static tables ** Module to control static tables
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: table.h,v 2.9 1994/11/23 14:31:11 roberto Stab roberto $ ** $Id: table.h,v 2.20 1996/03/14 15:57:19 roberto Exp roberto $
*/ */
#ifndef table_h #ifndef table_h
@@ -10,22 +10,29 @@
#include "tree.h" #include "tree.h"
#include "opcode.h" #include "opcode.h"
typedef struct
{
Object object;
TaggedString *varname;
} Symbol;
extern Symbol *lua_table; extern Symbol *lua_table;
extern Word lua_ntable;
extern TaggedString **lua_constant; extern TaggedString **lua_constant;
extern Word lua_nconstant;
extern char *lua_file[]; void luaI_initsymbol (void);
extern int lua_nfile; void luaI_initconstant (void);
void lua_initconstant (void);
Word luaI_findsymbolbyname (char *name); Word luaI_findsymbolbyname (char *name);
Word luaI_findsymbol (TreeNode *t); Word luaI_findsymbol (TaggedString *t);
Word luaI_findconstant (TreeNode *t); Word luaI_findconstant (TaggedString *t);
void lua_travsymbol (void (*fn)(Object *)); Word luaI_findconstantbyname (char *name);
void lua_markobject (Object *o); TaggedString *luaI_createfixedstring (char *str);
int lua_markobject (Object *o);
int luaI_ismarked (Object *o);
Long luaI_collectgarbage (void);
void lua_pack (void); void lua_pack (void);
char *lua_addfile (char *fn);
int lua_delfile (void);
char *lua_filename (void);
#endif #endif

206
tree.c
View File

@@ -3,7 +3,7 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_tree="$Id: tree.c,v 1.12 1994/12/20 21:20:36 roberto Exp roberto $"; char *rcs_tree="$Id: tree.c,v 1.19 1996/02/22 20:34:33 roberto Exp $";
#include <string.h> #include <string.h>
@@ -11,66 +11,104 @@ char *rcs_tree="$Id: tree.c,v 1.12 1994/12/20 21:20:36 roberto Exp roberto $";
#include "mem.h" #include "mem.h"
#include "lua.h" #include "lua.h"
#include "tree.h" #include "tree.h"
#include "lex.h"
#include "hash.h"
#include "table.h" #include "table.h"
#define lua_strcmp(a,b) (a[0]<b[0]?(-1):(a[0]>b[0]?(1):strcmp(a,b))) #define NUM_HASHS 64
typedef struct {
int size;
int nuse; /* number of elements (including EMPTYs) */
TaggedString **hash;
} stringtable;
static int initialized = 0;
static stringtable string_root[NUM_HASHS];
static TaggedString EMPTY = {NOT_USED, NOT_USED, 0, 2, {0}};
typedef struct StringNode { static unsigned long hash (char *str)
struct StringNode *next;
TaggedString ts;
} StringNode;
static StringNode *string_root = NULL;
static TreeNode *constant_root = NULL;
/*
** Insert a new constant/variable at the tree.
*/
static TreeNode *tree_create (TreeNode **node, char *str)
{ {
if (*node == NULL) unsigned long h = 0;
{ while (*str)
*node = (TreeNode *) luaI_malloc(sizeof(TreeNode)+strlen(str)); h = ((h<<5)-h)^(unsigned char)*(str++);
(*node)->left = (*node)->right = NULL; return h;
strcpy((*node)->ts.str, str); }
(*node)->ts.marked = 0;
(*node)->ts.hash = 0; static void initialize (void)
(*node)->varindex = (*node)->constindex = NOT_USED; {
return *node; initialized = 1;
} luaI_addReserved();
else luaI_initsymbol();
{ luaI_initconstant();
int c = lua_strcmp(str, (*node)->ts.str); }
if (c < 0)
return tree_create(&(*node)->left, str);
else if (c > 0) static void grow (stringtable *tb)
return tree_create(&(*node)->right, str); {
int newsize = luaI_redimension(tb->size);
TaggedString **newhash = newvector(newsize, TaggedString *);
int i;
for (i=0; i<newsize; i++)
newhash[i] = NULL;
/* rehash */
tb->nuse = 0;
for (i=0; i<tb->size; i++)
if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)
{
int h = tb->hash[i]->hash%newsize;
while (newhash[h])
h = (h+1)%newsize;
newhash[h] = tb->hash[i];
tb->nuse++;
}
luaI_free(tb->hash);
tb->size = newsize;
tb->hash = newhash;
}
static TaggedString *insert (char *str, stringtable *tb)
{
TaggedString *ts;
unsigned long h = hash(str);
int i;
int j = -1;
if ((Long)tb->nuse*3 >= (Long)tb->size*2)
{
if (!initialized)
initialize();
grow(tb);
}
i = h%tb->size;
while (tb->hash[i])
{
if (tb->hash[i] == &EMPTY)
j = i;
else if (strcmp(str, tb->hash[i]->str) == 0)
return tb->hash[i];
i = (i+1)%tb->size;
}
/* not found */
lua_pack();
if (j != -1) /* is there an EMPTY space? */
i = j;
else else
return *node; tb->nuse++;
} ts = tb->hash[i] = (TaggedString *)luaI_malloc(sizeof(TaggedString)+strlen(str));
strcpy(ts->str, str);
ts->marked = 0;
ts->hash = h;
ts->varindex = ts->constindex = NOT_USED;
return ts;
} }
TaggedString *lua_createstring (char *str) TaggedString *lua_createstring (char *str)
{ {
StringNode *newString; return insert(str, &string_root[(unsigned)str[0]%NUM_HASHS]);
if (str == NULL) return NULL;
lua_pack();
newString = (StringNode *)luaI_malloc(sizeof(StringNode)+strlen(str));
newString->ts.marked = 0;
newString->ts.hash = 0;
strcpy(newString->ts.str, str);
newString->next = string_root;
string_root = newString;
return &(newString->ts);
}
TreeNode *lua_constcreate (char *str)
{
return tree_create(&constant_root, str);
} }
@@ -80,62 +118,28 @@ TreeNode *lua_constcreate (char *str)
*/ */
Long lua_strcollector (void) Long lua_strcollector (void)
{ {
StringNode *curr = string_root, *prev = NULL;
Long counter = 0; Long counter = 0;
while (curr) int i;
for (i=0; i<NUM_HASHS; i++)
{ {
StringNode *next = curr->next; stringtable *tb = &string_root[i];
if (!curr->ts.marked) int j;
for (j=0; j<tb->size; j++)
{ {
if (prev == NULL) string_root = next; TaggedString *t = tb->hash[j];
else prev->next = next; if (t != NULL && t->marked <= 1)
luaI_free(curr); {
++counter; if (t->marked)
t->marked = 0;
else
{
luaI_free(t);
tb->hash[j] = &EMPTY;
counter++;
}
}
} }
else
{
curr->ts.marked = 0;
prev = curr;
}
curr = next;
} }
return counter; return counter;
} }
/*
** Return next variable.
*/
static TreeNode *tree_next (TreeNode *node, char *str)
{
if (node == NULL) return NULL;
else if (str == NULL) return node;
else
{
int c = lua_strcmp(str, node->ts.str);
if (c == 0)
return node->left != NULL ? node->left : node->right;
else if (c < 0)
{
TreeNode *result = tree_next(node->left, str);
return result != NULL ? result : node->right;
}
else
return tree_next(node->right, str);
}
}
TreeNode *lua_varnext (char *n)
{
TreeNode *result;
char *name = n;
while (1)
{ /* repeat until a valid (non nil) variable */
result = tree_next(constant_root, name);
if (result == NULL) return NULL;
if (result->varindex != NOT_USED &&
s_tag(result->varindex) != LUA_T_NIL)
return result;
name = result->ts.str;
}
}

17
tree.h
View File

@@ -1,7 +1,7 @@
/* /*
** tree.h ** tree.h
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
** $Id: tree.h,v 1.8 1994/12/20 21:20:36 roberto Exp roberto $ ** $Id: tree.h,v 1.13 1996/02/14 13:35:51 roberto Exp roberto $
*/ */
#ifndef tree_h #ifndef tree_h
@@ -14,24 +14,15 @@
typedef struct TaggedString typedef struct TaggedString
{ {
Word varindex; /* != NOT_USED if this is a symbol */
Word constindex; /* != NOT_USED if this is a constant */
unsigned long hash; /* 0 if not initialized */ unsigned long hash; /* 0 if not initialized */
char marked; /* for garbage collection */ int marked; /* for garbage collection; never collect (nor change) if > 1 */
char str[1]; /* \0 byte already reserved */ char str[1]; /* \0 byte already reserved */
} TaggedString; } TaggedString;
typedef struct TreeNode
{
struct TreeNode *right;
struct TreeNode *left;
unsigned short varindex; /* != NOT_USED if this is a symbol */
unsigned short constindex; /* != NOT_USED if this is a constant */
TaggedString ts;
} TreeNode;
TaggedString *lua_createstring (char *str); TaggedString *lua_createstring (char *str);
TreeNode *lua_constcreate (char *str);
Long lua_strcollector (void); Long lua_strcollector (void);
TreeNode *lua_varnext (char *n);
#endif #endif

View File

@@ -1,6 +1,6 @@
/* /*
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: types.h,v 1.2 1994/12/27 20:41:47 celes Exp roberto $ ** $Id: types.h,v 1.3 1995/02/06 19:32:43 roberto Exp roberto $
*/ */
#ifndef types_h #ifndef types_h
@@ -12,8 +12,6 @@
#define real float #define real float
#endif #endif
typedef int Bool; /* boolean values */
#define Byte lua_Byte /* some systems have Byte as a predefined type */ #define Byte lua_Byte /* some systems have Byte as a predefined type */
typedef unsigned char Byte; /* unsigned 8 bits */ typedef unsigned char Byte; /* unsigned 8 bits */

36
ugly.h
View File

@@ -1,36 +0,0 @@
/*
** ugly.h
** TecCGraf - PUC-Rio
** $Id: $
*/
#ifndef ugly_h
#define ugly_h
/* This enum must have the same order of the array 'reserved' in lex.c */
enum {
U_and=128,
U_do,
U_else,
U_elseif,
U_end,
U_function,
U_if,
U_local,
U_nil,
U_not,
U_or,
U_repeat,
U_return,
U_then,
U_until,
U_while,
U_eq = '='+128,
U_le = '<'+128,
U_ge = '>'+128,
U_ne = '~'+128,
U_sc = '.'+128
};
#endif

326
undump.c Normal file
View File

@@ -0,0 +1,326 @@
/*
** undump.c
** load bytecodes from files
*/
char* rcs_undump="$Id: undump.c,v 1.13 1996/03/12 20:00:40 lhf Exp lhf $";
#include <stdio.h>
#include <string.h>
#include "opcode.h"
#include "mem.h"
#include "table.h"
#include "undump.h"
static int swapword=0;
static int swapfloat=0;
static TFunc* Main=NULL; /* functions in a chunk */
static TFunc* lastF=NULL;
static void warn(char* s) /* TODO: remove */
{
#if 0
fprintf(stderr,"undump: %s\n",s);
#endif
}
static void FixCode(Byte* code, Byte* end) /* swap words */
{
Byte* p;
for (p=code; p!=end;)
{
OpCode op=(OpCode)*p;
switch (op)
{
case PUSHNIL:
case PUSH0:
case PUSH1:
case PUSH2:
case PUSHLOCAL0:
case PUSHLOCAL1:
case PUSHLOCAL2:
case PUSHLOCAL3:
case PUSHLOCAL4:
case PUSHLOCAL5:
case PUSHLOCAL6:
case PUSHLOCAL7:
case PUSHLOCAL8:
case PUSHLOCAL9:
case PUSHINDEXED:
case STORELOCAL0:
case STORELOCAL1:
case STORELOCAL2:
case STORELOCAL3:
case STORELOCAL4:
case STORELOCAL5:
case STORELOCAL6:
case STORELOCAL7:
case STORELOCAL8:
case STORELOCAL9:
case STOREINDEXED0:
case ADJUST0:
case EQOP:
case LTOP:
case LEOP:
case GTOP:
case GEOP:
case ADDOP:
case SUBOP:
case MULTOP:
case DIVOP:
case POWOP:
case CONCOP:
case MINUSOP:
case NOTOP:
case POP:
case RETCODE0:
p++;
break;
case PUSHBYTE:
case PUSHLOCAL:
case STORELOCAL:
case STOREINDEXED:
case STORELIST0:
case ADJUST:
case RETCODE:
p+=2;
break;
case STORELIST:
case CALLFUNC:
p+=3;
break;
case PUSHFUNCTION:
p+=5;
break;
case PUSHWORD:
case PUSHSELF:
case CREATEARRAY:
case ONTJMP:
case ONFJMP:
case JMP:
case UPJMP:
case IFFJMP:
case IFFUPJMP:
case SETLINE:
case PUSHSTRING:
case PUSHGLOBAL:
case STOREGLOBAL:
{
Byte t;
t=p[1]; p[1]=p[2]; p[2]=t;
p+=3;
break;
}
case PUSHFLOAT:
{
Byte t;
t=p[1]; p[1]=p[4]; p[4]=t;
t=p[2]; p[2]=p[3]; p[3]=t;
p+=5;
break;
}
case STORERECORD:
{
int n=*++p;
p++;
while (n--)
{
Byte t;
t=p[0]; p[0]=p[1]; p[1]=t;
p+=2;
}
break;
}
default:
lua_error("corrupt binary file");
break;
}
}
}
static void Unthread(Byte* code, int i, int v)
{
while (i!=0)
{
CodeWord c;
Byte* p=code+i;
get_word(c,p);
i=c.w;
c.w=v;
p[-2]=c.m.c1;
p[-1]=c.m.c2;
}
}
static int LoadWord(FILE* D)
{
Word w;
fread(&w,sizeof(w),1,D);
if (swapword)
{
Byte* p=(Byte*)&w; /* TODO: need union? */
Byte t;
t=p[0]; p[0]=p[1]; p[1]=t;
}
return w;
}
static int LoadSize(FILE* D)
{
Word hi=LoadWord(D);
Word lo=LoadWord(D);
int s=(hi<<16)|lo;
if ((Word)s != s) lua_error("code too long");
return s;
}
static char* LoadBlock(int size, FILE* D)
{
char* b=luaI_malloc(size);
fread(b,size,1,D);
return b;
}
static char* LoadString(FILE* D)
{
int size=LoadWord(D);
char *b=luaI_buffer(size);
fread(b,size,1,D);
return b;
}
static char* LoadNewString(FILE* D)
{
return LoadBlock(LoadWord(D),D);
}
static void LoadFunction(FILE* D)
{
TFunc* tf=new(TFunc);
tf->next=NULL;
tf->locvars=NULL;
tf->size=LoadSize(D);
tf->lineDefined=LoadWord(D);
if (IsMain(tf)) /* new main */
{
tf->fileName=LoadNewString(D);
Main=lastF=tf;
}
else /* fix PUSHFUNCTION */
{
CodeCode c;
Byte* p;
tf->marked=LoadWord(D);
tf->fileName=Main->fileName;
p=Main->code+tf->marked;
c.tf=tf;
*p++=c.m.c1; *p++=c.m.c2; *p++=c.m.c3; *p++=c.m.c4;
lastF=lastF->next=tf;
}
tf->code=LoadBlock(tf->size,D);
if (swapword || swapfloat) FixCode(tf->code,tf->code+tf->size);
while (1) /* unthread */
{
int c=getc(D);
if (c==ID_VAR) /* global var */
{
int i=LoadWord(D);
char* s=LoadString(D);
int v=luaI_findsymbolbyname(s);
Unthread(tf->code,i,v);
}
else if (c==ID_STR) /* constant string */
{
int i=LoadWord(D);
char* s=LoadString(D);
int v=luaI_findconstantbyname(s);
Unthread(tf->code,i,v);
}
else
{
ungetc(c,D);
break;
}
}
}
static void LoadSignature(FILE* D)
{
char* s=SIGNATURE;
while (*s!=0 && getc(D)==*s)
++s;
if (*s!=0) lua_error("bad signature");
}
static void LoadHeader(FILE* D) /* TODO: error handling */
{
Word w,tw=TEST_WORD;
float f,tf=TEST_FLOAT;
LoadSignature(D);
getc(D); /* skip version */
fread(&w,sizeof(w),1,D); /* test word */
if (w!=tw)
{
swapword=1;
warn("different byte order");
}
fread(&f,sizeof(f),1,D); /* test float */
if (f!=tf)
{
Byte* p=(Byte*)&f; /* TODO: need union? */
Byte t;
swapfloat=1;
t=p[0]; p[0]=p[3]; p[3]=t;
t=p[1]; p[1]=p[2]; p[2]=t;
if (f!=tf) /* TODO: try another perm? */
lua_error("different float representation");
else
warn("different byte order in floats");
}
}
static void LoadChunk(FILE* D)
{
LoadHeader(D);
while (1)
{
int c=getc(D);
if (c==ID_FUN) LoadFunction(D); else { ungetc(c,D); break; }
}
}
/*
** load one chunk from a file.
** return list of functions found, headed by main, or NULL at EOF.
*/
TFunc* luaI_undump1(FILE* D)
{
while (1)
{
int c=getc(D);
if (c==ID_CHUNK)
{
LoadChunk(D);
return Main;
}
else if (c==EOF)
return NULL;
else
lua_error("not a lua binary file");
}
}
/*
** load and run all chunks in a file
*/
int luaI_undump(FILE* D)
{
TFunc* m;
while ((m=luaI_undump1(D)))
{
int status=luaI_dorun(m);
luaI_freefunc(m);
if (status!=0) return status;
}
return 0;
}

23
undump.h Normal file
View File

@@ -0,0 +1,23 @@
/*
** undump.h
** definitions for lua decompiler
** $Id: undump.h,v 1.1 1996/03/08 21:43:21 lhf Exp lhf $
*/
#include "func.h"
#define IsMain(f) (f->lineDefined==0)
/* definitions for chunk headers */
#define ID_CHUNK 27 /* ESC */
#define ID_FUN 'F'
#define ID_VAR 'V'
#define ID_STR 'S'
#define SIGNATURE "Lua"
#define VERSION 0x23 /* 2.3 */
#define TEST_WORD 0x1234 /* a word for testing byte ordering */
#define TEST_FLOAT 0.123456789e-23 /* a float for testing representation */
TFunc* luaI_undump1(FILE* D); /* load one chunk */
int luaI_undump(FILE* D); /* load all chunks */