Compare commits

...

87 Commits

Author SHA1 Message Date
Roberto Ierusalimschy
42359b8b13 new version 1996-11-20 11:49:32 -02:00
Roberto Ierusalimschy
169870e37d BUG: ISO chars are negative, ISO ints are not. 1996-11-20 11:47:59 -02:00
Roberto Ierusalimschy
78e454d864 BUG: ISO chars are negative, ISO ints are not.
new "balanced" pattern.
1996-11-20 11:47:59 -02:00
Roberto Ierusalimschy
dbfe28e199 correction in inheritance code in C 1996-11-18 12:27:42 -02:00
Roberto Ierusalimschy
d59c52753f undump needs file in binary mode 1996-11-18 11:48:44 -02:00
Roberto Ierusalimschy
62e1a4c84d BUG: problems with negative indexes 1996-11-18 11:48:44 -02:00
Luiz Henrique de Figueiredo
81411e8913 headers includes sizeof(Word) not sizeof(int) 1996-11-18 09:18:29 -02:00
Luiz Henrique de Figueiredo
62aa717f7e stdlib.h for exit
blocks are void*
1996-11-16 18:14:23 -02:00
Roberto Ierusalimschy
a5614eae3c spelling corrections. 1996-11-14 15:45:37 -02:00
Luiz Henrique de Figueiredo
536bae5871 corrected version test (0x23 not 23) 1996-11-14 13:00:32 -02:00
Luiz Henrique de Figueiredo
679eddf296 1996-11-14 11:33:15 -02:00
Luiz Henrique de Figueiredo
d991def36c added 3 new bytes to header (sizeof's) 1996-11-14 09:44:34 -02:00
Luiz Henrique de Figueiredo
8b195533d2 new header version 1996-11-14 09:44:34 -02:00
Roberto Ierusalimschy
3ccdd57c26 new version 1996-11-12 14:00:16 -02:00
Roberto Ierusalimschy
a103455dda better format for error messages. 1996-11-08 17:08:30 -02:00
Roberto Ierusalimschy
60242e1930 error message for syntax "1..2";
syntax error function is in "lex.c" (it has the token)
1996-11-08 10:49:35 -02:00
Roberto Ierusalimschy
a0e9bfbb48 syntax error function is in "lex.c" (it has the token) 1996-11-08 10:49:35 -02:00
Roberto Ierusalimschy
2f19e0ba16 SunOS is not ANSI about the return value of "sprintf". 1996-11-07 18:26:19 -02:00
Roberto Ierusalimschy
ab7fdcbbed corrected copyright notice 1996-11-07 18:26:08 -02:00
Luiz Henrique de Figueiredo
48cf1de356 replaced unions by memcpy 1996-11-07 12:13:28 -02:00
Luiz Henrique de Figueiredo
8d50122af0 replaced unions by memcpy 1996-11-07 11:59:51 -02:00
Roberto Ierusalimschy
fd379b38f7 new flag for STRERROR; libs now are called lib... 1996-11-06 18:48:03 -02:00
Roberto Ierusalimschy
aa4d865077 anna's comments 1996-11-06 18:26:56 -02:00
Roberto Ierusalimschy
3e94febfc1 pragmas should not be recognized inside literal strings. 1996-11-06 18:24:29 -02:00
Roberto Ierusalimschy
243b3a1a47 i/o functions return an error message 1996-11-01 16:02:53 -02:00
Roberto Ierusalimschy
389e808c60 although an ANSI function, some systems do not offer "strerror" 1996-11-01 15:54:41 -02:00
Roberto Ierusalimschy
450465c4d4 new parameters for "read" and "write". BIG CHANGE. 1996-11-01 15:03:36 -02:00
Roberto Ierusalimschy
2f44cc9f4d new pattern matching facilities; new version of i/o lib;
other small corrections.
1996-11-01 15:02:10 -02:00
Roberto Ierusalimschy
d106f3f43c pre-defined variable _VERSION_ 1996-11-01 10:47:45 -02:00
Roberto Ierusalimschy
bf3091d94f new version number 1996-11-01 10:46:59 -02:00
Roberto Ierusalimschy
4dbf7285a8 small omission corrected ("s_tsvalue") 1996-11-01 10:46:59 -02:00
Roberto Ierusalimschy
a1e41e3a12 small corrections in error messages 1996-10-31 18:18:05 -02:00
Roberto Ierusalimschy
9d0044ce53 "strfind" has an extra parameter to turn off all special characteres. 1996-10-31 15:26:04 -02:00
Roberto Ierusalimschy
37bf74efb7 some compilers do not accept "stdin"/"stdout" as constants. 1996-10-16 18:22:34 -02:00
Roberto Ierusalimschy
8c37d3b9d6 documentation of opcode meanings (thanks to lhf) 1996-09-26 18:08:41 -03:00
Roberto Ierusalimschy
0af581f0bf new way to handle pragmas (at the lexical level, instead of parsing). 1996-09-25 18:52:00 -03:00
Roberto Ierusalimschy
2a506ea9d2 lua_linenumber is initialized in lex.c 1996-09-25 09:57:22 -03:00
Roberto Ierusalimschy
e5ec547eb3 "call" returns separate results, instead of a table. 1996-09-24 18:46:44 -03:00
Roberto Ierusalimschy
6d383202dc "dofile" and "dostring" may return values. 1996-09-24 14:30:28 -03:00
Roberto Ierusalimschy
7b8166d7b3 a chunk may end with a return. 1996-09-24 14:29:50 -03:00
Roberto Ierusalimschy
3636bbad3a new function "strrep" 1996-09-20 15:20:44 -03:00
Roberto Ierusalimschy
82f9f3e552 better structure to control stack interface lua-C.
beginblock-endblock keeps better control over stack
1996-09-20 09:51:16 -03:00
Roberto Ierusalimschy
c96ad1c945 "strmap" replaced by "strupper" and "strlower" (that's what people will
use, anyway).
"gsub" aceppts a function to give the replacement string.
1996-09-16 15:02:40 -03:00
Roberto Ierusalimschy
5b9fbfa006 "dostring" now stores the prefix of its string, to improve error messages. 1996-09-11 18:53:02 -03:00
Roberto Ierusalimschy
f0cc2d5506 BUG: a program ending in a comment without EOL made lex loops forever. 1996-09-09 11:11:11 -03:00
Roberto Ierusalimschy
d289ac81d3 functions may have tags CMARK and MARK, too. 1996-09-02 18:57:51 -03:00
Roberto Ierusalimschy
15791f93fe lhf's corrections. 1996-08-28 17:46:26 -03:00
Roberto Ierusalimschy
d763b69740 skip first line of a lua file if it starts with a '#' (to allow shell
scripts).
1996-08-15 15:40:55 -03:00
Roberto Ierusalimschy
36dd1af92d "[^]]" must mean "not ]". 1996-08-09 10:14:11 -03:00
Roberto Ierusalimschy
25b6dae7c0 singlematch and item_end are used by "read", in iolib. 1996-08-05 17:55:24 -03:00
Roberto Ierusalimschy
1630c2533a Pattern-Matching!
plus several other changes...
1996-08-01 11:55:33 -03:00
Roberto Ierusalimschy
1d373d77de more functions exported. 1996-08-01 11:55:33 -03:00
Roberto Ierusalimschy
f025b0d160 "pushnil" is not needed (default return is nil). 1996-08-01 11:55:33 -03:00
Roberto Ierusalimschy
cc02b4729b new mod implementation (more portable). 1996-08-01 11:55:33 -03:00
Roberto Ierusalimschy
2bb3830fc1 "memcpy" is defined in "string.h". 1996-07-24 15:01:52 -03:00
Roberto Ierusalimschy
7a38bdd4b3 "exit" is defined in "stdlib". 1996-07-24 14:55:57 -03:00
Roberto Ierusalimschy
7614b17e85 very small corrections 1996-07-24 11:38:12 -03:00
Roberto Ierusalimschy
6dfdb76538 C functions don't need to "pushnil" to return nil value (this is
the default value).
1996-07-12 17:00:26 -03:00
Roberto Ierusalimschy
9a3c51cff1 new name for POSIX flag (this one turns on some posix stuff in standard
header files).
1996-07-06 17:20:35 -03:00
Roberto Ierusalimschy
6336d2f9e1 flag for direct execution is "-e"; argument with an "=" goes to
direct execution, independently of flags.
1996-07-05 17:55:43 -03:00
Roberto Ierusalimschy
ec6677e551 when "block" is computed, "nentity" == "block". So the change is only
a simpler way to write the same expression.
1996-06-18 18:12:23 -03:00
Roberto Ierusalimschy
20cbca699a "lua_dofile" has a more informative return code. 1996-06-18 17:08:40 -03:00
Roberto Ierusalimschy
3211a9648a "lua_dofile" returns different error codes if it could not open the file 1996-06-10 16:36:24 -03:00
Roberto Ierusalimschy
0baa915343 new option "-x" to execute a string given as argument. 1996-06-10 16:35:46 -03:00
Roberto Ierusalimschy
5cddb264d4 lexical analiser may use luaI_buffer, instead of waste space with
a separate buffer.
1996-05-30 11:04:07 -03:00
Roberto Ierusalimschy
9863223fbf first version of vararg facility (plus new function "call"). 1996-05-28 18:07:32 -03:00
Roberto Ierusalimschy
9a1948e67d small correction. 1996-05-27 11:06:58 -03:00
Roberto Ierusalimschy
f9deeac632 "luaI_malloc(s)" is just a macro to "luaI_realloc(NULL, s)". 1996-05-24 11:31:10 -03:00
Roberto Ierusalimschy
29f0021837 variables which contain string lengths must be long (if they also may
be negative) or size_t.
1996-05-22 18:59:07 -03:00
Roberto Ierusalimschy
7acddb871d memory manager for old versions of Lua. It should be in RCS since
the beginning.
1996-05-06 18:37:28 -03:00
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
26 changed files with 1991 additions and 1632 deletions

View File

