xref: /netbsd-src/external/mit/lua/dist/src/lobject.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /*	$NetBSD: lobject.c,v 1.12 2018/08/04 17:30:01 alnsn Exp $	*/
2 
3 /*
4 ** Id: lobject.c,v 2.113.1.1 2017/04/19 17:29:57 roberto Exp
5 ** Some generic functions over Lua objects
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lobject_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <locale.h>
17 #include <math.h>
18 #include <stdarg.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #endif /* _KERNEL */
23 
24 #include "lua.h"
25 
26 #include "lctype.h"
27 #include "ldebug.h"
28 #include "ldo.h"
29 #include "lmem.h"
30 #include "lobject.h"
31 #include "lstate.h"
32 #include "lstring.h"
33 #include "lvm.h"
34 
35 
36 
37 LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
38 
39 
40 /*
41 ** converts an integer to a "floating point byte", represented as
42 ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
43 ** eeeee != 0 and (xxx) otherwise.
44 */
45 int luaO_int2fb (unsigned int x) {
46   int e = 0;  /* exponent */
47   if (x < 8) return x;
48   while (x >= (8 << 4)) {  /* coarse steps */
49     x = (x + 0xf) >> 4;  /* x = ceil(x / 16) */
50     e += 4;
51   }
52   while (x >= (8 << 1)) {  /* fine steps */
53     x = (x + 1) >> 1;  /* x = ceil(x / 2) */
54     e++;
55   }
56   return ((e+1) << 3) | (cast_int(x) - 8);
57 }
58 
59 
60 /* converts back */
61 int luaO_fb2int (int x) {
62   return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);
63 }
64 
65 
66 /*
67 ** Computes ceil(log2(x))
68 */
69 int luaO_ceillog2 (unsigned int x) {
70   static const lu_byte log_2[256] = {  /* log_2[i] = ceil(log2(i - 1)) */
71     0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
72     6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
73     7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
74     7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
75     8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
76     8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
77     8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
78     8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
79   };
80   int l = 0;
81   x--;
82   while (x >= 256) { l += 8; x >>= 8; }
83   return l + log_2[x];
84 }
85 
86 
87 static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
88                                                    lua_Integer v2) {
89   switch (op) {
90     case LUA_OPADD: return intop(+, v1, v2);
91     case LUA_OPSUB:return intop(-, v1, v2);
92     case LUA_OPMUL:return intop(*, v1, v2);
93     case LUA_OPMOD: return luaV_mod(L, v1, v2);
94     case LUA_OPIDIV: return luaV_div(L, v1, v2);
95     case LUA_OPBAND: return intop(&, v1, v2);
96     case LUA_OPBOR: return intop(|, v1, v2);
97     case LUA_OPBXOR: return intop(^, v1, v2);
98     case LUA_OPSHL: return luaV_shiftl(v1, v2);
99     case LUA_OPSHR: return luaV_shiftl(v1, -v2);
100     case LUA_OPUNM: return intop(-, 0, v1);
101     case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
102     default: lua_assert(0); return 0;
103   }
104 }
105 
106 
107 #ifndef _KERNEL
108 static lua_Number numarith (lua_State *L, int op, lua_Number v1,
109                                                   lua_Number v2) {
110   switch (op) {
111     case LUA_OPADD: return luai_numadd(L, v1, v2);
112     case LUA_OPSUB: return luai_numsub(L, v1, v2);
113     case LUA_OPMUL: return luai_nummul(L, v1, v2);
114     case LUA_OPDIV: return luai_numdiv(L, v1, v2);
115     case LUA_OPPOW: return luai_numpow(L, v1, v2);
116     case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
117     case LUA_OPUNM: return luai_numunm(L, v1);
118     case LUA_OPMOD: {
119       lua_Number m;
120       luai_nummod(L, v1, v2, m);
121       return m;
122     }
123     default: lua_assert(0); return 0;
124   }
125 }
126 #endif /* _KERNEL */
127 
128 
129 void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
130                  TValue *res) {
131   switch (op) {
132     case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
133     case LUA_OPSHL: case LUA_OPSHR:
134     case LUA_OPBNOT: {  /* operate only on integers */
135       lua_Integer i1; lua_Integer i2;
136       if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
137         setivalue(res, intarith(L, op, i1, i2));
138         return;
139       }
140       else break;  /* go to the end */
141     }
142 #ifndef _KERNEL
143     case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */
144       lua_Number n1; lua_Number n2;
145       if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
146         setfltvalue(res, numarith(L, op, n1, n2));
147         return;
148       }
149       else break;  /* go to the end */
150     }
151 #endif /* _KERNEL */
152     default: {  /* other operations */
153 #ifndef _KERNEL
154       lua_Number n1; lua_Number n2;
155       if (ttisinteger(p1) && ttisinteger(p2)) {
156         setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
157         return;
158       }
159       else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
160         setfltvalue(res, numarith(L, op, n1, n2));
161         return;
162       }
163 #else /* _KERNEL */
164       lua_Integer i1; lua_Integer i2;
165       if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
166         setivalue(res, intarith(L, op, i1, i2));
167         return;
168       }
169 #endif /* _KERNEL */
170       else break;  /* go to the end */
171     }
172   }
173   /* could not perform raw operation; try metamethod */
174   lua_assert(L != NULL);  /* should not fail when folding (compile time) */
175   luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
176 }
177 
178 
179 int luaO_hexavalue (int c) {
180   if (lisdigit(c)) return c - '0';
181   else return (ltolower(c) - 'a') + 10;
182 }
183 
184 
185 static int isneg (const char **s) {
186   if (**s == '-') { (*s)++; return 1; }
187   else if (**s == '+') (*s)++;
188   return 0;
189 }
190 
191 
192 
193 #ifndef _KERNEL
194 /*
195 ** {==================================================================
196 ** Lua's implementation for 'lua_strx2number'
197 ** ===================================================================
198 */
199 
200 #if !defined(lua_strx2number)
201 
202 /* maximum number of significant digits to read (to avoid overflows
203    even with single floats) */
204 #define MAXSIGDIG	30
205 
206 /*
207 ** convert an hexadecimal numeric string to a number, following
208 ** C99 specification for 'strtod'
209 */
210 static lua_Number lua_strx2number (const char *s, char **endptr) {
211   int dot = lua_getlocaledecpoint();
212   lua_Number r = 0.0;  /* result (accumulator) */
213   int sigdig = 0;  /* number of significant digits */
214   int nosigdig = 0;  /* number of non-significant digits */
215   int e = 0;  /* exponent correction */
216   int neg;  /* 1 if number is negative */
217   int hasdot = 0;  /* true after seen a dot */
218   *endptr = cast(char *, s);  /* nothing is valid yet */
219   while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
220   neg = isneg(&s);  /* check signal */
221   if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */
222     return 0.0;  /* invalid format (no '0x') */
223   for (s += 2; ; s++) {  /* skip '0x' and read numeral */
224     if (*s == dot) {
225       if (hasdot) break;  /* second dot? stop loop */
226       else hasdot = 1;
227     }
228     else if (lisxdigit(cast_uchar(*s))) {
229       if (sigdig == 0 && *s == '0')  /* non-significant digit (zero)? */
230         nosigdig++;
231       else if (++sigdig <= MAXSIGDIG)  /* can read it without overflow? */
232           r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
233       else e++; /* too many digits; ignore, but still count for exponent */
234       if (hasdot) e--;  /* decimal digit? correct exponent */
235     }
236     else break;  /* neither a dot nor a digit */
237   }
238   if (nosigdig + sigdig == 0)  /* no digits? */
239     return 0.0;  /* invalid format */
240   *endptr = cast(char *, s);  /* valid up to here */
241   e *= 4;  /* each digit multiplies/divides value by 2^4 */
242   if (*s == 'p' || *s == 'P') {  /* exponent part? */
243     int exp1 = 0;  /* exponent value */
244     int neg1;  /* exponent signal */
245     s++;  /* skip 'p' */
246     neg1 = isneg(&s);  /* signal */
247     if (!lisdigit(cast_uchar(*s)))
248       return 0.0;  /* invalid; must have at least one digit */
249     while (lisdigit(cast_uchar(*s)))  /* read exponent */
250       exp1 = exp1 * 10 + *(s++) - '0';
251     if (neg1) exp1 = -exp1;
252     e += exp1;
253     *endptr = cast(char *, s);  /* valid up to here */
254   }
255   if (neg) r = -r;
256   return l_mathop(ldexp)(r, e);
257 }
258 
259 #endif
260 /* }====================================================== */
261 
262 
263 /* maximum length of a numeral */
264 #if !defined (L_MAXLENNUM)
265 #define L_MAXLENNUM	200
266 #endif
267 
268 static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
269   char *endptr;
270   *result = (mode == 'x') ? lua_strx2number(s, &endptr)  /* try to convert */
271                           : lua_str2number(s, &endptr);
272   if (endptr == s) return NULL;  /* nothing recognized? */
273   while (lisspace(cast_uchar(*endptr))) endptr++;  /* skip trailing spaces */
274   return (*endptr == '\0') ? endptr : NULL;  /* OK if no trailing characters */
275 }
276 
277 
278 /*
279 ** Convert string 's' to a Lua number (put in 'result'). Return NULL
280 ** on fail or the address of the ending '\0' on success.
281 ** 'pmode' points to (and 'mode' contains) special things in the string:
282 ** - 'x'/'X' means an hexadecimal numeral
283 ** - 'n'/'N' means 'inf' or 'nan' (which should be rejected)
284 ** - '.' just optimizes the search for the common case (nothing special)
285 ** This function accepts both the current locale or a dot as the radix
286 ** mark. If the convertion fails, it may mean number has a dot but
287 ** locale accepts something else. In that case, the code copies 's'
288 ** to a buffer (because 's' is read-only), changes the dot to the
289 ** current locale radix mark, and tries to convert again.
290 */
291 static const char *l_str2d (const char *s, lua_Number *result) {
292   const char *endptr;
293   const char *pmode = strpbrk(s, ".xXnN");
294   int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
295   if (mode == 'n')  /* reject 'inf' and 'nan' */
296     return NULL;
297   endptr = l_str2dloc(s, result, mode);  /* try to convert */
298   if (endptr == NULL) {  /* failed? may be a different locale */
299     char buff[L_MAXLENNUM + 1];
300     const char *pdot = strchr(s, '.');
301     if (strlen(s) > L_MAXLENNUM || pdot == NULL)
302       return NULL;  /* string too long or no dot; fail */
303     strcpy(buff, s);  /* copy string to buffer */
304     buff[pdot - s] = lua_getlocaledecpoint();  /* correct decimal point */
305     endptr = l_str2dloc(buff, result, mode);  /* try again */
306     if (endptr != NULL)
307       endptr = s + (endptr - buff);  /* make relative to 's' */
308   }
309   return endptr;
310 }
311 #endif /* _KERNEL */
312 
313 
314 #define MAXBY10		cast(lua_Unsigned, LUA_MAXINTEGER / 10)
315 #define MAXLASTD	cast_int(LUA_MAXINTEGER % 10)
316 
317 static const char *l_str2int (const char *s, lua_Integer *result) {
318   lua_Unsigned a = 0;
319   int empty = 1;
320   int neg;
321   while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
322   neg = isneg(&s);
323   if (s[0] == '0' &&
324       (s[1] == 'x' || s[1] == 'X')) {  /* hex? */
325     s += 2;  /* skip '0x' */
326     for (; lisxdigit(cast_uchar(*s)); s++) {
327       a = a * 16 + luaO_hexavalue(*s);
328       empty = 0;
329     }
330   }
331   else {  /* decimal */
332     for (; lisdigit(cast_uchar(*s)); s++) {
333       int d = *s - '0';
334       if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg))  /* overflow? */
335         return NULL;  /* do not accept it (as integer) */
336       a = a * 10 + d;
337       empty = 0;
338     }
339   }
340   while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */
341   if (empty || *s != '\0') return NULL;  /* something wrong in the numeral */
342   else {
343     *result = l_castU2S((neg) ? 0u - a : a);
344     return s;
345   }
346 }
347 
348 
349 size_t luaO_str2num (const char *s, TValue *o) {
350 #ifndef _KERNEL
351   lua_Integer i; lua_Number n;
352 #else /* _KERNEL */
353   lua_Integer i;
354 #endif /* _KERNEL */
355   const char *e;
356   if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */
357     setivalue(o, i);
358   }
359 #ifndef _KERNEL
360   else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */
361     setfltvalue(o, n);
362   }
363 #endif /* _KERNEL */
364   else
365     return 0;  /* conversion failed */
366   return (e - s) + 1;  /* success; return string size */
367 }
368 
369 
370 int luaO_utf8esc (char *buff, unsigned long x) {
371   int n = 1;  /* number of bytes put in buffer (backwards) */
372   lua_assert(x <= 0x10FFFF);
373   if (x < 0x80)  /* ascii? */
374     buff[UTF8BUFFSZ - 1] = cast(char, x);
375   else {  /* need continuation bytes */
376     unsigned int mfb = 0x3f;  /* maximum that fits in first byte */
377     do {  /* add continuation bytes */
378       buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
379       x >>= 6;  /* remove added bits */
380       mfb >>= 1;  /* now there is one less bit available in first byte */
381     } while (x > mfb);  /* still needs continuation byte? */
382     buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x);  /* add first byte */
383   }
384   return n;
385 }
386 
387 
388 /* maximum length of the conversion of a number to a string */
389 #define MAXNUMBER2STR	50
390 
391 
392 /*
393 ** Convert a number object to a string
394 */
395 void luaO_tostring (lua_State *L, StkId obj) {
396   char buff[MAXNUMBER2STR];
397   size_t len;
398   lua_assert(ttisnumber(obj));
399 #ifndef _KERNEL
400   if (ttisinteger(obj))
401     len = lua_integer2str(buff, sizeof(buff), ivalue(obj));
402   else {
403     len = lua_number2str(buff, sizeof(buff), fltvalue(obj));
404 #if !defined(LUA_COMPAT_FLOATSTRING)
405     if (buff[strspn(buff, "-0123456789")] == '\0') {  /* looks like an int? */
406       buff[len++] = lua_getlocaledecpoint();
407       buff[len++] = '0';  /* adds '.0' to result */
408     }
409 #endif
410   }
411 #else /* _KERNEL */
412   lua_assert(ttisinteger(obj));
413   len = lua_integer2str(buff, sizeof(buff), ivalue(obj));
414 #endif /* _KERNEL */
415   setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
416 }
417 
418 
419 static void pushstr (lua_State *L, const char *str, size_t l) {
420   setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
421   luaD_inctop(L);
422 }
423 
424 
425 /*
426 ** this function handles only '%d', '%c', '%f', '%p', and '%s'
427    conventional formats, plus Lua-specific '%I' and '%U'
428 */
429 const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
430   int n = 0;
431   for (;;) {
432     const char *e = strchr(fmt, '%');
433     if (e == NULL) break;
434     pushstr(L, fmt, e - fmt);
435     switch (*(e+1)) {
436       case 's': {  /* zero-terminated string */
437         const char *s = va_arg(argp, char *);
438         if (s == NULL) s = "(null)";
439         pushstr(L, s, strlen(s));
440         break;
441       }
442       case 'c': {  /* an 'int' as a character */
443         char buff = cast(char, va_arg(argp, int));
444         if (lisprint(cast_uchar(buff)))
445           pushstr(L, &buff, 1);
446         else  /* non-printable character; print its code */
447           luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
448         break;
449       }
450       case 'd': {  /* an 'int' */
451         setivalue(L->top, va_arg(argp, int));
452         goto top2str;
453       }
454       case 'I': {  /* a 'lua_Integer' */
455         setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt)));
456 #ifndef _KERNEL
457         goto top2str;
458       }
459       case 'f': {  /* a 'lua_Number' */
460         setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
461 #endif /* _KERNEL */
462       top2str:  /* convert the top element to a string */
463         luaD_inctop(L);
464         luaO_tostring(L, L->top - 1);
465         break;
466       }
467       case 'p': {  /* a pointer */
468         char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
469         void *p = va_arg(argp, void *);
470         int l = lua_pointer2str(buff, sizeof(buff), p);
471         pushstr(L, buff, l);
472         break;
473       }
474       case 'U': {  /* an 'int' as a UTF-8 sequence */
475         char buff[UTF8BUFFSZ];
476         int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
477         pushstr(L, buff + UTF8BUFFSZ - l, l);
478         break;
479       }
480       case '%': {
481         pushstr(L, "%", 1);
482         break;
483       }
484       default: {
485         luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
486                          *(e + 1));
487       }
488     }
489     n += 2;
490     fmt = e+2;
491   }
492   luaD_checkstack(L, 1);
493   pushstr(L, fmt, strlen(fmt));
494   if (n > 0) luaV_concat(L, n + 1);
495   return svalue(L->top - 1);
496 }
497 
498 
499 const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
500   const char *msg;
501   va_list argp;
502   va_start(argp, fmt);
503   msg = luaO_pushvfstring(L, fmt, argp);
504   va_end(argp);
505   return msg;
506 }
507 
508 
509 /* number of chars of a literal string without the ending \0 */
510 #define LL(x)	(sizeof(x)/sizeof(char) - 1)
511 
512 #define RETS	"..."
513 #define PRE	"[string \""
514 #define POS	"\"]"
515 
516 #define addstr(a,b,l)	( memcpy(a,b,(l) * sizeof(char)), a += (l) )
517 
518 void luaO_chunkid (char *out, const char *source, size_t bufflen) {
519   size_t l = strlen(source);
520   if (*source == '=') {  /* 'literal' source */
521     if (l <= bufflen)  /* small enough? */
522       memcpy(out, source + 1, l * sizeof(char));
523     else {  /* truncate it */
524       addstr(out, source + 1, bufflen - 1);
525       *out = '\0';
526     }
527   }
528   else if (*source == '@') {  /* file name */
529     if (l <= bufflen)  /* small enough? */
530       memcpy(out, source + 1, l * sizeof(char));
531     else {  /* add '...' before rest of name */
532       addstr(out, RETS, LL(RETS));
533       bufflen -= LL(RETS);
534       memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
535     }
536   }
537   else {  /* string; format as [string "source"] */
538     const char *nl = strchr(source, '\n');  /* find first new line (if any) */
539     addstr(out, PRE, LL(PRE));  /* add prefix */
540     bufflen -= LL(PRE RETS POS) + 1;  /* save space for prefix+suffix+'\0' */
541     if (l < bufflen && nl == NULL) {  /* small one-line source? */
542       addstr(out, source, l);  /* keep it */
543     }
544     else {
545       if (nl != NULL) l = nl - source;  /* stop at first newline */
546       if (l > bufflen) l = bufflen;
547       addstr(out, source, l);
548       addstr(out, RETS, LL(RETS));
549     }
550     memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
551   }
552 }
553 
554