xref: /minix3/external/mit/lua/dist/src/lauxlib.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /*	$NetBSD: lauxlib.c,v 1.5 2015/10/08 13:21:00 mbalmer Exp $	*/
2 
3 /*
4 ** Id: lauxlib.c,v 1.280 2015/02/03 17:38:24 roberto Exp
5 ** Auxiliary functions for building Lua libraries
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lauxlib_c
10 #define LUA_LIB
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <errno.h>
17 #endif
18 #include <stdarg.h>
19 #ifndef _KERNEL
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #endif
24 
25 
26 /* This file uses only the official API of Lua.
27 ** Any function declared here could be written as an application function.
28 */
29 
30 #include "lua.h"
31 
32 #include "lauxlib.h"
33 
34 
35 /*
36 ** {======================================================
37 ** Traceback
38 ** =======================================================
39 */
40 
41 
42 #define LEVELS1	12	/* size of the first part of the stack */
43 #define LEVELS2	10	/* size of the second part of the stack */
44 
45 
46 
47 /*
48 ** search for 'objidx' in table at index -1.
49 ** return 1 + string at top if find a good name.
50 */
findfield(lua_State * L,int objidx,int level)51 static int findfield (lua_State *L, int objidx, int level) {
52   if (level == 0 || !lua_istable(L, -1))
53     return 0;  /* not found */
54   lua_pushnil(L);  /* start 'next' loop */
55   while (lua_next(L, -2)) {  /* for each pair in table */
56     if (lua_type(L, -2) == LUA_TSTRING) {  /* ignore non-string keys */
57       if (lua_rawequal(L, objidx, -1)) {  /* found object? */
58         lua_pop(L, 1);  /* remove value (but keep name) */
59         return 1;
60       }
61       else if (findfield(L, objidx, level - 1)) {  /* try recursively */
62         lua_remove(L, -2);  /* remove table (but keep name) */
63         lua_pushliteral(L, ".");
64         lua_insert(L, -2);  /* place '.' between the two names */
65         lua_concat(L, 3);
66         return 1;
67       }
68     }
69     lua_pop(L, 1);  /* remove value */
70   }
71   return 0;  /* not found */
72 }
73 
74 
75 /*
76 ** Search for a name for a function in all loaded modules
77 ** (registry._LOADED).
78 */
pushglobalfuncname(lua_State * L,lua_Debug * ar)79 static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
80   int top = lua_gettop(L);
81   lua_getinfo(L, "f", ar);  /* push function */
82   lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
83   if (findfield(L, top + 1, 2)) {
84     const char *name = lua_tostring(L, -1);
85     if (strncmp(name, "_G.", 3) == 0) {  /* name start with '_G.'? */
86       lua_pushstring(L, name + 3);  /* push name without prefix */
87       lua_remove(L, -2);  /* remove original name */
88     }
89     lua_copy(L, -1, top + 1);  /* move name to proper place */
90     lua_pop(L, 2);  /* remove pushed values */
91     return 1;
92   }
93   else {
94     lua_settop(L, top);  /* remove function and global table */
95     return 0;
96   }
97 }
98 
99 
pushfuncname(lua_State * L,lua_Debug * ar)100 static void pushfuncname (lua_State *L, lua_Debug *ar) {
101   if (pushglobalfuncname(L, ar)) {  /* try first a global name */
102     lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
103     lua_remove(L, -2);  /* remove name */
104   }
105   else if (*ar->namewhat != '\0')  /* is there a name from code? */
106     lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name);  /* use it */
107   else if (*ar->what == 'm')  /* main? */
108       lua_pushliteral(L, "main chunk");
109   else if (*ar->what != 'C')  /* for Lua functions, use <file:line> */
110     lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
111   else  /* nothing left... */
112     lua_pushliteral(L, "?");
113 }
114 
115 
countlevels(lua_State * L)116 static int countlevels (lua_State *L) {
117   lua_Debug ar;
118   int li = 1, le = 1;
119   /* find an upper bound */
120   while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
121   /* do a binary search */
122   while (li < le) {
123     int m = (li + le)/2;
124     if (lua_getstack(L, m, &ar)) li = m + 1;
125     else le = m;
126   }
127   return le - 1;
128 }
129 
130 
luaL_traceback(lua_State * L,lua_State * L1,const char * msg,int level)131 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
132                                 const char *msg, int level) {
133   lua_Debug ar;
134   int top = lua_gettop(L);
135   int numlevels = countlevels(L1);
136   int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
137   if (msg) lua_pushfstring(L, "%s\n", msg);
138   lua_pushliteral(L, "stack traceback:");
139   while (lua_getstack(L1, level++, &ar)) {
140     if (level == mark) {  /* too many levels? */
141       lua_pushliteral(L, "\n\t...");  /* add a '...' */
142       level = numlevels - LEVELS2;  /* and skip to last ones */
143     }
144     else {
145       lua_getinfo(L1, "Slnt", &ar);
146       lua_pushfstring(L, "\n\t%s:", ar.short_src);
147       if (ar.currentline > 0)
148         lua_pushfstring(L, "%d:", ar.currentline);
149       lua_pushliteral(L, " in ");
150       pushfuncname(L, &ar);
151       if (ar.istailcall)
152         lua_pushliteral(L, "\n\t(...tail calls...)");
153       lua_concat(L, lua_gettop(L) - top);
154     }
155   }
156   lua_concat(L, lua_gettop(L) - top);
157 }
158 
159 /* }====================================================== */
160 
161 
162 /*
163 ** {======================================================
164 ** Error-report functions
165 ** =======================================================
166 */
167 
luaL_argerror(lua_State * L,int arg,const char * extramsg)168 LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
169   lua_Debug ar;
170   if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
171     return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
172   lua_getinfo(L, "n", &ar);
173   if (strcmp(ar.namewhat, "method") == 0) {
174     arg--;  /* do not count 'self' */
175     if (arg == 0)  /* error is in the self argument itself? */
176       return luaL_error(L, "calling '%s' on bad self (%s)",
177                            ar.name, extramsg);
178   }
179   if (ar.name == NULL)
180     ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
181   return luaL_error(L, "bad argument #%d to '%s' (%s)",
182                         arg, ar.name, extramsg);
183 }
184 
185 
typeerror(lua_State * L,int arg,const char * tname)186 static int typeerror (lua_State *L, int arg, const char *tname) {
187   const char *msg;
188   const char *typearg;  /* name for the type of the actual argument */
189   if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
190     typearg = lua_tostring(L, -1);  /* use the given type name */
191   else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
192     typearg = "light userdata";  /* special name for messages */
193   else
194     typearg = luaL_typename(L, arg);  /* standard name */
195   msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
196   return luaL_argerror(L, arg, msg);
197 }
198 
199 
tag_error(lua_State * L,int arg,int tag)200 static void tag_error (lua_State *L, int arg, int tag) {
201   typeerror(L, arg, lua_typename(L, tag));
202 }
203 
204 
luaL_where(lua_State * L,int level)205 LUALIB_API void luaL_where (lua_State *L, int level) {
206   lua_Debug ar;
207   if (lua_getstack(L, level, &ar)) {  /* check function at level */
208     lua_getinfo(L, "Sl", &ar);  /* get info about it */
209     if (ar.currentline > 0) {  /* is there info? */
210       lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
211       return;
212     }
213   }
214   lua_pushliteral(L, "");  /* else, no information available... */
215 }
216 
217 
luaL_error(lua_State * L,const char * fmt,...)218 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
219   va_list argp;
220   va_start(argp, fmt);
221   luaL_where(L, 1);
222   lua_pushvfstring(L, fmt, argp);
223   va_end(argp);
224   lua_concat(L, 2);
225   return lua_error(L);
226 }
227 
228 
229 #ifndef _KERNEL
luaL_fileresult(lua_State * L,int stat,const char * fname)230 LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
231   int en = errno;  /* calls to Lua API may change this value */
232   if (stat) {
233     lua_pushboolean(L, 1);
234     return 1;
235   }
236   else {
237     lua_pushnil(L);
238     if (fname)
239       lua_pushfstring(L, "%s: %s", fname, strerror(en));
240     else
241       lua_pushstring(L, strerror(en));
242     lua_pushinteger(L, en);
243     return 3;
244   }
245 }
246 #endif
247 
248 
249 #if !defined(l_inspectstat)	/* { */
250 
251 #if defined(LUA_USE_POSIX)
252 
253 #include <sys/wait.h>
254 
255 /*
256 ** use appropriate macros to interpret 'pclose' return status
257 */
258 #define l_inspectstat(stat,what)  \
259    if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
260    else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
261 
262 #else
263 
264 #define l_inspectstat(stat,what)  /* no op */
265 
266 #endif
267 
268 #endif				/* } */
269 
270 
271 #ifndef _KERNEL
luaL_execresult(lua_State * L,int stat)272 LUALIB_API int luaL_execresult (lua_State *L, int stat) {
273   const char *what = "exit";  /* type of termination */
274   if (stat == -1)  /* error? */
275     return luaL_fileresult(L, 0, NULL);
276   else {
277     l_inspectstat(stat, what);  /* interpret result */
278     if (*what == 'e' && stat == 0)  /* successful termination? */
279       lua_pushboolean(L, 1);
280     else
281       lua_pushnil(L);
282     lua_pushstring(L, what);
283     lua_pushinteger(L, stat);
284     return 3;  /* return true/nil,what,code */
285   }
286 }
287 #endif
288 
289 /* }====================================================== */
290 
291 
292 /*
293 ** {======================================================
294 ** Userdata's metatable manipulation
295 ** =======================================================
296 */
297 
luaL_newmetatable(lua_State * L,const char * tname)298 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
299   if (luaL_getmetatable(L, tname) != LUA_TNIL)  /* name already in use? */
300     return 0;  /* leave previous value on top, but return 0 */
301   lua_pop(L, 1);
302   lua_newtable(L);  /* create metatable */
303   lua_pushstring(L, tname);
304   lua_setfield(L, -2, "__name");  /* metatable.__name = tname */
305   lua_pushvalue(L, -1);
306   lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
307   return 1;
308 }
309 
310 
luaL_setmetatable(lua_State * L,const char * tname)311 LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
312   luaL_getmetatable(L, tname);
313   lua_setmetatable(L, -2);
314 }
315 
316 
luaL_testudata(lua_State * L,int ud,const char * tname)317 LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
318   void *p = lua_touserdata(L, ud);
319   if (p != NULL) {  /* value is a userdata? */
320     if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
321       luaL_getmetatable(L, tname);  /* get correct metatable */
322       if (!lua_rawequal(L, -1, -2))  /* not the same? */
323         p = NULL;  /* value is a userdata with wrong metatable */
324       lua_pop(L, 2);  /* remove both metatables */
325       return p;
326     }
327   }
328   return NULL;  /* value is not a userdata with a metatable */
329 }
330 
331 
luaL_checkudata(lua_State * L,int ud,const char * tname)332 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
333   void *p = luaL_testudata(L, ud, tname);
334   if (p == NULL) typeerror(L, ud, tname);
335   return p;
336 }
337 
338 /* }====================================================== */
339 
340 
341 /*
342 ** {======================================================
343 ** Argument check functions
344 ** =======================================================
345 */
346 
luaL_checkoption(lua_State * L,int arg,const char * def,const char * const lst[])347 LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
348                                  const char *const lst[]) {
349   const char *name = (def) ? luaL_optstring(L, arg, def) :
350                              luaL_checkstring(L, arg);
351   int i;
352   for (i=0; lst[i]; i++)
353     if (strcmp(lst[i], name) == 0)
354       return i;
355   return luaL_argerror(L, arg,
356                        lua_pushfstring(L, "invalid option '%s'", name));
357 }
358 
359 
luaL_checkstack(lua_State * L,int space,const char * msg)360 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
361   /* keep some extra space to run error routines, if needed */
362   const int extra = LUA_MINSTACK;
363   if (!lua_checkstack(L, space + extra)) {
364     if (msg)
365       luaL_error(L, "stack overflow (%s)", msg);
366     else
367       luaL_error(L, "stack overflow");
368   }
369 }
370 
371 
luaL_checktype(lua_State * L,int arg,int t)372 LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
373   if (lua_type(L, arg) != t)
374     tag_error(L, arg, t);
375 }
376 
377 
luaL_checkany(lua_State * L,int arg)378 LUALIB_API void luaL_checkany (lua_State *L, int arg) {
379   if (lua_type(L, arg) == LUA_TNONE)
380     luaL_argerror(L, arg, "value expected");
381 }
382 
383 
luaL_checklstring(lua_State * L,int arg,size_t * len)384 LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
385   const char *s = lua_tolstring(L, arg, len);
386   if (!s) tag_error(L, arg, LUA_TSTRING);
387   return s;
388 }
389 
390 
luaL_optlstring(lua_State * L,int arg,const char * def,size_t * len)391 LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
392                                         const char *def, size_t *len) {
393   if (lua_isnoneornil(L, arg)) {
394     if (len)
395       *len = (def ? strlen(def) : 0);
396     return def;
397   }
398   else return luaL_checklstring(L, arg, len);
399 }
400 
401 
luaL_checknumber(lua_State * L,int arg)402 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
403   int isnum;
404   lua_Number d = lua_tonumberx(L, arg, &isnum);
405   if (!isnum)
406     tag_error(L, arg, LUA_TNUMBER);
407   return d;
408 }
409 
410 
luaL_optnumber(lua_State * L,int arg,lua_Number def)411 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
412   return luaL_opt(L, luaL_checknumber, arg, def);
413 }
414 
415 
416 #ifndef _KERNEL
interror(lua_State * L,int arg)417 static void interror (lua_State *L, int arg) {
418   if (lua_isnumber(L, arg))
419     luaL_argerror(L, arg, "number has no integer representation");
420   else
421     tag_error(L, arg, LUA_TNUMBER);
422 }
423 
424 
luaL_checkinteger(lua_State * L,int arg)425 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
426   int isnum;
427   lua_Integer d = lua_tointegerx(L, arg, &isnum);
428   if (!isnum) {
429     interror(L, arg);
430   }
431   return d;
432 }
433 
434 
luaL_optinteger(lua_State * L,int arg,lua_Integer def)435 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
436                                                       lua_Integer def) {
437   return luaL_opt(L, luaL_checkinteger, arg, def);
438 }
439 #endif
440 
441 /* }====================================================== */
442 
443 
444 /*
445 ** {======================================================
446 ** Generic Buffer manipulation
447 ** =======================================================
448 */
449 
450 /*
451 ** check whether buffer is using a userdata on the stack as a temporary
452 ** buffer
453 */
454 #define buffonstack(B)	((B)->b != (B)->initb)
455 
456 
457 /*
458 ** returns a pointer to a free area with at least 'sz' bytes
459 */
luaL_prepbuffsize(luaL_Buffer * B,size_t sz)460 LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
461   lua_State *L = B->L;
462   if (B->size - B->n < sz) {  /* not enough space? */
463     char *newbuff;
464     size_t newsize = B->size * 2;  /* double buffer size */
465     if (newsize - B->n < sz)  /* not big enough? */
466       newsize = B->n + sz;
467     if (newsize < B->n || newsize - B->n < sz)
468       luaL_error(L, "buffer too large");
469     /* create larger buffer */
470     newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
471     /* move content to new buffer */
472     memcpy(newbuff, B->b, B->n * sizeof(char));
473     if (buffonstack(B))
474       lua_remove(L, -2);  /* remove old buffer */
475     B->b = newbuff;
476     B->size = newsize;
477   }
478   return &B->b[B->n];
479 }
480 
481 
luaL_addlstring(luaL_Buffer * B,const char * s,size_t l)482 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
483   char *b = luaL_prepbuffsize(B, l);
484   memcpy(b, s, l * sizeof(char));
485   luaL_addsize(B, l);
486 }
487 
488 
luaL_addstring(luaL_Buffer * B,const char * s)489 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
490   luaL_addlstring(B, s, strlen(s));
491 }
492 
493 
luaL_pushresult(luaL_Buffer * B)494 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
495   lua_State *L = B->L;
496   lua_pushlstring(L, B->b, B->n);
497   if (buffonstack(B))
498     lua_remove(L, -2);  /* remove old buffer */
499 }
500 
501 
luaL_pushresultsize(luaL_Buffer * B,size_t sz)502 LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
503   luaL_addsize(B, sz);
504   luaL_pushresult(B);
505 }
506 
507 
luaL_addvalue(luaL_Buffer * B)508 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
509   lua_State *L = B->L;
510   size_t l;
511   const char *s = lua_tolstring(L, -1, &l);
512   if (buffonstack(B))
513     lua_insert(L, -2);  /* put value below buffer */
514   luaL_addlstring(B, s, l);
515   lua_remove(L, (buffonstack(B)) ? -2 : -1);  /* remove value */
516 }
517 
518 
luaL_buffinit(lua_State * L,luaL_Buffer * B)519 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
520   B->L = L;
521   B->b = B->initb;
522   B->n = 0;
523   B->size = LUAL_BUFFERSIZE;
524 }
525 
526 
luaL_buffinitsize(lua_State * L,luaL_Buffer * B,size_t sz)527 LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
528   luaL_buffinit(L, B);
529   return luaL_prepbuffsize(B, sz);
530 }
531 
532 /* }====================================================== */
533 
534 
535 /*
536 ** {======================================================
537 ** Reference system
538 ** =======================================================
539 */
540 
541 /* index of free-list header */
542 #define freelist	0
543 
544 
luaL_ref(lua_State * L,int t)545 LUALIB_API int luaL_ref (lua_State *L, int t) {
546   int ref;
547   if (lua_isnil(L, -1)) {
548     lua_pop(L, 1);  /* remove from stack */
549     return LUA_REFNIL;  /* 'nil' has a unique fixed reference */
550   }
551   t = lua_absindex(L, t);
552   lua_rawgeti(L, t, freelist);  /* get first free element */
553   ref = (int)lua_tointeger(L, -1);  /* ref = t[freelist] */
554   lua_pop(L, 1);  /* remove it from stack */
555   if (ref != 0) {  /* any free element? */
556     lua_rawgeti(L, t, ref);  /* remove it from list */
557     lua_rawseti(L, t, freelist);  /* (t[freelist] = t[ref]) */
558   }
559   else  /* no free elements */
560     ref = (int)lua_rawlen(L, t) + 1;  /* get a new reference */
561   lua_rawseti(L, t, ref);
562   return ref;
563 }
564 
565 
luaL_unref(lua_State * L,int t,int ref)566 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
567   if (ref >= 0) {
568     t = lua_absindex(L, t);
569     lua_rawgeti(L, t, freelist);
570     lua_rawseti(L, t, ref);  /* t[ref] = t[freelist] */
571     lua_pushinteger(L, ref);
572     lua_rawseti(L, t, freelist);  /* t[freelist] = ref */
573   }
574 }
575 
576 /* }====================================================== */
577 
578 
579 /*
580 ** {======================================================
581 ** Load functions
582 ** =======================================================
583 */
584 
585 #ifndef _KERNEL
586 typedef struct LoadF {
587   int n;  /* number of pre-read characters */
588   FILE *f;  /* file being read */
589   char buff[BUFSIZ];  /* area for reading file */
590 } LoadF;
591 
592 
getF(lua_State * L,void * ud,size_t * size)593 static const char *getF (lua_State *L, void *ud, size_t *size) {
594   LoadF *lf = (LoadF *)ud;
595   (void)L;  /* not used */
596   if (lf->n > 0) {  /* are there pre-read characters to be read? */
597     *size = lf->n;  /* return them (chars already in buffer) */
598     lf->n = 0;  /* no more pre-read characters */
599   }
600   else {  /* read a block from file */
601     /* 'fread' can return > 0 *and* set the EOF flag. If next call to
602        'getF' called 'fread', it might still wait for user input.
603        The next check avoids this problem. */
604     if (feof(lf->f)) return NULL;
605     *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);  /* read block */
606   }
607   return lf->buff;
608 }
609 
610 
errfile(lua_State * L,const char * what,int fnameindex)611 static int errfile (lua_State *L, const char *what, int fnameindex) {
612   const char *serr = strerror(errno);
613   const char *filename = lua_tostring(L, fnameindex) + 1;
614   lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
615   lua_remove(L, fnameindex);
616   return LUA_ERRFILE;
617 }
618 
619 
skipBOM(LoadF * lf)620 static int skipBOM (LoadF *lf) {
621   const char *p = "\xEF\xBB\xBF";  /* Utf8 BOM mark */
622   int c;
623   lf->n = 0;
624   do {
625     c = getc(lf->f);
626     if (c == EOF || c != *(const unsigned char *)p++) return c;
627     lf->buff[lf->n++] = c;  /* to be read by the parser */
628   } while (*p != '\0');
629   lf->n = 0;  /* prefix matched; discard it */
630   return getc(lf->f);  /* return next character */
631 }
632 
633 
634 /*
635 ** reads the first character of file 'f' and skips an optional BOM mark
636 ** in its beginning plus its first line if it starts with '#'. Returns
637 ** true if it skipped the first line.  In any case, '*cp' has the
638 ** first "valid" character of the file (after the optional BOM and
639 ** a first-line comment).
640 */
skipcomment(LoadF * lf,int * cp)641 static int skipcomment (LoadF *lf, int *cp) {
642   int c = *cp = skipBOM(lf);
643   if (c == '#') {  /* first line is a comment (Unix exec. file)? */
644     do {  /* skip first line */
645       c = getc(lf->f);
646     } while (c != EOF && c != '\n') ;
647     *cp = getc(lf->f);  /* skip end-of-line, if present */
648     return 1;  /* there was a comment */
649   }
650   else return 0;  /* no comment */
651 }
652 
653 
luaL_loadfilex(lua_State * L,const char * filename,const char * mode)654 LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
655                                              const char *mode) {
656   LoadF lf;
657   int status, readstatus;
658   int c;
659   int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
660   if (filename == NULL) {
661     lua_pushliteral(L, "=stdin");
662     lf.f = stdin;
663   }
664   else {
665     lua_pushfstring(L, "@%s", filename);
666     lf.f = fopen(filename, "r");
667     if (lf.f == NULL) return errfile(L, "open", fnameindex);
668   }
669   if (skipcomment(&lf, &c))  /* read initial portion */
670     lf.buff[lf.n++] = '\n';  /* add line to correct line numbers */
671   if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
672     lf.f = freopen(filename, "rb", lf.f);  /* reopen in binary mode */
673     if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
674     skipcomment(&lf, &c);  /* re-read initial portion */
675   }
676   if (c != EOF)
677     lf.buff[lf.n++] = c;  /* 'c' is the first character of the stream */
678   status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
679   readstatus = ferror(lf.f);
680   if (filename) fclose(lf.f);  /* close file (even in case of errors) */
681   if (readstatus) {
682     lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */
683     return errfile(L, "read", fnameindex);
684   }
685   lua_remove(L, fnameindex);
686   return status;
687 }
688 #endif
689 
690 
691 typedef struct LoadS {
692   const char *s;
693   size_t size;
694 } LoadS;
695 
696 
getS(lua_State * L,void * ud,size_t * size)697 static const char *getS (lua_State *L, void *ud, size_t *size) {
698   LoadS *ls = (LoadS *)ud;
699   (void)L;  /* not used */
700   if (ls->size == 0) return NULL;
701   *size = ls->size;
702   ls->size = 0;
703   return ls->s;
704 }
705 
706 
luaL_loadbufferx(lua_State * L,const char * buff,size_t size,const char * name,const char * mode)707 LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
708                                  const char *name, const char *mode) {
709   LoadS ls;
710   ls.s = buff;
711   ls.size = size;
712   return lua_load(L, getS, &ls, name, mode);
713 }
714 
715 
luaL_loadstring(lua_State * L,const char * s)716 LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
717   return luaL_loadbuffer(L, s, strlen(s), s);
718 }
719 
720 /* }====================================================== */
721 
722 
723 
luaL_getmetafield(lua_State * L,int obj,const char * event)724 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
725   if (!lua_getmetatable(L, obj))  /* no metatable? */
726     return LUA_TNIL;
727   else {
728     int tt;
729     lua_pushstring(L, event);
730     tt = lua_rawget(L, -2);
731     if (tt == LUA_TNIL)  /* is metafield nil? */
732       lua_pop(L, 2);  /* remove metatable and metafield */
733     else
734       lua_remove(L, -2);  /* remove only metatable */
735     return tt;  /* return metafield type */
736   }
737 }
738 
739 
luaL_callmeta(lua_State * L,int obj,const char * event)740 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
741   obj = lua_absindex(L, obj);
742   if (luaL_getmetafield(L, obj, event) == LUA_TNIL)  /* no metafield? */
743     return 0;
744   lua_pushvalue(L, obj);
745   lua_call(L, 1, 1);
746   return 1;
747 }
748 
749 
luaL_len(lua_State * L,int idx)750 LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
751   lua_Integer l;
752   int isnum;
753   lua_len(L, idx);
754   l = lua_tointegerx(L, -1, &isnum);
755   if (!isnum)
756     luaL_error(L, "object length is not an integer");
757   lua_pop(L, 1);  /* remove object */
758   return l;
759 }
760 
761 
luaL_tolstring(lua_State * L,int idx,size_t * len)762 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
763   if (!luaL_callmeta(L, idx, "__tostring")) {  /* no metafield? */
764     switch (lua_type(L, idx)) {
765       case LUA_TNUMBER: {
766         if (lua_isinteger(L, idx))
767           lua_pushfstring(L, "%I", lua_tointeger(L, idx));
768         else
769           lua_pushfstring(L, "%f", lua_tonumber(L, idx));
770         break;
771       }
772       case LUA_TSTRING:
773         lua_pushvalue(L, idx);
774         break;
775       case LUA_TBOOLEAN:
776         lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
777         break;
778       case LUA_TNIL:
779         lua_pushliteral(L, "nil");
780         break;
781       default:
782         lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
783                                             lua_topointer(L, idx));
784         break;
785     }
786   }
787   return lua_tolstring(L, -1, len);
788 }
789 
790 
791 /*
792 ** {======================================================
793 ** Compatibility with 5.1 module functions
794 ** =======================================================
795 */
796 #if defined(LUA_COMPAT_MODULE)
797 
luaL_findtable(lua_State * L,int idx,const char * fname,int szhint)798 static const char *luaL_findtable (lua_State *L, int idx,
799                                    const char *fname, int szhint) {
800   const char *e;
801   if (idx) lua_pushvalue(L, idx);
802   do {
803     e = strchr(fname, '.');
804     if (e == NULL) e = fname + strlen(fname);
805     lua_pushlstring(L, fname, e - fname);
806     if (lua_rawget(L, -2) == LUA_TNIL) {  /* no such field? */
807       lua_pop(L, 1);  /* remove this nil */
808       lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
809       lua_pushlstring(L, fname, e - fname);
810       lua_pushvalue(L, -2);
811       lua_settable(L, -4);  /* set new table into field */
812     }
813     else if (!lua_istable(L, -1)) {  /* field has a non-table value? */
814       lua_pop(L, 2);  /* remove table and value */
815       return fname;  /* return problematic part of the name */
816     }
817     lua_remove(L, -2);  /* remove previous table */
818     fname = e + 1;
819   } while (*e == '.');
820   return NULL;
821 }
822 
823 
824 /*
825 ** Count number of elements in a luaL_Reg list.
826 */
libsize(const luaL_Reg * l)827 static int libsize (const luaL_Reg *l) {
828   int size = 0;
829   for (; l && l->name; l++) size++;
830   return size;
831 }
832 
833 
834 /*
835 ** Find or create a module table with a given name. The function
836 ** first looks at the _LOADED table and, if that fails, try a
837 ** global variable with that name. In any case, leaves on the stack
838 ** the module table.
839 */
luaL_pushmodule(lua_State * L,const char * modname,int sizehint)840 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
841                                  int sizehint) {
842   luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);  /* get _LOADED table */
843   if (lua_getfield(L, -1, modname) != LUA_TTABLE) {  /* no _LOADED[modname]? */
844     lua_pop(L, 1);  /* remove previous result */
845     /* try global variable (and create one if it does not exist) */
846     lua_pushglobaltable(L);
847     if (luaL_findtable(L, 0, modname, sizehint) != NULL)
848       luaL_error(L, "name conflict for module '%s'", modname);
849     lua_pushvalue(L, -1);
850     lua_setfield(L, -3, modname);  /* _LOADED[modname] = new table */
851   }
852   lua_remove(L, -2);  /* remove _LOADED table */
853 }
854 
855 
luaL_openlib(lua_State * L,const char * libname,const luaL_Reg * l,int nup)856 LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
857                                const luaL_Reg *l, int nup) {
858   luaL_checkversion(L);
859   if (libname) {
860     luaL_pushmodule(L, libname, libsize(l));  /* get/create library table */
861     lua_insert(L, -(nup + 1));  /* move library table to below upvalues */
862   }
863   if (l)
864     luaL_setfuncs(L, l, nup);
865   else
866     lua_pop(L, nup);  /* remove upvalues */
867 }
868 
869 #endif
870 /* }====================================================== */
871 
872 /*
873 ** set functions from list 'l' into table at top - 'nup'; each
874 ** function gets the 'nup' elements at the top as upvalues.
875 ** Returns with only the table at the stack.
876 */
luaL_setfuncs(lua_State * L,const luaL_Reg * l,int nup)877 LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
878   luaL_checkstack(L, nup, "too many upvalues");
879   for (; l->name != NULL; l++) {  /* fill the table with given functions */
880     int i;
881     for (i = 0; i < nup; i++)  /* copy upvalues to the top */
882       lua_pushvalue(L, -nup);
883     lua_pushcclosure(L, l->func, nup);  /* closure with those upvalues */
884     lua_setfield(L, -(nup + 2), l->name);
885   }
886   lua_pop(L, nup);  /* remove upvalues */
887 }
888 
889 
890 /*
891 ** ensure that stack[idx][fname] has a table and push that table
892 ** into the stack
893 */
luaL_getsubtable(lua_State * L,int idx,const char * fname)894 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
895   if (lua_getfield(L, idx, fname) == LUA_TTABLE)
896     return 1;  /* table already there */
897   else {
898     lua_pop(L, 1);  /* remove previous result */
899     idx = lua_absindex(L, idx);
900     lua_newtable(L);
901     lua_pushvalue(L, -1);  /* copy to be left at top */
902     lua_setfield(L, idx, fname);  /* assign new table to field */
903     return 0;  /* false, because did not find table there */
904   }
905 }
906 
907 
908 /*
909 ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
910 ** to open a module, registers the result in 'package.loaded' table and,
911 ** if 'glb' is true, also registers the result in the global table.
912 ** Leaves resulting module on the top.
913 */
luaL_requiref(lua_State * L,const char * modname,lua_CFunction openf,int glb)914 LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
915                                lua_CFunction openf, int glb) {
916   luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
917   lua_getfield(L, -1, modname);  /* _LOADED[modname] */
918   if (!lua_toboolean(L, -1)) {  /* package not already loaded? */
919     lua_pop(L, 1);  /* remove field */
920     lua_pushcfunction(L, openf);
921     lua_pushstring(L, modname);  /* argument to open function */
922     lua_call(L, 1, 1);  /* call 'openf' to open module */
923     lua_pushvalue(L, -1);  /* make copy of module (call result) */
924     lua_setfield(L, -3, modname);  /* _LOADED[modname] = module */
925   }
926   lua_remove(L, -2);  /* remove _LOADED table */
927   if (glb) {
928     lua_pushvalue(L, -1);  /* copy of module */
929     lua_setglobal(L, modname);  /* _G[modname] = module */
930   }
931 }
932 
933 
luaL_gsub(lua_State * L,const char * s,const char * p,const char * r)934 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
935                                                                const char *r) {
936   const char *wild;
937   size_t l = strlen(p);
938   luaL_Buffer b;
939   luaL_buffinit(L, &b);
940   while ((wild = strstr(s, p)) != NULL) {
941     luaL_addlstring(&b, s, wild - s);  /* push prefix */
942     luaL_addstring(&b, r);  /* push replacement in place of pattern */
943     s = wild + l;  /* continue after 'p' */
944   }
945   luaL_addstring(&b, s);  /* push last suffix */
946   luaL_pushresult(&b);
947   return lua_tostring(L, -1);
948 }
949 
950 
951 #ifndef _KERNEL
l_alloc(void * ud,void * ptr,size_t osize,size_t nsize)952 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
953   (void)ud; (void)osize;  /* not used */
954   if (nsize == 0) {
955     free(ptr);
956     return NULL;
957   }
958   else
959     return realloc(ptr, nsize);
960 }
961 
962 
panic(lua_State * L)963 static int panic (lua_State *L) {
964   lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
965                         lua_tostring(L, -1));
966   return 0;  /* return to Lua to abort */
967 }
968 
969 
luaL_newstate(void)970 LUALIB_API lua_State *luaL_newstate (void) {
971   lua_State *L = lua_newstate(l_alloc, NULL);
972   if (L) lua_atpanic(L, &panic);
973   return L;
974 }
975 #endif
976 
977 
luaL_checkversion_(lua_State * L,lua_Number ver,size_t sz)978 LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
979   const lua_Number *v = lua_version(L);
980   if (sz != LUAL_NUMSIZES)  /* check numeric types */
981     luaL_error(L, "core and library have incompatible numeric types");
982   if (v != lua_version(NULL))
983     luaL_error(L, "multiple Lua VMs detected");
984   else if (*v != ver)
985     luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
986                   ver, *v);
987 }
988 
989