@@ -3,7 +3,7 @@
** TecCGraf - PUC-Rio
*/
char *rcs_fallback="$Id: fallback.c,v 1.22 1996/03/19 22:28:37 roberto Exp roberto $";
char *rcs_fallback="$Id: fallback.c,v 1.24 1996/04/22 18:00:37 roberto Exp roberto $";
#include <stdio.h>
#include <string.h>
@@ -12,6 +12,7 @@ char *rcs_fallback="$Id: fallback.c,v 1.22 1996/03/19 22:28:37 roberto Exp rober
#include "fallback.h"
#include "opcode.h"
#include "lua.h"
#include "table.h"
static void errorFB (void);
@@ -112,59 +113,74 @@ static void funcFB (void)
/*
** Lock routines
** Reference routines
*/
static Object *lockArray = NULL;
static int lockSize = 0;
static struct ref {
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)
{
int i;
int oldSize;
if (tag(object) == LUA_T_NIL)
return -1; /* special lock ref for nil */
for (i=0; i<lockSize; i++)
if (tag(&lockArray[i]) == LUA_T_NIL)
{
lockArray[i] = *object;
return i;
}
return -1; /* special ref for nil */
for (i=0; i<refSize; i++)
if (refArray[i].status == FREE)
goto found;
/* no more empty spaces */
oldSize = lockSize;
lockSize = growvector(&lockArray, lockSize, Object, lockEM, MAX_WORD);
for (i=oldSize; i<lockSize; i++)
tag(&lockArray[i]) = LUA_T_NIL;
lockArray[oldSize] = *object;
return oldSize;
oldSize = refSize;
refSize = growvector(&refArray, refSize, struct ref, refEM, MAX_WORD);
for (i=oldSize; i<refSize; i++)
refArray[i].status = FREE;
i = oldSize;
found:
refArray[i].o = *object;
refArray[i].status = lock ? LOCK : HOLD;
return i;
}
void lua_unlock (int ref)
void lua_unref (int ref)
{
if (ref >= 0 && ref < lockSize)
tag(&lockArray[ref]) = LUA_T_NIL;
if (ref >= 0 && ref < refSize)
refArray[ref].status = FREE;
}
Object *luaI_getlocked (int ref)
Object *luaI_getref (int ref)
{
static Object nul = {LUA_T_NIL, {0}};
if (ref >= 0 && ref < lockSize)
return &lockArray[ref];
else
if (ref == -1)
return &nul;
if (ref >= 0 && ref < refSize &&
(refArray[ref].status == LOCK || refArray[ref].status == HOLD))
return &refArray[ref].o;
else
return NULL;
}
void luaI_travlock (int (*fn)(Object *))
{
int i;
for (i=0; i<lockSize; i++)
fn(&lockArray[i]);
for (i=0; i<refSize; i++)
if (refArray[i].status == LOCK)
fn(&refArray[i].o);
}
void luaI_invalidaterefs (void)
{
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 *))
{
int i;

View File

@@ -1,10 +1,11 @@
/*
** $Id: fallback.h,v 1.10 1995/10/17 11:52:38 roberto Exp roberto $
** $Id: fallback.h,v 1.12 1996/04/22 18:00:37 roberto Exp roberto $
*/
#ifndef fallback_h
#define fallback_h
#include "lua.h"
#include "opcode.h"
extern struct FB {
@@ -26,9 +27,10 @@ extern struct FB {
#define FB_GETGLOBAL 9
void luaI_setfallback (void);
int luaI_lock (Object *object);
Object *luaI_getlocked (int ref);
int luaI_ref (Object *object, int lock);
Object *luaI_getref (int ref);
void luaI_travlock (int (*fn)(Object *));
void luaI_invalidaterefs (void);
char *luaI_travfallbacks (int (*fn)(Object *));
#endif

2
func.c
View File

@@ -1,4 +1,4 @@
#include <stdlib.h>
#include <string.h>
#include "luadebug.h"
#include "table.h"

89
hash.c
View File

@@ -3,7 +3,7 @@
** hash manager for lua
*/
char *rcs_hash="$Id: hash.c,v 2.28 1996/02/12 18:32:40 roberto Exp roberto $";
char *rcs_hash="$Id: hash.c,v 2.31 1996/07/12 20:00:26 roberto Exp roberto $";
#include "mem.h"
@@ -29,14 +29,15 @@ static Hash *listhead = NULL;
/* hash dimensions values */
static Word dimensions[] =
{3, 5, 7, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421,
12853, 25717, 51437, 65521, 0}; /* 65521 == last prime < MAX_WORD */
static Long dimensions[] =
{3L, 5L, 7L, 11L, 23L, 47L, 97L, 197L, 397L, 797L, 1597L, 3203L, 6421L,
12853L, 25717L, 51437L, 102811L, 205619L, 411233L, 822433L,
1644817L, 3289613L, 6579211L, 13158023L, MAX_INT};
Word luaI_redimension (Word nhash)
int luaI_redimension (int nhash)
{
Word i;
for (i=0; dimensions[i]!=0; i++)
int i;
for (i=0; dimensions[i]<MAX_INT; i++)
{
if (dimensions[i] > nhash)
return dimensions[i];
@@ -45,26 +46,28 @@ Word luaI_redimension (Word nhash)
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))
{
case LUA_T_NIL:
lua_error ("unexpected type to index table");
return -1; /* UNREACHEABLE */
case LUA_T_NUMBER:
return (((Word)nvalue(ref))%nhash(t));
case LUA_T_STRING:
return (Word)((tsvalue(ref)->hash)%nhash(t)); /* make it a valid index */
case LUA_T_FUNCTION:
return (((IntPoint)ref->value.tf)%nhash(t));
case LUA_T_CFUNCTION:
return (((IntPoint)fvalue(ref))%nhash(t));
case LUA_T_ARRAY:
return (((IntPoint)avalue(ref))%nhash(t));
default: /* user data */
return (((IntPoint)uvalue(ref))%nhash(t));
}
long int h;
switch (tag(ref)) {
case LUA_T_NIL:
lua_error ("unexpected type to index table");
h = 0; /* UNREACHEABLE */
case LUA_T_NUMBER:
h = (long int)nvalue(ref); break;
case LUA_T_STRING:
h = tsvalue(ref)->hash; break;
case LUA_T_FUNCTION:
h = (IntPoint)ref->value.tf; break;
case LUA_T_CFUNCTION:
h = (IntPoint)fvalue(ref); break;
case LUA_T_ARRAY:
h = (IntPoint)avalue(ref); break;
default: /* user data */
h = (IntPoint)uvalue(ref); break;
}
if (h < 0) h = -h;
return h%nhash(t); /* make it a valid index */
}
int lua_equalObj (Object *t1, Object *t2)
@@ -82,9 +85,9 @@ int lua_equalObj (Object *t1, Object *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)
{
if (lua_equalObj(ref, ref(node(t, h))))
@@ -98,9 +101,9 @@ static Word present (Hash *t, Object *ref)
/*
** Alloc a vector node
*/
static Node *hashnodecreate (Word nhash)
static Node *hashnodecreate (int nhash)
{
Word i;
int i;
Node *v = newvector (nhash, Node);
for (i=0; i<nhash; i++)
tag(ref(&v[i])) = LUA_T_NIL;
@@ -110,10 +113,10 @@ static Node *hashnodecreate (Word nhash)
/*
** 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);
nhash = luaI_redimension((Word)((float)nhash/REHASH_LIMIT));
nhash = luaI_redimension((int)((float)nhash/REHASH_LIMIT));
nodevector(t) = hashnodecreate(nhash);
nhash(t) = nhash;
nuse(t) = 0;
@@ -138,7 +141,7 @@ void lua_hashmark (Hash *h)
{
if (markarray(h) == 0)
{
Word i;
int i;
markarray(h) = 1;
for (i=0; i<nhash(h); i++)
{
@@ -205,7 +208,7 @@ Long lua_hashcollector (void)
** executes garbage collection if the number of arrays created
** exceed a pre-defined range.
*/
Hash *lua_createarray (Word nhash)
Hash *lua_createarray (int nhash)
{
Hash *array;
lua_pack();
@@ -221,8 +224,8 @@ Hash *lua_createarray (Word nhash)
*/
static void rehash (Hash *t)
{
Word i;
Word nold = nhash(t);
int i;
int nold = nhash(t);
Node *vold = nodevector(t);
nhash(t) = luaI_redimension(nhash(t));
nodevector(t) = hashnodecreate(nhash(t));
@@ -241,7 +244,7 @@ static void rehash (Hash *t)
*/
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));
else return NULL;
}
@@ -253,7 +256,7 @@ Object *lua_hashget (Hash *t, Object *ref)
*/
Object *lua_hashdefine (Hash *t, Object *ref)
{
Word h;
int h;
Node *n;
h = present(t, ref);
n = node(t, h);
@@ -279,20 +282,14 @@ Object *lua_hashdefine (Hash *t, Object *ref)
** in the hash.
** 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))
{
lua_pushnil(); lua_pushnil();
return;
}
while (tag(ref(node(t,i))) == LUA_T_NIL || tag(val(node(t,i))) == LUA_T_NIL)
{
if (++i >= nhash(t))
{
lua_pushnil(); lua_pushnil();
return;
}
}
luaI_pushobject(ref(node(t,i)));
luaI_pushobject(val(node(t,i)));
@@ -316,7 +313,7 @@ void lua_next (void)
}
else
{
Word h = present (t, luaI_Address(r));
int h = present (t, luaI_Address(r));
hashnext(t, h+1);
}
}

12
hash.h
View File

@@ -1,7 +1,7 @@
/*
** hash.h
** hash manager for lua
** $Id: hash.h,v 2.10 1996/02/12 18:32:40 roberto Exp roberto $
** $Id: hash.h,v 2.11 1996/03/08 12:04:04 roberto Exp roberto $
*/
#ifndef hash_h
@@ -19,16 +19,16 @@ typedef struct node
typedef struct Hash
{
struct Hash *next;
char mark;
Word nhash;
Word nuse;
Node *node;
int nhash;
int nuse;
char mark;
} Hash;
int lua_equalObj (Object *t1, Object *t2);
Word luaI_redimension (Word nhash);
Hash *lua_createarray (Word nhash);
int luaI_redimension (int nhash);
Hash *lua_createarray (int nhash);
void lua_hashmark (Hash *h);
Long lua_hashcollector (void);
Object *lua_hashget (Hash *t, Object *ref);

98
inout.c
View File

@@ -5,9 +5,10 @@
** Also provides some predefined lua functions.
*/
char *rcs_inout="$Id: inout.c,v 2.35 1996/03/19 16:50:24 roberto Exp roberto $";
char *rcs_inout="$Id: inout.c,v 2.42 1996/09/24 21:46:44 roberto Exp roberto $";
#include <stdio.h>
#include <string.h>
#include "lex.h"
#include "opcode.h"
@@ -31,7 +32,8 @@ static char *st;
*/
static int fileinput (void)
{
return fgetc (fp);
int c = fgetc(fp);
return (c == EOF) ? 0 : c;
}
/*
@@ -58,7 +60,6 @@ FILE *lua_openfile (char *fn)
fp = fopen (fn, "r");
if (fp == NULL)
return NULL;
lua_linenumber = 1;
lua_parsedfile = luaI_createfixedstring(fn)->str;
return fp;
}
@@ -78,12 +79,16 @@ void lua_closefile (void)
/*
** Function to open a string to be input unit
*/
#define SIZE_PREF 20 /* size of string prefix to appear in error messages */
void lua_openstring (char *s)
{
lua_setinput (stringinput);
st = s;
lua_linenumber = 1;
lua_parsedfile = luaI_createfixedstring("(string)")->str;
char buff[SIZE_PREF+25];
lua_setinput(stringinput);
st = s;
strcpy(buff, "(dostring) >> ");
strncat(buff, s, SIZE_PREF);
if (strlen(s) > SIZE_PREF) strcat(buff, "...");
lua_parsedfile = luaI_createfixedstring(buff)->str;
}
/*
@@ -93,17 +98,36 @@ void lua_closestring (void)
{
}
static void check_arg (int cond, char *func)
{
if (!cond)
{
char buff[100];
sprintf(buff, "incorrect argument to function `%s'", func);
lua_error(buff);
}
}
static int passresults (void)
{
int arg = 0;
lua_Object obj;
while ((obj = lua_getresult(++arg)) != LUA_NOOBJECT)
lua_pushobject(obj);
return arg-1;
}
/*
** Internal function: do a string
*/
void lua_internaldostring (void)
{
lua_Object obj = lua_getparam (1);
if (lua_isstring(obj) && !lua_dostring(lua_getstring(obj)))
lua_pushnumber(1);
else
lua_pushnil();
lua_Object obj = lua_getparam (1);
if (lua_isstring(obj) && lua_dostring(lua_getstring(obj)) == 0)
if (passresults() == 0)
lua_pushuserdata(NULL); /* at least one result to signal no errors */
}
/*
@@ -118,10 +142,9 @@ void lua_internaldofile (void)
else if (obj != LUA_NOOBJECT)
lua_error("invalid argument to function `dofile'");
/* else fname = NULL */
if (!lua_dofile(fname))
lua_pushnumber(1);
else
lua_pushnil();
if (lua_dofile(fname) == 0)
if (passresults() == 0)
lua_pushuserdata(NULL); /* at least one result to signal no errors */
}
@@ -207,8 +230,6 @@ void lua_obj2number (void)
lua_Object o = lua_getparam(1);
if (lua_isnumber(o))
lua_pushnumber(lua_getnumber(o));
else
lua_pushnil();
}
@@ -230,8 +251,7 @@ 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'");
check_arg(lua_isstring(name), "setglobal");
lua_pushobject(value);
lua_storeglobal(lua_getstring(name));
lua_pushobject(value); /* return given value */
@@ -240,7 +260,41 @@ void luaI_setglobal (void)
void luaI_getglobal (void)
{
lua_Object name = lua_getparam(1);
if (!lua_isstring(name))
lua_error("incorrect argument to function `getglobal'");
check_arg(lua_isstring(name), "getglobal");
lua_pushobject(lua_getglobal(lua_getstring(name)));
}
#define MAXPARAMS 256
void luaI_call (void)
{
lua_Object f = lua_getparam(1);
lua_Object arg = lua_getparam(2);
lua_Object temp, params[MAXPARAMS];
int narg, i;
check_arg(lua_istable(arg), "call");
check_arg(lua_isfunction(f), "call");
/* narg = arg.n */
lua_pushobject(arg);
lua_pushstring("n");
temp = lua_getsubscript();
narg = lua_isnumber(temp) ? lua_getnumber(temp) : MAXPARAMS+1;
/* read arg[1...n] */
for (i=0; i<narg; i++) {
if (i>=MAXPARAMS)
lua_error("argument list too long in function `call'");
lua_pushobject(arg);
lua_pushnumber(i+1);
params[i] = lua_getsubscript();
if (narg == MAXPARAMS+1 && lua_isnil(params[i])) {
narg = i;
break;
}
}
/* push parameters and do the call */
for (i=0; i<narg; i++)
lua_pushobject(params[i]);
if (lua_callfunction(f))
lua_error(NULL);
else
passresults();
}

View File

@@ -1,5 +1,5 @@
/*
** $Id: inout.h,v 1.14 1996/03/15 13:13:13 roberto Exp roberto $
** $Id: inout.h,v 1.15 1996/03/15 18:21:58 roberto Exp roberto $
*/
@@ -29,5 +29,6 @@ void luaI_error (void);
void luaI_assert (void);
void luaI_setglobal (void);
void luaI_getglobal (void);
void luaI_call (void);
#endif

633
iolib.c
View File

