History

Lua 5.3.0-work3

Lua Team committed 12 years ago

Commit f8a66271 parent ad386d945 files · +2323 −1590Browse files

Showing the changes to src/lua.c (1 of 45 files). Show all

Unified · Split

src/lua.c+223−153
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.c,v 1.210 2014/02/26 15:27:56 roberto Exp $
2+** $Id: lua.c,v 1.211 2014/06/05 20:42:06 roberto Exp $
33 ** Lua stand-alone interpreter
44 ** See Copyright Notice in lua.h
55 */
@@ -103,17 +103,24 @@ static lua_State *globalL = NULL; · 97 unmodified lines
103103 static const char *progname = LUA_PROGNAME;
104104
105105
106−
106+/*
107+** Hook set by signal function to stop the interpreter.
108+*/
107109 static void lstop (lua_State *L, lua_Debug *ar) {
108110 (void)ar; /* unused arg. */
109− lua_sethook(L, NULL, 0, 0);
111+ lua_sethook(L, NULL, 0, 0); /* reset hook */
110112 luaL_error(L, "interrupted!");
111113 }
112114
113115
116+/*
117+** Function to be called at a C signal. Because a C signal cannot
118+** just change a Lua state (as there is no proper syncronization),
119+** this function only sets a hook that, when called, will stop the
120+** interpreter.
121+*/
114122 static void laction (int i) {
115− signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
116− terminate process (default action) */
123+ signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
117124 lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
118125 }
119126
@@ -139,27 +146,23 @@ static void print_usage (const char *badoption) { · 19 unmodified lines
139146 }
140147
141148
149+/*
150+** Prints an error message, adding the program name in front of it
151+** (if present)
152+*/
142153 static void l_message (const char *pname, const char *msg) {
143154 if (pname) luai_writestringerror("%s: ", pname);
144155 luai_writestringerror("%s\n", msg);
145156 }
146157
147158
159+/*
160+** Check whether 'status' is not OK and, if so, prints the error
161+** message on the top of the stack. Because this function can be called
162+** unprotected, it only accepts actual strings as error messages. (A
163+** coercion could raise a memory error.)
164+*/
148165 static int report (lua_State *L, int status) {
149− if (status != LUA_OK && !lua_isnil(L, -1)) {
150− const char *msg = lua_tostring(L, -1);
151− if (msg == NULL) msg = "(error object is not a string)";
152− l_message(progname, msg);
153− lua_pop(L, 1);
154− /* force a complete garbage collection in case of errors */
155− lua_gc(L, LUA_GCCOLLECT, 0);
156− }
157− return status;
158−}
159−
160−
161−/* the next function is called unprotected, so it must avoid errors */
162−static void finalreport (lua_State *L, int status) {
163166 if (status != LUA_OK) {
164167 const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
165168 : NULL;
@@ -167,31 +170,39 @@ static void finalreport (lua_State *L, int status) { · 1 unmodified line
167170 l_message(progname, msg);
168171 lua_pop(L, 1);
169172 }
173+ return status;
170174 }
171175
172176
173−static int traceback (lua_State *L) {
177+/*
178+** Message handler to be used to run all chunks
179+*/
180+static int msghandler (lua_State *L) {
174181 const char *msg = lua_tostring(L, 1);
175− if (msg)
176− luaL_traceback(L, L, msg, 1);
177− else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */
182+ if (msg) /* is error object a string? */
183+ luaL_traceback(L, L, msg, 1); /* use standard traceback */
184+ else if (!lua_isnoneornil(L, 1)) { /* non-string error object? */
178185 if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
179186 lua_pushliteral(L, "(no error message)");
180− }
187+ } /* else no error object, does nothing */
181188 return 1;
182189 }
183190
184191
192+/*
193+** Interface to 'lua_pcall', which sets appropriate message function
194+** and C-signal handler. Used to run all chunks.
195+*/
185196 static int docall (lua_State *L, int narg, int nres) {
186197 int status;
187198 int base = lua_gettop(L) - narg; /* function index */
188− lua_pushcfunction(L, traceback); /* push traceback function */
189− lua_insert(L, base); /* put it under chunk and args */
199+ lua_pushcfunction(L, msghandler); /* push message handler */
200+ lua_insert(L, base); /* put it under function and args */
190201 globalL = L; /* to be available to 'laction' */
191− signal(SIGINT, laction);
202+ signal(SIGINT, laction); /* set C-signal handler */
192203 status = lua_pcall(L, narg, nres, base);
193− signal(SIGINT, SIG_DFL);
194− lua_remove(L, base); /* remove traceback function */
204+ signal(SIGINT, SIG_DFL); /* reset C-signal handler */
205+ lua_remove(L, base); /* remove message handler from the stack */
195206 return status;
196207 }
197208
@@ -202,38 +213,47 @@ static void print_version (void) { · 4 unmodified lines
202213 }
203214
204215
205−static int getargs (lua_State *L, char **argv, int n) {
206− int narg;
207− int i;
208− int argc = 0;
209− while (argv[argc]) argc++; /* count total number of arguments */
210− narg = argc - (n + 1); /* number of arguments to the script */
211− luaL_checkstack(L, narg + 3, "too many arguments to script");
212− for (i=n+1; i < argc; i++)
213− lua_pushstring(L, argv[i]);
214− lua_createtable(L, narg, n + 1);
215− for (i=0; i < argc; i++) {
216+/*
217+** Create the 'arg' table, which stores all arguments from the
218+** command line ('argv'). It should be aligned so that, at index 0,
219+** it has 'argv[script]', which is the script name. The arguments
220+** to the script (everything after 'script') go to positive indices;
221+** other arguments (before the script name) go to negative indices.
222+** If there is no script name, assume interpreter's name as base.
223+*/
224+static void createargtable (lua_State *L, char **argv, int argc, int script) {
225+ int i, narg;
226+ if (script == argc) script = 0; /* no script name? */
227+ narg = argc - (script + 1); /* number of positive indices */
228+ lua_createtable(L, narg, script + 1);
229+ for (i = 0; i < argc; i++) {
216230 lua_pushstring(L, argv[i]);
217− lua_rawseti(L, -2, i - n);
231+ lua_rawseti(L, -2, i - script);
218232 }
219− return narg;
233+ lua_setglobal(L, "arg");
220234 }
221235
222236
223−static int dofile (lua_State *L, const char *name) {
224− int status = luaL_loadfile(L, name);
237+static int dochunk (lua_State *L, int status) {
225238 if (status == LUA_OK) status = docall(L, 0, 0);
226239 return report(L, status);
227240 }
228241
229242
243+static int dofile (lua_State *L, const char *name) {
244+ return dochunk(L, luaL_loadfile(L, name));
245+}
246+
247+
230248 static int dostring (lua_State *L, const char *s, const char *name) {
231− int status = luaL_loadbuffer(L, s, strlen(s), name);
232− if (status == LUA_OK) status = docall(L, 0, 0);
233− return report(L, status);
249+ return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
234250 }
235251
236252
253+/*
254+** Calls 'require(name)' and stores the result in a global variable
255+** with the given name.
256+*/
237257 static int dolibrary (lua_State *L, const char *name) {
238258 int status;
239259 lua_getglobal(L, "require");
@@ -245,6 +265,9 @@ static int dolibrary (lua_State *L, const char *name) { · 5 unmodified lines
245265 }
246266
247267
268+/*
269+** Returns the string to be used as a prompt by the interpreter.
270+*/
248271 static const char *get_prompt (lua_State *L, int firstline) {
249272 const char *p;
250273 lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
@@ -257,6 +280,12 @@ static const char *get_prompt (lua_State *L, int firstline) { · 6 unmodified lines
257280 #define EOFMARK "<eof>"
258281 #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
259282
283+
284+/*
285+** Check whether 'status' signals a syntax error and the error
286+** message at the top of the stack ends with the above mark for
287+** incoplete statements.
288+*/
260289 static int incomplete (lua_State *L, int status) {
261290 if (status == LUA_ERRSYNTAX) {
262291 size_t lmsg;
@@ -270,7 +299,9 @@ static int incomplete (lua_State *L, int status) { · 7 unmodified lines
270299 }
271300
272301
273−/* prompt the user, read a line, and push it into the Lua stack */
302+/*
303+** Prompt the user, read a line, and push it into the Lua stack.
304+*/
274305 static int pushline (lua_State *L, int firstline) {
275306 char buffer[LUA_MAXINPUT];
276307 char *b = buffer;
@@ -292,8 +323,10 @@ static int pushline (lua_State *L, int firstline) { · 15 unmodified lines
292323 }
293324
294325
295−/* try to compile line on the stack as 'return <line>'; on return, stack
296− has either compiled chunk or original line (if compilation failed) */
326+/*
327+** Try to compile line on the stack as 'return <line>'; on return, stack
328+** has either compiled chunk or original line (if compilation failed).
329+*/
297330 static int addreturn (lua_State *L) {
298331 int status;
299332 size_t len; const char *line;
@@ -309,14 +342,16 @@ static int addreturn (lua_State *L) { · 9 unmodified lines
309342 }
310343
311344
312−/* read multiple lines until a complete line */
345+/*
346+** Read multiple lines until a complete Lua statement
347+*/
313348 static int multiline (lua_State *L) {
314− for (;;) { /* repeat until gets a complete line */
349+ for (;;) { /* repeat until gets a complete statement */
315350 size_t len;
316351 const char *line = lua_tolstring(L, 1, &len); /* get what it has */
317352 int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
318353 if (!incomplete(L, status) || !pushline(L, 0))
319− return status; /* cannot/should not try to add continuation line */
354+ return status; /* cannot or should not try to add continuation line */
320355 lua_pushliteral(L, "\n"); /* add newline... */
321356 lua_insert(L, -2); /* ...between the two lines */
322357 lua_concat(L, 3); /* join them */
@@ -324,6 +359,12 @@ static int multiline (lua_State *L) { · 1 unmodified line
324359 }
325360
326361
362+/*
363+** Read a line and try to load (compile) it first as an expression (by
364+** adding "return " in front of it) and second as a statement. Return
365+** the final status of load/call with the resulting function (if any)
366+** in the top of the stack.
367+*/
327368 static int loadline (lua_State *L) {
328369 int status;
329370 lua_settop(L, 0);
@@ -331,29 +372,43 @@ static int loadline (lua_State *L) { · 1 unmodified line
331372 return -1; /* no input */
332373 if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
333374 status = multiline(L); /* try as command, maybe with continuation lines */
334− lua_saveline(L, 1);
335− lua_remove(L, 1); /* remove line */
375+ lua_saveline(L, 1); /* keep history */
376+ lua_remove(L, 1); /* remove line from the stack */
336377 lua_assert(lua_gettop(L) == 1);
337378 return status;
338379 }
339380
340381
341−static void dotty (lua_State *L) {
382+/*
383+** Prints (calling the Lua 'print' function) any values on the stack
384+*/
385+static void l_print (lua_State *L) {
386+ int n = lua_gettop(L);
387+ if (n > 0) { /* any result to be printed? */
388+ luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
389+ lua_getglobal(L, "print");
390+ lua_insert(L, 1);
391+ if (lua_pcall(L, n, 0, 0) != LUA_OK)
392+ l_message(progname, lua_pushfstring(L,
393+ "error calling " LUA_QL("print") " (%s)",
394+ lua_tostring(L, -1)));
395+ }
396+}
397+
398+
399+/*
400+** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
401+** print any results.
402+*/
403+static void doREPL (lua_State *L) {
342404 int status;
343405 const char *oldprogname = progname;
344− progname = NULL;
406+ progname = NULL; /* no 'progname' on errors in interactive mode */
345407 while ((status = loadline(L)) != -1) {
346− if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
347− report(L, status);
348− if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
349− luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
350− lua_getglobal(L, "print");
351− lua_insert(L, 1);
352− if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
353− l_message(progname, lua_pushfstring(L,
354− "error calling " LUA_QL("print") " (%s)",
355− lua_tostring(L, -1)));
356− }
408+ if (status == LUA_OK)
409+ status = docall(L, 0, LUA_MULTRET);
410+ if (status == LUA_OK) l_print(L);
411+ else report(L, status);
357412 }
358413 lua_settop(L, 0); /* clear stack */
359414 luai_writeline();
@@ -361,97 +416,109 @@ static void dotty (lua_State *L) { · 1 unmodified line
361416 }
362417
363418
419+/*
420+** Push on the stack 'n' strings from 'argv'
421+*/
422+static void pushargs (lua_State *L, char **argv, int n) {
423+ int i;
424+ luaL_checkstack(L, n + 3, "too many arguments to script");
425+ for (i = 1; i < n; i++) /* skip 0 (the script name) */
426+ lua_pushstring(L, argv[i]);
427+}
428+
429+
364430 static int handle_script (lua_State *L, char **argv, int n) {
365431 int status;
366− const char *fname;
367− int narg = getargs(L, argv, n); /* collect arguments */
368− lua_setglobal(L, "arg");
369− fname = argv[n];
370− if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
432+ const char *fname = argv[0];
433+ if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
371434 fname = NULL; /* stdin */
372435 status = luaL_loadfile(L, fname);
373− lua_insert(L, -(narg+1));
374− if (status == LUA_OK)
375− status = docall(L, narg, LUA_MULTRET);
376− else
377− lua_pop(L, narg);
436+ if (status == LUA_OK) {
437+ pushargs(L, argv, n); /* push arguments to script */
438+ status = docall(L, n - 1, LUA_MULTRET);
439+ }
378440 return report(L, status);
379441 }
380442
381443
382−/* check that argument has no extra characters at the end */
383−#define noextrachars(x) {if ((x)[2] != '\0') return -1;}
384−
385−
386−/* indices of various argument indicators in array args */
387−#define has_i 0 /* -i */
388−#define has_v 1 /* -v */
389−#define has_e 2 /* -e */
390−#define has_E 3 /* -E */
391−
392−#define num_has 4 /* number of 'has_*' */
393444
445+/* bits of various argument indicators in 'args' */
446+#define has_error 1 /* bad option */
447+#define has_i 2 /* -i */
448+#define has_v 4 /* -v */
449+#define has_e 8 /* -e */
450+#define has_E 16 /* -E */
394451
395−static int collectargs (char **argv, int *args) {
452+/*
453+** Traverses all arguments from 'argv', returning a mask with those
454+** needed before running any Lua code (or an error code if it finds
455+** any invalid argument). 'first' returns the first not-handled argument
456+** (either the script name or a bad argument in case of error).
457+*/
458+static int collectargs (char **argv, int *first) {
459+ int args = 0;
396460 int i;
397461 for (i = 1; argv[i] != NULL; i++) {
462+ *first = i;
398463 if (argv[i][0] != '-') /* not an option? */
399− return i;
400− switch (argv[i][1]) { /* option */
401− case '-':
402− noextrachars(argv[i]);
403− return (argv[i+1] != NULL ? i+1 : 0);
404− case '\0':
405− return i;
464+ return args; /* stop handling options */
465+ switch (argv[i][1]) { /* else check option */
466+ case '-': /* '--' */
467+ if (argv[i][2] != '\0') /* extra characters after '--'? */
468+ return has_error; /* invalid option */
469+ *first = i + 1;
470+ return args;
471+ case '\0': /* '-' */
472+ return args; /* script "name" is '-' */
406473 case 'E':
407− args[has_E] = 1;
474+ if (argv[i][2] != '\0') /* extra characters after 1st? */
475+ return has_error; /* invalid option */
476+ args |= has_E;
408477 break;
409478 case 'i':
410− noextrachars(argv[i]);
411− args[has_i] = 1; /* go through */
479+ args |= has_i; /* goes through (-i implies -v) */
412480 case 'v':
413− noextrachars(argv[i]);
414− args[has_v] = 1;
481+ if (argv[i][2] != '\0') /* extra characters after 1st? */
482+ return has_error; /* invalid option */
483+ args |= has_v;
415484 break;
416485 case 'e':
417− args[has_e] = 1; /* go through */
486+ args |= has_e; /* go through */
418487 case 'l': /* both options need an argument */
419488 if (argv[i][2] == '\0') { /* no concatenated argument? */
420489 i++; /* try next 'argv' */
421490 if (argv[i] == NULL || argv[i][0] == '-')
422− return -(i - 1); /* no next argument or it is another option */
491+ return has_error; /* no next argument or it is another option */
423492 }
424493 break;
425− default: /* invalid option; return its index... */
426− return -i; /* ...as a negative value */
494+ default: /* invalid option */
495+ return has_error;
427496 }
428497 }
429− return 0;
498+ *first = i; /* no script name */
499+ return args;
430500 }
431501
432502
503+/*
504+** Processes options 'e' and 'l', which involve running Lua code.
505+** Returns 0 if some code raises an error.
506+*/
433507 static int runargs (lua_State *L, char **argv, int n) {
434508 int i;
435509 for (i = 1; i < n; i++) {
436− lua_assert(argv[i][0] == '-');
437− switch (argv[i][1]) { /* option */
438− case 'e': {
439− const char *chunk = argv[i] + 2;
440− if (*chunk == '\0') chunk = argv[++i];
441− lua_assert(chunk != NULL);
442− if (dostring(L, chunk, "=(command line)") != LUA_OK)
443− return 0;
444− break;
445− }
446− case 'l': {
447− const char *filename = argv[i] + 2;
448− if (*filename == '\0') filename = argv[++i];
449− lua_assert(filename != NULL);
450− if (dolibrary(L, filename) != LUA_OK)
451− return 0; /* stop if file fails */
452− break;
453− }
454− default: break;
510+ int status;
511+ int option = argv[i][1];
512+ lua_assert(argv[i][0] == '-'); /* already checked */
513+ if (option == 'e' || option == 'l') {
514+ const char *extra = argv[i] + 2; /* both options need an argument */
515+ if (*extra == '\0') extra = argv[++i];
516+ lua_assert(extra != NULL);
517+ if (option == 'e')
518+ status = dostring(L, extra, "=(command line)");
519+ else
520+ status = dolibrary(L, extra);
521+ if (status != LUA_OK) return 0;
455522 }
456523 }
457524 return 1;
@@ -473,40 +540,44 @@ static int handle_luainit (lua_State *L) { · 15 unmodified lines
473540 }
474541
475542
543+/*
544+** Main body of stand-alone interpreter (to be called in protected mode).
545+** Reads the options and handles them all.
546+*/
476547 static int pmain (lua_State *L) {
477548 int argc = (int)lua_tointeger(L, 1);
478549 char **argv = (char **)lua_touserdata(L, 2);
479550 int script;
480− int args[num_has];
481− args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
551+ int args = collectargs(argv, &script);
552+ luaL_checkversion(L); /* check that interpreter has correct version */
482553 if (argv[0] && argv[0][0]) progname = argv[0];
483− script = collectargs(argv, args);
484− if (script < 0) { /* invalid arg? */
485− print_usage(argv[-script]);
554+ if (args == has_error) { /* bad arg? */
555+ print_usage(argv[script]); /* 'script' has index of bad arg. */
486556 return 0;
487557 }
488− if (args[has_v]) print_version();
489− if (args[has_E]) { /* option '-E'? */
558+ if (args & has_v) /* option '-v'? */
559+ print_version();
560+ if (args & has_E) { /* option '-E'? */
490561 lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
491562 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
492563 }
493− /* open standard libraries */
494− luaL_checkversion(L);
495− lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
496− luaL_openlibs(L); /* open libraries */
497− lua_gc(L, LUA_GCRESTART, 0);
498− if (!args[has_E] && handle_luainit(L) != LUA_OK)
499− return 0; /* error running LUA_INIT */
500− /* execute arguments -e and -l */
501− if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
502− /* execute main script (if there is one) */
503− if (script && handle_script(L, argv, script) != LUA_OK) return 0;
504− if (args[has_i]) /* -i option? */
505− dotty(L);
506− else if (script == 0 && !args[has_e] && !args[has_v]) { /* no arguments? */
507− if (lua_stdin_is_tty()) {
564+ luaL_openlibs(L); /* open standard libraries */
565+ createargtable(L, argv, argc, script); /* create table 'arg' */
566+ if (!(args & has_E)) { /* no option '-E'? */
567+ if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
568+ return 0; /* error running LUA_INIT */
569+ }
570+ if (!runargs(L, argv, script)) /* execute arguments -e and -l */
571+ return 0; /* something failed */
572+ if (script < argc && /* execute main script (if there is one) */
573+ handle_script(L, argv + script, argc - script) != LUA_OK)
574+ return 0;
575+ if (args & has_i) /* -i option? */
576+ doREPL(L); /* do read-eval-print loop */
577+ else if (script == argc && !(args & (has_e | has_v))) { /* no arguments? */
578+ if (lua_stdin_is_tty()) { /* running in interactive mode? */
508579 print_version();
509− dotty(L);
580+ doREPL(L); /* do read-eval-print loop */
510581 }
511582 else dofile(L, NULL); /* executes stdin as a file */
512583 }
@@ -522,13 +593,12 @@ int main (int argc, char **argv) { · 9 unmodified lines
522593 l_message(argv[0], "cannot create state: not enough memory");
523594 return EXIT_FAILURE;
524595 }
525− /* call 'pmain' in protected mode */
526− lua_pushcfunction(L, &pmain);
596+ lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
527597 lua_pushinteger(L, argc); /* 1st argument */
528598 lua_pushlightuserdata(L, argv); /* 2nd argument */
529− status = lua_pcall(L, 2, 1, 0);
599+ status = lua_pcall(L, 2, 1, 0); /* do the call */
530600 result = lua_toboolean(L, -1); /* get result */
531− finalreport(L, status);
601+ report(L, status);
532602 lua_close(L);
533603 return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
534604 }