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