@@ -1,14 +1,5 @@
/*
** iolib.c
** Input/output library to LUA
*/
char *rcs_iolib="$Id: iolib.c,v 1.39 1996/03/14 15:55:18 roberto Exp roberto $";
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
@@ -18,7 +9,8 @@ char *rcs_iolib="$Id: iolib.c,v 1.39 1996/03/14 15:55:18 roberto Exp roberto $";
#include "luadebug.h"
#include "lualib.h"
static FILE *in=stdin, *out=stdout;
FILE *lua_infile, *lua_outfile;
#ifdef POPEN
@@ -33,544 +25,225 @@ int pclose();
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;
lua_pushuserdata(NULL);
else {
lua_pushnil();
#ifndef NOSTRERROR
lua_pushstring(strerror(errno));
#else
lua_pushstring("system unable to define the error");
#endif
}
}
static void closewrite (void)
static void closefile (FILE *f)
{
if (out != stdout)
{
if (pclose(out) == -1)
fclose(out);
out = stdout;
}
if (f == stdin || f == stdout)
return;
if (f == lua_infile)
lua_infile = stdin;
if (f == lua_outfile)
lua_outfile = stdout;
if (pclose(f) == -1)
fclose(f);
}
/*
** Open a file to read.
** LUA interface:
** status = readfrom (filename)
** where:
** status = 1 -> success
** status = nil -> error
*/
static void io_readfrom (void)
{
if (lua_getparam (1) == LUA_NOOBJECT)
{ /* restore standart input */
closeread();
lua_pushnumber (1);
}
else
{
char *s = lua_check_string(1, "readfrom");
FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
if (fp == NULL)
lua_pushnil();
else
{
closeread();
in = fp;
lua_pushnumber (1);
}
}
lua_Object f = lua_getparam(1);
if (f == LUA_NOOBJECT)
closefile(lua_infile); /* restore standart input */
else if (lua_isuserdata(f))
lua_infile = lua_getuserdata(f);
else {
char *s = lua_check_string(1, "readfrom");
FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
if (fp)
lua_infile = fp;
else {
pushresult(0);
return;
}
}
lua_pushuserdata(lua_infile);
}
/*
** Open a file to write.
** LUA interface:
** status = writeto (filename)
** where:
** status = 1 -> success
** status = nil -> error
*/
static void io_writeto (void)
{
if (lua_getparam (1) == LUA_NOOBJECT) /* restore standart output */
{
closewrite();
lua_pushnumber (1);
}
else
{
char *s = lua_check_string(1, "writeto");
FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
if (fp == NULL)
lua_pushnil();
else
{
closewrite();
out = fp;
lua_pushnumber (1);
}
}
lua_Object f = lua_getparam(1);
if (f == LUA_NOOBJECT)
closefile(lua_outfile); /* restore standart output */
else if (lua_isuserdata(f))
lua_outfile = lua_getuserdata(f);
else {
char *s = lua_check_string(1, "writeto");
FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
if (fp)
lua_outfile = fp;
else {
pushresult(0);
return;
}
}
lua_pushuserdata(lua_outfile);
}
/*
** Open a file to write appended.
** LUA interface:
** status = appendto (filename)
** where:
** status = 2 -> success (already exist)
** status = 1 -> success (new file)
** status = nil -> error
*/
static void io_appendto (void)
{
char *s = lua_check_string(1, "appendto");
struct stat st;
int r = (stat(s, &st) == -1) ? 1 : 2;
FILE *fp = fopen (s, "a");
if (fp == NULL)
lua_pushnil();
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');
char *s = lua_check_string(1, "appendto");
FILE *fp = fopen (s, "a");
if (fp != NULL) {
lua_outfile = fp;
lua_pushuserdata(lua_outfile);
}
else
*m = -1;
if (*f == '.')
{
f++; /* skip point */
*n = 0;
while (isdigit(*f))
*n = *n*10 + (*f++ - '0');
}
else
*n = -1;
return t;
pushresult(0);
}
/*
** Read a variable. On error put nil on stack.
** LUA interface:
** variable = read ([format])
**
** O formato pode ter um dos seguintes especificadores:
**
** s ou S -> para string
** f ou F, g ou G, e ou E -> para reais
** i ou I -> para inteiros
**
** Estes especificadores podem vir seguidos de numero que representa
** o numero de campos a serem lidos.
*/
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)
{
int c;
while (isspace(c=fgetc(in)))
;
if (c == EOF)
{
lua_pushnil();
return;
}
if (c == '\"' || c == '\'')
{ /* string */
c = read_until_char(c);
if (c == EOF)
lua_pushnil();
else
lua_pushstring(luaI_addchar(0));
}
else
{
double d;
char dummy;
char *s;
luaI_addchar(c);
read_until_blank();
s = luaI_addchar(0);
if (sscanf(s, "%lf %c", &d, &dummy) == 1)
lua_pushnumber(d);
else
lua_pushstring(s);
}
}
#define NEED_OTHER (EOF-1) /* just some flag different from EOF */
static void io_read (void)
{
lua_Object o = lua_getparam (1);
luaI_addchar(0); /* initialize buffer */
if (o == LUA_NOOBJECT) /* free format */
read_free();
else /* formatted */
{
int m, dummy1, dummy2;
switch (getformat(lua_check_string(1, "read"), &dummy1, &m, &dummy2))
{
case 's':
{
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)");
}
}
}
/*
** Read characters until a given one. The delimiter is not read.
*/
static void io_readuntil (void)
{
int del, c;
lua_Object p = lua_getparam(1);
luaI_addchar(0); /* initialize buffer */
if (p == LUA_NOOBJECT || lua_isnil(p))
del = EOF;
else
del = *lua_check_string(1, "readuntil");
c = read_until_char(del);
if (c != EOF) ungetc(c,in);
lua_pushstring(luaI_addchar(0));
}
/*
** Write a variable. On error put 0 on stack, otherwise put 1.
** LUA interface:
** status = write (variable [,format])
**
** O formato pode ter um dos seguintes especificadores:
**
** s ou S -> para string
** f ou F, g ou G, e ou E -> para reais
** i ou I -> para inteiros
**
** Estes especificadores podem vir seguidos de:
**
** [?][m][.n]
**
** onde:
** ? -> indica justificacao
** < = esquerda
** | = centro
** > = direita (default)
** m -> numero maximo de campos (se exceder estoura)
** n -> indica precisao para
** reais -> numero de casas decimais
** inteiros -> numero minimo de digitos
** string -> nao se aplica
*/
static int write_fill (int n, int c)
{
while (n--)
if (fputc(c, out) == EOF)
return 0;
return 1;
}
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)
{
char *buff;
char *p = lua_opt_string(1, "[^\n]*{\n}", "read");
int inskip = 0; /* to control {skips} */
int c = NEED_OTHER;
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);
while (*p) {
if (*p == '{' || *p == '}') {
inskip = (*p == '{');
p++;
}
else {
char *ep = item_end(p); /* get what is next */
int m; /* match result */
if (c == NEED_OTHER) c = getc(lua_infile);
m = (c == EOF) ? 0 : singlematch((char)c, p);
if (m) {
if (!inskip) luaI_addchar(c);
c = NEED_OTHER;
}
switch (*ep) {
case '*': /* repetition */
if (!m) p = ep+1; /* else stay in (repeat) the same item */
break;
case '?': /* optional */
p = ep+1; /* continues reading the pattern */
break;
default:
if (m) p = ep; /* continues reading the pattern */
else
goto break_while; /* pattern fails */
}
}
} break_while:
if (c >= 0) /* not EOF nor NEED_OTHER? */
ungetc(c, lua_infile);
buff = luaI_addchar(0);
if (*buff != 0 || *p == 0) /* read something or did not fail? */
lua_pushstring(buff);
}
static void io_write (void)
{
int status = 0;
if (lua_getparam (2) == LUA_NOOBJECT) /* free format */
{
lua_Object o1 = lua_getparam(1);
int t = lua_type(o1);
if (t == LUA_T_NUMBER)
status = fprintf (out, "%g", lua_getnumber(o1)) >= 0;
else if (t == LUA_T_STRING)
status = fprintf (out, "%s", lua_getstring(o1)) >= 0;
}
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();
int arg = 1;
int status = 1;
char *s;
while ((s = lua_opt_string(arg++, NULL, "write")) != NULL)
status = status && (fputs(s, lua_outfile) != EOF);
pushresult(status);
}
/*
** Execute a executable program using "system".
** Return the result of execution.
*/
static void io_execute (void)
{
lua_pushnumber(system(lua_check_string(1, "execute")));
}
/*
** Remove a file. On error return nil.
*/
static void io_remove (void)
{
pushresult(remove(lua_check_string(1, "remove")) == 0);
}
static void io_rename (void)
{
char *f1 = lua_check_string(1, "rename");
char *f2 = lua_check_string(2, "rename");
pushresult(rename(f1, f2) == 0);
pushresult(rename(lua_check_string(1, "rename"),
lua_check_string(2, "rename")) == 0);
}
static void io_tmpname (void)
{
lua_pushstring(tmpnam(NULL));
}
static void io_errorno (void)
{
/* lua_pushstring(strerror(errno));*/
}
/*
** To get a environment variable
*/
static void io_getenv (void)
{
char *env = getenv(lua_check_string(1, "getenv"));
lua_pushstring(env); /* if NULL push nil */
lua_pushstring(getenv(lua_check_string(1, "getenv"))); /* if NULL push nil */
}
/*
** Return user formatted time stamp
*/
static void io_date (void)
{
time_t t;
struct tm *tm;
char *s;
char b[BUFSIZ];
if (lua_getparam(1) == LUA_NOOBJECT)
s = "%c";
else
s = lua_check_string(1, "date");
time(&t); tm = localtime(&t);
if (strftime(b,sizeof(b),s,tm))
lua_pushstring(b);
else
lua_error("invalid `date' format");
time_t t;
struct tm *tm;
char *s = lua_opt_string(1, "%c", "date");
char b[BUFSIZ];
time(&t); tm = localtime(&t);
if (strftime(b,sizeof(b),s,tm))
lua_pushstring(b);
else
lua_error("invalid `date' format");
}
/*
** To exit
*/
static void io_exit (void)
{
lua_Object o = lua_getparam(1);
if (lua_isstring(o))
fprintf(stderr, "%s\n", lua_getstring(o));
exit(1);
lua_Object o = lua_getparam(1);
exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
}
/*
** To debug a lua program. Start a dialog with the user, interpreting
lua commands until an 'cont'.
*/
static void io_debug (void)
{
while (1)
{
while (1) {
char buffer[250];
fprintf(stderr, "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
if (strcmp(buffer, "cont") == 0) return;
if (strcmp(buffer, "cont\n") == 0) return;
lua_dostring(buffer);
}
}
void lua_printstack (FILE *f)
static void lua_printstack (FILE *f)
{
int level = 0;
lua_Object func;
fprintf(f, "Active Stack:\n");
while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT)
{
while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
char *name;
int currentline;
fprintf(f, "\t");
switch (*lua_getobjname(func, &name))
{
switch (*lua_getobjname(func, &name)) {
case 'g':
fprintf(f, "function %s", name);
break;
case 'f':
fprintf(f, "`%s' fallback", name);
break;
default:
{
default: {
char *filename;
int linedefined;
lua_funcinfo(func, &filename, &linedefined);
@@ -591,34 +264,32 @@ void lua_printstack (FILE *f)
static void errorfb (void)
{
lua_Object o = lua_getparam(1);
char *s = lua_isstring(o) ? lua_getstring(o) : "(no messsage)";
char *s = lua_opt_string(1, "(no messsage)", NULL);
fprintf(stderr, "lua: %s\n", s);
lua_printstack(stderr);
}
/*
** Open io library
*/
static struct lua_reg iolib[] = {
{"readfrom", io_readfrom},
{"writeto", io_writeto},
{"appendto", io_appendto},
{"read", io_read},
{"write", io_write},
{"execute", io_execute},
{"remove", io_remove},
{"rename", io_rename},
{"tmpname", io_tmpname},
{"getenv", io_getenv},
{"date", io_date},
{"exit", io_exit},
{"debug", io_debug},
{"print_stack", errorfb}
};
void iolib_open (void)
{
lua_register ("readfrom", io_readfrom);
lua_register ("writeto", io_writeto);
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 ("rename", io_rename);
lua_register ("tmpname", io_tmpname);
lua_register ("ioerror", io_errorno);
lua_register ("getenv", io_getenv);
lua_register ("date", io_date);
lua_register ("exit", io_exit);
lua_register ("debug", io_debug);
lua_register ("print_stack", errorfb);
lua_setfallback("error", errorfb);
lua_infile=stdin; lua_outfile=stdout;
luaI_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
lua_setfallback("error", errorfb);
}

213
lex.c
View File

@@ -1,5 +1,5 @@
char *rcs_lex = "$Id: lex.c,v 2.31 1996/03/19 16:50:24 roberto Exp roberto $";
char *rcs_lex = "$Id: lex.c,v 2.38 1996/11/08 12:49:35 roberto Exp roberto $";
#include <ctype.h>
#include <string.h>
@@ -14,32 +14,31 @@ char *rcs_lex = "$Id: lex.c,v 2.31 1996/03/19 16:50:24 roberto Exp roberto $";
#define MINBUFF 260
#define next() { current = input(); }
#define save(x) { *yytextLast++ = (x); }
#define save_and_next() { save(current); next(); }
#define next() (current = input())
#define save(x) (yytext[tokensize++] = (x))
#define save_and_next() (save(current), next())
static int current;
static char *yytext = NULL;
static int textsize = 0;
static char *yytextLast;
static Input input;
static int current; /* look ahead character */
static Input input; /* input function */
void lua_setinput (Input fn)
{
current = ' ';
current = '\n';
lua_linenumber = 0;
input = fn;
if (yytext == NULL)
{
textsize = MINBUFF;
yytext = newvector(textsize, char);
}
}
char *lua_lasttext (void)
void luaI_syntaxerror (char *s)
{
*yytextLast = 0;
return yytext;
char msg[256];
char *token = luaI_buffer(1);
if (token[0] == 0)
token = "<eof>";
sprintf (msg,"%s;\n> last token read: \"%s\" at line %d in file %s",
s, token, lua_linenumber, lua_parsedfile);
lua_error (msg);
}
@@ -79,95 +78,97 @@ void luaI_addReserved (void)
}
}
static void growtext (void)
static int inclinenumber (int pragma_allowed)
{
int size = yytextLast - yytext;
textsize = growvector(&yytext, textsize, char, lexEM, MAX_WORD);
yytextLast = yytext + size;
++lua_linenumber;
if (pragma_allowed && current == '$') { /* is a pragma? */
char *buff = luaI_buffer(MINBUFF+1);
int i = 0;
next(); /* skip $ */
while (isalnum(current)) {
if (i >= MINBUFF) luaI_syntaxerror("pragma too long");
buff[i++] = current;
next();
}
buff[i] = 0;
if (strcmp(buff, "debug") == 0)
lua_debug = 1;
else if (strcmp(buff, "nodebug") == 0)
lua_debug = 0;
else luaI_syntaxerror("invalid pragma");
}
return lua_linenumber;
}
static int read_long_string (void)
static int read_long_string (char *yytext, int buffsize)
{
int cont = 0;
int spaceleft = textsize - (yytextLast - yytext);
int tokensize = 2; /* '[[' already stored */
while (1)
{
if (spaceleft <= 2) /* may read more than 1 char in one cicle */
{
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
if (buffsize-tokensize <= 2) /* may read more than 1 char in one cicle */
yytext = luaI_buffer(buffsize *= 2);
switch (current)
{
case EOF:
case 0:
save(0);
return WRONGTOKEN;
case '[':
save_and_next(); spaceleft--;
save_and_next();
if (current == '[')
{
cont++;
save_and_next(); spaceleft--;
save_and_next();
}
continue;
continue;
case ']':
save_and_next(); spaceleft--;
save_and_next();
if (current == ']')
{
if (cont == 0) return STRING;
if (cont == 0) goto endloop;
cont--;
save_and_next(); spaceleft--;
save_and_next();
}
continue;
continue;
case '\n':
lua_linenumber++; /* goes through */
save_and_next();
inclinenumber(0);
continue;
default:
save_and_next(); spaceleft--;
save_and_next();
}
}
} endloop:
save_and_next(); /* pass the second ']' */
yytext[tokensize-2] = 0; /* erases ']]' */
luaY_lval.vWord = luaI_findconstantbyname(yytext+2);
yytext[tokensize-2] = ']'; /* restores ']]' */
save(0);
return STRING;
}
int luaY_lex (void)
{
double a;
static int linelasttoken = 0;
double a;
int buffsize = MINBUFF;
char *yytext = luaI_buffer(buffsize);
yytext[1] = yytext[2] = yytext[3] = 0;
if (lua_debug)
luaI_codedebugline(linelasttoken);
linelasttoken = lua_linenumber;
while (1)
{
yytextLast = yytext;
int tokensize = 0;
switch (current)
{
case EOF:
case 0:
return 0;
case '\n': linelasttoken = ++lua_linenumber;
case ' ':
case '\r': /* CR: to avoid problems with DOS/Windows */
case '\t':
case '\n':
next();
linelasttoken = inclinenumber(1);
continue;
case '$':
next();
while (isalnum(current) || current == '_')
save_and_next();
*yytextLast = 0;
if (strcmp(yytext, "debug") == 0)
{
luaY_lval.vInt = 1;
return DEBUG;
}
else if (strcmp(yytext, "nodebug") == 0)
{
luaY_lval.vInt = 0;
return DEBUG;
}
return WRONGTOKEN;
case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */
next();
continue;
case '-':
save_and_next();
@@ -181,12 +182,7 @@ int luaY_lex (void)
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;
return read_long_string(yytext, buffsize);
}
case '=':
@@ -213,21 +209,16 @@ int luaY_lex (void)
case '\'':
{
int del = current;
int spaceleft = textsize - (yytextLast - yytext);
next(); /* skip the delimiter */
save_and_next();
while (current != del)
{
if (spaceleft <= 2) /* may read more than 1 char in one cicle */
{
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
spaceleft--;
if (buffsize-tokensize <= 2) /* may read more than 1 char in one cicle */
yytext = luaI_buffer(buffsize *= 2);
switch (current)
{
case EOF:
case 0:
case '\n':
save(0);
return WRONGTOKEN;
case '\\':
next(); /* do not save the '\' */
@@ -236,17 +227,19 @@ int luaY_lex (void)
case 'n': save('\n'); next(); break;
case 't': save('\t'); next(); break;
case 'r': save('\r'); next(); break;
case '\n': lua_linenumber++; /* goes through */
default : save(current); next(); break;
case '\n': save_and_next(); inclinenumber(0); break;
default : save_and_next(); break;
}
break;
default:
save_and_next();
}
}
next(); /* skip the delimiter */
*yytextLast = 0;
luaY_lval.vWord = luaI_findconstantbyname(yytext);
next(); /* skip delimiter */
save(0);
luaY_lval.vWord = luaI_findconstantbyname(yytext+1);
tokensize--;
save(del); save(0); /* restore delimiter */
return STRING;
}
@@ -266,7 +259,7 @@ int luaY_lex (void)
{
TaggedString *ts;
do { save_and_next(); } while (isalnum(current) || current == '_');
*yytextLast = 0;
save(0);
ts = lua_createstring(yytext);
if (ts->marked > 2)
return ts->marked; /* reserved word */
@@ -280,7 +273,12 @@ int luaY_lex (void)
if (current == '.')
{
save_and_next();
return CONC;
if (current == '.')
{
save_and_next();
return DOTS; /* ... */
}
else return CONC; /* .. */
}
else if (!isdigit(current)) return '.';
/* current is a digit: goes through to number */
@@ -290,12 +288,24 @@ int luaY_lex (void)
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
a=0.0;
do { a=10.0*a+(current-'0'); save_and_next(); } while (isdigit(current));
if (current == '.') save_and_next();
fraction:
do {
a=10.0*a+(current-'0');
save_and_next();
} while (isdigit(current));
if (current == '.') {
save_and_next();
if (current == '.')
luaI_syntaxerror(
"ambiguous syntax (decimal point x string concatenation)");
}
fraction:
{ double da=0.1;
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')
{
int e=0;
@@ -304,19 +314,23 @@ fraction:
save_and_next();
neg=(current=='-');
if (current == '+' || current == '-') save_and_next();
if (!isdigit(current)) return WRONGTOKEN;
do { e=10.0*e+(current-'0'); save_and_next(); } while (isdigit(current));
for (ea=neg?0.1:10.0; e>0; e>>=1)
if (!isdigit(current)) { save(0); return WRONGTOKEN; }
do {
e=10.0*e+(current-'0');
save_and_next();
} while (isdigit(current));
for (ea=neg?0.1:10.0; e>0; e>>=1)
{
if (e & 1) a*=ea;
ea*=ea;
}
}
luaY_lval.vFloat = a;
save(0);
return NUMBER;
}
default: /* also end of file */
default: /* also end of program (0) */
{
save_and_next();
return yytext[0];
@@ -324,3 +338,4 @@ fraction:
}
}
}

4
lex.h
View File

@@ -1,7 +1,7 @@
/*
** lex.h
** TecCGraf - PUC-Rio
** $Id: lex.h,v 1.1 1996/02/13 17:30:39 roberto Exp roberto $
** $Id: lex.h,v 1.2 1996/02/14 13:35:51 roberto Exp roberto $
*/
#ifndef lex_h
@@ -11,7 +11,7 @@
typedef int (*Input) (void);
void lua_setinput (Input fn);
char *lua_lasttext (void);
void luaI_syntaxerror (char *s);
int luaY_lex (void);
void luaI_addReserved (void);

105
lua.c
View File

@@ -3,7 +3,7 @@
** Linguagem para Usuarios de Aplicacao
*/
char *rcs_lua="$Id: lua.c,v 1.7 1995/10/31 17:05:35 roberto Exp roberto $";
char *rcs_lua="$Id: lua.c,v 1.13 1996/07/06 20:20:35 roberto Exp roberto $";
#include <stdio.h>
#include <string.h>
@@ -11,41 +11,23 @@ char *rcs_lua="$Id: lua.c,v 1.7 1995/10/31 17:05:35 roberto Exp roberto $";
#include "lua.h"
#include "lualib.h"
static int lua_argc;
static char **lua_argv;
/*
** although this function is POSIX, there is no standard header file that
** defines it
*/
int isatty (int fd);
/*
%F Allow Lua code to access argv strings.
%i Receive from Lua the argument number (starting with 1).
%o Return to Lua the argument, or nil if it does not exist.
*/
static void lua_getargv (void)
{
lua_Object lo = lua_getparam(1);
if (!lua_isnumber(lo))
lua_pushnil();
else
{
int n = (int)lua_getnumber(lo);
if (n < 1 || n > lua_argc) lua_pushnil();
else lua_pushstring(lua_argv[n]);
}
}
#ifdef _POSIX_SOURCE
#include <unistd.h>
#else
#define isatty(x) (x==0) /* assume stdin is a tty */
#endif
static void manual_input (void)
{
if (isatty(fileno(stdin)))
{
char buffer[250];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
lua_dostring(buffer);
if (isatty(0)) {
char buffer[250];
while (fgets(buffer, sizeof(buffer), stdin) != 0) {
lua_beginblock();
lua_dostring(buffer);
lua_endblock();
}
}
else
lua_dofile(NULL); /* executes stdin as a file */
@@ -54,39 +36,36 @@ static void manual_input (void)
int main (int argc, char *argv[])
{
int i;
int result = 0;
iolib_open ();
strlib_open ();
mathlib_open ();
lua_register("argv", lua_getargv);
if (argc < 2)
manual_input();
else
{
for (i=1; i<argc; i++)
if (strcmp(argv[i], "--") == 0)
{
lua_argc = argc-i-1;
lua_argv = argv+i;
break;
}
for (i=1; i<argc; i++)
{
if (strcmp(argv[i], "--") == 0)
break;
else if (strcmp(argv[i], "-") == 0)
int i;
int result = 0;
iolib_open ();
strlib_open ();
mathlib_open ();
if (argc < 2)
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
result = lua_dofile (argv[i]);
else for (i=1; i<argc; i++) {
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 if ((strcmp(argv[i], "-e") == 0 && i++) || strchr(argv[i], '=')) {
if (lua_dostring(argv[i]) != 0) {
fprintf(stderr, "lua: error running argument `%s'\n", argv[i]);
return 1;
}
}
else {
result = lua_dofile (argv[i]);
if (result) {
if (result == 2) {
fprintf(stderr, "lua: cannot execute file `%s' - ", argv[i]);
perror(NULL);
}
return 1;
}
}
}
}
return result;
return result;
}

23
lua.h
View File

@@ -2,15 +2,15 @@
** LUA - Linguagem para Usuarios de Aplicacao
** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio
** $Id: lua.h,v 3.24 1996/03/19 22:28:37 roberto Exp roberto $
** $Id: lua.h,v 3.31 1996/11/12 16:00:16 roberto Exp roberto $
*/
#ifndef lua_h
#define lua_h
#define LUA_VERSION "Lua 2.4 (beta)"
#define LUA_COPYRIGHT "Copyright (C) 1994, 1995 TeCGraf"
#define LUA_VERSION "Lua 2.5.1"
#define LUA_COPYRIGHT "Copyright (C) 1994-1996 TeCGraf"
#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
@@ -80,17 +80,18 @@ lua_Object lua_getsubscript (void);
int lua_type (lua_Object object);
int lua_lock (void);
lua_Object lua_getlocked (int ref);
void lua_pushlocked (int ref);
void lua_unlock (int ref);
int lua_ref (int lock);
lua_Object lua_getref (int ref);
void lua_pushref (int ref);
void lua_unref (int ref);
lua_Object lua_createtable (void);
/* 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))
@@ -99,6 +100,12 @@ lua_Object lua_createtable (void);
/* for compatibility with old versions. 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())

110
lua.stx
View File

@@ -1,9 +1,10 @@
%{
char *rcs_luastx = "$Id: lua.stx,v 3.35 1996/03/08 12:02:37 roberto Exp roberto $";
char *rcs_luastx = "$Id: lua.stx,v 3.40 1996/09/25 21:52:00 roberto Exp roberto $";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "luadebug.h"
#include "mem.h"
@@ -58,58 +59,48 @@ int lua_debug = 0;
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);
luaI_syntaxerror(s);
}
static void check_space (int i)
{
if (pc+i>maxcurr-1) /* 1 byte free to code HALT of main code */
maxcurr = growvector(&basepc, maxcurr, Byte, codeEM, MAX_INT);
}
static void code_byte (Byte c)
{
if (pc>maxcurr-2) /* 1 byte free to code HALT of main code */
maxcurr = growvector(&basepc, maxcurr, Byte, codeEM, MAX_INT);
check_space(1);
basepc[pc++] = c;
}
static void code_word (Word n)
{
CodeWord code;
code.w = n;
code_byte(code.m.c1);
code_byte(code.m.c2);
check_space(sizeof(Word));
memcpy(basepc+pc, &n, sizeof(Word));
pc += sizeof(Word);
}
static void code_float (float n)
static void code_float (real n)
{
CodeFloat code;
code.f = n;
code_byte(code.m.c1);
code_byte(code.m.c2);
code_byte(code.m.c3);
code_byte(code.m.c4);
check_space(sizeof(real));
memcpy(basepc+pc, &n, sizeof(real));
pc += sizeof(real);
}
static void code_code (TFunc *tf)
{
CodeCode code;
code.tf = tf;
code_byte(code.m.c1);
code_byte(code.m.c2);
code_byte(code.m.c3);
code_byte(code.m.c4);
check_space(sizeof(TFunc *));
memcpy(basepc+pc, &tf, sizeof(TFunc *));
pc += sizeof(TFunc *);
}
static void code_word_at (Byte *p, int n)
{
CodeWord code;
if ((Word)n != n)
yyerror("block too big");
code.w = (Word)n;
*p++ = code.m.c1;
*p++ = code.m.c2;
Word w = n;
if (w != n)
yyerror("block too big");
memcpy(p, &w, sizeof(Word));
}
static void push_field (Word name)
@@ -322,6 +313,19 @@ static void adjust_mult_assign (int vars, Long exps, int temps)
lua_codeadjust(temps);
}
static int close_parlist (int dots)
{
if (!dots)
lua_codeadjust(0);
else
{
code_byte(VARARGS);
code_byte(nlocalvar);
add_localvar(luaI_createfixedstring("arg"));
}
return lua_linenumber;
}
static void storesinglevar (Long v)
{
if (v > 0) /* global var */
@@ -418,7 +422,7 @@ void lua_parse (TFunc *tf)
TaggedString *pTStr;
}
%start functionlist
%start chunk
%token WRONGTOKEN
%token NIL
@@ -426,10 +430,10 @@ void lua_parse (TFunc *tf)
%token RETURN
%token LOCAL
%token FUNCTION
%token DOTS
%token <vFloat> NUMBER
%token <vWord> STRING
%token <pTStr> NAME
%token <vInt> DEBUG
%type <vLong> PrepJump
%type <vLong> exprlist, exprlist1 /* if > 0, points to function return
@@ -440,7 +444,7 @@ void lua_parse (TFunc *tf)
%type <vInt> fieldlist, localdeclist, decinit
%type <vInt> ffieldlist, ffieldlist1, semicolonpart
%type <vInt> lfieldlist, lfieldlist1
%type <vInt> parlist
%type <vInt> parlist, parlist1, par
%type <vLong> var, singlevar, funcname
%type <pFunc> body
@@ -455,15 +459,12 @@ void lua_parse (TFunc *tf)
%% /* beginning of rules section */
chunk : chunklist ret
functionlist : /* empty */
| functionlist globalstat
| functionlist function
;
globalstat : stat sc
| setdebug
;
chunklist : /* empty */
| chunklist stat sc
| chunklist function
;
function : FUNCTION funcname body
{
@@ -580,6 +581,7 @@ PrepJump : /* empty */
code_byte(0); /* open space */
code_word (0);
}
;
expr1 : expr { adjust_functioncall($1, 1); }
;
@@ -674,13 +676,22 @@ exprlist1 : expr { if ($1 != 0) $$ = $1; else $$ = -1; }
}
;
parlist : /* empty */ { lua_codeadjust(0); $$ = lua_linenumber; }
| parlist1 { lua_codeadjust(0); $$ = lua_linenumber; }
parlist : /* empty */ { $$ = close_parlist(0); }
| parlist1 { $$ = close_parlist($1); }
;
parlist1 : NAME { add_localvar($1); }
| parlist1 ',' NAME { add_localvar($3); }
parlist1 : par { $$ = $1; }
| parlist1 ',' par
{
if ($1)
lua_error("invalid parameter list");
$$ = $3;
}
;
par : NAME { add_localvar($1); $$ = 0; }
| DOTS { $$ = 1; }
;
fieldlist : lfieldlist
{ flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); }
@@ -782,7 +793,4 @@ decinit : /* empty */ { $$ = 0; }
| '=' exprlist1 { $$ = $2; }
;
setdebug : DEBUG { lua_debug = $1; }
;
%%

View File

@@ -2,23 +2,37 @@
** Libraries to be used in LUA programs
** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio
** $Id: lualib.h,v 1.6 1996/02/09 19:00:23 roberto Exp roberto $
** $Id: lualib.h,v 1.9 1996/08/01 14:55:33 roberto Exp roberto $
*/
#ifndef lualib_h
#define lualib_h
#include "lua.h"
void iolib_open (void);
void strlib_open (void);
void mathlib_open (void);
/* auxiliar functions (private) */
void lua_arg_error(char *funcname);
struct lua_reg {
char *name;
lua_CFunction func;
};
void luaI_openlib (struct lua_reg *l, int n);
void lua_arg_check(int cond, char *funcname);
char *lua_check_string (int numArg, char *funcname);
char *lua_opt_string (int numArg, char *def, char *funcname);
double lua_check_number (int numArg, char *funcname);
long lua_opt_number (int numArg, long def, char *funcname);
char *luaI_addchar (int c);
void luaI_addquoted (char *s);
char *item_end (char *p);
int singlematch (int c, char *p);
#endif

View File

@@ -3,20 +3,14 @@
** TecCGraf - PUC-Rio
*/
char *rcs_mem = "$Id: mem.c,v 1.10 1996/03/21 16:31:32 roberto Exp roberto $";
char *rcs_mem = "$Id: mem.c,v 1.12 1996/05/06 16:59:00 roberto Exp roberto $";
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "mem.h"
#include "lua.h"
#include "table.h"
#define mem_error() lua_error(memEM)
void luaI_free (void *block)
{
if (block)
@@ -27,21 +21,15 @@ void luaI_free (void *block)
}
void *luaI_malloc (unsigned long size)
{
void *block = malloc((size_t)size);
if (block == NULL)
mem_error();
return block;
}
void *luaI_realloc (void *oldblock, unsigned long size)
{
void *block = oldblock ? realloc(oldblock, (size_t)size) :
malloc((size_t)size);
void *block;
size_t s = (size_t)size;
if (s != size)
lua_error("Allocation Error: Block too big");
block = oldblock ? realloc(oldblock, s) : malloc(s);
if (block == NULL)
mem_error();
lua_error(memEM);
return block;
}
@@ -55,7 +43,7 @@ int luaI_growvector (void **block, unsigned long nelems, int size,
if (nelems > limit)
nelems = limit;
*block = luaI_realloc(*block, nelems*size);
return (int) nelems;
return (int)nelems;
}

View File

@@ -1,7 +1,7 @@
/*
** mem.c
** memory manager for lua
** $Id: mem.h,v 1.5 1996/03/21 16:31:32 roberto Exp roberto $
** $Id: mem.h,v 1.7 1996/04/22 18:00:37 roberto Exp roberto $
*/
#ifndef mem_h
@@ -18,18 +18,18 @@
#define constantEM "constant table overflow"
#define stackEM "stack size overflow"
#define lexEM "lex buffer overflow"
#define lockEM "lock table overflow"
#define refEM "reference table overflow"
#define tableEM "table overflow"
#define memEM "not enough memory"
void luaI_free (void *block);
void *luaI_malloc (unsigned long size);
void *luaI_realloc (void *oldblock, unsigned long size);
void *luaI_buffer (unsigned long size);
int luaI_growvector (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit);
#define luaI_malloc(s) luaI_realloc(NULL, (s))
#define new(s) ((s *)luaI_malloc(sizeof(s)))
#define newvector(n,s) ((s *)luaI_malloc((n)*sizeof(s)))
#define growvector(old,n,s,e,l) \

View File

@@ -1,12 +1,15 @@
# $Id: makefile,v 1.21 1996/03/05 15:57:53 roberto Exp roberto $
# $Id: makefile,v 1.27 1996/08/28 20:45:48 roberto Exp roberto $
#configuration
# define (undefine) POPEN if your system (does not) support piped I/O
CONFIG = -DPOPEN
# define (undefine) _POSIX_SOURCE if your system is (not) POSIX compliant
#define (undefine) NOSTRERROR if your system does NOT have function "strerror"
# (although this is ANSI, SunOS does not comply; so, add "-DNOSTRERROR" on SunOS)
CONFIG = -DPOPEN -D_POSIX_SOURCE
# Compilation parameters
CC = gcc
CFLAGS = $(CONFIG) -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2
CFLAGS = $(CONFIG) -Wall -Wmissing-prototypes -Wshadow -ansi -O2 -pedantic
#CC = acc
#CFLAGS = -fast -I/usr/5include
@@ -14,6 +17,7 @@ CFLAGS = $(CONFIG) -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2
AR = ar
ARFLAGS = rvl
# Aplication modules
LUAOBJS = \
parser.o \
@@ -34,14 +38,14 @@ LIBOBJS = \
strlib.o
lua : lua.o lua.a lualib.a
$(CC) $(CFLAGS) -o $@ lua.o lua.a lualib.a -lm
lua : lua.o liblua.a liblualib.a
$(CC) $(CFLAGS) -o $@ lua.o -L. -llua -llualib -lm
lua.a : $(LUAOBJS)
liblua.a : $(LUAOBJS)
$(AR) $(ARFLAGS) $@ $?
ranlib lua.a
ranlib $@
lualib.a : $(LIBOBJS)
liblualib.a : $(LIBOBJS)
$(AR) $(ARFLAGS) $@ $?
ranlib $@
@@ -49,10 +53,10 @@ liblua.so.1.0 : lua.o
ld -o liblua.so.1.0 $(LUAOBJS)
y.tab.c y.tab.h : lua.stx
yacc++ -d lua.stx
yacc -d lua.stx
parser.c : y.tab.c
sed -e 's/yy/luaY_/g' y.tab.c > parser.c
sed -e 's/yy/luaY_/g' -e 's/malloc\.h/stdlib\.h/g' y.tab.c > parser.c
parser.h : y.tab.h
sed -e 's/yy/luaY_/g' y.tab.h > parser.h
@@ -64,12 +68,15 @@ clear :
co lua.h lualib.h luadebug.h
% : RCS/%,v
%.h : RCS/%.h,v
co $@
%.c : RCS/%.c,v
co $@
fallback.o : fallback.c mem.h fallback.h opcode.h lua.h types.h tree.h func.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 \
@@ -79,7 +86,7 @@ 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
mathlib.o : mathlib.c lualib.h lua.h
mem.o : mem.c mem.h lua.h table.h tree.h types.h opcode.h func.h
mem.o : mem.c mem.h lua.h
opcode.o : opcode.c luadebug.h lua.h mem.h opcode.h types.h tree.h func.h hash.h \
inout.h table.h fallback.h undump.h
parser.o : parser.c luadebug.h lua.h mem.h lex.h opcode.h types.h tree.h func.h \

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
** Mathematics library to LUA
*/
char *rcs_mathlib="$Id: mathlib.c,v 1.13 1995/11/10 17:54:31 roberto Exp roberto $";
char *rcs_mathlib="$Id: mathlib.c,v 1.17 1996/04/30 21:13:55 roberto Exp roberto $";
#include <stdlib.h>
#include <math.h>
@@ -92,9 +92,9 @@ static void math_floor (void)
static void math_mod (void)
{
int d1 = (int)lua_check_number(1, "mod");
int d2 = (int)lua_check_number(2, "mod");
lua_pushnumber (d1%d2);
float x = lua_check_number(1, "mod");
float y = lua_check_number(2, "mod");
lua_pushnumber(fmod(x, y));
}
@@ -113,7 +113,7 @@ static void math_pow (void)
lua_Object op = lua_getparam(3);
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(o2);
lua_pushobject(op);
@@ -195,33 +195,36 @@ static void math_randomseed (void)
}
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
*/
void mathlib_open (void)
{
lua_register ("abs", math_abs);
lua_register ("sin", math_sin);
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 ("atan2", math_atan2);
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);
lua_register ("random", math_random);
lua_register ("randomseed", math_randomseed);
old_pow = lua_lockobject(lua_setfallback("arith", math_pow));
luaI_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));
old_pow = lua_refobject(lua_setfallback("arith", math_pow), 1);
}

321
opcode.c
View File

@@ -3,11 +3,12 @@
** TecCGraf - PUC-Rio
*/
char *rcs_opcode="$Id: opcode.c,v 3.65 1996/03/21 18:55:02 roberto Exp roberto $";
char *rcs_opcode="$Id: opcode.c,v 3.76 1996/09/24 21:46:44 roberto Exp roberto $";
#include <setjmp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "luadebug.h"
#include "mem.h"
@@ -49,10 +50,14 @@ static Object *top = &initial_stack;
*/
#define incr_top if (++top >= stackLimit) growstack()
static StkId CBase = 0; /* when Lua calls C or C calls Lua, points to */
/* the first slot after the last parameter. */
static int CnResults = 0; /* when Lua calls C, has the number of parameters; */
/* when C calls Lua, has the number of results. */
struct C_Lua_Stack {
StkId base; /* when Lua calls C or C calls Lua, points to */
/* the first slot after the last parameter. */
int num; /* when Lua calls C, has the number of parameters; */
/* when C calls Lua, has the number of results. */
};
static struct C_Lua_Stack CLS_current = {0, 0};
static jmp_buf *errorJmp = NULL; /* current error recover point */
@@ -117,7 +122,7 @@ static void growstack (void)
*/
static char *lua_strconc (char *l, char *r)
{
int nl = strlen(l);
size_t nl = strlen(l);
char *buffer = luaI_buffer(nl+strlen(r)+1);
strcpy(buffer, l);
strcpy(buffer+nl, r);
@@ -177,7 +182,7 @@ static void adjust_top (StkId newtop)
top = nt; /* top could be bigger than newtop */
}
#define adjustC(nParams) adjust_top(CBase+nParams)
#define adjustC(nParams) adjust_top(CLS_current.base+nParams)
/*
@@ -197,14 +202,12 @@ static void open_stack (int nelems)
*/
static void lineHook (int line)
{
StkId oldBase = CBase;
int oldCnResults = CnResults;
StkId old_top = CBase = top-stack;
CnResults = 0;
struct C_Lua_Stack oldCLS = CLS_current;
StkId old_top = CLS_current.base = top-stack;
CLS_current.num = 0;
(*lua_linehook)(line);
top = stack+old_top;
CnResults = oldCnResults;
CBase = oldBase;
CLS_current = oldCLS;
}
@@ -214,10 +217,9 @@ static void lineHook (int line)
*/
static void callHook (StkId base, lua_Type type, int isreturn)
{
StkId oldBase = CBase;
int oldCnResults = CnResults;
StkId old_top = CBase = top-stack;
CnResults = 0;
struct C_Lua_Stack oldCLS = CLS_current;
StkId old_top = CLS_current.base = top-stack;
CLS_current.num = 0;
if (isreturn)
(*lua_callhook)(LUA_NOOBJECT, "(return)", 0);
else
@@ -229,32 +231,29 @@ static void callHook (StkId base, lua_Type type, int isreturn)
(*lua_callhook)(Ref(f), "(C)", -1);
}
top = stack+old_top;
CnResults = oldCnResults;
CBase = oldBase;
CLS_current = oldCLS;
}
/*
** Call a C function. CBase will point to the top of the stack,
** and CnResults is the number of parameters. Returns an index
** Call a C function. CLS_current.base will point to the top of the stack,
** and CLS_current.num is the number of parameters. Returns an index
** to the first result from C.
*/
static StkId callC (lua_CFunction func, StkId base)
{
StkId oldBase = CBase;
int oldCnResults = CnResults;
struct C_Lua_Stack oldCLS = CLS_current;
StkId firstResult;
CnResults = (top-stack) - base;
CLS_current.num = (top-stack) - base;
/* incorporate parameters on the stack */
CBase = base+CnResults; /* == top-stack */
CLS_current.base = base+CLS_current.num; /* == top-stack */
if (lua_callhook)
callHook(base, LUA_T_CMARK, 0);
(*func)();
if (lua_callhook) /* func may have changed lua_callhook */
callHook(base, LUA_T_CMARK, 1);
firstResult = CBase;
CBase = oldBase;
CnResults = oldCnResults;
firstResult = CLS_current.base;
CLS_current = oldCLS;
return firstResult;
}
@@ -449,27 +448,27 @@ int lua_setlocal (lua_Function func, int local_number)
/*
** Execute a protected call. Assumes that function is at CBase and
** parameters are on top of it. Leave nResults on the stack.
** Execute a protected call. Assumes that function is at CLS_current.base and
** parameters are on top of it. Leave nResults on the stack.
*/
static int do_protectedrun (int nResults)
{
jmp_buf myErrorJmp;
int status;
StkId oldCBase = CBase;
struct C_Lua_Stack oldCLS = CLS_current;
jmp_buf *oldErr = errorJmp;
errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0)
{
do_call(CBase+1, nResults);
CnResults = (top-stack) - CBase; /* number of results */
CBase += CnResults; /* incorporate results on the stack */
do_call(CLS_current.base+1, nResults);
CLS_current.num = (top-stack) - CLS_current.base; /* number of results */
CLS_current.base += CLS_current.num; /* incorporate results on the stack */
status = 0;
}
else
{ /* an error occurred: restore CBase and top */
CBase = oldCBase;
top = stack+CBase;
{ /* an error occurred: restore CLS_current and top */
CLS_current = oldCLS;
top = stack+CLS_current.base;
status = 1;
}
errorJmp = oldErr;
@@ -480,10 +479,9 @@ int luaI_dorun (TFunc *tf)
{
int status;
adjustC(1); /* one slot for the pseudo-function */
stack[CBase].tag = LUA_T_FUNCTION;
stack[CBase].value.tf = tf;
status = do_protectedrun(0);
adjustC(0);
stack[CLS_current.base].tag = LUA_T_FUNCTION;
stack[CLS_current.base].value.tf = tf;
status = do_protectedrun(MULT_RET);
return status;
}
@@ -521,8 +519,8 @@ int lua_callfunction (lua_Object function)
return 1;
else
{
open_stack((top-stack)-CBase);
stack[CBase] = *Address(function);
open_stack((top-stack)-CLS_current.base);
stack[CLS_current.base] = *Address(function);
return do_protectedrun (MULT_RET);
}
}
@@ -531,15 +529,15 @@ int lua_callfunction (lua_Object function)
int lua_call (char *funcname)
{
Word n = luaI_findsymbolbyname(funcname);
open_stack((top-stack)-CBase);
stack[CBase] = s_object(n);
open_stack((top-stack)-CLS_current.base);
stack[CLS_current.base] = s_object(n);
return do_protectedrun(MULT_RET);
}
/*
** Open file, generate opcode and execute global statement. Return 0 on
** success or 1 on error.
** success or non 0 on error.
*/
int lua_dofile (char *filename)
{
@@ -547,22 +545,32 @@ int lua_dofile (char *filename)
int c;
FILE *f = lua_openfile(filename);
if (f == NULL)
return 1;
return 2;
c = fgetc(f);
ungetc(c, f);
status = (c == ID_CHUNK) ? luaI_undump(f) : do_protectedmain();
if (c == ID_CHUNK) {
f = freopen(filename, "rb", f); /* set binary mode */
status = luaI_undump(f);
}
else {
if (c == '#')
while ((c=fgetc(f)) != '\n') /* skip first line */;
status = do_protectedmain();
}
lua_closefile();
return status;
}
/*
** Generate opcode stored on string and execute global statement. Return 0 on
** success or 1 on error.
** success or non 0 on error.
*/
int lua_dostring (char *string)
int lua_dostring (char *str)
{
int status;
lua_openstring(string);
if (str == NULL)
return 1;
lua_openstring(str);
status = do_protectedmain();
lua_closestring();
return status;
@@ -575,8 +583,8 @@ int lua_dostring (char *string)
lua_Object lua_setfallback (char *name, lua_CFunction fallback)
{
adjustC(1); /* one slot for the pseudo-function */
stack[CBase].tag = LUA_T_CFUNCTION;
stack[CBase].value.f = luaI_setfallback;
stack[CLS_current.base].tag = LUA_T_CFUNCTION;
stack[CLS_current.base].value.f = luaI_setfallback;
lua_pushstring(name);
lua_pushcfunction(fallback);
if (do_protectedrun(1) == 0)
@@ -594,7 +602,7 @@ lua_Object lua_getsubscript (void)
{
adjustC(2);
pushsubscript();
CBase++; /* incorporate object in the stack */
CLS_current.base++; /* incorporate object in the stack */
return (Ref(top-1));
}
@@ -602,7 +610,7 @@ lua_Object lua_getsubscript (void)
#define MAX_C_BLOCKS 10
static int numCblocks = 0;
static StkId Cblocks[MAX_C_BLOCKS];
static struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];
/*
** API: starts a new block
@@ -611,7 +619,7 @@ void lua_beginblock (void)
{
if (numCblocks >= MAX_C_BLOCKS)
lua_error("`lua_beginblock': too many nested blocks");
Cblocks[numCblocks] = CBase;
Cblocks[numCblocks] = CLS_current;
numCblocks++;
}
@@ -621,7 +629,7 @@ void lua_beginblock (void)
void lua_endblock (void)
{
--numCblocks;
CBase = Cblocks[numCblocks];
CLS_current = Cblocks[numCblocks];
adjustC(0);
}
@@ -643,7 +651,7 @@ lua_Object lua_createtable (void)
avalue(top) = lua_createarray(0);
tag(top) = LUA_T_ARRAY;
incr_top;
CBase++; /* incorporate object in the stack */
CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1);
}
@@ -653,10 +661,10 @@ lua_Object lua_createtable (void)
*/
lua_Object lua_getparam (int number)
{
if (number <= 0 || number > CnResults) return LUA_NOOBJECT;
/* Ref(stack+(CBase-CnResults+number-1)) ==
stack+(CBase-CnResults+number-1)-stack+1 == */
return CBase-CnResults+number;
if (number <= 0 || number > CLS_current.num) return LUA_NOOBJECT;
/* Ref(stack+(CLS_current.base-CLS_current.num+number-1)) ==
stack+(CLS_current.base-CLS_current.num+number-1)-stack+1 == */
return CLS_current.base-CLS_current.num+number;
}
int lua_isnumber (lua_Object object)
@@ -673,7 +681,8 @@ int lua_isstring (lua_Object object)
int lua_isfunction (lua_Object object)
{
int t = lua_type(object);
return (t == LUA_T_FUNCTION) || (t == LUA_T_CFUNCTION);
return (t == LUA_T_FUNCTION) || (t == LUA_T_CFUNCTION) ||
(t == LUA_T_MARK) || (t == LUA_T_CMARK);
}
/*
@@ -701,7 +710,8 @@ char *lua_getstring (lua_Object object)
*/
lua_CFunction lua_getcfunction (lua_Object object)
{
if (object == LUA_NOOBJECT || tag(Address(object)) != LUA_T_CFUNCTION)
if (object == LUA_NOOBJECT || ((tag(Address(object)) != LUA_T_CFUNCTION) &&
(tag(Address(object)) != LUA_T_CMARK)))
return NULL;
else return (fvalue(Address(object)));
}
@@ -717,27 +727,31 @@ void *lua_getuserdata (lua_Object object)
}
lua_Object lua_getlocked (int ref)
lua_Object lua_getref (int ref)
{
adjustC(0);
*top = *luaI_getlocked(ref);
incr_top;
CBase++; /* incorporate object in the stack */
return Ref(top-1);
Object *o = luaI_getref(ref);
if (o == NULL)
return LUA_NOOBJECT;
adjustC(0);
luaI_pushobject(o);
CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1);
}
void lua_pushlocked (int ref)
void lua_pushref (int ref)
{
*top = *luaI_getlocked(ref);
incr_top;
Object *o = luaI_getref(ref);
if (o == NULL)
lua_error("access to invalid (possibly garbage collected) reference");
luaI_pushobject(o);
}
int lua_lock (void)
int lua_ref (int lock)
{
adjustC(1);
return luaI_lock(--top);
return luaI_ref(--top, lock);
}
@@ -749,7 +763,7 @@ lua_Object lua_getglobal (char *name)
{
adjustC(0);
getglobal(luaI_findsymbolbyname(name));
CBase++; /* incorporate object in the stack */
CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1);
}
@@ -812,20 +826,12 @@ void lua_pushcfunction (lua_CFunction fn)
*/
void lua_pushusertag (void *u, int tag)
{
if (tag < LUA_T_USERDATA) return;
if (tag < LUA_T_USERDATA)
lua_error("invalid tag in `lua_pushusertag'");
tag(top) = tag; uvalue(top) = u;
incr_top;
}
/*
** Push a lua_Object to stack.
*/
void lua_pushobject (lua_Object o)
{
*top = *Address(o);
incr_top;
}
/*
** Push an object on the stack.
*/
@@ -835,6 +841,19 @@ void luaI_pushobject (Object *o)
incr_top;
}
/*
** Push a lua_Object on stack.
*/
void lua_pushobject (lua_Object o)
{
if (o == LUA_NOOBJECT)
lua_error("attempt to push a NOOBJECT");
*top = *Address(o);
if (tag(top) == LUA_T_MARK) tag(top) = LUA_T_FUNCTION;
else if (tag(top) == LUA_T_CMARK) tag(top) = LUA_T_CFUNCTION;
incr_top;
}
int lua_type (lua_Object o)
{
if (o == LUA_NOOBJECT)
@@ -880,6 +899,34 @@ static void comparison (lua_Type tag_less, lua_Type tag_equal,
}
static void adjust_varargs (StkId first_extra_arg)
{
Object arg;
Object *firstelem = stack+first_extra_arg;
int nvararg = top-firstelem;
int i;
if (nvararg < 0) nvararg = 0;
avalue(&arg) = lua_createarray(nvararg+1); /* +1 for field 'n' */
tag(&arg) = LUA_T_ARRAY;
for (i=0; i<nvararg; i++) {
Object index;
tag(&index) = LUA_T_NUMBER;
nvalue(&index) = i+1;
*(lua_hashdefine(avalue(&arg), &index)) = *(firstelem+i);
}
/* store counter in field "n" */ {
Object index, extra;
tag(&index) = LUA_T_STRING;
tsvalue(&index) = lua_createstring("n");
tag(&extra) = LUA_T_NUMBER;
nvalue(&extra) = nvararg;
*(lua_hashdefine(avalue(&arg), &index)) = extra;
}
adjust_top(first_extra_arg);
*top = arg; incr_top;
}
/*
** Execute the given opcode, until a RET. Parameters are between
@@ -908,38 +955,38 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHWORD:
{
CodeWord code;
get_word(code,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = code.w;
Word w;
get_word(w,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = w;
incr_top;
}
break;
case PUSHFLOAT:
{
CodeFloat code;
get_float(code,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = code.f;
real num;
get_float(num,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = num;
incr_top;
}
break;
case PUSHSTRING:
{
CodeWord code;
get_word(code,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w];
Word w;
get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
incr_top;
}
break;
case PUSHFUNCTION:
{
CodeCode code;
get_code(code,pc);
luaI_insertfunction(code.tf); /* may take part in GC */
TFunc *f;
get_code(f,pc);
luaI_insertfunction(f); /* may take part in GC */
top->tag = LUA_T_FUNCTION;
top->value.tf = code.tf;
top->value.tf = f;
incr_top;
}
break;
@@ -954,9 +1001,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHGLOBAL:
{
CodeWord code;
get_word(code,pc);
getglobal(code.w);
Word w;
get_word(w,pc);
getglobal(w);
}
break;
@@ -967,9 +1014,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHSELF:
{
Object receiver = *(top-1);
CodeWord code;
get_word(code,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w];
Word w;
get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
incr_top;
pushsubscript();
*top = receiver;
@@ -988,9 +1035,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case STOREGLOBAL:
{
CodeWord code;
get_word(code,pc);
s_object(code.w) = *(--top);
Word w;
get_word(w,pc);
s_object(w) = *(--top);
}
break;
@@ -1044,9 +1091,9 @@ static StkId lua_execute (Byte *pc, StkId base)
Object *arr = top-n-1;
while (n)
{
CodeWord code;
get_word(code,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w];
Word w;
get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
*(lua_hashdefine (avalue(arr), top)) = *(top-1);
top--;
n--;
@@ -1062,11 +1109,15 @@ static StkId lua_execute (Byte *pc, StkId base)
adjust_top(base + *(pc++));
break;
case VARARGS:
adjust_varargs(base + *(pc++));
break;
case CREATEARRAY:
{
CodeWord size;
Word size;
get_word(size,pc);
avalue(top) = lua_createarray(size.w);
avalue(top) = lua_createarray(size);
tag(top) = LUA_T_ARRAY;
incr_top;
}
@@ -1189,51 +1240,51 @@ static StkId lua_execute (Byte *pc, StkId base)
case ONTJMP:
{
CodeWord code;
get_word(code,pc);
if (tag(top-1) != LUA_T_NIL) pc += code.w;
Word w;
get_word(w,pc);
if (tag(top-1) != LUA_T_NIL) pc += w;
}
break;
case ONFJMP:
{
CodeWord code;
get_word(code,pc);
if (tag(top-1) == LUA_T_NIL) pc += code.w;
Word w;
get_word(w,pc);
if (tag(top-1) == LUA_T_NIL) pc += w;
}
break;
case JMP:
{
CodeWord code;
get_word(code,pc);
pc += code.w;
Word w;
get_word(w,pc);
pc += w;
}
break;
case UPJMP:
{
CodeWord code;
get_word(code,pc);
pc -= code.w;
Word w;
get_word(w,pc);
pc -= w;
}
break;
case IFFJMP:
{
CodeWord code;
get_word(code,pc);
Word w;
get_word(w,pc);
top--;
if (tag(top) == LUA_T_NIL) pc += code.w;
if (tag(top) == LUA_T_NIL) pc += w;
}
break;
case IFFUPJMP:
{
CodeWord code;
get_word(code,pc);
Word w;
get_word(w,pc);
top--;
if (tag(top) == LUA_T_NIL) pc -= code.w;
if (tag(top) == LUA_T_NIL) pc -= w;
}
break;
@@ -1256,8 +1307,8 @@ static StkId lua_execute (Byte *pc, StkId base)
case SETLINE:
{
CodeWord code;
get_word(code,pc);
Word line;
get_word(line,pc);
if ((stack+base-1)->tag != LUA_T_LINE)
{
/* open space for LINE value */
@@ -1265,9 +1316,9 @@ static StkId lua_execute (Byte *pc, StkId base)
base++;
(stack+base-1)->tag = LUA_T_LINE;
}
(stack+base-1)->value.i = code.w;
(stack+base-1)->value.i = line;
if (lua_linehook)
lineHook (code.w);
lineHook (line);
break;
}

155
opcode.h
View File

@@ -1,6 +1,6 @@
/*
** TeCGraf - PUC-Rio
** $Id: opcode.h,v 3.19 1996/03/06 13:11:23 roberto Exp $
** $Id: opcode.h,v 3.23 1996/09/26 21:08:41 roberto Exp roberto $
*/
#ifndef opcode_h
@@ -15,59 +15,83 @@
#define FIELDS_PER_FLUSH 40
typedef enum
{
PUSHNIL,
PUSH0, PUSH1, PUSH2,
PUSHBYTE,
PUSHWORD,
PUSHFLOAT,
PUSHSTRING,
PUSHFUNCTION,
PUSHLOCAL0, PUSHLOCAL1, PUSHLOCAL2, PUSHLOCAL3, PUSHLOCAL4,
PUSHLOCAL5, PUSHLOCAL6, PUSHLOCAL7, PUSHLOCAL8, PUSHLOCAL9,
PUSHLOCAL,
PUSHGLOBAL,
PUSHINDEXED,
PUSHSELF,
STORELOCAL0, STORELOCAL1, STORELOCAL2, STORELOCAL3, STORELOCAL4,
STORELOCAL5, STORELOCAL6, STORELOCAL7, STORELOCAL8, STORELOCAL9,
STORELOCAL,
STOREGLOBAL,
STOREINDEXED0,
STOREINDEXED,
STORELIST0,
STORELIST,
STORERECORD,
ADJUST0,
ADJUST,
CREATEARRAY,
EQOP,
LTOP,
LEOP,
GTOP,
GEOP,
ADDOP,
SUBOP,
MULTOP,
DIVOP,
POWOP,
CONCOP,
MINUSOP,
NOTOP,
ONTJMP,
ONFJMP,
JMP,
UPJMP,
IFFJMP,
IFFUPJMP,
POP,
CALLFUNC,
RETCODE0,
RETCODE,
SETLINE
typedef enum {
/* name parm before after side effect
-----------------------------------------------------------------------------*/
PUSHNIL,/* - nil */
PUSH0,/* - 0.0 */
PUSH1,/* - 1.0 */
PUSH2,/* - 2.0 */
PUSHBYTE,/* b - (float)b */
PUSHWORD,/* w - (float)w */
PUSHFLOAT,/* f - f */
PUSHSTRING,/* w - STR[w] */
PUSHFUNCTION,/* p - FUN(p) */
PUSHLOCAL0,/* - LOC[0] */
PUSHLOCAL1,/* - LOC[1] */
PUSHLOCAL2,/* - LOC[2] */
PUSHLOCAL3,/* - LOC[3] */
PUSHLOCAL4,/* - LOC[4] */
PUSHLOCAL5,/* - LOC[5] */
PUSHLOCAL6,/* - LOC[6] */
PUSHLOCAL7,/* - LOC[7] */
PUSHLOCAL8,/* - LOC[8] */
PUSHLOCAL9,/* - LOC[9] */
PUSHLOCAL,/* w - LOC[w] */
PUSHGLOBAL,/* w - VAR[w] */
PUSHINDEXED,/* i t t[i] */
PUSHSELF,/* w t t t[STR[w]] */
STORELOCAL0,/* x - LOC[0]=x */
STORELOCAL1,/* x - LOC[1]=x */
STORELOCAL2,/* x - LOC[2]=x */
STORELOCAL3,/* x - LOC[3]=x */
STORELOCAL4,/* x - LOC[4]=x */
STORELOCAL5,/* x - LOC[5]=x */
STORELOCAL6,/* x - LOC[6]=x */
STORELOCAL7,/* x - LOC[7]=x */
STORELOCAL8,/* x - LOC[8]=x */
STORELOCAL9,/* x - LOC[9]=x */
STORELOCAL,/* w x - LOC[w]=x */
STOREGLOBAL,/* w x - VAR[w]=x */
STOREINDEXED0,/* v i t - t[i]=v */
STOREINDEXED,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
STORELIST0,/* w v_w...v_1 t - t[i]=v_i */
STORELIST,/* w n v_w...v_1 t - t[i+n*FPF]=v_i */
STORERECORD,/* n
w_n...w_1 v_n...v_1 t - t[STR[w_i]]=v_i */
ADJUST0,/* - - TOP=BASE */
ADJUST,/* b - - TOP=BASE+b */
CREATEARRAY,/* w - newarray(size = w) */
EQOP,/* y x (x==y)? 1 : nil */
LTOP,/* y x (x<y)? 1 : nil */
LEOP,/* y x (x<y)? 1 : nil */
GTOP,/* y x (x>y)? 1 : nil */
GEOP,/* y x (x>=y)? 1 : nil */
ADDOP,/* y x x+y */
SUBOP,/* y x x-y */
MULTOP,/* y x x*y */
DIVOP,/* y x x/y */
POWOP,/* y x x^y */
CONCOP,/* y x x..y */
MINUSOP,/* x -x */
NOTOP,/* x (x==nil)? 1 : nil */
ONTJMP,/* w x - (x!=nil)? PC+=w */
ONFJMP,/* w x - (x==nil)? PC+=w */
JMP,/* w - - PC+=w */
UPJMP,/* w - - PC-=w */
IFFJMP,/* w x - (x==nil)? PC+=w */
IFFUPJMP,/* w x - (x==nil)? PC-=w */
POP,/* x - */
CALLFUNC,/* n m v_n...v_1 f r_m...r_1 f(v1,...,v_n) */
RETCODE0,
RETCODE,/* b - - */
SETLINE,/* w - - LINE=w */
VARARGS/* b v_n...v_1 {v_1...v_n;n=n} */
} OpCode;
#define MULT_RET 255
@@ -103,32 +127,15 @@ typedef struct Object
#define s_tag(i) (tag(&s_object(i)))
#define s_nvalue(i) (nvalue(&s_object(i)))
#define s_svalue(i) (svalue(&s_object(i)))
#define s_tsvalue(i) (tsvalue(&s_object(i)))
#define s_avalue(i) (avalue(&s_object(i)))
#define s_fvalue(i) (fvalue(&s_object(i)))
#define s_uvalue(i) (uvalue(&s_object(i)))
typedef union
{
struct {Byte c1; Byte c2;} m;
Word w;
} CodeWord;
#define get_word(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;}
typedef union
{
struct {Byte c1; Byte c2; Byte c3; Byte c4;} m;
float f;
} CodeFloat;
#define get_float(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\
code.m.c3 = *pc++; code.m.c4 = *pc++;}
typedef union
{
struct {Byte c1; Byte c2; Byte c3; Byte c4;} m;
TFunc *tf;
} CodeCode;
#define get_code(code,pc) {code.m.c1 = *pc++; code.m.c2 = *pc++;\
code.m.c3 = *pc++; code.m.c4 = *pc++;}
#define get_word(code,pc) {memcpy(&code, pc, sizeof(Word)); pc+=sizeof(Word);}
#define get_float(code,pc){memcpy(&code, pc, sizeof(real)); pc+=sizeof(real);}
#define get_code(code,pc) {memcpy(&code, pc, sizeof(TFunc *)); \
pc+=sizeof(TFunc *);}
/* Exported functions */

