xref: /netbsd/external/mit/lua/dist/src/lauxlib.c (revision 6550d01e)
1 /*	$NetBSD: lauxlib.c,v 1.1.1.1 2010/10/31 11:16:54 mbalmer Exp $	*/
2 
3 /*
4 ** Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp
5 ** Auxiliary functions for building Lua libraries
6 ** See Copyright Notice in lua.h
7 */
8 
9 
10 #include <ctype.h>
11 #include <errno.h>
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 
17 
18 /* This file uses only the official API of Lua.
19 ** Any function declared here could be written as an application function.
20 */
21 
22 #define lauxlib_c
23 #define LUA_LIB
24 
25 #include "lua.h"
26 
27 #include "lauxlib.h"
28 
29 
30 #define FREELIST_REF	0	/* free list of references */
31 
32 
33 /* convert a stack index to positive */
34 #define abs_index(L, i)		((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
35 					lua_gettop(L) + (i) + 1)
36 
37 
38 /*
39 ** {======================================================
40 ** Error-report functions
41 ** =======================================================
42 */
43 
44 
45 LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
46   lua_Debug ar;
47   if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
48     return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
49   lua_getinfo(L, "n", &ar);
50   if (strcmp(ar.namewhat, "method") == 0) {
51     narg--;  /* do not count `self' */
52     if (narg == 0)  /* error is in the self argument itself? */
53       return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
54                            ar.name, extramsg);
55   }
56   if (ar.name == NULL)
57     ar.name = "?";
58   return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
59                         narg, ar.name, extramsg);
60 }
61 
62 
63 LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
64   const char *msg = lua_pushfstring(L, "%s expected, got %s",
65                                     tname, luaL_typename(L, narg));
66   return luaL_argerror(L, narg, msg);
67 }
68 
69 
70 static void tag_error (lua_State *L, int narg, int tag) {
71   luaL_typerror(L, narg, lua_typename(L, tag));
72 }
73 
74 
75 LUALIB_API void luaL_where (lua_State *L, int level) {
76   lua_Debug ar;
77   if (lua_getstack(L, level, &ar)) {  /* check function at level */
78     lua_getinfo(L, "Sl", &ar);  /* get info about it */
79     if (ar.currentline > 0) {  /* is there info? */
80       lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
81       return;
82     }
83   }
84   lua_pushliteral(L, "");  /* else, no information available... */
85 }
86 
87 
88 LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
89   va_list argp;
90   va_start(argp, fmt);
91   luaL_where(L, 1);
92   lua_pushvfstring(L, fmt, argp);
93   va_end(argp);
94   lua_concat(L, 2);
95   return lua_error(L);
96 }
97 
98 /* }====================================================== */
99 
100 
101 LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
102                                  const char *const lst[]) {
103   const char *name = (def) ? luaL_optstring(L, narg, def) :
104                              luaL_checkstring(L, narg);
105   int i;
106   for (i=0; lst[i]; i++)
107     if (strcmp(lst[i], name) == 0)
108       return i;
109   return luaL_argerror(L, narg,
110                        lua_pushfstring(L, "invalid option " LUA_QS, name));
111 }
112 
113 
114 LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
115   lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get registry.name */
116   if (!lua_isnil(L, -1))  /* name already in use? */
117     return 0;  /* leave previous value on top, but return 0 */
118   lua_pop(L, 1);
119   lua_newtable(L);  /* create metatable */
120   lua_pushvalue(L, -1);
121   lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
122   return 1;
123 }
124 
125 
126 LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
127   void *p = lua_touserdata(L, ud);
128   if (p != NULL) {  /* value is a userdata? */
129     if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
130       lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get correct metatable */
131       if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */
132         lua_pop(L, 2);  /* remove both metatables */
133         return p;
134       }
135     }
136   }
137   luaL_typerror(L, ud, tname);  /* else error */
138   return NULL;  /* to avoid warnings */
139 }
140 
141 
142 LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
143   if (!lua_checkstack(L, space))
144     luaL_error(L, "stack overflow (%s)", mes);
145 }
146 
147 
148 LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
149   if (lua_type(L, narg) != t)
150     tag_error(L, narg, t);
151 }
152 
153 
154 LUALIB_API void luaL_checkany (lua_State *L, int narg) {
155   if (lua_type(L, narg) == LUA_TNONE)
156     luaL_argerror(L, narg, "value expected");
157 }
158 
159 
160 LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
161   const char *s = lua_tolstring(L, narg, len);
162   if (!s) tag_error(L, narg, LUA_TSTRING);
163   return s;
164 }
165 
166 
167 LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
168                                         const char *def, size_t *len) {
169   if (lua_isnoneornil(L, narg)) {
170     if (len)
171       *len = (def ? strlen(def) : 0);
172     return def;
173   }
174   else return luaL_checklstring(L, narg, len);
175 }
176 
177 
178 LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
179   lua_Number d = lua_tonumber(L, narg);
180   if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
181     tag_error(L, narg, LUA_TNUMBER);
182   return d;
183 }
184 
185 
186 LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
187   return luaL_opt(L, luaL_checknumber, narg, def);
188 }
189 
190 
191 LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
192   lua_Integer d = lua_tointeger(L, narg);
193   if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
194     tag_error(L, narg, LUA_TNUMBER);
195   return d;
196 }
197 
198 
199 LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
200                                                       lua_Integer def) {
201   return luaL_opt(L, luaL_checkinteger, narg, def);
202 }
203 
204 
205 LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
206   if (!lua_getmetatable(L, obj))  /* no metatable? */
207     return 0;
208   lua_pushstring(L, event);
209   lua_rawget(L, -2);
210   if (lua_isnil(L, -1)) {
211     lua_pop(L, 2);  /* remove metatable and metafield */
212     return 0;
213   }
214   else {
215     lua_remove(L, -2);  /* remove only metatable */
216     return 1;
217   }
218 }
219 
220 
221 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
222   obj = abs_index(L, obj);
223   if (!luaL_getmetafield(L, obj, event))  /* no metafield? */
224     return 0;
225   lua_pushvalue(L, obj);
226   lua_call(L, 1, 1);
227   return 1;
228 }
229 
230 
231 LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
232                                 const luaL_Reg *l) {
233   luaI_openlib(L, libname, l, 0);
234 }
235 
236 
237 static int libsize (const luaL_Reg *l) {
238   int size = 0;
239   for (; l->name; l++) size++;
240   return size;
241 }
242 
243 
244 LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
245                               const luaL_Reg *l, int nup) {
246   if (libname) {
247     int size = libsize(l);
248     /* check whether lib already exists */
249     luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
250     lua_getfield(L, -1, libname);  /* get _LOADED[libname] */
251     if (!lua_istable(L, -1)) {  /* not found? */
252       lua_pop(L, 1);  /* remove previous result */
253       /* try global variable (and create one if it does not exist) */
254       if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
255         luaL_error(L, "name conflict for module " LUA_QS, libname);
256       lua_pushvalue(L, -1);
257       lua_setfield(L, -3, libname);  /* _LOADED[libname] = new table */
258     }
259     lua_remove(L, -2);  /* remove _LOADED table */
260     lua_insert(L, -(nup+1));  /* move library table to below upvalues */
261   }
262   for (; l->name; l++) {
263     int i;
264     for (i=0; i<nup; i++)  /* copy upvalues to the top */
265       lua_pushvalue(L, -nup);
266     lua_pushcclosure(L, l->func, nup);
267     lua_setfield(L, -(nup+2), l->name);
268   }
269   lua_pop(L, nup);  /* remove upvalues */
270 }
271 
272 
273 
274 /*
275 ** {======================================================
276 ** getn-setn: size for arrays
277 ** =======================================================
278 */
279 
280 #if defined(LUA_COMPAT_GETN)
281 
282 static int checkint (lua_State *L, int topop) {
283   int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
284   lua_pop(L, topop);
285   return n;
286 }
287 
288 
289 static void getsizes (lua_State *L) {
290   lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
291   if (lua_isnil(L, -1)) {  /* no `size' table? */
292     lua_pop(L, 1);  /* remove nil */
293     lua_newtable(L);  /* create it */
294     lua_pushvalue(L, -1);  /* `size' will be its own metatable */
295     lua_setmetatable(L, -2);
296     lua_pushliteral(L, "kv");
297     lua_setfield(L, -2, "__mode");  /* metatable(N).__mode = "kv" */
298     lua_pushvalue(L, -1);
299     lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");  /* store in register */
300   }
301 }
302 
303 
304 LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
305   t = abs_index(L, t);
306   lua_pushliteral(L, "n");
307   lua_rawget(L, t);
308   if (checkint(L, 1) >= 0) {  /* is there a numeric field `n'? */
309     lua_pushliteral(L, "n");  /* use it */
310     lua_pushinteger(L, n);
311     lua_rawset(L, t);
312   }
313   else {  /* use `sizes' */
314     getsizes(L);
315     lua_pushvalue(L, t);
316     lua_pushinteger(L, n);
317     lua_rawset(L, -3);  /* sizes[t] = n */
318     lua_pop(L, 1);  /* remove `sizes' */
319   }
320 }
321 
322 
323 LUALIB_API int luaL_getn (lua_State *L, int t) {
324   int n;
325   t = abs_index(L, t);
326   lua_pushliteral(L, "n");  /* try t.n */
327   lua_rawget(L, t);
328   if ((n = checkint(L, 1)) >= 0) return n;
329   getsizes(L);  /* else try sizes[t] */
330   lua_pushvalue(L, t);
331   lua_rawget(L, -2);
332   if ((n = checkint(L, 2)) >= 0) return n;
333   return (int)lua_objlen(L, t);
334 }
335 
336 #endif
337 
338 /* }====================================================== */
339 
340 
341 
342 LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
343                                                                const char *r) {
344   const char *wild;
345   size_t l = strlen(p);
346   luaL_Buffer b;
347   luaL_buffinit(L, &b);
348   while ((wild = strstr(s, p)) != NULL) {
349     luaL_addlstring(&b, s, wild - s);  /* push prefix */
350     luaL_addstring(&b, r);  /* push replacement in place of pattern */
351     s = wild + l;  /* continue after `p' */
352   }
353   luaL_addstring(&b, s);  /* push last suffix */
354   luaL_pushresult(&b);
355   return lua_tostring(L, -1);
356 }
357 
358 
359 LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
360                                        const char *fname, int szhint) {
361   const char *e;
362   lua_pushvalue(L, idx);
363   do {
364     e = strchr(fname, '.');
365     if (e == NULL) e = fname + strlen(fname);
366     lua_pushlstring(L, fname, e - fname);
367     lua_rawget(L, -2);
368     if (lua_isnil(L, -1)) {  /* no such field? */
369       lua_pop(L, 1);  /* remove this nil */
370       lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
371       lua_pushlstring(L, fname, e - fname);
372       lua_pushvalue(L, -2);
373       lua_settable(L, -4);  /* set new table into field */
374     }
375     else if (!lua_istable(L, -1)) {  /* field has a non-table value? */
376       lua_pop(L, 2);  /* remove table and value */
377       return fname;  /* return problematic part of the name */
378     }
379     lua_remove(L, -2);  /* remove previous table */
380     fname = e + 1;
381   } while (*e == '.');
382   return NULL;
383 }
384 
385 
386 
387 /*
388 ** {======================================================
389 ** Generic Buffer manipulation
390 ** =======================================================
391 */
392 
393 
394 #define bufflen(B)	((B)->p - (B)->buffer)
395 #define bufffree(B)	((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
396 
397 #define LIMIT	(LUA_MINSTACK/2)
398 
399 
400 static int emptybuffer (luaL_Buffer *B) {
401   size_t l = bufflen(B);
402   if (l == 0) return 0;  /* put nothing on stack */
403   else {
404     lua_pushlstring(B->L, B->buffer, l);
405     B->p = B->buffer;
406     B->lvl++;
407     return 1;
408   }
409 }
410 
411 
412 static void adjuststack (luaL_Buffer *B) {
413   if (B->lvl > 1) {
414     lua_State *L = B->L;
415     int toget = 1;  /* number of levels to concat */
416     size_t toplen = lua_strlen(L, -1);
417     do {
418       size_t l = lua_strlen(L, -(toget+1));
419       if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
420         toplen += l;
421         toget++;
422       }
423       else break;
424     } while (toget < B->lvl);
425     lua_concat(L, toget);
426     B->lvl = B->lvl - toget + 1;
427   }
428 }
429 
430 
431 LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
432   if (emptybuffer(B))
433     adjuststack(B);
434   return B->buffer;
435 }
436 
437 
438 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
439   while (l--)
440     luaL_addchar(B, *s++);
441 }
442 
443 
444 LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
445   luaL_addlstring(B, s, strlen(s));
446 }
447 
448 
449 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
450   emptybuffer(B);
451   lua_concat(B->L, B->lvl);
452   B->lvl = 1;
453 }
454 
455 
456 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
457   lua_State *L = B->L;
458   size_t vl;
459   const char *s = lua_tolstring(L, -1, &vl);
460   if (vl <= bufffree(B)) {  /* fit into buffer? */
461     memcpy(B->p, s, vl);  /* put it there */
462     B->p += vl;
463     lua_pop(L, 1);  /* remove from stack */
464   }
465   else {
466     if (emptybuffer(B))
467       lua_insert(L, -2);  /* put buffer before new value */
468     B->lvl++;  /* add new value into B stack */
469     adjuststack(B);
470   }
471 }
472 
473 
474 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
475   B->L = L;
476   B->p = B->buffer;
477   B->lvl = 0;
478 }
479 
480 /* }====================================================== */
481 
482 
483 LUALIB_API int luaL_ref (lua_State *L, int t) {
484   int ref;
485   t = abs_index(L, t);
486   if (lua_isnil(L, -1)) {
487     lua_pop(L, 1);  /* remove from stack */
488     return LUA_REFNIL;  /* `nil' has a unique fixed reference */
489   }
490   lua_rawgeti(L, t, FREELIST_REF);  /* get first free element */
491   ref = (int)lua_tointeger(L, -1);  /* ref = t[FREELIST_REF] */
492   lua_pop(L, 1);  /* remove it from stack */
493   if (ref != 0) {  /* any free element? */
494     lua_rawgeti(L, t, ref);  /* remove it from list */
495     lua_rawseti(L, t, FREELIST_REF);  /* (t[FREELIST_REF] = t[ref]) */
496   }
497   else {  /* no free elements */
498     ref = (int)lua_objlen(L, t);
499     ref++;  /* create new reference */
500   }
501   lua_rawseti(L, t, ref);
502   return ref;
503 }
504 
505 
506 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
507   if (ref >= 0) {
508     t = abs_index(L, t);
509     lua_rawgeti(L, t, FREELIST_REF);
510     lua_rawseti(L, t, ref);  /* t[ref] = t[FREELIST_REF] */
511     lua_pushinteger(L, ref);
512     lua_rawseti(L, t, FREELIST_REF);  /* t[FREELIST_REF] = ref */
513   }
514 }
515 
516 
517 
518 /*
519 ** {======================================================
520 ** Load functions
521 ** =======================================================
522 */
523 
524 typedef struct LoadF {
525   int extraline;
526   FILE *f;
527   char buff[LUAL_BUFFERSIZE];
528 } LoadF;
529 
530 
531 static const char *getF (lua_State *L, void *ud, size_t *size) {
532   LoadF *lf = (LoadF *)ud;
533   (void)L;
534   if (lf->extraline) {
535     lf->extraline = 0;
536     *size = 1;
537     return "\n";
538   }
539   if (feof(lf->f)) return NULL;
540   *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
541   return (*size > 0) ? lf->buff : NULL;
542 }
543 
544 
545 static int errfile (lua_State *L, const char *what, int fnameindex) {
546   const char *serr = strerror(errno);
547   const char *filename = lua_tostring(L, fnameindex) + 1;
548   lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
549   lua_remove(L, fnameindex);
550   return LUA_ERRFILE;
551 }
552 
553 
554 LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
555   LoadF lf;
556   int status, readstatus;
557   int c;
558   int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
559   lf.extraline = 0;
560   if (filename == NULL) {
561     lua_pushliteral(L, "=stdin");
562     lf.f = stdin;
563   }
564   else {
565     lua_pushfstring(L, "@%s", filename);
566     lf.f = fopen(filename, "r");
567     if (lf.f == NULL) return errfile(L, "open", fnameindex);
568   }
569   c = getc(lf.f);
570   if (c == '#') {  /* Unix exec. file? */
571     lf.extraline = 1;
572     while ((c = getc(lf.f)) != EOF && c != '\n') ;  /* skip first line */
573     if (c == '\n') c = getc(lf.f);
574   }
575   if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
576     lf.f = freopen(filename, "rb", lf.f);  /* reopen in binary mode */
577     if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
578     /* skip eventual `#!...' */
579    while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
580     lf.extraline = 0;
581   }
582   ungetc(c, lf.f);
583   status = lua_load(L, getF, &lf, lua_tostring(L, -1));
584   readstatus = ferror(lf.f);
585   if (filename) fclose(lf.f);  /* close file (even in case of errors) */
586   if (readstatus) {
587     lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
588     return errfile(L, "read", fnameindex);
589   }
590   lua_remove(L, fnameindex);
591   return status;
592 }
593 
594 
595 typedef struct LoadS {
596   const char *s;
597   size_t size;
598 } LoadS;
599 
600 
601 static const char *getS (lua_State *L, void *ud, size_t *size) {
602   LoadS *ls = (LoadS *)ud;
603   (void)L;
604   if (ls->size == 0) return NULL;
605   *size = ls->size;
606   ls->size = 0;
607   return ls->s;
608 }
609 
610 
611 LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
612                                 const char *name) {
613   LoadS ls;
614   ls.s = buff;
615   ls.size = size;
616   return lua_load(L, getS, &ls, name);
617 }
618 
619 
620 LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
621   return luaL_loadbuffer(L, s, strlen(s), s);
622 }
623 
624 
625 
626 /* }====================================================== */
627 
628 
629 static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
630   (void)ud;
631   (void)osize;
632   if (nsize == 0) {
633     free(ptr);
634     return NULL;
635   }
636   else
637     return realloc(ptr, nsize);
638 }
639 
640 
641 static int panic (lua_State *L) {
642   (void)L;  /* to avoid warnings */
643   fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
644                    lua_tostring(L, -1));
645   return 0;
646 }
647 
648 
649 LUALIB_API lua_State *luaL_newstate (void) {
650   lua_State *L = lua_newstate(l_alloc, NULL);
651   if (L) lua_atpanic(L, &panic);
652   return L;
653 }
654 
655