xref: /minix3/external/mit/lua/dist/src/lbaselib.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /*	$NetBSD: lbaselib.c,v 1.5 2015/10/08 13:21:00 mbalmer Exp $	*/
2 
3 /*
4 ** Id: lbaselib.c,v 1.310 2015/03/28 19:14:47 roberto Exp
5 ** Basic library
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lbaselib_c
10 #define LUA_LIB
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <ctype.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #endif
21 
22 #include "lua.h"
23 
24 #include "lauxlib.h"
25 #include "lualib.h"
26 
27 
luaB_print(lua_State * L)28 static int luaB_print (lua_State *L) {
29   int n = lua_gettop(L);  /* number of arguments */
30   int i;
31   lua_getglobal(L, "tostring");
32   for (i=1; i<=n; i++) {
33     const char *s;
34     size_t l;
35     lua_pushvalue(L, -1);  /* function to be called */
36     lua_pushvalue(L, i);   /* value to print */
37     lua_call(L, 1, 1);
38     s = lua_tolstring(L, -1, &l);  /* get result */
39     if (s == NULL)
40       return luaL_error(L, "'tostring' must return a string to 'print'");
41     if (i>1) lua_writestring("\t", 1);
42     lua_writestring(s, l);
43     lua_pop(L, 1);  /* pop result */
44   }
45   lua_writeline();
46   return 0;
47 }
48 
49 
50 #define SPACECHARS	" \f\n\r\t\v"
51 
b_str2int(const char * s,int base,lua_Integer * pn)52 static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
53   lua_Unsigned n = 0;
54   int neg = 0;
55   s += strspn(s, SPACECHARS);  /* skip initial spaces */
56   if (*s == '-') { s++; neg = 1; }  /* handle signal */
57   else if (*s == '+') s++;
58   if (!isalnum((unsigned char)*s))  /* no digit? */
59     return NULL;
60   do {
61     int digit = (isdigit((unsigned char)*s)) ? *s - '0'
62                    : (toupper((unsigned char)*s) - 'A') + 10;
63     if (digit >= base) return NULL;  /* invalid numeral */
64     n = n * base + digit;
65     s++;
66   } while (isalnum((unsigned char)*s));
67   s += strspn(s, SPACECHARS);  /* skip trailing spaces */
68   *pn = (lua_Integer)((neg) ? (0u - n) : n);
69   return s;
70 }
71 
72 
luaB_tonumber(lua_State * L)73 static int luaB_tonumber (lua_State *L) {
74   if (lua_isnoneornil(L, 2)) {  /* standard conversion? */
75     luaL_checkany(L, 1);
76     if (lua_type(L, 1) == LUA_TNUMBER) {  /* already a number? */
77       lua_settop(L, 1);  /* yes; return it */
78       return 1;
79     }
80     else {
81       size_t l;
82       const char *s = lua_tolstring(L, 1, &l);
83       if (s != NULL && lua_stringtonumber(L, s) == l + 1)
84         return 1;  /* successful conversion to number */
85       /* else not a number */
86     }
87   }
88   else {
89     size_t l;
90     const char *s;
91     lua_Integer n = 0;  /* to avoid warnings */
92     lua_Integer base = luaL_checkinteger(L, 2);
93     luaL_checktype(L, 1, LUA_TSTRING);  /* before 'luaL_checklstring'! */
94     s = luaL_checklstring(L, 1, &l);
95     luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
96     if (b_str2int(s, (int)base, &n) == s + l) {
97       lua_pushinteger(L, n);
98       return 1;
99     }  /* else not a number */
100   }  /* else not a number */
101   lua_pushnil(L);  /* not a number */
102   return 1;
103 }
104 
105 
luaB_error(lua_State * L)106 static int luaB_error (lua_State *L) {
107   int level = (int)luaL_optinteger(L, 2, 1);
108   lua_settop(L, 1);
109   if (lua_isstring(L, 1) && level > 0) {  /* add extra information? */
110     luaL_where(L, level);
111     lua_pushvalue(L, 1);
112     lua_concat(L, 2);
113   }
114   return lua_error(L);
115 }
116 
117 
luaB_getmetatable(lua_State * L)118 static int luaB_getmetatable (lua_State *L) {
119   luaL_checkany(L, 1);
120   if (!lua_getmetatable(L, 1)) {
121     lua_pushnil(L);
122     return 1;  /* no metatable */
123   }
124   luaL_getmetafield(L, 1, "__metatable");
125   return 1;  /* returns either __metatable field (if present) or metatable */
126 }
127 
128 
luaB_setmetatable(lua_State * L)129 static int luaB_setmetatable (lua_State *L) {
130   int t = lua_type(L, 2);
131   luaL_checktype(L, 1, LUA_TTABLE);
132   luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
133                     "nil or table expected");
134   if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
135     return luaL_error(L, "cannot change a protected metatable");
136   lua_settop(L, 2);
137   lua_setmetatable(L, 1);
138   return 1;
139 }
140 
141 
luaB_rawequal(lua_State * L)142 static int luaB_rawequal (lua_State *L) {
143   luaL_checkany(L, 1);
144   luaL_checkany(L, 2);
145   lua_pushboolean(L, lua_rawequal(L, 1, 2));
146   return 1;
147 }
148 
149 
luaB_rawlen(lua_State * L)150 static int luaB_rawlen (lua_State *L) {
151   int t = lua_type(L, 1);
152   luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
153                    "table or string expected");
154   lua_pushinteger(L, lua_rawlen(L, 1));
155   return 1;
156 }
157 
158 
luaB_rawget(lua_State * L)159 static int luaB_rawget (lua_State *L) {
160   luaL_checktype(L, 1, LUA_TTABLE);
161   luaL_checkany(L, 2);
162   lua_settop(L, 2);
163   lua_rawget(L, 1);
164   return 1;
165 }
166 
luaB_rawset(lua_State * L)167 static int luaB_rawset (lua_State *L) {
168   luaL_checktype(L, 1, LUA_TTABLE);
169   luaL_checkany(L, 2);
170   luaL_checkany(L, 3);
171   lua_settop(L, 3);
172   lua_rawset(L, 1);
173   return 1;
174 }
175 
176 
luaB_collectgarbage(lua_State * L)177 static int luaB_collectgarbage (lua_State *L) {
178   static const char *const opts[] = {"stop", "restart", "collect",
179     "count", "step", "setpause", "setstepmul",
180     "isrunning", NULL};
181   static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
182     LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
183     LUA_GCISRUNNING};
184   int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
185   int ex = (int)luaL_optinteger(L, 2, 0);
186   int res = lua_gc(L, o, ex);
187   switch (o) {
188     case LUA_GCCOUNT: {
189       int b = lua_gc(L, LUA_GCCOUNTB, 0);
190       lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
191       return 1;
192     }
193     case LUA_GCSTEP: case LUA_GCISRUNNING: {
194       lua_pushboolean(L, res);
195       return 1;
196     }
197     default: {
198       lua_pushinteger(L, res);
199       return 1;
200     }
201   }
202 }
203 
204 
205 /*
206 ** This function has all type names as upvalues, to maximize performance.
207 */
luaB_type(lua_State * L)208 static int luaB_type (lua_State *L) {
209   luaL_checkany(L, 1);
210   lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
211   return 1;
212 }
213 
214 
pairsmeta(lua_State * L,const char * method,int iszero,lua_CFunction iter)215 static int pairsmeta (lua_State *L, const char *method, int iszero,
216                       lua_CFunction iter) {
217   if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */
218     luaL_checktype(L, 1, LUA_TTABLE);  /* argument must be a table */
219     lua_pushcfunction(L, iter);  /* will return generator, */
220     lua_pushvalue(L, 1);  /* state, */
221     if (iszero) lua_pushinteger(L, 0);  /* and initial value */
222     else lua_pushnil(L);
223   }
224   else {
225     lua_pushvalue(L, 1);  /* argument 'self' to metamethod */
226     lua_call(L, 1, 3);  /* get 3 values from metamethod */
227   }
228   return 3;
229 }
230 
231 
luaB_next(lua_State * L)232 static int luaB_next (lua_State *L) {
233   luaL_checktype(L, 1, LUA_TTABLE);
234   lua_settop(L, 2);  /* create a 2nd argument if there isn't one */
235   if (lua_next(L, 1))
236     return 2;
237   else {
238     lua_pushnil(L);
239     return 1;
240   }
241 }
242 
243 
luaB_pairs(lua_State * L)244 static int luaB_pairs (lua_State *L) {
245   return pairsmeta(L, "__pairs", 0, luaB_next);
246 }
247 
248 
249 /*
250 ** Traversal function for 'ipairs' for raw tables
251 */
ipairsaux_raw(lua_State * L)252 static int ipairsaux_raw (lua_State *L) {
253   lua_Integer i = luaL_checkinteger(L, 2) + 1;
254   luaL_checktype(L, 1, LUA_TTABLE);
255   lua_pushinteger(L, i);
256   return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
257 }
258 
259 
260 /*
261 ** Traversal function for 'ipairs' for tables with metamethods
262 */
ipairsaux(lua_State * L)263 static int ipairsaux (lua_State *L) {
264   lua_Integer i = luaL_checkinteger(L, 2) + 1;
265   lua_pushinteger(L, i);
266   return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
267 }
268 
269 
270 /*
271 ** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
272 ** traverse a table, depending on whether the table has metamethods
273 ** that can affect the traversal.
274 */
luaB_ipairs(lua_State * L)275 static int luaB_ipairs (lua_State *L) {
276   lua_CFunction iter = (luaL_getmetafield(L, 1, "__index") != LUA_TNIL)
277                        ? ipairsaux : ipairsaux_raw;
278 #if defined(LUA_COMPAT_IPAIRS)
279   return pairsmeta(L, "__ipairs", 1, iter);
280 #else
281   luaL_checkany(L, 1);
282   lua_pushcfunction(L, iter);  /* iteration function */
283   lua_pushvalue(L, 1);  /* state */
284   lua_pushinteger(L, 0);  /* initial value */
285   return 3;
286 #endif
287 }
288 
289 
load_aux(lua_State * L,int status,int envidx)290 static int load_aux (lua_State *L, int status, int envidx) {
291   if (status == LUA_OK) {
292     if (envidx != 0) {  /* 'env' parameter? */
293       lua_pushvalue(L, envidx);  /* environment for loaded function */
294       if (!lua_setupvalue(L, -2, 1))  /* set it as 1st upvalue */
295         lua_pop(L, 1);  /* remove 'env' if not used by previous call */
296     }
297     return 1;
298   }
299   else {  /* error (message is on top of the stack) */
300     lua_pushnil(L);
301     lua_insert(L, -2);  /* put before error message */
302     return 2;  /* return nil plus error message */
303   }
304 }
305 
306 
307 #ifndef _KERNEL
luaB_loadfile(lua_State * L)308 static int luaB_loadfile (lua_State *L) {
309   const char *fname = luaL_optstring(L, 1, NULL);
310   const char *mode = luaL_optstring(L, 2, NULL);
311   int env = (!lua_isnone(L, 3) ? 3 : 0);  /* 'env' index or 0 if no 'env' */
312   int status = luaL_loadfilex(L, fname, mode);
313   return load_aux(L, status, env);
314 }
315 #endif
316 
317 
318 /*
319 ** {======================================================
320 ** Generic Read function
321 ** =======================================================
322 */
323 
324 
325 /*
326 ** reserved slot, above all arguments, to hold a copy of the returned
327 ** string to avoid it being collected while parsed. 'load' has four
328 ** optional arguments (chunk, source name, mode, and environment).
329 */
330 #define RESERVEDSLOT	5
331 
332 
333 /*
334 ** Reader for generic 'load' function: 'lua_load' uses the
335 ** stack for internal stuff, so the reader cannot change the
336 ** stack top. Instead, it keeps its resulting string in a
337 ** reserved slot inside the stack.
338 */
generic_reader(lua_State * L,void * ud,size_t * size)339 static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
340   (void)(ud);  /* not used */
341   luaL_checkstack(L, 2, "too many nested functions");
342   lua_pushvalue(L, 1);  /* get function */
343   lua_call(L, 0, 1);  /* call it */
344   if (lua_isnil(L, -1)) {
345     lua_pop(L, 1);  /* pop result */
346     *size = 0;
347     return NULL;
348   }
349   else if (!lua_isstring(L, -1))
350     luaL_error(L, "reader function must return a string");
351   lua_replace(L, RESERVEDSLOT);  /* save string in reserved slot */
352   return lua_tolstring(L, RESERVEDSLOT, size);
353 }
354 
355 
luaB_load(lua_State * L)356 static int luaB_load (lua_State *L) {
357   int status;
358   size_t l;
359   const char *s = lua_tolstring(L, 1, &l);
360   const char *mode = luaL_optstring(L, 3, "bt");
361   int env = (!lua_isnone(L, 4) ? 4 : 0);  /* 'env' index or 0 if no 'env' */
362   if (s != NULL) {  /* loading a string? */
363     const char *chunkname = luaL_optstring(L, 2, s);
364     status = luaL_loadbufferx(L, s, l, chunkname, mode);
365   }
366   else {  /* loading from a reader function */
367     const char *chunkname = luaL_optstring(L, 2, "=(load)");
368     luaL_checktype(L, 1, LUA_TFUNCTION);
369     lua_settop(L, RESERVEDSLOT);  /* create reserved slot */
370     status = lua_load(L, generic_reader, NULL, chunkname, mode);
371   }
372   return load_aux(L, status, env);
373 }
374 
375 /* }====================================================== */
376 
377 
378 #ifndef _KERNEL
dofilecont(lua_State * L,int d1,lua_KContext d2)379 static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
380   (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */
381   return lua_gettop(L) - 1;
382 }
383 
384 
luaB_dofile(lua_State * L)385 static int luaB_dofile (lua_State *L) {
386   const char *fname = luaL_optstring(L, 1, NULL);
387   lua_settop(L, 1);
388   if (luaL_loadfile(L, fname) != LUA_OK)
389     return lua_error(L);
390   lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
391   return dofilecont(L, 0, 0);
392 }
393 #endif
394 
395 
luaB_assert(lua_State * L)396 static int luaB_assert (lua_State *L) {
397   if (lua_toboolean(L, 1))  /* condition is true? */
398     return lua_gettop(L);  /* return all arguments */
399   else {  /* error */
400     luaL_checkany(L, 1);  /* there must be a condition */
401     lua_remove(L, 1);  /* remove it */
402     lua_pushliteral(L, "assertion failed!");  /* default message */
403     lua_settop(L, 1);  /* leave only message (default if no other one) */
404     return luaB_error(L);  /* call 'error' */
405   }
406 }
407 
408 
luaB_select(lua_State * L)409 static int luaB_select (lua_State *L) {
410   int n = lua_gettop(L);
411   if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
412     lua_pushinteger(L, n-1);
413     return 1;
414   }
415   else {
416     lua_Integer i = luaL_checkinteger(L, 1);
417     if (i < 0) i = n + i;
418     else if (i > n) i = n;
419     luaL_argcheck(L, 1 <= i, 1, "index out of range");
420     return n - (int)i;
421   }
422 }
423 
424 
425 /*
426 ** Continuation function for 'pcall' and 'xpcall'. Both functions
427 ** already pushed a 'true' before doing the call, so in case of success
428 ** 'finishpcall' only has to return everything in the stack minus
429 ** 'extra' values (where 'extra' is exactly the number of items to be
430 ** ignored).
431 */
finishpcall(lua_State * L,int status,lua_KContext extra)432 static int finishpcall (lua_State *L, int status, lua_KContext extra) {
433   if (status != LUA_OK && status != LUA_YIELD) {  /* error? */
434     lua_pushboolean(L, 0);  /* first result (false) */
435     lua_pushvalue(L, -2);  /* error message */
436     return 2;  /* return false, msg */
437   }
438   else
439     return lua_gettop(L) - (int)extra;  /* return all results */
440 }
441 
442 
luaB_pcall(lua_State * L)443 static int luaB_pcall (lua_State *L) {
444   int status;
445   luaL_checkany(L, 1);
446   lua_pushboolean(L, 1);  /* first result if no errors */
447   lua_insert(L, 1);  /* put it in place */
448   status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
449   return finishpcall(L, status, 0);
450 }
451 
452 
453 /*
454 ** Do a protected call with error handling. After 'lua_rotate', the
455 ** stack will have <f, err, true, f, [args...]>; so, the function passes
456 ** 2 to 'finishpcall' to skip the 2 first values when returning results.
457 */
luaB_xpcall(lua_State * L)458 static int luaB_xpcall (lua_State *L) {
459   int status;
460   int n = lua_gettop(L);
461   luaL_checktype(L, 2, LUA_TFUNCTION);  /* check error function */
462   lua_pushboolean(L, 1);  /* first result */
463   lua_pushvalue(L, 1);  /* function */
464   lua_rotate(L, 3, 2);  /* move them below function's arguments */
465   status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
466   return finishpcall(L, status, 2);
467 }
468 
469 
luaB_tostring(lua_State * L)470 static int luaB_tostring (lua_State *L) {
471   luaL_checkany(L, 1);
472   luaL_tolstring(L, 1, NULL);
473   return 1;
474 }
475 
476 
477 static const luaL_Reg base_funcs[] = {
478   {"assert", luaB_assert},
479   {"collectgarbage", luaB_collectgarbage},
480 #ifndef _KERNEL
481   {"dofile", luaB_dofile},
482 #endif
483   {"error", luaB_error},
484   {"getmetatable", luaB_getmetatable},
485   {"ipairs", luaB_ipairs},
486 #ifndef _KERNEL
487   {"loadfile", luaB_loadfile},
488 #endif
489   {"load", luaB_load},
490 #if defined(LUA_COMPAT_LOADSTRING)
491   {"loadstring", luaB_load},
492 #endif
493   {"next", luaB_next},
494   {"pairs", luaB_pairs},
495   {"pcall", luaB_pcall},
496   {"print", luaB_print},
497   {"rawequal", luaB_rawequal},
498   {"rawlen", luaB_rawlen},
499   {"rawget", luaB_rawget},
500   {"rawset", luaB_rawset},
501   {"select", luaB_select},
502   {"setmetatable", luaB_setmetatable},
503   {"tonumber", luaB_tonumber},
504   {"tostring", luaB_tostring},
505   {"xpcall", luaB_xpcall},
506   /* placeholders */
507   {"type", NULL},
508   {"_G", NULL},
509   {"_VERSION", NULL},
510   {NULL, NULL}
511 };
512 
513 
luaopen_base(lua_State * L)514 LUAMOD_API int luaopen_base (lua_State *L) {
515   int i;
516   /* open lib into global table */
517   lua_pushglobaltable(L);
518   luaL_setfuncs(L, base_funcs, 0);
519   /* set global _G */
520   lua_pushvalue(L, -1);
521   lua_setfield(L, -2, "_G");
522   /* set global _VERSION */
523   lua_pushliteral(L, LUA_VERSION);
524   lua_setfield(L, -2, "_VERSION");
525   /* set function 'type' with proper upvalues */
526   for (i = 0; i < LUA_NUMTAGS; i++)  /* push all type names as upvalues */
527     lua_pushstring(L, lua_typename(L, i));
528   lua_pushcclosure(L, luaB_type, LUA_NUMTAGS);
529   lua_setfield(L, -2, "type");
530   return 1;
531 }
532 
533