561
strlib.c
View File

@@ -3,134 +3,151 @@
** String library to LUA
*/
char *rcs_strlib="$Id: strlib.c,v 1.21 1996/03/21 22:18:08 roberto Exp roberto $";
char *rcs_strlib="$Id: strlib.c,v 1.32 1996/11/07 20:26:19 roberto Exp roberto $";
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include "lua.h"
#include "lualib.h"
void lua_arg_error(char *funcname)
struct lbuff {
char *b;
size_t max;
size_t size;
};
static struct lbuff lbuffer = {NULL, 0, 0};
static char *lua_strbuffer (unsigned long size)
{
char buff[100];
sprintf(buff, "incorrect arguments to function `%s'", funcname);
lua_error(buff);
if (size > lbuffer.max) {
/* ANSI "realloc" doesn't need this test, but some machines (Sun!)
don't follow ANSI */
lbuffer.b = (lbuffer.b) ? realloc(lbuffer.b, lbuffer.max=size) :
malloc(lbuffer.max=size);
if (lbuffer.b == NULL)
lua_error("memory overflow");
}
return lbuffer.b;
}
static char *openspace (unsigned long size)
{
char *buff = lua_strbuffer(lbuffer.size+size);
return buff+lbuffer.size;
}
void lua_arg_check(int cond, char *funcname)
{
if (!cond) {
char buff[100];
sprintf(buff, "incorrect argument to function `%s'", funcname);
lua_error(buff);
}
}
char *lua_check_string (int numArg, char *funcname)
{
lua_Object o = lua_getparam(numArg);
if (!lua_isstring(o))
lua_arg_error(funcname);
lua_arg_check(lua_isstring(o), funcname);
return lua_getstring(o);
}
char *lua_opt_string (int numArg, char *def, char *funcname)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
lua_check_string(numArg, funcname);
}
double lua_check_number (int numArg, char *funcname)
{
lua_Object o = lua_getparam(numArg);
if (!lua_isnumber(o))
lua_arg_error(funcname);
lua_arg_check(lua_isnumber(o), funcname);
return lua_getnumber(o);
}
static int lua_opt_number (int numArg, int def, char *funcname)
long lua_opt_number (int numArg, long def, char *funcname)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
(int)lua_check_number(numArg, funcname);
(long)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 (lbuffer.size >= lbuffer.max)
lua_strbuffer(lbuffer.max == 0 ? 100 : lbuffer.max*2);
lbuffer.b[lbuffer.size++] = c;
if (c == 0)
n = 0; /* prepare for next string */
return buff;
lbuffer.size = 0; /* prepare for next string */
return lbuffer.b;
}
static void addnchar (char *s, int n)
{
char *b = openspace(n);
strncpy(b, s, n);
lbuffer.size += n;
}
static void addstr (char *s)
{
addnchar(s, strlen(s));
}
/*
** Return the position of the first caracter of a substring into a string
** LUA interface:
** n = strfind (string, substring, init, end)
** Interface to strtok
*/
static void str_find (void)
static void str_tok (void)
{
char *s1 = lua_check_string(1, "strfind");
char *s2 = lua_check_string(2, "strfind");
int init = lua_opt_number(3, 1, "strfind") - 1;
char *f = (init>=0 && init<=strlen(s1)) ? strstr(s1+init,s2) : NULL;
if (f != NULL)
{
int pos = f-s1+1;
if (lua_opt_number(4, INT_MAX, "strfind") >= pos+strlen(s2)-1)
lua_pushnumber (pos);
else
lua_pushnil();
}
else
lua_pushnil();
char *s1 = lua_check_string(1, "strtok");
char *del = lua_check_string(2, "strtok");
lua_Object t = lua_createtable();
int i = 1;
/* As strtok changes s1, and s1 is "constant", make a copy of it */
s1 = strcpy(lua_strbuffer(strlen(s1+1)), s1);
while ((s1 = strtok(s1, del)) != NULL) {
lua_pushobject(t);
lua_pushnumber(i++);
lua_pushstring(s1);
lua_storesubscript();
s1 = NULL; /* prepare for next strtok */
}
lua_pushobject(t);
lua_pushnumber(i-1); /* total number of tokens */
}
/*
** Return the string length
** LUA interface:
** n = strlen (string)
*/
static void str_len (void)
{
char *s = lua_check_string(1, "strlen");
lua_pushnumber(strlen(s));
lua_pushnumber(strlen(lua_check_string(1, "strlen")));
}
/*
** Return the substring of a string, from start to end
** LUA interface:
** substring = strsub (string, start, end)
** Return the substring of a string
*/
static void str_sub (void)
{
char *s = lua_check_string(1, "strsub");
int start = (int)lua_check_number(2, "strsub");
int end = lua_opt_number(3, strlen(s), "strsub");
if (end < start || start < 1 || end > strlen(s))
lua_pushliteral("");
else
{
luaI_addchar(0);
while (start <= end)
luaI_addchar(s[start++ - 1]);
lua_pushstring (luaI_addchar(0));
}
char *s = lua_check_string(1, "strsub");
long start = (long)lua_check_number(2, "strsub");
long end = lua_opt_number(3, strlen(s), "strsub");
if (1 <= start && start <= end && end <= strlen(s)) {
luaI_addchar(0);
addnchar(s+start-1, end-start+1);
lua_pushstring(luaI_addchar(0));
}
else lua_pushliteral("");
}
/*
** Convert a string to lower case.
** LUA interface:
** lowercase = strlower (string)
*/
static void str_lower (void)
{
@@ -141,11 +158,8 @@ static void str_lower (void)
lua_pushstring(luaI_addchar(0));
}
/*
** Convert a string to upper case.
** LUA interface:
** uppercase = strupper (string)
*/
static void str_upper (void)
{
@@ -156,78 +170,357 @@ static void str_upper (void)
lua_pushstring(luaI_addchar(0));
}
static void str_rep (void)
{
char *s = lua_check_string(1, "strrep");
int n = (int)lua_check_number(2, "strrep");
luaI_addchar(0);
while (n-- > 0)
addstr(s);
lua_pushstring(luaI_addchar(0));
}
/*
** get ascii value of a character in a string
*/
static void str_ascii (void)
{
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]);
long pos = lua_opt_number(2, 1, "ascii") - 1;
lua_arg_check(0<=pos && pos<strlen(s), "ascii");
lua_pushnumber((unsigned char)s[pos]);
}
/* pattern matching */
#define ESC '%'
#define SPECIALS "^$*?.([%"
static char *bracket_end (char *p)
{
return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
}
char *item_end (char *p)
{
switch (*p++) {
case '\0': return p-1;
case ESC:
if (*p == 0) lua_error("incorrect pattern");
return p+1;
case '[': {
char *end = bracket_end(p);
if (end == NULL) lua_error("incorrect pattern");
return end+1;
}
default:
return p;
}
}
static int matchclass (int c, int cl)
{
int res;
switch (tolower(cl)) {
case 'a' : res = isalpha(c); break;
case 'c' : res = iscntrl(c); break;
case 'd' : res = isdigit(c); break;
case 'l' : res = islower(c); break;
case 'p' : res = ispunct(c); break;
case 's' : res = isspace(c); break;
case 'u' : res = isupper(c); break;
case 'w' : res = isalnum(c); break;
default: return (cl == c);
}
return (islower(cl) ? res : !res);
}
int singlematch (int c, char *p)
{
if (c == 0) return 0;
switch (*p) {
case '.': return 1;
case ESC: return matchclass(c, *(p+1));
case '[': {
char *end = bracket_end(p+1);
int sig = *(p+1) == '^' ? (p++, 0) : 1;
while (++p < end) {
if (*p == ESC) {
if (((p+1) < end) && matchclass(c, *++p)) return sig;
}
else if ((*(p+1) == '-') && (p+2 < end)) {
p+=2;
if (*(p-2) <= c && c <= *p) return sig;
}
else if (*p == c) return sig;
}
return !sig;
}
default: return (*p == c);
}
}
#define MAX_CAPT 9
static struct {
char *init;
int len; /* -1 signals unfinished capture */
} capture[MAX_CAPT];
static int num_captures; /* only valid after a sucessful call to match */
static void push_captures (void)
{
int i;
for (i=0; i<num_captures; i++) {
int l = capture[i].len;
char *buff = openspace(l+1);
if (l == -1) lua_error("unfinished capture");
strncpy(buff, capture[i].init, l);
buff[l] = 0;
lua_pushstring(buff);
}
}
static int check_cap (int l, int level)
{
l -= '1';
if (!(0 <= l && l < level && capture[l].len != -1))
lua_error("invalid capture index");
return l;
}
static int capture_to_close (int level)
{
for (level--; level>=0; level--)
if (capture[level].len == -1) return level;
lua_error("invalid pattern capture");
return 0; /* to avoid warnings */
}
static char *matchbalance (char *s, int b, int e)
{
if (*s != b) return NULL;
else {
int cont = 1;
while (*(++s)) {
if (*s == e) {
if (--cont == 0) return s+1;
}
else if (*s == b) cont++;
}
}
return NULL; /* string ends out of balance */
}
static char *match (char *s, char *p, int level)
{
init: /* using goto's to optimize tail recursion */
switch (*p) {
case '(': /* start capture */
if (level >= MAX_CAPT) lua_error("too many captures");
capture[level].init = s;
capture[level].len = -1;
level++; p++; goto init; /* return match(s, p+1, level); */
case ')': { /* end capture */
int l = capture_to_close(level);
char *res;
capture[l].len = s - capture[l].init; /* close capture */
if ((res = match(s, p+1, level)) == NULL) /* match failed? */
capture[l].len = -1; /* undo capture */
return res;
}
case ESC:
if (isdigit(*(p+1))) { /* capture */
int l = check_cap(*(p+1), level);
if (strncmp(capture[l].init, s, capture[l].len) == 0) {
/* return match(p+2, s+capture[l].len, level); */
p+=2; s+=capture[l].len; goto init;
}
else return NULL;
}
else if (*(p+1) == 'b') { /* balanced string */
if (*(p+2) == 0 || *(p+3) == 0)
lua_error("bad balanced pattern specification");
s = matchbalance(s, *(p+2), *(p+3));
if (s == NULL) return NULL;
else { /* return match(p+4, s, level); */
p+=4; goto init;
}
}
else goto dflt;
case '\0': case '$': /* (possibly) end of pattern */
if (*p == 0 || (*(p+1) == 0 && *s == 0)) {
num_captures = level;
return s;
}
else goto dflt;
default: dflt: { /* it is a pattern item */
int m = singlematch(*s, p);
char *ep = item_end(p); /* get what is next */
switch (*ep) {
case '*': { /* repetition */
char *res;
if (m && (res = match(s+1, p, level)))
return res;
p=ep+1; goto init; /* else return match(s, ep+1, level); */
}
case '?': { /* optional */
char *res;
if (m && (res = match(s+1, ep+1, level)))
return res;
p=ep+1; goto init; /* else return match(s, ep+1, level); */
}
default:
if (m) { s++; p=ep; goto init; } /* return match(s+1, ep, level); */
else return NULL;
}
}
}
}
static void str_find (void)
{
char *s = lua_check_string(1, "strfind");
char *p = lua_check_string(2, "strfind");
long init = lua_opt_number(3, 1, "strfind") - 1;
lua_arg_check(0 <= init && init <= strlen(s), "strfind");
if (lua_getparam(4) != LUA_NOOBJECT ||
strpbrk(p, SPECIALS) == NULL) { /* no special caracters? */
char *s2 = strstr(s+init, p);
if (s2) {
lua_pushnumber(s2-s+1);
lua_pushnumber(s2-s+strlen(p));
}
}
else {
int anchor = (*p == '^') ? (p++, 1) : 0;
char *s1=s+init;
do {
char *res;
if ((res=match(s1, p, 0)) != NULL) {
lua_pushnumber(s1-s+1); /* start */
lua_pushnumber(res-s); /* end */
push_captures();
return;
}
} while (*s1++ && !anchor);
}
}
static void add_s (lua_Object newp)
{
if (lua_isstring(newp)) {
char *news = lua_getstring(newp);
while (*news) {
if (*news != ESC || !isdigit(*++news))
luaI_addchar(*news++);
else {
int l = check_cap(*news++, num_captures);
addnchar(capture[l].init, capture[l].len);
}
}
}
else if (lua_isfunction(newp)) {
lua_Object res;
struct lbuff oldbuff;
lua_beginblock();
push_captures();
/* function may use lbuffer, so save it and create a new one */
oldbuff = lbuffer;
lbuffer.b = NULL; lbuffer.max = lbuffer.size = 0;
lua_callfunction(newp);
/* restore old buffer */
free(lbuffer.b);
lbuffer = oldbuff;
res = lua_getresult(1);
addstr(lua_isstring(res) ? lua_getstring(res) : "");
lua_endblock();
}
else lua_arg_check(0, "gsub");
}
static void str_gsub (void)
{
char *src = lua_check_string(1, "gsub");
char *p = lua_check_string(2, "gsub");
lua_Object newp = lua_getparam(3);
int max_s = lua_opt_number(4, strlen(src), "gsub");
int anchor = (*p == '^') ? (p++, 1) : 0;
int n = 0;
luaI_addchar(0);
while (*src && n < max_s) {
char *e;
if ((e=match(src, p, 0)) == NULL)
luaI_addchar(*src++);
else {
if (e == src) lua_error("empty pattern in substitution");
add_s(newp);
src = e;
n++;
}
if (anchor) break;
}
addstr(src);
lua_pushstring(luaI_addchar(0));
lua_pushnumber(n); /* number of substitutions */
}
static void str_set (void)
{
char *item = lua_check_string(1, "strset");
int i;
lua_arg_check(*item_end(item) == 0, "strset");
luaI_addchar(0);
for (i=1; i<256; i++) /* 0 cannot be part of a set */
if (singlematch(i, item))
luaI_addchar(i);
lua_pushstring(luaI_addchar(0));
}
void luaI_addquoted (char *s)
{
luaI_addchar('"');
for (; *s; s++)
{
if (*s == '"' || *s == '\\' || *s == '\n')
for (; *s; s++) {
if (strchr("\"\\\n", *s))
luaI_addchar('\\');
luaI_addchar(*s);
}
luaI_addchar('"');
}
#define MAX_CONVERTION 2000
#define MAX_FORMAT 50
#define MAX_FORMAT 200
static void str_format (void)
{
int arg = 1;
char *strfrmt = lua_check_string(arg++, "format");
luaI_addchar(0); /* initialize */
while (*strfrmt)
{
while (*strfrmt) {
if (*strfrmt != '%')
luaI_addchar(*strfrmt++);
else if (*++strfrmt == '%')
luaI_addchar(*strfrmt++); /* %% */
else
{ /* format item */
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])
{
char *buff;
char *initf = strfrmt-1; /* -1 to include % */
strfrmt = match(strfrmt, "[-+ #]*(%d*)%.?(%d*)", 0);
if (capture[0].len > 3 || capture[1].len > 3) /* < 1000? */
lua_error("invalid format (width/precision too long)");
strncpy(form, initf, strfrmt-initf+1); /* +1 to include convertion */
form[strfrmt-initf+1] = 0;
buff = openspace(1000); /* to store the formated value */
switch (*strfrmt++) {
case 'q':
luaI_addquoted(lua_check_string(arg++, "format"));
buff[0] = '\0'; /* addchar already done */
break;
case 's':
{
continue;
case 's': {
char *s = lua_check_string(arg++, "format");
if (strlen(s) >= MAX_CONVERTION)
lua_error("string argument too long in function `format'");
buff = openspace(strlen(s));
sprintf(buff, form, s);
break;
}
@@ -241,24 +534,40 @@ static void str_format (void)
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]);
lbuffer.size += strlen(buff);
}
}
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[] = {
{"strtok", str_tok},
{"strlen", str_len},
{"strsub", str_sub},
{"strset", str_set},
{"strlower", str_lower},
{"strupper", str_upper},
{"strrep", str_rep},
{"ascii", str_ascii},
{"format", str_format},
{"strfind", str_find},
{"gsub", str_gsub}
};
/*
** Open string library
*/
void strlib_open (void)
{
lua_register ("strfind", str_find);
lua_register ("strlen", str_len);
lua_register ("strsub", str_sub);
lua_register ("strlower", str_lower);
lua_register ("strupper", str_upper);
lua_register ("ascii", str_ascii);
lua_register ("format", str_format);
luaI_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
}

54
table.c
View File

@@ -3,7 +3,7 @@
** Module to control static tables
*/
char *rcs_table="$Id: table.c,v 2.50 1996/03/21 16:31:32 roberto Exp roberto $";
char *rcs_table="$Id: table.c,v 2.57 1996/07/12 20:00:26 roberto Exp roberto $";
#include "mem.h"
#include "opcode.h"
@@ -27,8 +27,7 @@ Word lua_nconstant = 0;
static Long lua_maxconstant = 0;
#define GARBAGE_BLOCK 1024
#define MIN_GARBAGE_BLOCK (GARBAGE_BLOCK/2)
#define GARBAGE_BLOCK 50
static void lua_nextvar (void);
@@ -40,6 +39,7 @@ static struct {
lua_CFunction func;
} int_funcs[] = {
{"assert", luaI_assert},
{"call", luaI_call},
{"dofile", lua_internaldofile},
{"dostring", lua_internaldostring},
{"error", luaI_error},
@@ -60,13 +60,16 @@ static struct {
void luaI_initsymbol (void)
{
int i;
Word n;
lua_maxsymbol = BUFFER_BLOCK;
lua_table = newvector(lua_maxsymbol, Symbol);
for (i=0; i<INTFUNCSIZE; i++)
{
Word n = luaI_findsymbolbyname(int_funcs[i].name);
n = luaI_findsymbolbyname(int_funcs[i].name);
s_tag(n) = LUA_T_CFUNCTION; s_fvalue(n) = int_funcs[i].func;
}
n = luaI_findsymbolbyname("_VERSION_");
s_tag(n) = LUA_T_STRING; s_tsvalue(n) = lua_createstring(LUA_VERSION);
}
@@ -170,6 +173,24 @@ int lua_markobject (Object *o)
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;
}
}
/*
** Garbage collection.
@@ -182,6 +203,7 @@ Long luaI_collectgarbage (void)
lua_travsymbol(lua_markobject); /* mark symbol table objects */
luaI_travlock(lua_markobject); /* mark locked objects */
luaI_travfallbacks(lua_markobject); /* mark fallbacks */
luaI_invalidaterefs();
recovered += lua_strcollector();
recovered += lua_hashcollector();
recovered += luaI_funccollector();
@@ -190,14 +212,13 @@ Long luaI_collectgarbage (void)
void lua_pack (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;
static unsigned long block = GARBAGE_BLOCK;
static unsigned long nentity = 0; /* total of strings, arrays, etc */
unsigned long recovered = 0;
if (nentity++ < block) return;
recovered = luaI_collectgarbage();
nentity = 0; /* reset counter */
block=(16*block-7*recovered)/12; /* adapt block size */
if (block < MIN_GARBAGE_BLOCK) block = MIN_GARBAGE_BLOCK;
block = 2*(block-recovered);
nentity -= recovered;
}
@@ -222,18 +243,9 @@ static void lua_nextvar (void)
else
next = luaI_findsymbolbyname(lua_getstring(o)) + 1;
while (next < lua_ntable && s_tag(next) == LUA_T_NIL) next++;
if (next >= lua_ntable)
if (next < lua_ntable)
{
lua_pushnil();
lua_pushnil();
}
else
{
TaggedString *t = lua_table[next].varname;
Object name;
tag(&name) = LUA_T_STRING;
tsvalue(&name) = t;
luaI_pushobject(&name);
lua_pushstring(lua_table[next].varname->str);
luaI_pushobject(&s_object(next));
}
}

View File

@@ -1,7 +1,7 @@
/*
** Module to control static tables
** TeCGraf - PUC-Rio
** $Id: table.h,v 2.19 1996/02/26 21:00:27 roberto Exp roberto $
** $Id: table.h,v 2.20 1996/03/14 15:57:19 roberto Exp roberto $
*/
#ifndef table_h
@@ -30,6 +30,7 @@ Word luaI_findconstant (TaggedString *t);
Word luaI_findconstantbyname (char *name);
TaggedString *luaI_createfixedstring (char *str);
int lua_markobject (Object *o);
int luaI_ismarked (Object *o);
Long luaI_collectgarbage (void);
void lua_pack (void);

View File

@@ -3,7 +3,7 @@
** load bytecodes from files
*/
char* rcs_undump="$Id: undump.c,v 1.13 1996/03/12 20:00:40 lhf Exp lhf $";
char* rcs_undump="$Id: undump.c,v 1.20 1996/11/16 20:14:23 lhf Exp lhf $";
#include <stdio.h>
#include <string.h>
@@ -90,7 +90,7 @@ static void FixCode(Byte* code, Byte* end) /* swap words */
p+=3;
break;
case PUSHFUNCTION:
p+=5;
p+=5; /* TODO: use sizeof(TFunc*) or old? */
break;
case PUSHWORD:
case PUSHSELF:
@@ -111,7 +111,7 @@ static void FixCode(Byte* code, Byte* end) /* swap words */
p+=3;
break;
}
case PUSHFLOAT:
case PUSHFLOAT: /* assumes sizeof(float)==4 */
{
Byte t;
t=p[1]; p[1]=p[4]; p[4]=t;
@@ -142,13 +142,11 @@ static void Unthread(Byte* code, int i, int v)
{
while (i!=0)
{
CodeWord c;
Word w;
Byte* p=code+i;
get_word(c,p);
i=c.w;
c.w=v;
p[-2]=c.m.c1;
p[-1]=c.m.c2;
memcpy(&w,p,sizeof(w));
i=w; w=v;
memcpy(p,&w,sizeof(w));
}
}
@@ -174,9 +172,9 @@ static int LoadSize(FILE* D)
return s;
}
static char* LoadBlock(int size, FILE* D)
static void* LoadBlock(int size, FILE* D)
{
char* b=luaI_malloc(size);
void* b=luaI_malloc(size);
fread(b,size,1,D);
return b;
}
@@ -208,13 +206,9 @@ static void LoadFunction(FILE* D)
}
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;
memcpy(Main->code+tf->marked,&tf,sizeof(tf));
lastF=lastF->next=tf;
}
tf->code=LoadBlock(tf->size,D);
@@ -256,8 +250,21 @@ static void LoadHeader(FILE* D) /* TODO: error handling */
{
Word w,tw=TEST_WORD;
float f,tf=TEST_FLOAT;
int version;
LoadSignature(D);
getc(D); /* skip version */
version=getc(D);
if (version>0x23) /* after 2.5 */
{
int oldsizeofW=getc(D);
int oldsizeofF=getc(D);
int oldsizeofP=getc(D);
if (oldsizeofW!=2)
lua_error("cannot load binary file created on machine with sizeof(Word)!=2");
if (oldsizeofF!=4)
lua_error("cannot load binary file created on machine with sizeof(float)!=4. not an IEEE machine?");
if (oldsizeofP!=sizeof(TFunc*)) /* TODO: pack */
lua_error("cannot load binary file: different pointer sizes");
}
fread(&w,sizeof(w),1,D); /* test word */
if (w!=tw)
{

View File

@@ -1,7 +1,7 @@
/*
** undump.h
** definitions for lua decompiler
** $Id: undump.h,v 1.1 1996/03/08 21:43:21 lhf Exp lhf $
** $Id: undump.h,v 1.2 1996/03/11 21:59:41 lhf Exp lhf $
*/
#include "func.h"
@@ -15,7 +15,7 @@
#define ID_VAR 'V'
#define ID_STR 'S'
#define SIGNATURE "Lua"
#define VERSION 0x23 /* 2.3 */
#define VERSION 0x25 /* 2.5 */
#define TEST_WORD 0x1234 /* a word for testing byte ordering */
#define TEST_FLOAT 0.123456789e-23 /* a float for testing representation */