xref: /netbsd-src/external/mit/lua/dist/src/lbaselib.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: lbaselib.c,v 1.10 2018/08/04 17:30:01 alnsn Exp $	*/
2 
3 /*
4 ** Id: lbaselib.c,v 1.314.1.1 2017/04/19 17:39:34 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 /* _KERNEL */
21 
22 #include "lua.h"
23 
24 #include "lauxlib.h"
25 #include "lualib.h"
26 
27 
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 
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 
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);  /* no numbers as strings */
94     s = lua_tolstring(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 
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_type(L, 1) == LUA_TSTRING && level > 0) {
110     luaL_where(L, level);   /* add extra information */
111     lua_pushvalue(L, 1);
112     lua_concat(L, 2);
113   }
114   return lua_error(L);
115 }
116 
117 
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 
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 
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 
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 
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 
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 
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 static int luaB_type (lua_State *L) {
206   int t = lua_type(L, 1);
207   luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
208   lua_pushstring(L, lua_typename(L, t));
209   return 1;
210 }
211 
212 
213 static int pairsmeta (lua_State *L, const char *method, int iszero,
214                       lua_CFunction iter) {
215   luaL_checkany(L, 1);
216   if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */
217     lua_pushcfunction(L, iter);  /* will return generator, */
218     lua_pushvalue(L, 1);  /* state, */
219     if (iszero) lua_pushinteger(L, 0);  /* and initial value */
220     else lua_pushnil(L);
221   }
222   else {
223     lua_pushvalue(L, 1);  /* argument 'self' to metamethod */
224     lua_call(L, 1, 3);  /* get 3 values from metamethod */
225   }
226   return 3;
227 }
228 
229 
230 static int luaB_next (lua_State *L) {
231   luaL_checktype(L, 1, LUA_TTABLE);
232   lua_settop(L, 2);  /* create a 2nd argument if there isn't one */
233   if (lua_next(L, 1))
234     return 2;
235   else {
236     lua_pushnil(L);
237     return 1;
238   }
239 }
240 
241 
242 static int luaB_pairs (lua_State *L) {
243   return pairsmeta(L, "__pairs", 0, luaB_next);
244 }
245 
246 
247 /*
248 ** Traversal function for 'ipairs'
249 */
250 static int ipairsaux (lua_State *L) {
251   lua_Integer i = luaL_checkinteger(L, 2) + 1;
252   lua_pushinteger(L, i);
253   return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
254 }
255 
256 
257 /*
258 ** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
259 ** (The given "table" may not be a table.)
260 */
261 static int luaB_ipairs (lua_State *L) {
262 #if defined(LUA_COMPAT_IPAIRS)
263   return pairsmeta(L, "__ipairs", 1, ipairsaux);
264 #else
265   luaL_checkany(L, 1);
266   lua_pushcfunction(L, ipairsaux);  /* iteration function */
267   lua_pushvalue(L, 1);  /* state */
268   lua_pushinteger(L, 0);  /* initial value */
269   return 3;
270 #endif
271 }
272 
273 
274 static int load_aux (lua_State *L, int status, int envidx) {
275   if (status == LUA_OK) {
276     if (envidx != 0) {  /* 'env' parameter? */
277       lua_pushvalue(L, envidx);  /* environment for loaded function */
278       if (!lua_setupvalue(L, -2, 1))  /* set it as 1st upvalue */
279         lua_pop(L, 1);  /* remove 'env' if not used by previous call */
280     }
281     return 1;
282   }
283   else {  /* error (message is on top of the stack) */
284     lua_pushnil(L);
285     lua_insert(L, -2);  /* put before error message */
286     return 2;  /* return nil plus error message */
287   }
288 }
289 
290 
291 #ifndef _KERNEL
292 static int luaB_loadfile (lua_State *L) {
293   const char *fname = luaL_optstring(L, 1, NULL);
294   const char *mode = luaL_optstring(L, 2, NULL);
295   int env = (!lua_isnone(L, 3) ? 3 : 0);  /* 'env' index or 0 if no 'env' */
296   int status = luaL_loadfilex(L, fname, mode);
297   return load_aux(L, status, env);
298 }
299 #endif /* _KERNEL */
300 
301 
302 /*
303 ** {======================================================
304 ** Generic Read function
305 ** =======================================================
306 */
307 
308 
309 /*
310 ** reserved slot, above all arguments, to hold a copy of the returned
311 ** string to avoid it being collected while parsed. 'load' has four
312 ** optional arguments (chunk, source name, mode, and environment).
313 */
314 #define RESERVEDSLOT	5
315 
316 
317 /*
318 ** Reader for generic 'load' function: 'lua_load' uses the
319 ** stack for internal stuff, so the reader cannot change the
320 ** stack top. Instead, it keeps its resulting string in a
321 ** reserved slot inside the stack.
322 */
323 static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
324   (void)(ud);  /* not used */
325   luaL_checkstack(L, 2, "too many nested functions");
326   lua_pushvalue(L, 1);  /* get function */
327   lua_call(L, 0, 1);  /* call it */
328   if (lua_isnil(L, -1)) {
329     lua_pop(L, 1);  /* pop result */
330     *size = 0;
331     return NULL;
332   }
333   else if (!lua_isstring(L, -1))
334     luaL_error(L, "reader function must return a string");
335   lua_replace(L, RESERVEDSLOT);  /* save string in reserved slot */
336   return lua_tolstring(L, RESERVEDSLOT, size);
337 }
338 
339 
340 static int luaB_load (lua_State *L) {
341   int status;
342   size_t l;
343   const char *s = lua_tolstring(L, 1, &l);
344   const char *mode = luaL_optstring(L, 3, "bt");
345   int env = (!lua_isnone(L, 4) ? 4 : 0);  /* 'env' index or 0 if no 'env' */
346   if (s != NULL) {  /* loading a string? */
347     const char *chunkname = luaL_optstring(L, 2, s);
348     status = luaL_loadbufferx(L, s, l, chunkname, mode);
349   }
350   else {  /* loading from a reader function */
351     const char *chunkname = luaL_optstring(L, 2, "=(load)");
352     luaL_checktype(L, 1, LUA_TFUNCTION);
353     lua_settop(L, RESERVEDSLOT);  /* create reserved slot */
354     status = lua_load(L, generic_reader, NULL, chunkname, mode);
355   }
356   return load_aux(L, status, env);
357 }
358 
359 /* }====================================================== */
360 
361 
362 #ifndef _KERNEL
363 static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
364   (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */
365   return lua_gettop(L) - 1;
366 }
367 
368 
369 static int luaB_dofile (lua_State *L) {
370   const char *fname = luaL_optstring(L, 1, NULL);
371   lua_settop(L, 1);
372   if (luaL_loadfile(L, fname) != LUA_OK)
373     return lua_error(L);
374   lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
375   return dofilecont(L, 0, 0);
376 }
377 #endif /* _KERNEL */
378 
379 
380 static int luaB_assert (lua_State *L) {
381   if (lua_toboolean(L, 1))  /* condition is true? */
382     return lua_gettop(L);  /* return all arguments */
383   else {  /* error */
384     luaL_checkany(L, 1);  /* there must be a condition */
385     lua_remove(L, 1);  /* remove it */
386     lua_pushliteral(L, "assertion failed!");  /* default message */
387     lua_settop(L, 1);  /* leave only message (default if no other one) */
388     return luaB_error(L);  /* call 'error' */
389   }
390 }
391 
392 
393 static int luaB_select (lua_State *L) {
394   int n = lua_gettop(L);
395   if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
396     lua_pushinteger(L, n-1);
397     return 1;
398   }
399   else {
400     lua_Integer i = luaL_checkinteger(L, 1);
401     if (i < 0) i = n + i;
402     else if (i > n) i = n;
403     luaL_argcheck(L, 1 <= i, 1, "index out of range");
404     return n - (int)i;
405   }
406 }
407 
408 
409 /*
410 ** Continuation function for 'pcall' and 'xpcall'. Both functions
411 ** already pushed a 'true' before doing the call, so in case of success
412 ** 'finishpcall' only has to return everything in the stack minus
413 ** 'extra' values (where 'extra' is exactly the number of items to be
414 ** ignored).
415 */
416 static int finishpcall (lua_State *L, int status, lua_KContext extra) {
417   if (status != LUA_OK && status != LUA_YIELD) {  /* error? */
418     lua_pushboolean(L, 0);  /* first result (false) */
419     lua_pushvalue(L, -2);  /* error message */
420     return 2;  /* return false, msg */
421   }
422   else
423     return lua_gettop(L) - (int)extra;  /* return all results */
424 }
425 
426 
427 static int luaB_pcall (lua_State *L) {
428   int status;
429   luaL_checkany(L, 1);
430   lua_pushboolean(L, 1);  /* first result if no errors */
431   lua_insert(L, 1);  /* put it in place */
432   status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
433   return finishpcall(L, status, 0);
434 }
435 
436 
437 /*
438 ** Do a protected call with error handling. After 'lua_rotate', the
439 ** stack will have <f, err, true, f, [args...]>; so, the function passes
440 ** 2 to 'finishpcall' to skip the 2 first values when returning results.
441 */
442 static int luaB_xpcall (lua_State *L) {
443   int status;
444   int n = lua_gettop(L);
445   luaL_checktype(L, 2, LUA_TFUNCTION);  /* check error function */
446   lua_pushboolean(L, 1);  /* first result */
447   lua_pushvalue(L, 1);  /* function */
448   lua_rotate(L, 3, 2);  /* move them below function's arguments */
449   status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
450   return finishpcall(L, status, 2);
451 }
452 
453 
454 static int luaB_tostring (lua_State *L) {
455   luaL_checkany(L, 1);
456   luaL_tolstring(L, 1, NULL);
457   return 1;
458 }
459 
460 
461 static const luaL_Reg base_funcs[] = {
462   {"assert", luaB_assert},
463   {"collectgarbage", luaB_collectgarbage},
464 #ifndef _KERNEL
465   {"dofile", luaB_dofile},
466 #endif /* _KERNEL */
467   {"error", luaB_error},
468   {"getmetatable", luaB_getmetatable},
469   {"ipairs", luaB_ipairs},
470 #ifndef _KERNEL
471   {"loadfile", luaB_loadfile},
472 #endif /* _KERNEL */
473   {"load", luaB_load},
474 #if defined(LUA_COMPAT_LOADSTRING)
475   {"loadstring", luaB_load},
476 #endif
477   {"next", luaB_next},
478   {"pairs", luaB_pairs},
479   {"pcall", luaB_pcall},
480   {"print", luaB_print},
481   {"rawequal", luaB_rawequal},
482   {"rawlen", luaB_rawlen},
483   {"rawget", luaB_rawget},
484   {"rawset", luaB_rawset},
485   {"select", luaB_select},
486   {"setmetatable", luaB_setmetatable},
487   {"tonumber", luaB_tonumber},
488   {"tostring", luaB_tostring},
489   {"type", luaB_type},
490   {"xpcall", luaB_xpcall},
491   /* placeholders */
492   {"_G", NULL},
493   {"_VERSION", NULL},
494   {NULL, NULL}
495 };
496 
497 
498 LUAMOD_API int luaopen_base (lua_State *L) {
499   /* open lib into global table */
500   lua_pushglobaltable(L);
501   luaL_setfuncs(L, base_funcs, 0);
502   /* set global _G */
503   lua_pushvalue(L, -1);
504   lua_setfield(L, -2, "_G");
505   /* set global _VERSION */
506   lua_pushliteral(L, LUA_VERSION);
507   lua_setfield(L, -2, "_VERSION");
508   return 1;
509 }
510 
511