Compare commits

..

49 Commits

Author SHA1 Message Date
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
19 changed files with 1642 additions and 1408 deletions

2
func.c
View File

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

8
hash.c
View File

@@ -3,7 +3,7 @@
** hash manager for lua ** hash manager for lua
*/ */
char *rcs_hash="$Id: hash.c,v 2.29 1996/02/14 18:25:04 roberto Exp roberto $"; char *rcs_hash="$Id: hash.c,v 2.30 1996/05/06 14:30:27 roberto Exp roberto $";
#include "mem.h" #include "mem.h"
@@ -283,17 +283,11 @@ Object *lua_hashdefine (Hash *t, Object *ref)
static void hashnext (Hash *t, int i) static void hashnext (Hash *t, int i)
{ {
if (i >= nhash(t)) if (i >= nhash(t))
{
lua_pushnil(); lua_pushnil();
return; return;
}
while (tag(ref(node(t,i))) == LUA_T_NIL || tag(val(node(t,i))) == LUA_T_NIL) while (tag(ref(node(t,i))) == LUA_T_NIL || tag(val(node(t,i))) == LUA_T_NIL)
{ {
if (++i >= nhash(t)) if (++i >= nhash(t))
{
lua_pushnil(); lua_pushnil();
return; return;
}
} }
luaI_pushobject(ref(node(t,i))); luaI_pushobject(ref(node(t,i)));
luaI_pushobject(val(node(t,i))); luaI_pushobject(val(node(t,i)));

98
inout.c
View File

@@ -5,9 +5,10 @@
** Also provides some predefined lua functions. ** 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 <stdio.h>
#include <string.h>
#include "lex.h" #include "lex.h"
#include "opcode.h" #include "opcode.h"
@@ -31,7 +32,8 @@ static char *st;
*/ */
static int fileinput (void) 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"); fp = fopen (fn, "r");
if (fp == NULL) if (fp == NULL)
return NULL; return NULL;
lua_linenumber = 1;
lua_parsedfile = luaI_createfixedstring(fn)->str; lua_parsedfile = luaI_createfixedstring(fn)->str;
return fp; return fp;
} }
@@ -78,12 +79,16 @@ void lua_closefile (void)
/* /*
** Function to open a string to be input unit ** 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) void lua_openstring (char *s)
{ {
lua_setinput (stringinput); char buff[SIZE_PREF+25];
st = s; lua_setinput(stringinput);
lua_linenumber = 1; st = s;
lua_parsedfile = luaI_createfixedstring("(string)")->str; 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 ** Internal function: do a string
*/ */
void lua_internaldostring (void) void lua_internaldostring (void)
{ {
lua_Object obj = lua_getparam (1); lua_Object obj = lua_getparam (1);
if (lua_isstring(obj) && !lua_dostring(lua_getstring(obj))) if (lua_isstring(obj) && lua_dostring(lua_getstring(obj)) == 0)
lua_pushnumber(1); if (passresults() == 0)
else lua_pushuserdata(NULL); /* at least one result to signal no errors */
lua_pushnil();
} }
/* /*
@@ -118,10 +142,9 @@ void lua_internaldofile (void)
else if (obj != LUA_NOOBJECT) else if (obj != LUA_NOOBJECT)
lua_error("invalid argument to function `dofile'"); lua_error("invalid argument to function `dofile'");
/* else fname = NULL */ /* else fname = NULL */
if (!lua_dofile(fname)) if (lua_dofile(fname) == 0)
lua_pushnumber(1); if (passresults() == 0)
else lua_pushuserdata(NULL); /* at least one result to signal no errors */
lua_pushnil();
} }
@@ -207,8 +230,6 @@ void lua_obj2number (void)
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
if (lua_isnumber(o)) if (lua_isnumber(o))
lua_pushnumber(lua_getnumber(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 name = lua_getparam(1);
lua_Object value = lua_getparam(2); lua_Object value = lua_getparam(2);
if (!lua_isstring(name)) check_arg(lua_isstring(name), "setglobal");
lua_error("incorrect argument to function `setglobal'");
lua_pushobject(value); lua_pushobject(value);
lua_storeglobal(lua_getstring(name)); lua_storeglobal(lua_getstring(name));
lua_pushobject(value); /* return given value */ lua_pushobject(value); /* return given value */
@@ -240,7 +260,41 @@ void luaI_setglobal (void)
void luaI_getglobal (void) void luaI_getglobal (void)
{ {
lua_Object name = lua_getparam(1); lua_Object name = lua_getparam(1);
if (!lua_isstring(name)) check_arg(lua_isstring(name), "getglobal");
lua_error("incorrect argument to function `getglobal'");
lua_pushobject(lua_getglobal(lua_getstring(name))); 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_assert (void);
void luaI_setglobal (void); void luaI_setglobal (void);
void luaI_getglobal (void); void luaI_getglobal (void);
void luaI_call (void);
#endif #endif

586
iolib.c
View File

@@ -1,10 +1,3 @@
/*
** iolib.c
** Input/output library to LUA
*/
char *rcs_iolib="$Id: iolib.c,v 1.43 1996/04/30 21:13:55 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <ctype.h> #include <ctype.h>
#include <string.h> #include <string.h>
@@ -16,7 +9,8 @@ char *rcs_iolib="$Id: iolib.c,v 1.43 1996/04/30 21:13:55 roberto Exp roberto $";
#include "luadebug.h" #include "luadebug.h"
#include "lualib.h" #include "lualib.h"
static FILE *in=stdin, *out=stdout;
FILE *lua_infile, *lua_outfile;
#ifdef POPEN #ifdef POPEN
@@ -31,515 +25,202 @@ int pclose();
static void pushresult (int i) static void pushresult (int i)
{ {
if (i) if (i)
lua_pushnumber (1); lua_pushuserdata(NULL);
else else {
lua_pushnil(); lua_pushnil();
} #ifndef NOSTRERROR
lua_pushstring(strerror(errno));
static void closeread (void) #else
{ lua_pushstring("system unable to define the error");
if (in != stdin) #endif
{
if (pclose(in) == -1)
fclose(in);
in = stdin;
} }
} }
static void closewrite (void)
static void closefile (FILE *f)
{ {
if (out != stdout) if (f == stdin || f == stdout)
{ return;
if (pclose(out) == -1) if (f == lua_infile)
fclose(out); lua_infile = stdin;
out = stdout; 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) static void io_readfrom (void)
{ {
if (lua_getparam (1) == LUA_NOOBJECT) lua_Object f = lua_getparam(1);
{ /* restore standart input */ if (f == LUA_NOOBJECT)
closeread(); closefile(lua_infile); /* restore standart input */
lua_pushnumber (1); else if (lua_isuserdata(f))
} lua_infile = lua_getuserdata(f);
else else {
{ char *s = lua_check_string(1, "readfrom");
char *s = lua_check_string(1, "readfrom"); FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r"); if (fp)
if (fp == NULL) lua_infile = fp;
lua_pushnil(); else {
else pushresult(0);
{ return;
closeread(); }
in = fp; }
lua_pushnumber (1); 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) static void io_writeto (void)
{ {
if (lua_getparam (1) == LUA_NOOBJECT) /* restore standart output */ lua_Object f = lua_getparam(1);
{ if (f == LUA_NOOBJECT)
closewrite(); closefile(lua_outfile); /* restore standart output */
lua_pushnumber (1); else if (lua_isuserdata(f))
} lua_outfile = lua_getuserdata(f);
else else {
{ char *s = lua_check_string(1, "writeto");
char *s = lua_check_string(1, "writeto"); FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w"); if (fp)
if (fp == NULL) lua_outfile = fp;
lua_pushnil(); else {
else pushresult(0);
{ return;
closewrite(); }
out = fp; }
lua_pushnumber (1); lua_pushuserdata(lua_outfile);
}
}
} }
/*
** Open a file to write appended.
** LUA interface:
** status = appendto (filename)
** where:
** status = 1 -> success
** status = nil -> error
*/
static void io_appendto (void) static void io_appendto (void)
{ {
char *s = lua_check_string(1, "appendto"); char *s = lua_check_string(1, "appendto");
FILE *fp = fopen (s, "a"); FILE *fp = fopen (s, "a");
if (fp == NULL) if (fp != NULL) {
lua_pushnil(); lua_outfile = fp;
else lua_pushuserdata(lua_outfile);
{
if (out != stdout) fclose (out);
out = fp;
lua_pushnumber(1);
}
}
static char getformat (char *f, int *just, int *m, int *n)
{
int t;
switch (*f++)
{
case 'q': case 'Q':
case 's': case 'S':
case 'i': case 'I':
t = tolower(*(f-1));
break;
case 'f': case 'F': case 'g': case 'G': case 'e': case 'E':
t = 'f';
break;
default:
t = 0; /* to avoid compiler warnings */
lua_arg_error("read/write (format)");
}
*just = (*f == '<' || *f == '>' || *f == '|') ? *f++ : '>';
if (isdigit(*f))
{
*m = 0;
while (isdigit(*f))
*m = *m*10 + (*f++ - '0');
} }
else else
*m = -1; pushresult(0);
if (*f == '.')
{
f++; /* skip point */
*n = 0;
while (isdigit(*f))
*n = *n*10 + (*f++ - '0');
}
else
*n = -1;
return t;
} }
/* #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
** 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);
}
}
static void io_read (void) static void io_read (void)
{ {
lua_Object o = lua_getparam (1); char *buff;
luaI_addchar(0); /* initialize buffer */ char *p = lua_opt_string(1, "[^\n]*{\n}", "read");
if (o == LUA_NOOBJECT) /* free format */ int inskip = 0; /* to control {skips} */
read_free(); int c = NEED_OTHER;
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)
{
luaI_addchar(0); luaI_addchar(0);
luaI_addquoted(lua_check_string(1, "write")); while (*p) {
return write_string(luaI_addchar(0), just, m); if (*p == '{' || *p == '}') {
} inskip = (*p == '{');
p++;
static int write_float (int just, int m, int n) }
{ else {
char buffer[100]; char *ep = item_end(p); /* get what is next */
lua_Object p = lua_getparam(1); int m;
float number; if (c == NEED_OTHER) c = getc(lua_infile);
if (!lua_isnumber(p)) return 0; if ((m = singlematch(c, p)) != 0) {
number = lua_getnumber(p); if (!inskip) luaI_addchar(c);
if (n >= 0) c = NEED_OTHER;
sprintf(buffer, "%.*f", n, number); }
else switch (*ep) {
sprintf(buffer, "%g", number); case '*': /* repetition */
return write_string(buffer, just, m); if (!m) p = ep+1; /* else stay in (repeat) the same item */
} break;
case '?': /* optional */
p = ep+1; /* continues reading the pattern */
static int write_int (int just, int m, int n) break;
{ default:
char buffer[100]; if (m) p = ep; /* continues reading the pattern */
lua_Object p = lua_getparam(1); else
int number; goto break_while; /* pattern fails */
if (!lua_isnumber(p)) return 0; }
number = (int)lua_getnumber(p); }
if (n >= 0) } break_while:
sprintf(buffer, "%.*d", n, number); if (c >= 0) /* not EOF nor NEED_OTHER? */
else ungetc(c, lua_infile);
sprintf(buffer, "%d", number); buff = luaI_addchar(0);
return write_string(buffer, just, m); if (*buff != 0 || *p == 0) /* read something or did not fail? */
lua_pushstring(buff);
} }
static void io_write (void) static void io_write (void)
{ {
int status = 0; int arg = 1;
if (lua_getparam (2) == LUA_NOOBJECT) /* free format */ int status = 1;
{ char *s;
lua_Object o1 = lua_getparam(1); while ((s = lua_opt_string(arg++, NULL, "write")) != NULL)
int t = lua_type(o1); status = status && (fputs(s, lua_outfile) != EOF);
if (t == LUA_T_NUMBER) pushresult(status);
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();
} }
/*
** Execute a executable program using "system".
** Return the result of execution.
*/
static void io_execute (void) static void io_execute (void)
{ {
lua_pushnumber(system(lua_check_string(1, "execute"))); lua_pushnumber(system(lua_check_string(1, "execute")));
} }
/*
** Remove a file. On error return nil.
*/
static void io_remove (void) static void io_remove (void)
{ {
pushresult(remove(lua_check_string(1, "remove")) == 0); pushresult(remove(lua_check_string(1, "remove")) == 0);
} }
static void io_rename (void) static void io_rename (void)
{ {
char *f1 = lua_check_string(1, "rename"); pushresult(rename(lua_check_string(1, "rename"),
char *f2 = lua_check_string(2, "rename"); lua_check_string(2, "rename")) == 0);
pushresult(rename(f1, f2) == 0);
} }
static void io_tmpname (void) static void io_tmpname (void)
{ {
lua_pushstring(tmpnam(NULL)); lua_pushstring(tmpnam(NULL));
} }
static void io_errorno (void)
{
/* lua_pushstring(strerror(errno));*/
}
/*
** To get a environment variable
*/
static void io_getenv (void) static void io_getenv (void)
{ {
char *env = getenv(lua_check_string(1, "getenv")); lua_pushstring(getenv(lua_check_string(1, "getenv"))); /* if NULL push nil */
lua_pushstring(env); /* if NULL push nil */
} }
/*
** Return user formatted time stamp
*/
static void io_date (void) static void io_date (void)
{ {
time_t t; time_t t;
struct tm *tm; struct tm *tm;
char *s; char *s = lua_opt_string(1, "%c", "date");
char b[BUFSIZ]; char b[BUFSIZ];
if (lua_getparam(1) == LUA_NOOBJECT) time(&t); tm = localtime(&t);
s = "%c"; if (strftime(b,sizeof(b),s,tm))
else lua_pushstring(b);
s = lua_check_string(1, "date"); else
time(&t); tm = localtime(&t); lua_error("invalid `date' format");
if (strftime(b,sizeof(b),s,tm))
lua_pushstring(b);
else
lua_error("invalid `date' format");
} }
/*
** To exit
*/
static void io_exit (void) static void io_exit (void)
{ {
lua_Object o = lua_getparam(1); lua_Object o = lua_getparam(1);
int code = lua_isnumber(o) ? (int)lua_getnumber(o) : 1; exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
exit(code);
} }
/*
** To debug a lua program. Start a dialog with the user, interpreting
lua commands until an 'cont'.
*/
static void io_debug (void) static void io_debug (void)
{ {
while (1) while (1) {
{
char buffer[250]; char buffer[250];
fprintf(stderr, "lua_debug> "); fprintf(stderr, "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0) return; if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
if (strcmp(buffer, "cont") == 0) return; if (strcmp(buffer, "cont\n") == 0) return;
lua_dostring(buffer); lua_dostring(buffer);
} }
} }
@@ -550,21 +231,18 @@ static void lua_printstack (FILE *f)
int level = 0; int level = 0;
lua_Object func; lua_Object func;
fprintf(f, "Active Stack:\n"); fprintf(f, "Active Stack:\n");
while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
{
char *name; char *name;
int currentline; int currentline;
fprintf(f, "\t"); fprintf(f, "\t");
switch (*lua_getobjname(func, &name)) switch (*lua_getobjname(func, &name)) {
{
case 'g': case 'g':
fprintf(f, "function %s", name); fprintf(f, "function %s", name);
break; break;
case 'f': case 'f':
fprintf(f, "`%s' fallback", name); fprintf(f, "`%s' fallback", name);
break; break;
default: default: {
{
char *filename; char *filename;
int linedefined; int linedefined;
lua_funcinfo(func, &filename, &linedefined); lua_funcinfo(func, &filename, &linedefined);
@@ -585,8 +263,7 @@ static void lua_printstack (FILE *f)
static void errorfb (void) static void errorfb (void)
{ {
lua_Object o = lua_getparam(1); char *s = lua_opt_string(1, "(no messsage)", NULL);
char *s = lua_isstring(o) ? lua_getstring(o) : "(no messsage)";
fprintf(stderr, "lua: %s\n", s); fprintf(stderr, "lua: %s\n", s);
lua_printstack(stderr); lua_printstack(stderr);
} }
@@ -597,13 +274,11 @@ static struct lua_reg iolib[] = {
{"writeto", io_writeto}, {"writeto", io_writeto},
{"appendto", io_appendto}, {"appendto", io_appendto},
{"read", io_read}, {"read", io_read},
{"readuntil",io_readuntil},
{"write", io_write}, {"write", io_write},
{"execute", io_execute}, {"execute", io_execute},
{"remove", io_remove}, {"remove", io_remove},
{"rename", io_rename}, {"rename", io_rename},
{"tmpname", io_tmpname}, {"tmpname", io_tmpname},
{"ioerror", io_errorno},
{"getenv", io_getenv}, {"getenv", io_getenv},
{"date", io_date}, {"date", io_date},
{"exit", io_exit}, {"exit", io_exit},
@@ -613,6 +288,7 @@ static struct lua_reg iolib[] = {
void iolib_open (void) void iolib_open (void)
{ {
lua_infile=stdin; lua_outfile=stdout;
luaI_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0]))); luaI_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
lua_setfallback("error", errorfb); lua_setfallback("error", errorfb);
} }

197
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.36 1996/09/25 21:52:00 roberto Exp roberto $";
#include <ctype.h> #include <ctype.h>
#include <string.h> #include <string.h>
@@ -14,32 +14,25 @@ char *rcs_lex = "$Id: lex.c,v 2.31 1996/03/19 16:50:24 roberto Exp roberto $";
#define MINBUFF 260 #define MINBUFF 260
#define next() { current = input(); } #define next() (current = input())
#define save(x) { *yytextLast++ = (x); } #define save(x) (yytext[tokensize++] = (x))
#define save_and_next() { save(current); next(); } #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) void lua_setinput (Input fn)
{ {
current = ' '; current = '\n';
lua_linenumber = 0;
input = fn; input = fn;
if (yytext == NULL)
{
textsize = MINBUFF;
yytext = newvector(textsize, char);
}
} }
char *lua_lasttext (void) char *lua_lasttext (void)
{ {
*yytextLast = 0; return luaI_buffer(1);
return yytext;
} }
@@ -79,95 +72,96 @@ void luaI_addReserved (void)
} }
} }
static int inclinenumber (int pragma_allowed)
static void growtext (void)
{ {
int size = yytextLast - yytext; if (pragma_allowed && current == '$') { /* is a pragma? */
textsize = growvector(&yytext, textsize, char, lexEM, MAX_WORD); char buff[MINBUFF];
yytextLast = yytext + size; int i = 0;
next(); /* skip $ */
while (isalnum(current)) {
if (i >= MINBUFF) lua_error("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 lua_error("invalid pragma");
}
return ++lua_linenumber;
} }
static int read_long_string (char *yytext, int buffsize)
static int read_long_string (void)
{ {
int cont = 0; int cont = 0;
int spaceleft = textsize - (yytextLast - yytext); int tokensize = 2; /* '[[' already stored */
while (1) while (1)
{ {
if (spaceleft <= 2) /* may read more than 1 char in one cicle */ if (buffsize-tokensize <= 2) /* may read more than 1 char in one cicle */
{ yytext = luaI_buffer(buffsize *= 2);
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
switch (current) switch (current)
{ {
case EOF:
case 0: case 0:
save(0);
return WRONGTOKEN; return WRONGTOKEN;
case '[': case '[':
save_and_next(); spaceleft--; save_and_next();
if (current == '[') if (current == '[')
{ {
cont++; cont++;
save_and_next(); spaceleft--; save_and_next();
} }
continue; continue;
case ']': case ']':
save_and_next(); spaceleft--; save_and_next();
if (current == ']') if (current == ']')
{ {
if (cont == 0) return STRING; if (cont == 0) goto endloop;
cont--; cont--;
save_and_next(); spaceleft--; save_and_next();
} }
continue; continue;
case '\n': case '\n':
lua_linenumber++; /* goes through */ save_and_next();
inclinenumber(0);
continue;
default: 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) int luaY_lex (void)
{ {
double a;
static int linelasttoken = 0; static int linelasttoken = 0;
double a;
int buffsize = MINBUFF;
char *yytext = luaI_buffer(buffsize);
yytext[1] = yytext[2] = yytext[3] = 0;
if (lua_debug) if (lua_debug)
luaI_codedebugline(linelasttoken); luaI_codedebugline(linelasttoken);
linelasttoken = lua_linenumber; linelasttoken = lua_linenumber;
while (1) while (1)
{ {
yytextLast = yytext; int tokensize = 0;
switch (current) switch (current)
{ {
case EOF: case '\n':
case 0:
return 0;
case '\n': linelasttoken = ++lua_linenumber;
case ' ':
case '\r': /* CR: to avoid problems with DOS/Windows */
case '\t':
next(); next();
linelasttoken = inclinenumber(1);
continue; continue;
case '$': case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */
next(); next();
while (isalnum(current) || current == '_') continue;
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 '-':
save_and_next(); save_and_next();
@@ -181,12 +175,7 @@ int luaY_lex (void)
else else
{ {
save_and_next(); /* pass the second '[' */ save_and_next(); /* pass the second '[' */
if (read_long_string() == WRONGTOKEN) return read_long_string(yytext, buffsize);
return WRONGTOKEN;
save_and_next(); /* pass the second ']' */
*(yytextLast-2) = 0; /* erases ']]' */
luaY_lval.vWord = luaI_findconstantbyname(yytext+2);
return STRING;
} }
case '=': case '=':
@@ -213,21 +202,16 @@ int luaY_lex (void)
case '\'': case '\'':
{ {
int del = current; int del = current;
int spaceleft = textsize - (yytextLast - yytext); save_and_next();
next(); /* skip the delimiter */
while (current != del) while (current != del)
{ {
if (spaceleft <= 2) /* may read more than 1 char in one cicle */ if (buffsize-tokensize <= 2) /* may read more than 1 char in one cicle */
{ yytext = luaI_buffer(buffsize *= 2);
growtext();
spaceleft = textsize - (yytextLast - yytext);
}
spaceleft--;
switch (current) switch (current)
{ {
case EOF:
case 0: case 0:
case '\n': case '\n':
save(0);
return WRONGTOKEN; return WRONGTOKEN;
case '\\': case '\\':
next(); /* do not save the '\' */ next(); /* do not save the '\' */
@@ -236,17 +220,19 @@ int luaY_lex (void)
case 'n': save('\n'); next(); break; case 'n': save('\n'); next(); break;
case 't': save('\t'); next(); break; case 't': save('\t'); next(); break;
case 'r': save('\r'); next(); break; case 'r': save('\r'); next(); break;
case '\n': lua_linenumber++; /* goes through */ case '\n': save_and_next(); inclinenumber(0); break;
default : save(current); next(); break; default : save_and_next(); break;
} }
break; break;
default: default:
save_and_next(); save_and_next();
} }
} }
next(); /* skip the delimiter */ next(); /* skip delimiter */
*yytextLast = 0; save(0);
luaY_lval.vWord = luaI_findconstantbyname(yytext); luaY_lval.vWord = luaI_findconstantbyname(yytext+1);
tokensize--;
save(del); save(0); /* restore delimiter */
return STRING; return STRING;
} }
@@ -266,7 +252,7 @@ int luaY_lex (void)
{ {
TaggedString *ts; TaggedString *ts;
do { save_and_next(); } while (isalnum(current) || current == '_'); do { save_and_next(); } while (isalnum(current) || current == '_');
*yytextLast = 0; save(0);
ts = lua_createstring(yytext); ts = lua_createstring(yytext);
if (ts->marked > 2) if (ts->marked > 2)
return ts->marked; /* reserved word */ return ts->marked; /* reserved word */
@@ -280,7 +266,12 @@ int luaY_lex (void)
if (current == '.') if (current == '.')
{ {
save_and_next(); save_and_next();
return CONC; if (current == '.')
{
save_and_next();
return DOTS; /* ... */
}
else return CONC; /* .. */
} }
else if (!isdigit(current)) return '.'; else if (!isdigit(current)) return '.';
/* current is a digit: goes through to number */ /* current is a digit: goes through to number */
@@ -290,12 +281,19 @@ int luaY_lex (void)
case '0': case '1': case '2': case '3': case '4': case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': case '5': case '6': case '7': case '8': case '9':
a=0.0; a=0.0;
do { a=10.0*a+(current-'0'); save_and_next(); } while (isdigit(current)); do {
a=10.0*a+(current-'0');
save_and_next();
} while (isdigit(current));
if (current == '.') save_and_next(); if (current == '.') save_and_next();
fraction: fraction:
{ double da=0.1; { double da=0.1;
while (isdigit(current)) while (isdigit(current))
{a+=(current-'0')*da; da/=10.0; save_and_next()}; {
a+=(current-'0')*da;
da/=10.0;
save_and_next();
}
if (current == 'e' || current == 'E') if (current == 'e' || current == 'E')
{ {
int e=0; int e=0;
@@ -304,19 +302,23 @@ fraction:
save_and_next(); save_and_next();
neg=(current=='-'); neg=(current=='-');
if (current == '+' || current == '-') save_and_next(); if (current == '+' || current == '-') save_and_next();
if (!isdigit(current)) return WRONGTOKEN; if (!isdigit(current)) { save(0); return WRONGTOKEN; }
do { e=10.0*e+(current-'0'); save_and_next(); } while (isdigit(current)); do {
for (ea=neg?0.1:10.0; e>0; e>>=1) 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; if (e & 1) a*=ea;
ea*=ea; ea*=ea;
} }
} }
luaY_lval.vFloat = a; luaY_lval.vFloat = a;
save(0);
return NUMBER; return NUMBER;
} }
default: /* also end of file */ default: /* also end of program (0) */
{ {
save_and_next(); save_and_next();
return yytext[0]; return yytext[0];
@@ -324,3 +326,4 @@ fraction:
} }
} }
} }

107
lua.c
View File

@@ -3,7 +3,7 @@
** Linguagem para Usuarios de Aplicacao ** Linguagem para Usuarios de Aplicacao
*/ */
char *rcs_lua="$Id: lua.c,v 1.9 1996/04/23 12:43:07 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 <stdio.h>
#include <string.h> #include <string.h>
@@ -11,45 +11,23 @@ char *rcs_lua="$Id: lua.c,v 1.9 1996/04/23 12:43:07 roberto Exp roberto $";
#include "lua.h" #include "lua.h"
#include "lualib.h" #include "lualib.h"
static int lua_argc;
static char **lua_argv;
#ifdef POSIX #ifdef _POSIX_SOURCE
/* #include <unistd.h>
** although this function is POSIX, there is no standard header file that
** defines it
*/
int isatty (int fd);
#else #else
#define isatty(x) (x==0) /* assume stdin is a tty */ #define isatty(x) (x==0) /* assume stdin is a tty */
#endif #endif
/*
%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]);
}
}
static void manual_input (void) static void manual_input (void)
{ {
if (isatty(0)) if (isatty(0)) {
{ char buffer[250];
char buffer[250]; while (fgets(buffer, sizeof(buffer), stdin) != 0) {
while (fgets(buffer, sizeof(buffer), stdin) != 0) lua_beginblock();
lua_dostring(buffer); lua_dostring(buffer);
lua_endblock();
}
} }
else else
lua_dofile(NULL); /* executes stdin as a file */ lua_dofile(NULL); /* executes stdin as a file */
@@ -58,43 +36,36 @@ static void manual_input (void)
int main (int argc, char *argv[]) int main (int argc, char *argv[])
{ {
int i; int i;
int result = 0; int result = 0;
iolib_open (); iolib_open ();
strlib_open (); strlib_open ();
mathlib_open (); mathlib_open ();
if (argc < 2)
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)
manual_input(); manual_input();
else if (strcmp(argv[i], "-v") == 0) else for (i=1; i<argc; i++) {
printf("%s %s\n(written by %s)\n\n", if (strcmp(argv[i], "-") == 0)
LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS); manual_input();
else else if (strcmp(argv[i], "-v") == 0)
{ printf("%s %s\n(written by %s)\n\n",
result = lua_dofile (argv[i]); LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS);
if (result) else if ((strcmp(argv[i], "-e") == 0 && i++) || strchr(argv[i], '=')) {
fprintf(stderr, "lua: error trying to run file %s\n", 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;
} }

4
lua.h
View File

@@ -2,14 +2,14 @@
** LUA - Linguagem para Usuarios de Aplicacao ** LUA - Linguagem para Usuarios de Aplicacao
** Grupo de Tecnologia em Computacao Grafica ** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: lua.h,v 3.27 1996/04/25 14:10:00 roberto Exp roberto $ ** $Id: lua.h,v 3.28 1996/05/06 14:32:59 roberto Exp roberto $
*/ */
#ifndef lua_h #ifndef lua_h
#define lua_h #define lua_h
#define LUA_VERSION "Lua 2.4" #define LUA_VERSION "Lua 2.5 (beta)"
#define LUA_COPYRIGHT "Copyright (C) 1994, 1995 TeCGraf" #define LUA_COPYRIGHT "Copyright (C) 1994, 1995 TeCGraf"
#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo" #define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"

102
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.39 1996/09/24 17:29:50 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "luadebug.h" #include "luadebug.h"
#include "mem.h" #include "mem.h"
@@ -67,49 +68,45 @@ static void yyerror (char *s)
lua_error (msg); lua_error (msg);
} }
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) static void code_byte (Byte c)
{ {
if (pc>maxcurr-2) /* 1 byte free to code HALT of main code */ check_space(1);
maxcurr = growvector(&basepc, maxcurr, Byte, codeEM, MAX_INT);
basepc[pc++] = c; basepc[pc++] = c;
} }
static void code_word (Word n) static void code_word (Word n)
{ {
CodeWord code; check_space(sizeof(Word));
code.w = n; memcpy(basepc+pc, &n, sizeof(Word));
code_byte(code.m.c1); pc += sizeof(Word);
code_byte(code.m.c2);
} }
static void code_float (float n) static void code_float (real n)
{ {
CodeFloat code; check_space(sizeof(real));
code.f = n; memcpy(basepc+pc, &n, sizeof(real));
code_byte(code.m.c1); pc += sizeof(real);
code_byte(code.m.c2);
code_byte(code.m.c3);
code_byte(code.m.c4);
} }
static void code_code (TFunc *tf) static void code_code (TFunc *tf)
{ {
CodeCode code; check_space(sizeof(TFunc *));
code.tf = tf; memcpy(basepc+pc, &tf, sizeof(TFunc *));
code_byte(code.m.c1); pc += sizeof(TFunc *);
code_byte(code.m.c2);
code_byte(code.m.c3);
code_byte(code.m.c4);
} }
static void code_word_at (Byte *p, int n) static void code_word_at (Byte *p, int n)
{ {
CodeWord code; Word w = n;
if ((Word)n != n) if (w != n)
yyerror("block too big"); yyerror("block too big");
code.w = (Word)n; memcpy(p, &w, sizeof(Word));
*p++ = code.m.c1;
*p++ = code.m.c2;
} }
static void push_field (Word name) static void push_field (Word name)
@@ -322,6 +319,19 @@ static void adjust_mult_assign (int vars, Long exps, int temps)
lua_codeadjust(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) static void storesinglevar (Long v)
{ {
if (v > 0) /* global var */ if (v > 0) /* global var */
@@ -418,7 +428,7 @@ void lua_parse (TFunc *tf)
TaggedString *pTStr; TaggedString *pTStr;
} }
%start functionlist %start chunk
%token WRONGTOKEN %token WRONGTOKEN
%token NIL %token NIL
@@ -426,10 +436,10 @@ void lua_parse (TFunc *tf)
%token RETURN %token RETURN
%token LOCAL %token LOCAL
%token FUNCTION %token FUNCTION
%token DOTS
%token <vFloat> NUMBER %token <vFloat> NUMBER
%token <vWord> STRING %token <vWord> STRING
%token <pTStr> NAME %token <pTStr> NAME
%token <vInt> DEBUG
%type <vLong> PrepJump %type <vLong> PrepJump
%type <vLong> exprlist, exprlist1 /* if > 0, points to function return %type <vLong> exprlist, exprlist1 /* if > 0, points to function return
@@ -440,7 +450,7 @@ void lua_parse (TFunc *tf)
%type <vInt> fieldlist, localdeclist, decinit %type <vInt> fieldlist, localdeclist, decinit
%type <vInt> ffieldlist, ffieldlist1, semicolonpart %type <vInt> ffieldlist, ffieldlist1, semicolonpart
%type <vInt> lfieldlist, lfieldlist1 %type <vInt> lfieldlist, lfieldlist1
%type <vInt> parlist %type <vInt> parlist, parlist1, par
%type <vLong> var, singlevar, funcname %type <vLong> var, singlevar, funcname
%type <pFunc> body %type <pFunc> body
@@ -455,15 +465,12 @@ void lua_parse (TFunc *tf)
%% /* beginning of rules section */ %% /* beginning of rules section */
chunk : chunklist ret
functionlist : /* empty */ chunklist : /* empty */
| functionlist globalstat | chunklist stat sc
| functionlist function | chunklist function
; ;
globalstat : stat sc
| setdebug
;
function : FUNCTION funcname body function : FUNCTION funcname body
{ {
@@ -580,6 +587,7 @@ PrepJump : /* empty */
code_byte(0); /* open space */ code_byte(0); /* open space */
code_word (0); code_word (0);
} }
;
expr1 : expr { adjust_functioncall($1, 1); } expr1 : expr { adjust_functioncall($1, 1); }
; ;
@@ -674,13 +682,22 @@ exprlist1 : expr { if ($1 != 0) $$ = $1; else $$ = -1; }
} }
; ;
parlist : /* empty */ { lua_codeadjust(0); $$ = lua_linenumber; } parlist : /* empty */ { $$ = close_parlist(0); }
| parlist1 { lua_codeadjust(0); $$ = lua_linenumber; } | parlist1 { $$ = close_parlist($1); }
; ;
parlist1 : NAME { add_localvar($1); } parlist1 : par { $$ = $1; }
| parlist1 ',' NAME { add_localvar($3); } | parlist1 ',' par
{
if ($1)
lua_error("invalid parameter list");
$$ = $3;
}
; ;
par : NAME { add_localvar($1); $$ = 0; }
| DOTS { $$ = 1; }
;
fieldlist : lfieldlist fieldlist : lfieldlist
{ flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); } { flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); }
@@ -782,7 +799,4 @@ decinit : /* empty */ { $$ = 0; }
| '=' exprlist1 { $$ = $2; } | '=' exprlist1 { $$ = $2; }
; ;
setdebug : DEBUG { lua_debug = $1; }
;
%% %%

View File

@@ -2,7 +2,7 @@
** Libraries to be used in LUA programs ** Libraries to be used in LUA programs
** Grupo de Tecnologia em Computacao Grafica ** Grupo de Tecnologia em Computacao Grafica
** TeCGraf - PUC-Rio ** TeCGraf - PUC-Rio
** $Id: lualib.h,v 1.7 1996/03/14 15:53:09 roberto Exp roberto $ ** $Id: lualib.h,v 1.9 1996/08/01 14:55:33 roberto Exp roberto $
*/ */
#ifndef lualib_h #ifndef lualib_h
@@ -23,11 +23,16 @@ struct lua_reg {
}; };
void luaI_openlib (struct lua_reg *l, int n); void luaI_openlib (struct lua_reg *l, int n);
void lua_arg_error(char *funcname); void lua_arg_check(int cond, char *funcname);
char *lua_check_string (int numArg, 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); double lua_check_number (int numArg, char *funcname);
long lua_opt_number (int numArg, long def, char *funcname);
char *luaI_addchar (int c); char *luaI_addchar (int c);
void luaI_addquoted (char *s); void luaI_addquoted (char *s);
char *item_end (char *p);
int singlematch (int c, char *p);
#endif #endif

View File

@@ -3,7 +3,7 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_mem = "$Id: mem.c,v 1.11 1996/03/21 18:54:29 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 <stdlib.h>
@@ -11,9 +11,6 @@ char *rcs_mem = "$Id: mem.c,v 1.11 1996/03/21 18:54:29 roberto Exp roberto $";
#include "lua.h" #include "lua.h"
#define mem_error() lua_error(memEM)
void luaI_free (void *block) void luaI_free (void *block)
{ {
if (block) if (block)
@@ -24,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 *luaI_realloc (void *oldblock, unsigned long size)
{ {
void *block = oldblock ? realloc(oldblock, (size_t)size) : void *block;
malloc((size_t)size); 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) if (block == NULL)
mem_error(); lua_error(memEM);
return block; return block;
} }
@@ -52,7 +43,7 @@ int luaI_growvector (void **block, unsigned long nelems, int size,
if (nelems > limit) if (nelems > limit)
nelems = limit; nelems = limit;
*block = luaI_realloc(*block, nelems*size); *block = luaI_realloc(*block, nelems*size);
return (int) nelems; return (int)nelems;
} }

View File

@@ -1,7 +1,7 @@
/* /*
** mem.c ** mem.c
** memory manager for lua ** memory manager for lua
** $Id: mem.h,v 1.6 1996/03/21 18:54:29 roberto Exp roberto $ ** $Id: mem.h,v 1.7 1996/04/22 18:00:37 roberto Exp roberto $
*/ */
#ifndef mem_h #ifndef mem_h
@@ -24,12 +24,12 @@
void luaI_free (void *block); void luaI_free (void *block);
void *luaI_malloc (unsigned long size);
void *luaI_realloc (void *oldblock, unsigned long size); void *luaI_realloc (void *oldblock, unsigned long size);
void *luaI_buffer (unsigned long size); void *luaI_buffer (unsigned long size);
int luaI_growvector (void **block, unsigned long nelems, int size, int luaI_growvector (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit); char *errormsg, unsigned long limit);
#define luaI_malloc(s) luaI_realloc(NULL, (s))
#define new(s) ((s *)luaI_malloc(sizeof(s))) #define new(s) ((s *)luaI_malloc(sizeof(s)))
#define newvector(n,s) ((s *)luaI_malloc((n)*sizeof(s))) #define newvector(n,s) ((s *)luaI_malloc((n)*sizeof(s)))
#define growvector(old,n,s,e,l) \ #define growvector(old,n,s,e,l) \

View File

@@ -1,13 +1,15 @@
# $Id: makefile,v 1.25 1996/05/06 14:38:40 roberto Exp $ # $Id: makefile,v 1.27 1996/08/28 20:45:48 roberto Exp roberto $
#configuration #configuration
# define (undefine) POPEN if your system (does not) support piped I/O # define (undefine) POPEN if your system (does not) support piped I/O
# define (undefine) POSIX if your system is (not) POSIX compliant # define (undefine) _POSIX_SOURCE if your system is (not) POSIX compliant
CONFIG = -DPOPEN -DPOSIX #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 # Compilation parameters
CC = gcc CC = gcc
CFLAGS = $(CONFIG) -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2 CFLAGS = $(CONFIG) -Wall -Wmissing-prototypes -Wshadow -ansi -O2 -pedantic
#CC = acc #CC = acc
#CFLAGS = -fast -I/usr/5include #CFLAGS = -fast -I/usr/5include
@@ -15,6 +17,7 @@ CFLAGS = $(CONFIG) -I/usr/5include -Wall -Wmissing-prototypes -Wshadow -ansi -O2
AR = ar AR = ar
ARFLAGS = rvl ARFLAGS = rvl
# Aplication modules # Aplication modules
LUAOBJS = \ LUAOBJS = \
parser.o \ parser.o \
@@ -35,28 +38,28 @@ LIBOBJS = \
strlib.o strlib.o
lua : lua.o lua.a lualib.a lua : lua.o liblua.a liblualib.a
$(CC) $(CFLAGS) -o $@ lua.o lua.a lualib.a -lm $(CC) $(CFLAGS) -o $@ lua.o -L. -llua -llualib -lm
lua.a : $(LUAOBJS) liblua.a : $(LUAOBJS)
$(AR) $(ARFLAGS) $@ $? $(AR) $(ARFLAGS) $@ $?
ranlib lua.a ranlib $@
lualib.a : $(LIBOBJS) liblualib.a : $(LIBOBJS)
$(AR) $(ARFLAGS) $@ $? $(AR) $(ARFLAGS) $@ $?
ranlib $@ ranlib $@
liblua.so.1.0 : lua.o liblua.so.1.0 : lua.o
ld -o liblua.so.1.0 $(LUAOBJS) ld -o liblua.so.1.0 $(LUAOBJS)
#y.tab.c y.tab.h : lua.stx y.tab.c y.tab.h : lua.stx
# yacc++ -d lua.stx yacc -d lua.stx
#parser.c : y.tab.c parser.c : y.tab.c
# sed -e 's/yy/luaY_/g' -e 's/malloc\.h/stdlib\.h/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 parser.h : y.tab.h
# sed -e 's/yy/luaY_/g' y.tab.h > parser.h sed -e 's/yy/luaY_/g' y.tab.h > parser.h
clear : clear :
rcsclean rcsclean
@@ -65,8 +68,11 @@ clear :
co lua.h lualib.h luadebug.h co lua.h lualib.h luadebug.h
#% : RCS/%,v %.h : RCS/%.h,v
# co $@ co $@
%.c : RCS/%.c,v
co $@
fallback.o : fallback.c mem.h fallback.h lua.h opcode.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 \
@@ -80,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 luadebug.h parser.h
lua.o : lua.c lua.h lualib.h lua.o : lua.c lua.h lualib.h
mathlib.o : mathlib.c lualib.h lua.h mathlib.o : mathlib.c lualib.h lua.h
mem.o : mem.c mem.h lua.h 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 \ 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 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 \ 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 ** Mathematics library to LUA
*/ */
char *rcs_mathlib="$Id: mathlib.c,v 1.16 1996/04/25 14:10:00 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 <stdlib.h>
#include <math.h> #include <math.h>
@@ -92,9 +92,9 @@ static void math_floor (void)
static void math_mod (void) static void math_mod (void)
{ {
int d1 = (int)lua_check_number(1, "mod"); float x = lua_check_number(1, "mod");
int d2 = (int)lua_check_number(2, "mod"); float y = lua_check_number(2, "mod");
lua_pushnumber (d1%d2); lua_pushnumber(fmod(x, y));
} }

275
opcode.c
View File

@@ -3,11 +3,12 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_opcode="$Id: opcode.c,v 3.67 1996/04/22 18:00:37 roberto Exp roberto $"; char *rcs_opcode="$Id: opcode.c,v 3.75 1996/09/24 17:30:28 roberto Exp roberto $";
#include <setjmp.h> #include <setjmp.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdlib.h>
#include "luadebug.h" #include "luadebug.h"
#include "mem.h" #include "mem.h"
@@ -49,10 +50,14 @@ static Object *top = &initial_stack;
*/ */
#define incr_top if (++top >= stackLimit) growstack() #define incr_top if (++top >= stackLimit) growstack()
static StkId CBase = 0; /* when Lua calls C or C calls Lua, points to */ struct C_Lua_Stack {
/* the first slot after the last parameter. */ StkId base; /* when Lua calls C or C calls Lua, points to */
static int CnResults = 0; /* when Lua calls C, has the number of parameters; */ /* the first slot after the last parameter. */
/* when C calls Lua, has the number of results. */ 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 */ 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) 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); char *buffer = luaI_buffer(nl+strlen(r)+1);
strcpy(buffer, l); strcpy(buffer, l);
strcpy(buffer+nl, r); strcpy(buffer+nl, r);
@@ -177,7 +182,7 @@ static void adjust_top (StkId newtop)
top = nt; /* top could be bigger than 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) static void lineHook (int line)
{ {
StkId oldBase = CBase; struct C_Lua_Stack oldCLS = CLS_current;
int oldCnResults = CnResults; StkId old_top = CLS_current.base = top-stack;
StkId old_top = CBase = top-stack; CLS_current.num = 0;
CnResults = 0;
(*lua_linehook)(line); (*lua_linehook)(line);
top = stack+old_top; top = stack+old_top;
CnResults = oldCnResults; CLS_current = oldCLS;
CBase = oldBase;
} }
@@ -214,10 +217,9 @@ static void lineHook (int line)
*/ */
static void callHook (StkId base, lua_Type type, int isreturn) static void callHook (StkId base, lua_Type type, int isreturn)
{ {
StkId oldBase = CBase; struct C_Lua_Stack oldCLS = CLS_current;
int oldCnResults = CnResults; StkId old_top = CLS_current.base = top-stack;
StkId old_top = CBase = top-stack; CLS_current.num = 0;
CnResults = 0;
if (isreturn) if (isreturn)
(*lua_callhook)(LUA_NOOBJECT, "(return)", 0); (*lua_callhook)(LUA_NOOBJECT, "(return)", 0);
else else
@@ -229,32 +231,29 @@ static void callHook (StkId base, lua_Type type, int isreturn)
(*lua_callhook)(Ref(f), "(C)", -1); (*lua_callhook)(Ref(f), "(C)", -1);
} }
top = stack+old_top; top = stack+old_top;
CnResults = oldCnResults; CLS_current = oldCLS;
CBase = oldBase;
} }
/* /*
** Call a C function. CBase will point to the top of the stack, ** Call a C function. CLS_current.base will point to the top of the stack,
** and CnResults is the number of parameters. Returns an index ** and CLS_current.num is the number of parameters. Returns an index
** to the first result from C. ** to the first result from C.
*/ */
static StkId callC (lua_CFunction func, StkId base) static StkId callC (lua_CFunction func, StkId base)
{ {
StkId oldBase = CBase; struct C_Lua_Stack oldCLS = CLS_current;
int oldCnResults = CnResults;
StkId firstResult; StkId firstResult;
CnResults = (top-stack) - base; CLS_current.num = (top-stack) - base;
/* incorporate parameters on the stack */ /* incorporate parameters on the stack */
CBase = base+CnResults; /* == top-stack */ CLS_current.base = base+CLS_current.num; /* == top-stack */
if (lua_callhook) if (lua_callhook)
callHook(base, LUA_T_CMARK, 0); callHook(base, LUA_T_CMARK, 0);
(*func)(); (*func)();
if (lua_callhook) /* func may have changed lua_callhook */ if (lua_callhook) /* func may have changed lua_callhook */
callHook(base, LUA_T_CMARK, 1); callHook(base, LUA_T_CMARK, 1);
firstResult = CBase; firstResult = CLS_current.base;
CBase = oldBase; CLS_current = oldCLS;
CnResults = oldCnResults;
return firstResult; 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 ** Execute a protected call. Assumes that function is at CLS_current.base and
** parameters are on top of it. Leave nResults on the stack. ** parameters are on top of it. Leave nResults on the stack.
*/ */
static int do_protectedrun (int nResults) static int do_protectedrun (int nResults)
{ {
jmp_buf myErrorJmp; jmp_buf myErrorJmp;
int status; int status;
StkId oldCBase = CBase; struct C_Lua_Stack oldCLS = CLS_current;
jmp_buf *oldErr = errorJmp; jmp_buf *oldErr = errorJmp;
errorJmp = &myErrorJmp; errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0) if (setjmp(myErrorJmp) == 0)
{ {
do_call(CBase+1, nResults); do_call(CLS_current.base+1, nResults);
CnResults = (top-stack) - CBase; /* number of results */ CLS_current.num = (top-stack) - CLS_current.base; /* number of results */
CBase += CnResults; /* incorporate results on the stack */ CLS_current.base += CLS_current.num; /* incorporate results on the stack */
status = 0; status = 0;
} }
else else
{ /* an error occurred: restore CBase and top */ { /* an error occurred: restore CLS_current and top */
CBase = oldCBase; CLS_current = oldCLS;
top = stack+CBase; top = stack+CLS_current.base;
status = 1; status = 1;
} }
errorJmp = oldErr; errorJmp = oldErr;
@@ -480,10 +479,9 @@ int luaI_dorun (TFunc *tf)
{ {
int status; int status;
adjustC(1); /* one slot for the pseudo-function */ adjustC(1); /* one slot for the pseudo-function */
stack[CBase].tag = LUA_T_FUNCTION; stack[CLS_current.base].tag = LUA_T_FUNCTION;
stack[CBase].value.tf = tf; stack[CLS_current.base].value.tf = tf;
status = do_protectedrun(0); status = do_protectedrun(MULT_RET);
adjustC(0);
return status; return status;
} }
@@ -521,8 +519,8 @@ int lua_callfunction (lua_Object function)
return 1; return 1;
else else
{ {
open_stack((top-stack)-CBase); open_stack((top-stack)-CLS_current.base);
stack[CBase] = *Address(function); stack[CLS_current.base] = *Address(function);
return do_protectedrun (MULT_RET); return do_protectedrun (MULT_RET);
} }
} }
@@ -531,15 +529,15 @@ int lua_callfunction (lua_Object function)
int lua_call (char *funcname) int lua_call (char *funcname)
{ {
Word n = luaI_findsymbolbyname(funcname); Word n = luaI_findsymbolbyname(funcname);
open_stack((top-stack)-CBase); open_stack((top-stack)-CLS_current.base);
stack[CBase] = s_object(n); stack[CLS_current.base] = s_object(n);
return do_protectedrun(MULT_RET); return do_protectedrun(MULT_RET);
} }
/* /*
** Open file, generate opcode and execute global statement. Return 0 on ** 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) int lua_dofile (char *filename)
{ {
@@ -547,22 +545,30 @@ int lua_dofile (char *filename)
int c; int c;
FILE *f = lua_openfile(filename); FILE *f = lua_openfile(filename);
if (f == NULL) if (f == NULL)
return 1; return 2;
c = fgetc(f); c = fgetc(f);
ungetc(c, f); ungetc(c, f);
status = (c == ID_CHUNK) ? luaI_undump(f) : do_protectedmain(); if (c == ID_CHUNK)
status = luaI_undump(f);
else {
if (c == '#')
while ((c=fgetc(f)) != '\n') /* skip first line */;
status = do_protectedmain();
}
lua_closefile(); lua_closefile();
return status; return status;
} }
/* /*
** Generate opcode stored on string and execute global statement. Return 0 on ** 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; int status;
lua_openstring(string); if (str == NULL)
return 1;
lua_openstring(str);
status = do_protectedmain(); status = do_protectedmain();
lua_closestring(); lua_closestring();
return status; return status;
@@ -575,8 +581,8 @@ int lua_dostring (char *string)
lua_Object lua_setfallback (char *name, lua_CFunction fallback) lua_Object lua_setfallback (char *name, lua_CFunction fallback)
{ {
adjustC(1); /* one slot for the pseudo-function */ adjustC(1); /* one slot for the pseudo-function */
stack[CBase].tag = LUA_T_CFUNCTION; stack[CLS_current.base].tag = LUA_T_CFUNCTION;
stack[CBase].value.f = luaI_setfallback; stack[CLS_current.base].value.f = luaI_setfallback;
lua_pushstring(name); lua_pushstring(name);
lua_pushcfunction(fallback); lua_pushcfunction(fallback);
if (do_protectedrun(1) == 0) if (do_protectedrun(1) == 0)
@@ -594,7 +600,7 @@ lua_Object lua_getsubscript (void)
{ {
adjustC(2); adjustC(2);
pushsubscript(); pushsubscript();
CBase++; /* incorporate object in the stack */ CLS_current.base++; /* incorporate object in the stack */
return (Ref(top-1)); return (Ref(top-1));
} }
@@ -602,7 +608,7 @@ lua_Object lua_getsubscript (void)
#define MAX_C_BLOCKS 10 #define MAX_C_BLOCKS 10
static int numCblocks = 0; static int numCblocks = 0;
static StkId Cblocks[MAX_C_BLOCKS]; static struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];
/* /*
** API: starts a new block ** API: starts a new block
@@ -611,7 +617,7 @@ void lua_beginblock (void)
{ {
if (numCblocks >= MAX_C_BLOCKS) if (numCblocks >= MAX_C_BLOCKS)
lua_error("`lua_beginblock': too many nested blocks"); lua_error("`lua_beginblock': too many nested blocks");
Cblocks[numCblocks] = CBase; Cblocks[numCblocks] = CLS_current;
numCblocks++; numCblocks++;
} }
@@ -621,7 +627,7 @@ void lua_beginblock (void)
void lua_endblock (void) void lua_endblock (void)
{ {
--numCblocks; --numCblocks;
CBase = Cblocks[numCblocks]; CLS_current = Cblocks[numCblocks];
adjustC(0); adjustC(0);
} }
@@ -643,7 +649,7 @@ lua_Object lua_createtable (void)
avalue(top) = lua_createarray(0); avalue(top) = lua_createarray(0);
tag(top) = LUA_T_ARRAY; tag(top) = LUA_T_ARRAY;
incr_top; incr_top;
CBase++; /* incorporate object in the stack */ CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1); return Ref(top-1);
} }
@@ -653,10 +659,10 @@ lua_Object lua_createtable (void)
*/ */
lua_Object lua_getparam (int number) lua_Object lua_getparam (int number)
{ {
if (number <= 0 || number > CnResults) return LUA_NOOBJECT; if (number <= 0 || number > CLS_current.num) return LUA_NOOBJECT;
/* Ref(stack+(CBase-CnResults+number-1)) == /* Ref(stack+(CLS_current.base-CLS_current.num+number-1)) ==
stack+(CBase-CnResults+number-1)-stack+1 == */ stack+(CLS_current.base-CLS_current.num+number-1)-stack+1 == */
return CBase-CnResults+number; return CLS_current.base-CLS_current.num+number;
} }
int lua_isnumber (lua_Object object) int lua_isnumber (lua_Object object)
@@ -673,7 +679,8 @@ int lua_isstring (lua_Object object)
int lua_isfunction (lua_Object object) int lua_isfunction (lua_Object object)
{ {
int t = lua_type(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 +708,8 @@ char *lua_getstring (lua_Object object)
*/ */
lua_CFunction lua_getcfunction (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; return NULL;
else return (fvalue(Address(object))); else return (fvalue(Address(object)));
} }
@@ -724,7 +732,7 @@ lua_Object lua_getref (int ref)
return LUA_NOOBJECT; return LUA_NOOBJECT;
adjustC(0); adjustC(0);
luaI_pushobject(o); luaI_pushobject(o);
CBase++; /* incorporate object in the stack */ CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1); return Ref(top-1);
} }
@@ -753,7 +761,7 @@ lua_Object lua_getglobal (char *name)
{ {
adjustC(0); adjustC(0);
getglobal(luaI_findsymbolbyname(name)); getglobal(luaI_findsymbolbyname(name));
CBase++; /* incorporate object in the stack */ CLS_current.base++; /* incorporate object in the stack */
return Ref(top-1); return Ref(top-1);
} }
@@ -838,7 +846,10 @@ void lua_pushobject (lua_Object o)
{ {
if (o == LUA_NOOBJECT) if (o == LUA_NOOBJECT)
lua_error("attempt to push a NOOBJECT"); lua_error("attempt to push a NOOBJECT");
luaI_pushobject(Address(o)); *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) int lua_type (lua_Object o)
@@ -886,6 +897,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 ** Execute the given opcode, until a RET. Parameters are between
@@ -914,38 +953,38 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHWORD: case PUSHWORD:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = code.w; tag(top) = LUA_T_NUMBER; nvalue(top) = w;
incr_top; incr_top;
} }
break; break;
case PUSHFLOAT: case PUSHFLOAT:
{ {
CodeFloat code; real num;
get_float(code,pc); get_float(num,pc);
tag(top) = LUA_T_NUMBER; nvalue(top) = code.f; tag(top) = LUA_T_NUMBER; nvalue(top) = num;
incr_top; incr_top;
} }
break; break;
case PUSHSTRING: case PUSHSTRING:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w]; tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
incr_top; incr_top;
} }
break; break;
case PUSHFUNCTION: case PUSHFUNCTION:
{ {
CodeCode code; TFunc *f;
get_code(code,pc); get_code(f,pc);
luaI_insertfunction(code.tf); /* may take part in GC */ luaI_insertfunction(f); /* may take part in GC */
top->tag = LUA_T_FUNCTION; top->tag = LUA_T_FUNCTION;
top->value.tf = code.tf; top->value.tf = f;
incr_top; incr_top;
} }
break; break;
@@ -960,9 +999,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHGLOBAL: case PUSHGLOBAL:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
getglobal(code.w); getglobal(w);
} }
break; break;
@@ -973,9 +1012,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case PUSHSELF: case PUSHSELF:
{ {
Object receiver = *(top-1); Object receiver = *(top-1);
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w]; tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
incr_top; incr_top;
pushsubscript(); pushsubscript();
*top = receiver; *top = receiver;
@@ -994,9 +1033,9 @@ static StkId lua_execute (Byte *pc, StkId base)
case STOREGLOBAL: case STOREGLOBAL:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
s_object(code.w) = *(--top); s_object(w) = *(--top);
} }
break; break;
@@ -1050,9 +1089,9 @@ static StkId lua_execute (Byte *pc, StkId base)
Object *arr = top-n-1; Object *arr = top-n-1;
while (n) while (n)
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[code.w]; tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
*(lua_hashdefine (avalue(arr), top)) = *(top-1); *(lua_hashdefine (avalue(arr), top)) = *(top-1);
top--; top--;
n--; n--;
@@ -1068,11 +1107,15 @@ static StkId lua_execute (Byte *pc, StkId base)
adjust_top(base + *(pc++)); adjust_top(base + *(pc++));
break; break;
case VARARGS:
adjust_varargs(base + *(pc++));
break;
case CREATEARRAY: case CREATEARRAY:
{ {
CodeWord size; Word size;
get_word(size,pc); get_word(size,pc);
avalue(top) = lua_createarray(size.w); avalue(top) = lua_createarray(size);
tag(top) = LUA_T_ARRAY; tag(top) = LUA_T_ARRAY;
incr_top; incr_top;
} }
@@ -1195,51 +1238,51 @@ static StkId lua_execute (Byte *pc, StkId base)
case ONTJMP: case ONTJMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
if (tag(top-1) != LUA_T_NIL) pc += code.w; if (tag(top-1) != LUA_T_NIL) pc += w;
} }
break; break;
case ONFJMP: case ONFJMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
if (tag(top-1) == LUA_T_NIL) pc += code.w; if (tag(top-1) == LUA_T_NIL) pc += w;
} }
break; break;
case JMP: case JMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
pc += code.w; pc += w;
} }
break; break;
case UPJMP: case UPJMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
pc -= code.w; pc -= w;
} }
break; break;
case IFFJMP: case IFFJMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
top--; top--;
if (tag(top) == LUA_T_NIL) pc += code.w; if (tag(top) == LUA_T_NIL) pc += w;
} }
break; break;
case IFFUPJMP: case IFFUPJMP:
{ {
CodeWord code; Word w;
get_word(code,pc); get_word(w,pc);
top--; top--;
if (tag(top) == LUA_T_NIL) pc -= code.w; if (tag(top) == LUA_T_NIL) pc -= w;
} }
break; break;
@@ -1262,8 +1305,8 @@ static StkId lua_execute (Byte *pc, StkId base)
case SETLINE: case SETLINE:
{ {
CodeWord code; Word line;
get_word(code,pc); get_word(line,pc);
if ((stack+base-1)->tag != LUA_T_LINE) if ((stack+base-1)->tag != LUA_T_LINE)
{ {
/* open space for LINE value */ /* open space for LINE value */
@@ -1271,9 +1314,9 @@ static StkId lua_execute (Byte *pc, StkId base)
base++; base++;
(stack+base-1)->tag = LUA_T_LINE; (stack+base-1)->tag = LUA_T_LINE;
} }
(stack+base-1)->value.i = code.w; (stack+base-1)->value.i = line;
if (lua_linehook) if (lua_linehook)
lineHook (code.w); lineHook (line);
break; break;
} }

