beta-0.89.2
[luatex.git] / source / libs / luajit / LuaJIT-src / src / lib_base.c
blob887fea7a58a233ef5df8c3b9f820f93720b2c675
1 /*
2 ** Base and coroutine library.
3 ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
4 **
5 ** Major portions taken verbatim or adapted from the Lua interpreter.
6 ** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h
7 */
9 #include <stdio.h>
11 #define lib_base_c
12 #define LUA_LIB
14 #include "lua.h"
15 #include "lauxlib.h"
16 #include "lualib.h"
18 #include "lj_obj.h"
19 #include "lj_gc.h"
20 #include "lj_err.h"
21 #include "lj_debug.h"
22 #include "lj_str.h"
23 #include "lj_tab.h"
24 #include "lj_meta.h"
25 #include "lj_state.h"
26 #if LJ_HASFFI
27 #include "lj_ctype.h"
28 #include "lj_cconv.h"
29 #endif
30 #include "lj_bc.h"
31 #include "lj_ff.h"
32 #include "lj_dispatch.h"
33 #include "lj_char.h"
34 #include "lj_strscan.h"
35 #include "lj_strfmt.h"
36 #include "lj_lib.h"
38 /* -- Base library: checks ------------------------------------------------ */
40 #define LJLIB_MODULE_base
42 LJLIB_ASM(assert) LJLIB_REC(.)
44 GCstr *s;
45 lj_lib_checkany(L, 1);
46 s = lj_lib_optstr(L, 2);
47 if (s)
48 lj_err_callermsg(L, strdata(s));
49 else
50 lj_err_caller(L, LJ_ERR_ASSERT);
51 return FFH_UNREACHABLE;
54 /* ORDER LJ_T */
55 LJLIB_PUSH("nil")
56 LJLIB_PUSH("boolean")
57 LJLIB_PUSH(top-1) /* boolean */
58 LJLIB_PUSH("userdata")
59 LJLIB_PUSH("string")
60 LJLIB_PUSH("upval")
61 LJLIB_PUSH("thread")
62 LJLIB_PUSH("proto")
63 LJLIB_PUSH("function")
64 LJLIB_PUSH("trace")
65 LJLIB_PUSH("cdata")
66 LJLIB_PUSH("table")
67 LJLIB_PUSH(top-9) /* userdata */
68 LJLIB_PUSH("number")
69 LJLIB_ASM_(type) LJLIB_REC(.)
70 /* Recycle the lj_lib_checkany(L, 1) from assert. */
72 /* -- Base library: iterators --------------------------------------------- */
74 /* This solves a circular dependency problem -- change FF_next_N as needed. */
75 LJ_STATIC_ASSERT((int)FF_next == FF_next_N);
77 LJLIB_ASM(next)
79 lj_lib_checktab(L, 1);
80 return FFH_UNREACHABLE;
83 #if LJ_52 || LJ_HASFFI
84 static int ffh_pairs(lua_State *L, MMS mm)
86 TValue *o = lj_lib_checkany(L, 1);
87 cTValue *mo = lj_meta_lookup(L, o, mm);
88 if ((LJ_52 || tviscdata(o)) && !tvisnil(mo)) {
89 L->top = o+1; /* Only keep one argument. */
90 copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
91 return FFH_TAILCALL;
92 } else {
93 if (!tvistab(o)) lj_err_argt(L, 1, LUA_TTABLE);
94 if (LJ_FR2) { copyTV(L, o-1, o); o--; }
95 setfuncV(L, o-1, funcV(lj_lib_upvalue(L, 1)));
96 if (mm == MM_pairs) setnilV(o+1); else setintV(o+1, 0);
97 return FFH_RES(3);
100 #else
101 #define ffh_pairs(L, mm) (lj_lib_checktab(L, 1), FFH_UNREACHABLE)
102 #endif
104 LJLIB_PUSH(lastcl)
105 LJLIB_ASM(pairs) LJLIB_REC(xpairs 0)
107 return ffh_pairs(L, MM_pairs);
110 LJLIB_NOREGUV LJLIB_ASM(ipairs_aux) LJLIB_REC(.)
112 lj_lib_checktab(L, 1);
113 lj_lib_checkint(L, 2);
114 return FFH_UNREACHABLE;
117 LJLIB_PUSH(lastcl)
118 LJLIB_ASM(ipairs) LJLIB_REC(xpairs 1)
120 return ffh_pairs(L, MM_ipairs);
123 /* -- Base library: getters and setters ----------------------------------- */
125 LJLIB_ASM_(getmetatable) LJLIB_REC(.)
126 /* Recycle the lj_lib_checkany(L, 1) from assert. */
128 LJLIB_ASM(setmetatable) LJLIB_REC(.)
130 GCtab *t = lj_lib_checktab(L, 1);
131 GCtab *mt = lj_lib_checktabornil(L, 2);
132 if (!tvisnil(lj_meta_lookup(L, L->base, MM_metatable)))
133 lj_err_caller(L, LJ_ERR_PROTMT);
134 setgcref(t->metatable, obj2gco(mt));
135 if (mt) { lj_gc_objbarriert(L, t, mt); }
136 settabV(L, L->base-1-LJ_FR2, t);
137 return FFH_RES(1);
140 LJLIB_CF(getfenv) LJLIB_REC(.)
142 GCfunc *fn;
143 cTValue *o = L->base;
144 if (!(o < L->top && tvisfunc(o))) {
145 int level = lj_lib_optint(L, 1, 1);
146 o = lj_debug_frame(L, level, &level);
147 if (o == NULL)
148 lj_err_arg(L, 1, LJ_ERR_INVLVL);
149 if (LJ_FR2) o--;
151 fn = &gcval(o)->fn;
152 settabV(L, L->top++, isluafunc(fn) ? tabref(fn->l.env) : tabref(L->env));
153 return 1;
156 LJLIB_CF(setfenv)
158 GCfunc *fn;
159 GCtab *t = lj_lib_checktab(L, 2);
160 cTValue *o = L->base;
161 if (!(o < L->top && tvisfunc(o))) {
162 int level = lj_lib_checkint(L, 1);
163 if (level == 0) {
164 /* NOBARRIER: A thread (i.e. L) is never black. */
165 setgcref(L->env, obj2gco(t));
166 return 0;
168 o = lj_debug_frame(L, level, &level);
169 if (o == NULL)
170 lj_err_arg(L, 1, LJ_ERR_INVLVL);
171 if (LJ_FR2) o--;
173 fn = &gcval(o)->fn;
174 if (!isluafunc(fn))
175 lj_err_caller(L, LJ_ERR_SETFENV);
176 setgcref(fn->l.env, obj2gco(t));
177 lj_gc_objbarrier(L, obj2gco(fn), t);
178 setfuncV(L, L->top++, fn);
179 return 1;
182 LJLIB_ASM(rawget) LJLIB_REC(.)
184 lj_lib_checktab(L, 1);
185 lj_lib_checkany(L, 2);
186 return FFH_UNREACHABLE;
189 LJLIB_CF(rawset) LJLIB_REC(.)
191 lj_lib_checktab(L, 1);
192 lj_lib_checkany(L, 2);
193 L->top = 1+lj_lib_checkany(L, 3);
194 lua_rawset(L, 1);
195 return 1;
198 LJLIB_CF(rawequal) LJLIB_REC(.)
200 cTValue *o1 = lj_lib_checkany(L, 1);
201 cTValue *o2 = lj_lib_checkany(L, 2);
202 setboolV(L->top-1, lj_obj_equal(o1, o2));
203 return 1;
206 #if LJ_52
207 LJLIB_CF(rawlen) LJLIB_REC(.)
209 cTValue *o = L->base;
210 int32_t len;
211 if (L->top > o && tvisstr(o))
212 len = (int32_t)strV(o)->len;
213 else
214 len = (int32_t)lj_tab_len(lj_lib_checktab(L, 1));
215 setintV(L->top-1, len);
216 return 1;
218 #endif
220 LJLIB_CF(unpack)
222 GCtab *t = lj_lib_checktab(L, 1);
223 int32_t n, i = lj_lib_optint(L, 2, 1);
224 int32_t e = (L->base+3-1 < L->top && !tvisnil(L->base+3-1)) ?
225 lj_lib_checkint(L, 3) : (int32_t)lj_tab_len(t);
226 if (i > e) return 0;
227 n = e - i + 1;
228 if (n <= 0 || !lua_checkstack(L, n))
229 lj_err_caller(L, LJ_ERR_UNPACK);
230 do {
231 cTValue *tv = lj_tab_getint(t, i);
232 if (tv) {
233 copyTV(L, L->top++, tv);
234 } else {
235 setnilV(L->top++);
237 } while (i++ < e);
238 return n;
241 LJLIB_CF(select) LJLIB_REC(.)
243 int32_t n = (int32_t)(L->top - L->base);
244 if (n >= 1 && tvisstr(L->base) && *strVdata(L->base) == '#') {
245 setintV(L->top-1, n-1);
246 return 1;
247 } else {
248 int32_t i = lj_lib_checkint(L, 1);
249 if (i < 0) i = n + i; else if (i > n) i = n;
250 if (i < 1)
251 lj_err_arg(L, 1, LJ_ERR_IDXRNG);
252 return n - i;
256 /* -- Base library: conversions ------------------------------------------- */
258 LJLIB_ASM(tonumber) LJLIB_REC(.)
260 int32_t base = lj_lib_optint(L, 2, 10);
261 if (base == 10) {
262 TValue *o = lj_lib_checkany(L, 1);
263 if (lj_strscan_numberobj(o)) {
264 copyTV(L, L->base-1-LJ_FR2, o);
265 return FFH_RES(1);
267 #if LJ_HASFFI
268 if (tviscdata(o)) {
269 CTState *cts = ctype_cts(L);
270 CType *ct = lj_ctype_rawref(cts, cdataV(o)->ctypeid);
271 if (ctype_isenum(ct->info)) ct = ctype_child(cts, ct);
272 if (ctype_isnum(ct->info) || ctype_iscomplex(ct->info)) {
273 if (LJ_DUALNUM && ctype_isinteger_or_bool(ct->info) &&
274 ct->size <= 4 && !(ct->size == 4 && (ct->info & CTF_UNSIGNED))) {
275 int32_t i;
276 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o, 0);
277 setintV(L->base-1-LJ_FR2, i);
278 return FFH_RES(1);
280 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_DOUBLE),
281 (uint8_t *)&(L->base-1-LJ_FR2)->n, o, 0);
282 return FFH_RES(1);
285 #endif
286 } else {
287 const char *p = strdata(lj_lib_checkstr(L, 1));
288 char *ep;
289 unsigned long ul;
290 if (base < 2 || base > 36)
291 lj_err_arg(L, 2, LJ_ERR_BASERNG);
292 ul = strtoul(p, &ep, base);
293 if (p != ep) {
294 while (lj_char_isspace((unsigned char)(*ep))) ep++;
295 if (*ep == '\0') {
296 if (LJ_DUALNUM && LJ_LIKELY(ul < 0x80000000u))
297 setintV(L->base-1-LJ_FR2, (int32_t)ul);
298 else
299 setnumV(L->base-1-LJ_FR2, (lua_Number)ul);
300 return FFH_RES(1);
304 setnilV(L->base-1-LJ_FR2);
305 return FFH_RES(1);
308 LJLIB_ASM(tostring) LJLIB_REC(.)
310 TValue *o = lj_lib_checkany(L, 1);
311 cTValue *mo;
312 L->top = o+1; /* Only keep one argument. */
313 if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {
314 copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
315 return FFH_TAILCALL;
317 lj_gc_check(L);
318 setstrV(L, L->base-1-LJ_FR2, lj_strfmt_obj(L, L->base));
319 return FFH_RES(1);
322 /* -- Base library: throw and catch errors -------------------------------- */
324 LJLIB_CF(error)
326 int32_t level = lj_lib_optint(L, 2, 1);
327 lua_settop(L, 1);
328 if (lua_isstring(L, 1) && level > 0) {
329 luaL_where(L, level);
330 lua_pushvalue(L, 1);
331 lua_concat(L, 2);
333 return lua_error(L);
336 LJLIB_ASM(pcall) LJLIB_REC(.)
338 lj_lib_checkany(L, 1);
339 lj_lib_checkfunc(L, 2); /* For xpcall only. */
340 return FFH_UNREACHABLE;
342 LJLIB_ASM_(xpcall) LJLIB_REC(.)
344 /* -- Base library: load Lua code ----------------------------------------- */
346 static int load_aux(lua_State *L, int status, int envarg)
348 if (status == 0) {
349 if (tvistab(L->base+envarg-1)) {
350 GCfunc *fn = funcV(L->top-1);
351 GCtab *t = tabV(L->base+envarg-1);
352 setgcref(fn->c.env, obj2gco(t));
353 lj_gc_objbarrier(L, fn, t);
355 return 1;
356 } else {
357 setnilV(L->top-2);
358 return 2;
362 LJLIB_CF(loadfile)
364 GCstr *fname = lj_lib_optstr(L, 1);
365 GCstr *mode = lj_lib_optstr(L, 2);
366 int status;
367 lua_settop(L, 3); /* Ensure env arg exists. */
368 status = luaL_loadfilex(L, fname ? strdata(fname) : NULL,
369 mode ? strdata(mode) : NULL);
370 return load_aux(L, status, 3);
373 static const char *reader_func(lua_State *L, void *ud, size_t *size)
375 UNUSED(ud);
376 luaL_checkstack(L, 2, "too many nested functions");
377 copyTV(L, L->top++, L->base);
378 lua_call(L, 0, 1); /* Call user-supplied function. */
379 L->top--;
380 if (tvisnil(L->top)) {
381 *size = 0;
382 return NULL;
383 } else if (tvisstr(L->top) || tvisnumber(L->top)) {
384 copyTV(L, L->base+4, L->top); /* Anchor string in reserved stack slot. */
385 return lua_tolstring(L, 5, size);
386 } else {
387 lj_err_caller(L, LJ_ERR_RDRSTR);
388 return NULL;
392 LJLIB_CF(load)
394 GCstr *name = lj_lib_optstr(L, 2);
395 GCstr *mode = lj_lib_optstr(L, 3);
396 int status;
397 if (L->base < L->top && (tvisstr(L->base) || tvisnumber(L->base))) {
398 GCstr *s = lj_lib_checkstr(L, 1);
399 lua_settop(L, 4); /* Ensure env arg exists. */
400 status = luaL_loadbufferx(L, strdata(s), s->len, strdata(name ? name : s),
401 mode ? strdata(mode) : NULL);
402 } else {
403 lj_lib_checkfunc(L, 1);
404 lua_settop(L, 5); /* Reserve a slot for the string from the reader. */
405 status = lua_loadx(L, reader_func, NULL, name ? strdata(name) : "=(load)",
406 mode ? strdata(mode) : NULL);
408 return load_aux(L, status, 4);
411 LJLIB_CF(loadstring)
413 return lj_cf_load(L);
416 LJLIB_CF(dofile)
418 GCstr *fname = lj_lib_optstr(L, 1);
419 setnilV(L->top);
420 L->top = L->base+1;
421 if (luaL_loadfile(L, fname ? strdata(fname) : NULL) != 0)
422 lua_error(L);
423 lua_call(L, 0, LUA_MULTRET);
424 return (int)(L->top - L->base) - 1;
427 /* -- Base library: GC control -------------------------------------------- */
429 LJLIB_CF(gcinfo)
431 setintV(L->top++, (int32_t)(G(L)->gc.total >> 10));
432 return 1;
435 LJLIB_CF(collectgarbage)
437 int opt = lj_lib_checkopt(L, 1, LUA_GCCOLLECT, /* ORDER LUA_GC* */
438 "\4stop\7restart\7collect\5count\1\377\4step\10setpause\12setstepmul");
439 int32_t data = lj_lib_optint(L, 2, 0);
440 if (opt == LUA_GCCOUNT) {
441 setnumV(L->top, (lua_Number)G(L)->gc.total/1024.0);
442 } else {
443 int res = lua_gc(L, opt, data);
444 if (opt == LUA_GCSTEP)
445 setboolV(L->top, res);
446 else
447 setintV(L->top, res);
449 L->top++;
450 return 1;
453 /* -- Base library: miscellaneous functions ------------------------------- */
455 LJLIB_PUSH(top-2) /* Upvalue holds weak table. */
456 LJLIB_CF(newproxy)
458 lua_settop(L, 1);
459 lua_newuserdata(L, 0);
460 if (lua_toboolean(L, 1) == 0) { /* newproxy(): without metatable. */
461 return 1;
462 } else if (lua_isboolean(L, 1)) { /* newproxy(true): with metatable. */
463 lua_newtable(L);
464 lua_pushvalue(L, -1);
465 lua_pushboolean(L, 1);
466 lua_rawset(L, lua_upvalueindex(1)); /* Remember mt in weak table. */
467 } else { /* newproxy(proxy): inherit metatable. */
468 int validproxy = 0;
469 if (lua_getmetatable(L, 1)) {
470 lua_rawget(L, lua_upvalueindex(1));
471 validproxy = lua_toboolean(L, -1);
472 lua_pop(L, 1);
474 if (!validproxy)
475 lj_err_arg(L, 1, LJ_ERR_NOPROXY);
476 lua_getmetatable(L, 1);
478 lua_setmetatable(L, 2);
479 return 1;
482 LJLIB_PUSH("tostring")
483 LJLIB_CF(print)
485 ptrdiff_t i, nargs = L->top - L->base;
486 cTValue *tv = lj_tab_getstr(tabref(L->env), strV(lj_lib_upvalue(L, 1)));
487 int shortcut;
488 if (tv && !tvisnil(tv)) {
489 copyTV(L, L->top++, tv);
490 } else {
491 setstrV(L, L->top++, strV(lj_lib_upvalue(L, 1)));
492 lua_gettable(L, LUA_GLOBALSINDEX);
493 tv = L->top-1;
495 shortcut = (tvisfunc(tv) && funcV(tv)->c.ffid == FF_tostring);
496 for (i = 0; i < nargs; i++) {
497 cTValue *o = &L->base[i];
498 char buf[STRFMT_MAXBUF_NUM];
499 const char *str;
500 size_t size;
501 MSize len;
502 if (shortcut && (str = lj_strfmt_wstrnum(buf, o, &len)) != NULL) {
503 size = len;
504 } else {
505 copyTV(L, L->top+1, o);
506 copyTV(L, L->top, L->top-1);
507 L->top += 2;
508 lua_call(L, 1, 1);
509 str = lua_tolstring(L, -1, &size);
510 if (!str)
511 lj_err_caller(L, LJ_ERR_PRTOSTR);
512 L->top--;
514 if (i)
515 putchar('\t');
516 fwrite(str, 1, size, stdout);
518 putchar('\n');
519 return 0;
522 LJLIB_PUSH(top-3)
523 LJLIB_SET(_VERSION)
525 #include "lj_libdef.h"
527 /* -- Coroutine library --------------------------------------------------- */
529 #define LJLIB_MODULE_coroutine
531 LJLIB_CF(coroutine_status)
533 const char *s;
534 lua_State *co;
535 if (!(L->top > L->base && tvisthread(L->base)))
536 lj_err_arg(L, 1, LJ_ERR_NOCORO);
537 co = threadV(L->base);
538 if (co == L) s = "running";
539 else if (co->status == LUA_YIELD) s = "suspended";
540 else if (co->status != 0) s = "dead";
541 else if (co->base > tvref(co->stack)+1+LJ_FR2) s = "normal";
542 else if (co->top == co->base) s = "dead";
543 else s = "suspended";
544 lua_pushstring(L, s);
545 return 1;
548 LJLIB_CF(coroutine_running)
550 #if LJ_52
551 int ismain = lua_pushthread(L);
552 setboolV(L->top++, ismain);
553 return 2;
554 #else
555 if (lua_pushthread(L))
556 setnilV(L->top++);
557 return 1;
558 #endif
561 LJLIB_CF(coroutine_create)
563 lua_State *L1;
564 if (!(L->base < L->top && tvisfunc(L->base)))
565 lj_err_argt(L, 1, LUA_TFUNCTION);
566 L1 = lua_newthread(L);
567 setfuncV(L, L1->top++, funcV(L->base));
568 return 1;
571 LJLIB_ASM(coroutine_yield)
573 lj_err_caller(L, LJ_ERR_CYIELD);
574 return FFH_UNREACHABLE;
577 static int ffh_resume(lua_State *L, lua_State *co, int wrap)
579 if (co->cframe != NULL || co->status > LUA_YIELD ||
580 (co->status == 0 && co->top == co->base)) {
581 ErrMsg em = co->cframe ? LJ_ERR_CORUN : LJ_ERR_CODEAD;
582 if (wrap) lj_err_caller(L, em);
583 setboolV(L->base-1-LJ_FR2, 0);
584 setstrV(L, L->base-LJ_FR2, lj_err_str(L, em));
585 return FFH_RES(2);
587 lj_state_growstack(co, (MSize)(L->top - L->base));
588 return FFH_RETRY;
591 LJLIB_ASM(coroutine_resume)
593 if (!(L->top > L->base && tvisthread(L->base)))
594 lj_err_arg(L, 1, LJ_ERR_NOCORO);
595 return ffh_resume(L, threadV(L->base), 0);
598 LJLIB_NOREG LJLIB_ASM(coroutine_wrap_aux)
600 return ffh_resume(L, threadV(lj_lib_upvalue(L, 1)), 1);
603 /* Inline declarations. */
604 LJ_ASMF void lj_ff_coroutine_wrap_aux(void);
605 #if !(LJ_TARGET_MIPS && defined(ljamalg_c))
606 LJ_FUNCA_NORET void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L,
607 lua_State *co);
608 #endif
610 /* Error handler, called from assembler VM. */
611 void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L, lua_State *co)
613 co->top--; copyTV(L, L->top, co->top); L->top++;
614 if (tvisstr(L->top-1))
615 lj_err_callermsg(L, strVdata(L->top-1));
616 else
617 lj_err_run(L);
620 /* Forward declaration. */
621 static void setpc_wrap_aux(lua_State *L, GCfunc *fn);
623 LJLIB_CF(coroutine_wrap)
625 GCfunc *fn;
626 lj_cf_coroutine_create(L);
627 fn = lj_lib_pushcc(L, lj_ffh_coroutine_wrap_aux, FF_coroutine_wrap_aux, 1);
628 setpc_wrap_aux(L, fn);
629 return 1;
632 #include "lj_libdef.h"
634 /* Fix the PC of wrap_aux. Really ugly workaround. */
635 static void setpc_wrap_aux(lua_State *L, GCfunc *fn)
637 setmref(fn->c.pc, &L2GG(L)->bcff[lj_lib_init_coroutine[1]+2]);
640 /* ------------------------------------------------------------------------ */
642 static void newproxy_weaktable(lua_State *L)
644 /* NOBARRIER: The table is new (marked white). */
645 GCtab *t = lj_tab_new(L, 0, 1);
646 settabV(L, L->top++, t);
647 setgcref(t->metatable, obj2gco(t));
648 setstrV(L, lj_tab_setstr(L, t, lj_str_newlit(L, "__mode")),
649 lj_str_newlit(L, "kv"));
650 t->nomm = (uint8_t)(~(1u<<MM_mode));
653 LUALIB_API int luaopen_base(lua_State *L)
655 /* NOBARRIER: Table and value are the same. */
656 GCtab *env = tabref(L->env);
657 settabV(L, lj_tab_setstr(L, env, lj_str_newlit(L, "_G")), env);
658 lua_pushliteral(L, LUA_VERSION); /* top-3. */
659 newproxy_weaktable(L); /* top-2. */
660 LJ_LIB_REG(L, "_G", base);
661 LJ_LIB_REG(L, LUA_COLIBNAME, coroutine);
662 return 2;