155
opcode.h
View File

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

520
strlib.c
View File

@@ -3,134 +3,151 @@
** String library to LUA ** String library to LUA
*/ */
char *rcs_strlib="$Id: strlib.c,v 1.22 1996/03/22 17:57:24 roberto Exp roberto $"; char *rcs_strlib="$Id: strlib.c,v 1.30 1996/10/31 17:26:04 roberto Exp roberto $";
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
#include <limits.h>
#include "lua.h" #include "lua.h"
#include "lualib.h" #include "lualib.h"
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]; if (size > lbuffer.max) {
sprintf(buff, "incorrect arguments to function `%s'", funcname); /* ANSI "realloc" doesn't need this test, but some machines (Sun!)
lua_error(buff); 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) char *lua_check_string (int numArg, char *funcname)
{ {
lua_Object o = lua_getparam(numArg); lua_Object o = lua_getparam(numArg);
if (!lua_isstring(o)) lua_arg_check(lua_isstring(o), funcname);
lua_arg_error(funcname);
return lua_getstring(o); 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) double lua_check_number (int numArg, char *funcname)
{ {
lua_Object o = lua_getparam(numArg); lua_Object o = lua_getparam(numArg);
if (!lua_isnumber(o)) lua_arg_check(lua_isnumber(o), funcname);
lua_arg_error(funcname);
return lua_getnumber(o); 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 : return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
(int)lua_check_number(numArg, funcname); (long)lua_check_number(numArg, funcname);
} }
char *luaI_addchar (int c) char *luaI_addchar (int c)
{ {
static char *buff = NULL; if (lbuffer.size >= lbuffer.max)
static int max = 0; lua_strbuffer(lbuffer.max == 0 ? 100 : lbuffer.max*2);
static int n = 0; lbuffer.b[lbuffer.size++] = c;
if (n >= max)
{
if (max == 0)
{
max = 100;
buff = (char *)malloc(max);
}
else
{
max *= 2;
buff = (char *)realloc(buff, max);
}
if (buff == NULL)
lua_error("memory overflow");
}
buff[n++] = c;
if (c == 0) if (c == 0)
n = 0; /* prepare for next string */ lbuffer.size = 0; /* prepare for next string */
return buff; 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 ** Interface to strtok
** LUA interface:
** n = strfind (string, substring, init, end)
*/ */
static void str_find (void) static void str_tok (void)
{ {
char *s1 = lua_check_string(1, "strfind"); char *s1 = lua_check_string(1, "strtok");
char *s2 = lua_check_string(2, "strfind"); char *del = lua_check_string(2, "strtok");
int init = lua_opt_number(3, 1, "strfind") - 1; lua_Object t = lua_createtable();
char *f = (init>=0 && init<=strlen(s1)) ? strstr(s1+init,s2) : NULL; int i = 1;
if (f != NULL) /* As strtok changes s1, and s1 is "constant", make a copy of it */
{ s1 = strcpy(lua_strbuffer(strlen(s1+1)), s1);
int pos = f-s1+1; while ((s1 = strtok(s1, del)) != NULL) {
if (lua_opt_number(4, INT_MAX, "strfind") >= pos+strlen(s2)-1) lua_pushobject(t);
lua_pushnumber (pos); lua_pushnumber(i++);
else lua_pushstring(s1);
lua_pushnil(); lua_storesubscript();
} s1 = NULL; /* prepare for next strtok */
else }
lua_pushnil(); lua_pushobject(t);
lua_pushnumber(i-1); /* total number of tokens */
} }
/* /*
** Return the string length ** Return the string length
** LUA interface:
** n = strlen (string)
*/ */
static void str_len (void) static void str_len (void)
{ {
char *s = lua_check_string(1, "strlen"); lua_pushnumber(strlen(lua_check_string(1, "strlen")));
lua_pushnumber(strlen(s));
} }
/* /*
** Return the substring of a string, from start to end ** Return the substring of a string
** LUA interface:
** substring = strsub (string, start, end)
*/ */
static void str_sub (void) static void str_sub (void)
{ {
char *s = lua_check_string(1, "strsub"); char *s = lua_check_string(1, "strsub");
int start = (int)lua_check_number(2, "strsub"); long start = (long)lua_check_number(2, "strsub");
int end = lua_opt_number(3, strlen(s), "strsub"); long end = lua_opt_number(3, strlen(s), "strsub");
if (end < start || start < 1 || end > strlen(s)) if (1 <= start && start <= end && end <= strlen(s)) {
lua_pushliteral(""); luaI_addchar(0);
else addnchar(s+start-1, end-start+1);
{ lua_pushstring(luaI_addchar(0));
luaI_addchar(0); }
while (start <= end) else lua_pushliteral("");
luaI_addchar(s[start++ - 1]);
lua_pushstring (luaI_addchar(0));
}
} }
/* /*
** Convert a string to lower case. ** Convert a string to lower case.
** LUA interface:
** lowercase = strlower (string)
*/ */
static void str_lower (void) static void str_lower (void)
{ {
@@ -141,11 +158,8 @@ static void str_lower (void)
lua_pushstring(luaI_addchar(0)); lua_pushstring(luaI_addchar(0));
} }
/* /*
** Convert a string to upper case. ** Convert a string to upper case.
** LUA interface:
** uppercase = strupper (string)
*/ */
static void str_upper (void) static void str_upper (void)
{ {
@@ -156,93 +170,348 @@ static void str_upper (void)
lua_pushstring(luaI_addchar(0)); 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 ** get ascii value of a character in a string
*/ */
static void str_ascii (void) static void str_ascii (void)
{ {
char *s = lua_check_string(1, "ascii"); char *s = lua_check_string(1, "ascii");
int pos = lua_opt_number(2, 1, "ascii") - 1; long pos = lua_opt_number(2, 1, "ascii") - 1;
if (pos<0 || pos>=strlen(s)) lua_arg_check(0<=pos && pos<strlen(s), "ascii");
lua_arg_error("ascii"); lua_pushnumber((unsigned char)s[pos]);
lua_pushnumber(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; /* \0, EOF or other strange flags */
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 *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: /* possibly a capture (if followed by a digit) */
if (!isdigit(*(p+1))) goto dflt;
else {
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;
}
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) void luaI_addquoted (char *s)
{ {
luaI_addchar('"'); luaI_addchar('"');
for (; *s; s++) for (; *s; s++) {
{ if (strchr("\"\\\n", *s))
if (*s == '"' || *s == '\\' || *s == '\n')
luaI_addchar('\\'); luaI_addchar('\\');
luaI_addchar(*s); luaI_addchar(*s);
} }
luaI_addchar('"'); luaI_addchar('"');
} }
#define MAX_CONVERTION 2000 #define MAX_FORMAT 200
#define MAX_FORMAT 50
static void str_format (void) static void str_format (void)
{ {
int arg = 1; int arg = 1;
char *strfrmt = lua_check_string(arg++, "format"); char *strfrmt = lua_check_string(arg++, "format");
luaI_addchar(0); /* initialize */ luaI_addchar(0); /* initialize */
while (*strfrmt) while (*strfrmt) {
{
if (*strfrmt != '%') if (*strfrmt != '%')
luaI_addchar(*strfrmt++); luaI_addchar(*strfrmt++);
else if (*++strfrmt == '%') else if (*++strfrmt == '%')
luaI_addchar(*strfrmt++); /* %% */ luaI_addchar(*strfrmt++); /* %% */
else else { /* format item */
{ /* format item */
char form[MAX_FORMAT]; /* store the format ('%...') */ char form[MAX_FORMAT]; /* store the format ('%...') */
char buff[MAX_CONVERTION]; /* store the formated value */ char *buff;
int size = 0; char *initf = strfrmt-1; /* -1 to include % */
int i = 0; strfrmt = match(strfrmt, "[-+ #]*(%d*)%.?(%d*)", 0);
form[i++] = '%'; if (capture[0].len > 3 || capture[1].len > 3) /* < 1000? */
form[i] = *strfrmt++; lua_error("invalid format (width/precision too long)");
while (!isalpha(form[i])) strncpy(form, initf, strfrmt-initf+1); /* +1 to include convertion */
{ form[strfrmt-initf+1] = 0;
if (isdigit(form[i])) buff = openspace(1000); /* to store the formated value */
{ switch (*strfrmt++) {
size = size*10 + form[i]-'0';
if (size >= MAX_CONVERTION)
lua_error("format size/precision too long in function `format'");
}
else if (form[i] == '.')
size = 0; /* re-start */
if (++i >= MAX_FORMAT)
lua_error("bad format in function `format'");
form[i] = *strfrmt++;
}
form[i+1] = 0; /* ends string */
switch (form[i])
{
case 'q': case 'q':
luaI_addquoted(lua_check_string(arg++, "format")); luaI_addquoted(lua_check_string(arg++, "format"));
buff[0] = '\0'; /* addchar already done */
break; break;
case 's': case 's': {
{
char *s = lua_check_string(arg++, "format"); char *s = lua_check_string(arg++, "format");
if (strlen(s) >= MAX_CONVERTION) buff = openspace(strlen(s));
lua_error("string argument too long in function `format'"); lbuffer.size += sprintf(buff, form, s);
sprintf(buff, form, s);
break; break;
} }
case 'c': case 'd': case 'i': case 'o': case 'c': case 'd': case 'i': case 'o':
case 'u': case 'x': case 'X': case 'u': case 'x': case 'X':
sprintf(buff, form, (int)lua_check_number(arg++, "format")); lbuffer.size += sprintf(buff, form,
(int)lua_check_number(arg++, "format"));
break; break;
case 'e': case 'E': case 'f': case 'g': case 'e': case 'E': case 'f': case 'g':
sprintf(buff, form, lua_check_number(arg++, "format")); lbuffer.size += sprintf(buff, form,
lua_check_number(arg++, "format"));
break; break;
default: /* also treat cases 'pnLlh' */ default: /* also treat cases 'pnLlh' */
lua_error("invalid format option in function `format'"); lua_error("invalid format option in function `format'");
} }
for (i=0; buff[i]; i++) /* move formated value to result */
luaI_addchar(buff[i]);
} }
} }
lua_pushstring(luaI_addchar(0)); /* push the result */ lua_pushstring(luaI_addchar(0)); /* push the result */
@@ -256,14 +525,19 @@ void luaI_openlib (struct lua_reg *l, int n)
lua_register(l[i].name, l[i].func); lua_register(l[i].name, l[i].func);
} }
static struct lua_reg strlib[] = { static struct lua_reg strlib[] = {
{"strfind", str_find}, {"strtok", str_tok},
{"strlen", str_len}, {"strlen", str_len},
{"strsub", str_sub}, {"strsub", str_sub},
{"strset", str_set},
{"strlower", str_lower}, {"strlower", str_lower},
{"strupper", str_upper}, {"strupper", str_upper},
{"strrep", str_rep},
{"ascii", str_ascii}, {"ascii", str_ascii},
{"format", str_format} {"format", str_format},
{"strfind", str_find},
{"gsub", str_gsub}
}; };

17
table.c
View File

@@ -3,7 +3,7 @@
** Module to control static tables ** Module to control static tables
*/ */
char *rcs_table="$Id: table.c,v 2.53 1996/04/29 18:53:53 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 "mem.h"
#include "opcode.h" #include "opcode.h"
@@ -39,6 +39,7 @@ static struct {
lua_CFunction func; lua_CFunction func;
} int_funcs[] = { } int_funcs[] = {
{"assert", luaI_assert}, {"assert", luaI_assert},
{"call", luaI_call},
{"dofile", lua_internaldofile}, {"dofile", lua_internaldofile},
{"dostring", lua_internaldostring}, {"dostring", lua_internaldostring},
{"error", luaI_error}, {"error", luaI_error},
@@ -59,13 +60,16 @@ static struct {
void luaI_initsymbol (void) void luaI_initsymbol (void)
{ {
int i; int i;
Word n;
lua_maxsymbol = BUFFER_BLOCK; lua_maxsymbol = BUFFER_BLOCK;
lua_table = newvector(lua_maxsymbol, Symbol); lua_table = newvector(lua_maxsymbol, Symbol);
for (i=0; i<INTFUNCSIZE; i++) 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; 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);
} }
@@ -213,7 +217,7 @@ void lua_pack (void)
unsigned long recovered = 0; unsigned long recovered = 0;
if (nentity++ < block) return; if (nentity++ < block) return;
recovered = luaI_collectgarbage(); recovered = luaI_collectgarbage();
block = block*2*(1.0 - (float)recovered/nentity); block = 2*(block-recovered);
nentity -= recovered; nentity -= recovered;
} }
@@ -239,12 +243,7 @@ static void lua_nextvar (void)
else else
next = luaI_findsymbolbyname(lua_getstring(o)) + 1; next = luaI_findsymbolbyname(lua_getstring(o)) + 1;
while (next < lua_ntable && s_tag(next) == LUA_T_NIL) next++; while (next < lua_ntable && s_tag(next) == LUA_T_NIL) next++;
if (next >= lua_ntable) if (next < lua_ntable)
{
lua_pushnil();
lua_pushnil();
}
else
{ {
lua_pushstring(lua_table[next].varname->str); lua_pushstring(lua_table[next].varname->str);
luaI_pushobject(&s_object(next)); luaI_pushobject(&s_object(next));