Fix underflow handling in builtin string to number conversion.
[luajit-2.0/celess22.git] / src / lj_cparse.c
blobab5903fa210dce77e5878726d3b2643a4fd6878f
1 /*
2 ** C declaration parser.
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #include "lj_obj.h"
8 #if LJ_HASFFI
10 #include "lj_gc.h"
11 #include "lj_err.h"
12 #include "lj_str.h"
13 #include "lj_ctype.h"
14 #include "lj_cparse.h"
15 #include "lj_frame.h"
16 #include "lj_vm.h"
17 #include "lj_char.h"
18 #include "lj_strscan.h"
21 ** Important note: this is NOT a validating C parser! This is a minimal
22 ** C declaration parser, solely for use by the LuaJIT FFI.
24 ** It ought to return correct results for properly formed C declarations,
25 ** but it may accept some invalid declarations, too (and return nonsense).
26 ** Also, it shows rather generic error messages to avoid unnecessary bloat.
27 ** If in doubt, please check the input against your favorite C compiler.
30 /* -- C lexer ------------------------------------------------------------- */
32 /* C lexer token names. */
33 static const char *const ctoknames[] = {
34 #define CTOKSTR(name, str) str,
35 CTOKDEF(CTOKSTR)
36 #undef CTOKSTR
37 NULL
40 /* Forward declaration. */
41 LJ_NORET static void cp_err(CPState *cp, ErrMsg em);
43 static const char *cp_tok2str(CPState *cp, CPToken tok)
45 lua_assert(tok < CTOK_FIRSTDECL);
46 if (tok > CTOK_OFS)
47 return ctoknames[tok-CTOK_OFS-1];
48 else if (!lj_char_iscntrl(tok))
49 return lj_str_pushf(cp->L, "%c", tok);
50 else
51 return lj_str_pushf(cp->L, "char(%d)", tok);
54 /* End-of-line? */
55 static LJ_AINLINE int cp_iseol(CPChar c)
57 return (c == '\n' || c == '\r');
60 static LJ_AINLINE CPChar cp_get(CPState *cp);
62 /* Peek next raw character. */
63 static LJ_AINLINE CPChar cp_rawpeek(CPState *cp)
65 return (CPChar)(uint8_t)(*cp->p);
68 /* Transparently skip backslash-escaped line breaks. */
69 static LJ_NOINLINE CPChar cp_get_bs(CPState *cp)
71 CPChar c2, c = cp_rawpeek(cp);
72 if (!cp_iseol(c)) return cp->c;
73 cp->p++;
74 c2 = cp_rawpeek(cp);
75 if (cp_iseol(c2) && c2 != c) cp->p++;
76 cp->linenumber++;
77 return cp_get(cp);
80 /* Get next character. */
81 static LJ_AINLINE CPChar cp_get(CPState *cp)
83 cp->c = (CPChar)(uint8_t)(*cp->p++);
84 if (LJ_LIKELY(cp->c != '\\')) return cp->c;
85 return cp_get_bs(cp);
88 /* Grow save buffer. */
89 static LJ_NOINLINE void cp_save_grow(CPState *cp, CPChar c)
91 MSize newsize;
92 if (cp->sb.sz >= CPARSE_MAX_BUF/2)
93 cp_err(cp, LJ_ERR_XELEM);
94 newsize = cp->sb.sz * 2;
95 lj_str_resizebuf(cp->L, &cp->sb, newsize);
96 cp->sb.buf[cp->sb.n++] = (char)c;
99 /* Save character in buffer. */
100 static LJ_AINLINE void cp_save(CPState *cp, CPChar c)
102 if (LJ_UNLIKELY(cp->sb.n + 1 > cp->sb.sz))
103 cp_save_grow(cp, c);
104 else
105 cp->sb.buf[cp->sb.n++] = (char)c;
108 /* Skip line break. Handles "\n", "\r", "\r\n" or "\n\r". */
109 static void cp_newline(CPState *cp)
111 CPChar c = cp_rawpeek(cp);
112 if (cp_iseol(c) && c != cp->c) cp->p++;
113 cp->linenumber++;
116 LJ_NORET static void cp_errmsg(CPState *cp, CPToken tok, ErrMsg em, ...)
118 const char *msg, *tokstr;
119 lua_State *L;
120 va_list argp;
121 if (tok == 0) {
122 tokstr = NULL;
123 } else if (tok == CTOK_IDENT || tok == CTOK_INTEGER || tok == CTOK_STRING ||
124 tok >= CTOK_FIRSTDECL) {
125 if (cp->sb.n == 0) cp_save(cp, '$');
126 cp_save(cp, '\0');
127 tokstr = cp->sb.buf;
128 } else {
129 tokstr = cp_tok2str(cp, tok);
131 L = cp->L;
132 va_start(argp, em);
133 msg = lj_str_pushvf(L, err2msg(em), argp);
134 va_end(argp);
135 if (tokstr)
136 msg = lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tokstr);
137 if (cp->linenumber > 1)
138 msg = lj_str_pushf(L, "%s at line %d", msg, cp->linenumber);
139 lj_err_callermsg(L, msg);
142 LJ_NORET LJ_NOINLINE static void cp_err_token(CPState *cp, CPToken tok)
144 cp_errmsg(cp, cp->tok, LJ_ERR_XTOKEN, cp_tok2str(cp, tok));
147 LJ_NORET LJ_NOINLINE static void cp_err_badidx(CPState *cp, CType *ct)
149 GCstr *s = lj_ctype_repr(cp->cts->L, ctype_typeid(cp->cts, ct), NULL);
150 cp_errmsg(cp, 0, LJ_ERR_FFI_BADIDX, strdata(s));
153 LJ_NORET LJ_NOINLINE static void cp_err(CPState *cp, ErrMsg em)
155 cp_errmsg(cp, 0, em);
158 /* -- Main lexical scanner ------------------------------------------------ */
160 /* Parse number literal. Only handles int32_t/uint32_t right now. */
161 static CPToken cp_number(CPState *cp)
163 StrScanFmt fmt;
164 TValue o;
165 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
166 cp_save(cp, '\0');
167 fmt = lj_strscan_scan((const uint8_t *)cp->sb.buf, &o, STRSCAN_OPT_C);
168 if (fmt == STRSCAN_INT) cp->val.id = CTID_INT32;
169 else if (fmt == STRSCAN_U32) cp->val.id = CTID_UINT32;
170 else if (!(cp->mode & CPARSE_MODE_SKIP))
171 cp_errmsg(cp, CTOK_INTEGER, LJ_ERR_XNUMBER);
172 cp->val.u32 = (uint32_t)o.i;
173 return CTOK_INTEGER;
176 /* Parse identifier or keyword. */
177 static CPToken cp_ident(CPState *cp)
179 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
180 cp->str = lj_str_new(cp->L, cp->sb.buf, cp->sb.n);
181 cp->val.id = lj_ctype_getname(cp->cts, &cp->ct, cp->str, cp->tmask);
182 if (ctype_type(cp->ct->info) == CT_KW)
183 return ctype_cid(cp->ct->info);
184 return CTOK_IDENT;
187 /* Parse parameter. */
188 static CPToken cp_param(CPState *cp)
190 CPChar c = cp_get(cp);
191 TValue *o = cp->param;
192 if (lj_char_isident(c) || c == '$') /* Reserve $xyz for future extensions. */
193 cp_errmsg(cp, c, LJ_ERR_XSYNTAX);
194 if (!o || o >= cp->L->top)
195 cp_err(cp, LJ_ERR_FFI_NUMPARAM);
196 cp->param = o+1;
197 if (tvisstr(o)) {
198 cp->str = strV(o);
199 cp->val.id = 0;
200 cp->ct = &cp->cts->tab[0];
201 return CTOK_IDENT;
202 } else if (tvisnumber(o)) {
203 cp->val.i32 = numberVint(o);
204 cp->val.id = CTID_INT32;
205 return CTOK_INTEGER;
206 } else {
207 GCcdata *cd;
208 if (!tviscdata(o))
209 lj_err_argtype(cp->L, (int)(o-cp->L->base)+1, "type parameter");
210 cd = cdataV(o);
211 if (cd->ctypeid == CTID_CTYPEID)
212 cp->val.id = *(CTypeID *)cdataptr(cd);
213 else
214 cp->val.id = cd->ctypeid;
215 return '$';
219 /* Parse string or character constant. */
220 static CPToken cp_string(CPState *cp)
222 CPChar delim = cp->c;
223 cp_get(cp);
224 while (cp->c != delim) {
225 CPChar c = cp->c;
226 if (c == '\0') cp_errmsg(cp, CTOK_EOF, LJ_ERR_XSTR);
227 if (c == '\\') {
228 c = cp_get(cp);
229 switch (c) {
230 case '\0': cp_errmsg(cp, CTOK_EOF, LJ_ERR_XSTR); break;
231 case 'a': c = '\a'; break;
232 case 'b': c = '\b'; break;
233 case 'f': c = '\f'; break;
234 case 'n': c = '\n'; break;
235 case 'r': c = '\r'; break;
236 case 't': c = '\t'; break;
237 case 'v': c = '\v'; break;
238 case 'e': c = 27; break;
239 case 'x':
240 c = 0;
241 while (lj_char_isxdigit(cp_get(cp)))
242 c = (c<<4) + (lj_char_isdigit(cp->c) ? cp->c-'0' : (cp->c&15)+9);
243 cp_save(cp, (c & 0xff));
244 continue;
245 default:
246 if (lj_char_isdigit(c)) {
247 c -= '0';
248 if (lj_char_isdigit(cp_get(cp))) {
249 c = c*8 + (cp->c - '0');
250 if (lj_char_isdigit(cp_get(cp))) {
251 c = c*8 + (cp->c - '0');
252 cp_get(cp);
255 cp_save(cp, (c & 0xff));
256 continue;
258 break;
261 cp_save(cp, c);
262 cp_get(cp);
264 cp_get(cp);
265 if (delim == '"') {
266 cp->str = lj_str_new(cp->L, cp->sb.buf, cp->sb.n);
267 return CTOK_STRING;
268 } else {
269 if (cp->sb.n != 1) cp_err_token(cp, '\'');
270 cp->val.i32 = (int32_t)(char)cp->sb.buf[0];
271 cp->val.id = CTID_INT32;
272 return CTOK_INTEGER;
276 /* Skip C comment. */
277 static void cp_comment_c(CPState *cp)
279 do {
280 if (cp_get(cp) == '*') {
281 do {
282 if (cp_get(cp) == '/') { cp_get(cp); return; }
283 } while (cp->c == '*');
285 if (cp_iseol(cp->c)) cp_newline(cp);
286 } while (cp->c != '\0');
289 /* Skip C++ comment. */
290 static void cp_comment_cpp(CPState *cp)
292 while (!cp_iseol(cp_get(cp)) && cp->c != '\0')
296 /* Lexical scanner for C. Only a minimal subset is implemented. */
297 static CPToken cp_next_(CPState *cp)
299 lj_str_resetbuf(&cp->sb);
300 for (;;) {
301 if (lj_char_isident(cp->c))
302 return lj_char_isdigit(cp->c) ? cp_number(cp) : cp_ident(cp);
303 switch (cp->c) {
304 case '\n': case '\r': cp_newline(cp); /* fallthrough. */
305 case ' ': case '\t': case '\v': case '\f': cp_get(cp); break;
306 case '"': case '\'': return cp_string(cp);
307 case '/':
308 if (cp_get(cp) == '*') cp_comment_c(cp);
309 else if (cp->c == '/') cp_comment_cpp(cp);
310 else return '/';
311 break;
312 case '|':
313 if (cp_get(cp) != '|') return '|'; cp_get(cp); return CTOK_OROR;
314 case '&':
315 if (cp_get(cp) != '&') return '&'; cp_get(cp); return CTOK_ANDAND;
316 case '=':
317 if (cp_get(cp) != '=') return '='; cp_get(cp); return CTOK_EQ;
318 case '!':
319 if (cp_get(cp) != '=') return '!'; cp_get(cp); return CTOK_NE;
320 case '<':
321 if (cp_get(cp) == '=') { cp_get(cp); return CTOK_LE; }
322 else if (cp->c == '<') { cp_get(cp); return CTOK_SHL; }
323 return '<';
324 case '>':
325 if (cp_get(cp) == '=') { cp_get(cp); return CTOK_GE; }
326 else if (cp->c == '>') { cp_get(cp); return CTOK_SHR; }
327 return '>';
328 case '-':
329 if (cp_get(cp) != '>') return '-'; cp_get(cp); return CTOK_DEREF;
330 case '$':
331 return cp_param(cp);
332 case '\0': return CTOK_EOF;
333 default: { CPToken c = cp->c; cp_get(cp); return c; }
338 static LJ_NOINLINE CPToken cp_next(CPState *cp)
340 return (cp->tok = cp_next_(cp));
343 /* -- C parser ------------------------------------------------------------ */
345 /* Namespaces for resolving identifiers. */
346 #define CPNS_DEFAULT \
347 ((1u<<CT_KW)|(1u<<CT_TYPEDEF)|(1u<<CT_FUNC)|(1u<<CT_EXTERN)|(1u<<CT_CONSTVAL))
348 #define CPNS_STRUCT ((1u<<CT_KW)|(1u<<CT_STRUCT)|(1u<<CT_ENUM))
350 typedef CTypeID CPDeclIdx; /* Index into declaration stack. */
351 typedef uint32_t CPscl; /* Storage class flags. */
353 /* Type declaration context. */
354 typedef struct CPDecl {
355 CPDeclIdx top; /* Top of declaration stack. */
356 CPDeclIdx pos; /* Insertion position in declaration chain. */
357 CPDeclIdx specpos; /* Saved position for declaration specifier. */
358 uint32_t mode; /* Declarator mode. */
359 CPState *cp; /* C parser state. */
360 GCstr *name; /* Name of declared identifier (if direct). */
361 GCstr *redir; /* Redirected symbol name. */
362 CTypeID nameid; /* Existing typedef for declared identifier. */
363 CTInfo attr; /* Attributes. */
364 CTInfo fattr; /* Function attributes. */
365 CTInfo specattr; /* Saved attributes. */
366 CTInfo specfattr; /* Saved function attributes. */
367 CTSize bits; /* Field size in bits (if any). */
368 CType stack[CPARSE_MAX_DECLSTACK]; /* Type declaration stack. */
369 } CPDecl;
371 /* Forward declarations. */
372 static CPscl cp_decl_spec(CPState *cp, CPDecl *decl, CPscl scl);
373 static void cp_declarator(CPState *cp, CPDecl *decl);
374 static CTypeID cp_decl_abstract(CPState *cp);
376 /* Initialize C parser state. Caller must set up: L, p, srcname, mode. */
377 static void cp_init(CPState *cp)
379 cp->linenumber = 1;
380 cp->depth = 0;
381 cp->curpack = 0;
382 cp->packstack[0] = 255;
383 lj_str_initbuf(&cp->sb);
384 lj_str_resizebuf(cp->L, &cp->sb, LJ_MIN_SBUF);
385 lua_assert(cp->p != NULL);
386 cp_get(cp); /* Read-ahead first char. */
387 cp->tok = 0;
388 cp->tmask = CPNS_DEFAULT;
389 cp_next(cp); /* Read-ahead first token. */
392 /* Cleanup C parser state. */
393 static void cp_cleanup(CPState *cp)
395 global_State *g = G(cp->L);
396 lj_str_freebuf(g, &cp->sb);
399 /* Check and consume optional token. */
400 static int cp_opt(CPState *cp, CPToken tok)
402 if (cp->tok == tok) { cp_next(cp); return 1; }
403 return 0;
406 /* Check and consume token. */
407 static void cp_check(CPState *cp, CPToken tok)
409 if (cp->tok != tok) cp_err_token(cp, tok);
410 cp_next(cp);
413 /* Check if the next token may start a type declaration. */
414 static int cp_istypedecl(CPState *cp)
416 if (cp->tok >= CTOK_FIRSTDECL && cp->tok <= CTOK_LASTDECL) return 1;
417 if (cp->tok == CTOK_IDENT && ctype_istypedef(cp->ct->info)) return 1;
418 if (cp->tok == '$') return 1;
419 return 0;
422 /* -- Constant expression evaluator --------------------------------------- */
424 /* Forward declarations. */
425 static void cp_expr_unary(CPState *cp, CPValue *k);
426 static void cp_expr_sub(CPState *cp, CPValue *k, int pri);
428 /* Please note that type handling is very weak here. Most ops simply
429 ** assume integer operands. Accessors are only needed to compute types and
430 ** return synthetic values. The only purpose of the expression evaluator
431 ** is to compute the values of constant expressions one would typically
432 ** find in C header files. And again: this is NOT a validating C parser!
435 /* Parse comma separated expression and return last result. */
436 static void cp_expr_comma(CPState *cp, CPValue *k)
438 do { cp_expr_sub(cp, k, 0); } while (cp_opt(cp, ','));
441 /* Parse sizeof/alignof operator. */
442 static void cp_expr_sizeof(CPState *cp, CPValue *k, int wantsz)
444 CTSize sz;
445 CTInfo info;
446 if (cp_opt(cp, '(')) {
447 if (cp_istypedecl(cp))
448 k->id = cp_decl_abstract(cp);
449 else
450 cp_expr_comma(cp, k);
451 cp_check(cp, ')');
452 } else {
453 cp_expr_unary(cp, k);
455 info = lj_ctype_info(cp->cts, k->id, &sz);
456 if (wantsz) {
457 if (sz != CTSIZE_INVALID)
458 k->u32 = sz;
459 else if (k->id != CTID_A_CCHAR) /* Special case for sizeof("string"). */
460 cp_err(cp, LJ_ERR_FFI_INVSIZE);
461 } else {
462 k->u32 = 1u << ctype_align(info);
464 k->id = CTID_UINT32; /* Really size_t. */
467 /* Parse prefix operators. */
468 static void cp_expr_prefix(CPState *cp, CPValue *k)
470 if (cp->tok == CTOK_INTEGER) {
471 *k = cp->val; cp_next(cp);
472 } else if (cp_opt(cp, '+')) {
473 cp_expr_unary(cp, k); /* Nothing to do (well, integer promotion). */
474 } else if (cp_opt(cp, '-')) {
475 cp_expr_unary(cp, k); k->i32 = -k->i32;
476 } else if (cp_opt(cp, '~')) {
477 cp_expr_unary(cp, k); k->i32 = ~k->i32;
478 } else if (cp_opt(cp, '!')) {
479 cp_expr_unary(cp, k); k->i32 = !k->i32; k->id = CTID_INT32;
480 } else if (cp_opt(cp, '(')) {
481 if (cp_istypedecl(cp)) { /* Cast operator. */
482 CTypeID id = cp_decl_abstract(cp);
483 cp_check(cp, ')');
484 cp_expr_unary(cp, k);
485 k->id = id; /* No conversion performed. */
486 } else { /* Sub-expression. */
487 cp_expr_comma(cp, k);
488 cp_check(cp, ')');
490 } else if (cp_opt(cp, '*')) { /* Indirection. */
491 CType *ct;
492 cp_expr_unary(cp, k);
493 ct = lj_ctype_rawref(cp->cts, k->id);
494 if (!ctype_ispointer(ct->info))
495 cp_err_badidx(cp, ct);
496 k->u32 = 0; k->id = ctype_cid(ct->info);
497 } else if (cp_opt(cp, '&')) { /* Address operator. */
498 cp_expr_unary(cp, k);
499 k->id = lj_ctype_intern(cp->cts, CTINFO(CT_PTR, CTALIGN_PTR+k->id),
500 CTSIZE_PTR);
501 } else if (cp_opt(cp, CTOK_SIZEOF)) {
502 cp_expr_sizeof(cp, k, 1);
503 } else if (cp_opt(cp, CTOK_ALIGNOF)) {
504 cp_expr_sizeof(cp, k, 0);
505 } else if (cp->tok == CTOK_IDENT) {
506 if (ctype_type(cp->ct->info) == CT_CONSTVAL) {
507 k->u32 = cp->ct->size; k->id = ctype_cid(cp->ct->info);
508 } else if (ctype_type(cp->ct->info) == CT_EXTERN) {
509 k->u32 = cp->val.id; k->id = ctype_cid(cp->ct->info);
510 } else if (ctype_type(cp->ct->info) == CT_FUNC) {
511 k->u32 = cp->val.id; k->id = cp->val.id;
512 } else {
513 goto err_expr;
515 cp_next(cp);
516 } else if (cp->tok == CTOK_STRING) {
517 CTSize sz = cp->str->len;
518 while (cp_next(cp) == CTOK_STRING)
519 sz += cp->str->len;
520 k->u32 = sz + 1;
521 k->id = CTID_A_CCHAR;
522 } else {
523 err_expr:
524 cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
528 /* Parse postfix operators. */
529 static void cp_expr_postfix(CPState *cp, CPValue *k)
531 for (;;) {
532 CType *ct;
533 if (cp_opt(cp, '[')) { /* Array/pointer index. */
534 CPValue k2;
535 cp_expr_comma(cp, &k2);
536 ct = lj_ctype_rawref(cp->cts, k->id);
537 if (!ctype_ispointer(ct->info)) {
538 ct = lj_ctype_rawref(cp->cts, k2.id);
539 if (!ctype_ispointer(ct->info))
540 cp_err_badidx(cp, ct);
542 cp_check(cp, ']');
543 k->u32 = 0;
544 } else if (cp->tok == '.' || cp->tok == CTOK_DEREF) { /* Struct deref. */
545 CTSize ofs;
546 CType *fct;
547 ct = lj_ctype_rawref(cp->cts, k->id);
548 if (cp->tok == CTOK_DEREF) {
549 if (!ctype_ispointer(ct->info))
550 cp_err_badidx(cp, ct);
551 ct = lj_ctype_rawref(cp->cts, ctype_cid(ct->info));
553 cp_next(cp);
554 if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
555 if (!ctype_isstruct(ct->info) || ct->size == CTSIZE_INVALID ||
556 !(fct = lj_ctype_getfield(cp->cts, ct, cp->str, &ofs)) ||
557 ctype_isbitfield(fct->info)) {
558 GCstr *s = lj_ctype_repr(cp->cts->L, ctype_typeid(cp->cts, ct), NULL);
559 cp_errmsg(cp, 0, LJ_ERR_FFI_BADMEMBER, strdata(s), strdata(cp->str));
561 ct = fct;
562 k->u32 = ctype_isconstval(ct->info) ? ct->size : 0;
563 cp_next(cp);
564 } else {
565 return;
567 k->id = ctype_cid(ct->info);
571 /* Parse infix operators. */
572 static void cp_expr_infix(CPState *cp, CPValue *k, int pri)
574 CPValue k2;
575 k2.u32 = 0; k2.id = 0; /* Silence the compiler. */
576 for (;;) {
577 switch (pri) {
578 case 0:
579 if (cp_opt(cp, '?')) {
580 CPValue k3;
581 cp_expr_comma(cp, &k2); /* Right-associative. */
582 cp_check(cp, ':');
583 cp_expr_sub(cp, &k3, 0);
584 k->u32 = k->u32 ? k2.u32 : k3.u32;
585 k->id = k2.id > k3.id ? k2.id : k3.id;
586 continue;
588 case 1:
589 if (cp_opt(cp, CTOK_OROR)) {
590 cp_expr_sub(cp, &k2, 2); k->i32 = k->u32 || k2.u32; k->id = CTID_INT32;
591 continue;
593 case 2:
594 if (cp_opt(cp, CTOK_ANDAND)) {
595 cp_expr_sub(cp, &k2, 3); k->i32 = k->u32 && k2.u32; k->id = CTID_INT32;
596 continue;
598 case 3:
599 if (cp_opt(cp, '|')) {
600 cp_expr_sub(cp, &k2, 4); k->u32 = k->u32 | k2.u32; goto arith_result;
602 case 4:
603 if (cp_opt(cp, '^')) {
604 cp_expr_sub(cp, &k2, 5); k->u32 = k->u32 ^ k2.u32; goto arith_result;
606 case 5:
607 if (cp_opt(cp, '&')) {
608 cp_expr_sub(cp, &k2, 6); k->u32 = k->u32 & k2.u32; goto arith_result;
610 case 6:
611 if (cp_opt(cp, CTOK_EQ)) {
612 cp_expr_sub(cp, &k2, 7); k->i32 = k->u32 == k2.u32; k->id = CTID_INT32;
613 continue;
614 } else if (cp_opt(cp, CTOK_NE)) {
615 cp_expr_sub(cp, &k2, 7); k->i32 = k->u32 != k2.u32; k->id = CTID_INT32;
616 continue;
618 case 7:
619 if (cp_opt(cp, '<')) {
620 cp_expr_sub(cp, &k2, 8);
621 if (k->id == CTID_INT32 && k2.id == CTID_INT32)
622 k->i32 = k->i32 < k2.i32;
623 else
624 k->i32 = k->u32 < k2.u32;
625 k->id = CTID_INT32;
626 continue;
627 } else if (cp_opt(cp, '>')) {
628 cp_expr_sub(cp, &k2, 8);
629 if (k->id == CTID_INT32 && k2.id == CTID_INT32)
630 k->i32 = k->i32 > k2.i32;
631 else
632 k->i32 = k->u32 > k2.u32;
633 k->id = CTID_INT32;
634 continue;
635 } else if (cp_opt(cp, CTOK_LE)) {
636 cp_expr_sub(cp, &k2, 8);
637 if (k->id == CTID_INT32 && k2.id == CTID_INT32)
638 k->i32 = k->i32 <= k2.i32;
639 else
640 k->i32 = k->u32 <= k2.u32;
641 k->id = CTID_INT32;
642 continue;
643 } else if (cp_opt(cp, CTOK_GE)) {
644 cp_expr_sub(cp, &k2, 8);
645 if (k->id == CTID_INT32 && k2.id == CTID_INT32)
646 k->i32 = k->i32 >= k2.i32;
647 else
648 k->i32 = k->u32 >= k2.u32;
649 k->id = CTID_INT32;
650 continue;
652 case 8:
653 if (cp_opt(cp, CTOK_SHL)) {
654 cp_expr_sub(cp, &k2, 9); k->u32 = k->u32 << k2.u32;
655 continue;
656 } else if (cp_opt(cp, CTOK_SHR)) {
657 cp_expr_sub(cp, &k2, 9);
658 if (k->id == CTID_INT32)
659 k->i32 = k->i32 >> k2.i32;
660 else
661 k->u32 = k->u32 >> k2.u32;
662 continue;
664 case 9:
665 if (cp_opt(cp, '+')) {
666 cp_expr_sub(cp, &k2, 10); k->u32 = k->u32 + k2.u32;
667 arith_result:
668 if (k2.id > k->id) k->id = k2.id; /* Trivial promotion to unsigned. */
669 continue;
670 } else if (cp_opt(cp, '-')) {
671 cp_expr_sub(cp, &k2, 10); k->u32 = k->u32 - k2.u32; goto arith_result;
673 case 10:
674 if (cp_opt(cp, '*')) {
675 cp_expr_unary(cp, &k2); k->u32 = k->u32 * k2.u32; goto arith_result;
676 } else if (cp_opt(cp, '/')) {
677 cp_expr_unary(cp, &k2);
678 if (k2.id > k->id) k->id = k2.id; /* Trivial promotion to unsigned. */
679 if (k2.u32 == 0 ||
680 (k->id == CTID_INT32 && k->u32 == 0x80000000u && k2.i32 == -1))
681 cp_err(cp, LJ_ERR_BADVAL);
682 if (k->id == CTID_INT32)
683 k->i32 = k->i32 / k2.i32;
684 else
685 k->u32 = k->u32 / k2.u32;
686 continue;
687 } else if (cp_opt(cp, '%')) {
688 cp_expr_unary(cp, &k2);
689 if (k2.id > k->id) k->id = k2.id; /* Trivial promotion to unsigned. */
690 if (k2.u32 == 0 ||
691 (k->id == CTID_INT32 && k->u32 == 0x80000000u && k2.i32 == -1))
692 cp_err(cp, LJ_ERR_BADVAL);
693 if (k->id == CTID_INT32)
694 k->i32 = k->i32 % k2.i32;
695 else
696 k->u32 = k->u32 % k2.u32;
697 continue;
699 default:
700 return;
705 /* Parse and evaluate unary expression. */
706 static void cp_expr_unary(CPState *cp, CPValue *k)
708 if (++cp->depth > CPARSE_MAX_DECLDEPTH) cp_err(cp, LJ_ERR_XLEVELS);
709 cp_expr_prefix(cp, k);
710 cp_expr_postfix(cp, k);
711 cp->depth--;
714 /* Parse and evaluate sub-expression. */
715 static void cp_expr_sub(CPState *cp, CPValue *k, int pri)
717 cp_expr_unary(cp, k);
718 cp_expr_infix(cp, k, pri);
721 /* Parse constant integer expression. */
722 static void cp_expr_kint(CPState *cp, CPValue *k)
724 CType *ct;
725 cp_expr_sub(cp, k, 0);
726 ct = ctype_raw(cp->cts, k->id);
727 if (!ctype_isinteger(ct->info)) cp_err(cp, LJ_ERR_BADVAL);
730 /* Parse (non-negative) size expression. */
731 static CTSize cp_expr_ksize(CPState *cp)
733 CPValue k;
734 cp_expr_kint(cp, &k);
735 if (k.u32 >= 0x80000000u) cp_err(cp, LJ_ERR_FFI_INVSIZE);
736 return k.u32;
739 /* -- Type declaration stack management ----------------------------------- */
741 /* Add declaration element behind the insertion position. */
742 static CPDeclIdx cp_add(CPDecl *decl, CTInfo info, CTSize size)
744 CPDeclIdx top = decl->top;
745 if (top >= CPARSE_MAX_DECLSTACK) cp_err(decl->cp, LJ_ERR_XLEVELS);
746 decl->stack[top].info = info;
747 decl->stack[top].size = size;
748 decl->stack[top].sib = 0;
749 setgcrefnull(decl->stack[top].name);
750 decl->stack[top].next = decl->stack[decl->pos].next;
751 decl->stack[decl->pos].next = (CTypeID1)top;
752 decl->top = top+1;
753 return top;
756 /* Push declaration element before the insertion position. */
757 static CPDeclIdx cp_push(CPDecl *decl, CTInfo info, CTSize size)
759 return (decl->pos = cp_add(decl, info, size));
762 /* Push or merge attributes. */
763 static void cp_push_attributes(CPDecl *decl)
765 CType *ct = &decl->stack[decl->pos];
766 if (ctype_isfunc(ct->info)) { /* Ok to modify in-place. */
767 #if LJ_TARGET_X86
768 if ((decl->fattr & CTFP_CCONV))
769 ct->info = (ct->info & (CTMASK_NUM|CTF_VARARG|CTMASK_CID)) +
770 (decl->fattr & ~CTMASK_CID);
771 #endif
772 } else {
773 if ((decl->attr & CTFP_ALIGNED) && !(decl->mode & CPARSE_MODE_FIELD))
774 cp_push(decl, CTINFO(CT_ATTRIB, CTATTRIB(CTA_ALIGN)),
775 ctype_align(decl->attr));
779 /* Push unrolled type to declaration stack and merge qualifiers. */
780 static void cp_push_type(CPDecl *decl, CTypeID id)
782 CType *ct = ctype_get(decl->cp->cts, id);
783 CTInfo info = ct->info;
784 CTSize size = ct->size;
785 switch (ctype_type(info)) {
786 case CT_STRUCT: case CT_ENUM:
787 cp_push(decl, CTINFO(CT_TYPEDEF, id), 0); /* Don't copy unique types. */
788 if ((decl->attr & CTF_QUAL)) { /* Push unmerged qualifiers. */
789 cp_push(decl, CTINFO(CT_ATTRIB, CTATTRIB(CTA_QUAL)),
790 (decl->attr & CTF_QUAL));
791 decl->attr &= ~CTF_QUAL;
793 break;
794 case CT_ATTRIB:
795 if (ctype_isxattrib(info, CTA_QUAL))
796 decl->attr &= ~size; /* Remove redundant qualifiers. */
797 cp_push_type(decl, ctype_cid(info)); /* Unroll. */
798 cp_push(decl, info & ~CTMASK_CID, size); /* Copy type. */
799 break;
800 case CT_ARRAY:
801 cp_push_type(decl, ctype_cid(info)); /* Unroll. */
802 cp_push(decl, info & ~CTMASK_CID, size); /* Copy type. */
803 decl->stack[decl->pos].sib = 1; /* Mark as already checked and sized. */
804 /* Note: this is not copied to the ct->sib in the C type table. */
805 break;
806 case CT_FUNC:
807 /* Copy type, link parameters (shared). */
808 decl->stack[cp_push(decl, info, size)].sib = ct->sib;
809 break;
810 default:
811 /* Copy type, merge common qualifiers. */
812 cp_push(decl, info|(decl->attr & CTF_QUAL), size);
813 decl->attr &= ~CTF_QUAL;
814 break;
818 /* Consume the declaration element chain and intern the C type. */
819 static CTypeID cp_decl_intern(CPState *cp, CPDecl *decl)
821 CTypeID id = 0;
822 CPDeclIdx idx = 0;
823 CTSize csize = CTSIZE_INVALID;
824 CTSize cinfo = 0;
825 do {
826 CType *ct = &decl->stack[idx];
827 CTInfo info = ct->info;
828 CTInfo size = ct->size;
829 /* The cid is already part of info for copies of pointers/functions. */
830 idx = ct->next;
831 if (ctype_istypedef(info)) {
832 lua_assert(id == 0);
833 id = ctype_cid(info);
834 /* Always refetch info/size, since struct/enum may have been completed. */
835 cinfo = ctype_get(cp->cts, id)->info;
836 csize = ctype_get(cp->cts, id)->size;
837 lua_assert(ctype_isstruct(cinfo) || ctype_isenum(cinfo));
838 } else if (ctype_isfunc(info)) { /* Intern function. */
839 CType *fct;
840 CTypeID fid;
841 CTypeID sib;
842 if (id) {
843 CType *refct = ctype_raw(cp->cts, id);
844 /* Reject function or refarray return types. */
845 if (ctype_isfunc(refct->info) || ctype_isrefarray(refct->info))
846 cp_err(cp, LJ_ERR_FFI_INVTYPE);
848 /* No intervening attributes allowed, skip forward. */
849 while (idx) {
850 CType *ctn = &decl->stack[idx];
851 if (!ctype_isattrib(ctn->info)) break;
852 idx = ctn->next; /* Skip attribute. */
854 sib = ct->sib; /* Next line may reallocate the C type table. */
855 fid = lj_ctype_new(cp->cts, &fct);
856 csize = CTSIZE_INVALID;
857 fct->info = cinfo = info + id;
858 fct->size = size;
859 fct->sib = sib;
860 id = fid;
861 } else if (ctype_isattrib(info)) {
862 if (ctype_isxattrib(info, CTA_QUAL))
863 cinfo |= size;
864 else if (ctype_isxattrib(info, CTA_ALIGN))
865 CTF_INSERT(cinfo, ALIGN, size);
866 id = lj_ctype_intern(cp->cts, info+id, size);
867 /* Inherit csize/cinfo from original type. */
868 } else {
869 if (ctype_isnum(info)) { /* Handle mode/vector-size attributes. */
870 lua_assert(id == 0);
871 if (!(info & CTF_BOOL)) {
872 CTSize msize = ctype_msizeP(decl->attr);
873 CTSize vsize = ctype_vsizeP(decl->attr);
874 if (msize && (!(info & CTF_FP) || (msize == 4 || msize == 8))) {
875 CTSize malign = lj_fls(msize);
876 if (malign > 4) malign = 4; /* Limit alignment. */
877 CTF_INSERT(info, ALIGN, malign);
878 size = msize; /* Override size via mode. */
880 if (vsize) { /* Vector size set? */
881 CTSize esize = lj_fls(size);
882 if (vsize >= esize) {
883 /* Intern the element type first. */
884 id = lj_ctype_intern(cp->cts, info, size);
885 /* Then create a vector (array) with vsize alignment. */
886 size = (1u << vsize);
887 if (vsize > 4) vsize = 4; /* Limit alignment. */
888 if (ctype_align(info) > vsize) vsize = ctype_align(info);
889 info = CTINFO(CT_ARRAY, (info & CTF_QUAL) + CTF_VECTOR +
890 CTALIGN(vsize));
894 } else if (ctype_isptr(info)) {
895 /* Reject pointer/ref to ref. */
896 if (id && ctype_isref(ctype_raw(cp->cts, id)->info))
897 cp_err(cp, LJ_ERR_FFI_INVTYPE);
898 if (ctype_isref(info)) {
899 info &= ~CTF_VOLATILE; /* Refs are always const, never volatile. */
900 /* No intervening attributes allowed, skip forward. */
901 while (idx) {
902 CType *ctn = &decl->stack[idx];
903 if (!ctype_isattrib(ctn->info)) break;
904 idx = ctn->next; /* Skip attribute. */
907 } else if (ctype_isarray(info)) { /* Check for valid array size etc. */
908 if (ct->sib == 0) { /* Only check/size arrays not copied by unroll. */
909 if (ctype_isref(cinfo)) /* Reject arrays of refs. */
910 cp_err(cp, LJ_ERR_FFI_INVTYPE);
911 /* Reject VLS or unknown-sized types. */
912 if (ctype_isvltype(cinfo) || csize == CTSIZE_INVALID)
913 cp_err(cp, LJ_ERR_FFI_INVSIZE);
914 /* a[] and a[?] keep their invalid size. */
915 if (size != CTSIZE_INVALID) {
916 uint64_t xsz = (uint64_t)size * csize;
917 if (xsz >= 0x80000000u) cp_err(cp, LJ_ERR_FFI_INVSIZE);
918 size = (CTSize)xsz;
921 info |= (cinfo & (CTF_QUAL|CTF_ALIGN)); /* Inherit qual and align. */
922 } else {
923 lua_assert(ctype_isvoid(info));
925 csize = size;
926 cinfo = info+id;
927 id = lj_ctype_intern(cp->cts, info+id, size);
929 } while (idx);
930 return id;
933 /* -- C declaration parser ------------------------------------------------ */
935 #define H_(le, be) LJ_ENDIAN_SELECT(0x##le, 0x##be)
937 /* Reset declaration state to declaration specifier. */
938 static void cp_decl_reset(CPDecl *decl)
940 decl->pos = decl->specpos;
941 decl->top = decl->specpos+1;
942 decl->stack[decl->specpos].next = 0;
943 decl->attr = decl->specattr;
944 decl->fattr = decl->specfattr;
945 decl->name = NULL;
946 decl->redir = NULL;
949 /* Parse constant initializer. */
950 /* NYI: FP constants and strings as initializers. */
951 static CTypeID cp_decl_constinit(CPState *cp, CType **ctp, CTypeID ctypeid)
953 CType *ctt = ctype_get(cp->cts, ctypeid);
954 CTInfo info;
955 CTSize size;
956 CPValue k;
957 CTypeID constid;
958 while (ctype_isattrib(ctt->info)) { /* Skip attributes. */
959 ctypeid = ctype_cid(ctt->info); /* Update ID, too. */
960 ctt = ctype_get(cp->cts, ctypeid);
962 info = ctt->info;
963 size = ctt->size;
964 if (!ctype_isinteger(info) || !(info & CTF_CONST) || size > 4)
965 cp_err(cp, LJ_ERR_FFI_INVTYPE);
966 cp_check(cp, '=');
967 cp_expr_sub(cp, &k, 0);
968 constid = lj_ctype_new(cp->cts, ctp);
969 (*ctp)->info = CTINFO(CT_CONSTVAL, CTF_CONST|ctypeid);
970 k.u32 <<= 8*(4-size);
971 if ((info & CTF_UNSIGNED))
972 k.u32 >>= 8*(4-size);
973 else
974 k.u32 = (uint32_t)((int32_t)k.u32 >> 8*(4-size));
975 (*ctp)->size = k.u32;
976 return constid;
979 /* Parse size in parentheses as part of attribute. */
980 static CTSize cp_decl_sizeattr(CPState *cp)
982 CTSize sz;
983 uint32_t oldtmask = cp->tmask;
984 cp->tmask = CPNS_DEFAULT; /* Required for expression evaluator. */
985 cp_check(cp, '(');
986 sz = cp_expr_ksize(cp);
987 cp->tmask = oldtmask;
988 cp_check(cp, ')');
989 return sz;
992 /* Parse alignment attribute. */
993 static void cp_decl_align(CPState *cp, CPDecl *decl)
995 CTSize al = 4; /* Unspecified alignment is 16 bytes. */
996 if (cp->tok == '(') {
997 al = cp_decl_sizeattr(cp);
998 al = al ? lj_fls(al) : 0;
1000 CTF_INSERT(decl->attr, ALIGN, al);
1001 decl->attr |= CTFP_ALIGNED;
1004 /* Parse GCC asm("name") redirect. */
1005 static void cp_decl_asm(CPState *cp, CPDecl *decl)
1007 UNUSED(decl);
1008 cp_next(cp);
1009 cp_check(cp, '(');
1010 if (cp->tok == CTOK_STRING) {
1011 GCstr *str = cp->str;
1012 while (cp_next(cp) == CTOK_STRING) {
1013 lj_str_pushf(cp->L, "%s%s", strdata(str), strdata(cp->str));
1014 cp->L->top--;
1015 str = strV(cp->L->top);
1017 decl->redir = str;
1019 cp_check(cp, ')');
1022 /* Parse GCC __attribute__((mode(...))). */
1023 static void cp_decl_mode(CPState *cp, CPDecl *decl)
1025 cp_check(cp, '(');
1026 if (cp->tok == CTOK_IDENT) {
1027 const char *s = strdata(cp->str);
1028 CTSize sz = 0, vlen = 0;
1029 if (s[0] == '_' && s[1] == '_') s += 2;
1030 if (*s == 'V') {
1031 s++;
1032 vlen = *s++ - '0';
1033 if (*s >= '0' && *s <= '9')
1034 vlen = vlen*10 + (*s++ - '0');
1036 switch (*s++) {
1037 case 'Q': sz = 1; break;
1038 case 'H': sz = 2; break;
1039 case 'S': sz = 4; break;
1040 case 'D': sz = 8; break;
1041 case 'T': sz = 16; break;
1042 case 'O': sz = 32; break;
1043 default: goto bad_size;
1045 if (*s == 'I' || *s == 'F') {
1046 CTF_INSERT(decl->attr, MSIZEP, sz);
1047 if (vlen) CTF_INSERT(decl->attr, VSIZEP, lj_fls(vlen*sz));
1049 bad_size:
1050 cp_next(cp);
1052 cp_check(cp, ')');
1055 /* Parse GCC __attribute__((...)). */
1056 static void cp_decl_gccattribute(CPState *cp, CPDecl *decl)
1058 cp_next(cp);
1059 cp_check(cp, '(');
1060 cp_check(cp, '(');
1061 while (cp->tok != ')') {
1062 if (cp->tok == CTOK_IDENT) {
1063 GCstr *attrstr = cp->str;
1064 cp_next(cp);
1065 switch (attrstr->hash) {
1066 case H_(64a9208e,8ce14319): case H_(8e6331b2,95a282af): /* aligned */
1067 cp_decl_align(cp, decl);
1068 break;
1069 case H_(42eb47de,f0ede26c): case H_(29f48a09,cf383e0c): /* packed */
1070 decl->attr |= CTFP_PACKED;
1071 break;
1072 case H_(0a84eef6,8dfab04c): case H_(995cf92c,d5696591): /* mode */
1073 cp_decl_mode(cp, decl);
1074 break;
1075 case H_(0ab31997,2d5213fa): case H_(bf875611,200e9990): /* vector_size */
1077 CTSize vsize = cp_decl_sizeattr(cp);
1078 if (vsize) CTF_INSERT(decl->attr, VSIZEP, lj_fls(vsize));
1080 break;
1081 #if LJ_TARGET_X86
1082 case H_(5ad22db8,c689b848): case H_(439150fa,65ea78cb): /* regparm */
1083 CTF_INSERT(decl->fattr, REGPARM, cp_decl_sizeattr(cp));
1084 decl->fattr |= CTFP_CCONV;
1085 break;
1086 case H_(18fc0b98,7ff4c074): case H_(4e62abed,0a747424): /* cdecl */
1087 CTF_INSERT(decl->fattr, CCONV, CTCC_CDECL);
1088 decl->fattr |= CTFP_CCONV;
1089 break;
1090 case H_(72b2e41b,494c5a44): case H_(f2356d59,f25fc9bd): /* thiscall */
1091 CTF_INSERT(decl->fattr, CCONV, CTCC_THISCALL);
1092 decl->fattr |= CTFP_CCONV;
1093 break;
1094 case H_(0d0ffc42,ab746f88): case H_(21c54ba1,7f0ca7e3): /* fastcall */
1095 CTF_INSERT(decl->fattr, CCONV, CTCC_FASTCALL);
1096 decl->fattr |= CTFP_CCONV;
1097 break;
1098 case H_(ef76b040,9412e06a): case H_(de56697b,c750e6e1): /* stdcall */
1099 CTF_INSERT(decl->fattr, CCONV, CTCC_STDCALL);
1100 decl->fattr |= CTFP_CCONV;
1101 break;
1102 case H_(ea78b622,f234bd8e): case H_(252ffb06,8d50f34b): /* sseregparm */
1103 decl->fattr |= CTF_SSEREGPARM;
1104 decl->fattr |= CTFP_CCONV;
1105 break;
1106 #endif
1107 default: /* Skip all other attributes. */
1108 goto skip_attr;
1110 } else if (cp->tok >= CTOK_FIRSTDECL) { /* For __attribute((const)) etc. */
1111 cp_next(cp);
1112 skip_attr:
1113 if (cp_opt(cp, '(')) {
1114 while (cp->tok != ')' && cp->tok != CTOK_EOF) cp_next(cp);
1115 cp_check(cp, ')');
1117 } else {
1118 break;
1120 if (!cp_opt(cp, ',')) break;
1122 cp_check(cp, ')');
1123 cp_check(cp, ')');
1126 /* Parse MSVC __declspec(...). */
1127 static void cp_decl_msvcattribute(CPState *cp, CPDecl *decl)
1129 cp_next(cp);
1130 cp_check(cp, '(');
1131 while (cp->tok == CTOK_IDENT) {
1132 GCstr *attrstr = cp->str;
1133 cp_next(cp);
1134 switch (attrstr->hash) {
1135 case H_(bc2395fa,98f267f8): /* align */
1136 cp_decl_align(cp, decl);
1137 break;
1138 default: /* Ignore all other attributes. */
1139 if (cp_opt(cp, '(')) {
1140 while (cp->tok != ')' && cp->tok != CTOK_EOF) cp_next(cp);
1141 cp_check(cp, ')');
1143 break;
1146 cp_check(cp, ')');
1149 /* Parse declaration attributes (and common qualifiers). */
1150 static void cp_decl_attributes(CPState *cp, CPDecl *decl)
1152 for (;;) {
1153 switch (cp->tok) {
1154 case CTOK_CONST: decl->attr |= CTF_CONST; break;
1155 case CTOK_VOLATILE: decl->attr |= CTF_VOLATILE; break;
1156 case CTOK_RESTRICT: break; /* Ignore. */
1157 case CTOK_EXTENSION: break; /* Ignore. */
1158 case CTOK_ATTRIBUTE: cp_decl_gccattribute(cp, decl); continue;
1159 case CTOK_ASM: cp_decl_asm(cp, decl); continue;
1160 case CTOK_DECLSPEC: cp_decl_msvcattribute(cp, decl); continue;
1161 case CTOK_CCDECL:
1162 #if LJ_TARGET_X86
1163 CTF_INSERT(decl->fattr, CCONV, cp->ct->size);
1164 decl->fattr |= CTFP_CCONV;
1165 #endif
1166 break;
1167 case CTOK_PTRSZ:
1168 #if LJ_64
1169 CTF_INSERT(decl->attr, MSIZEP, cp->ct->size);
1170 #endif
1171 break;
1172 default: return;
1174 cp_next(cp);
1178 /* Parse struct/union/enum name. */
1179 static CTypeID cp_struct_name(CPState *cp, CPDecl *sdecl, CTInfo info)
1181 CTypeID sid;
1182 CType *ct;
1183 cp->tmask = CPNS_STRUCT;
1184 cp_next(cp);
1185 cp_decl_attributes(cp, sdecl);
1186 cp->tmask = CPNS_DEFAULT;
1187 if (cp->tok != '{') {
1188 if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
1189 if (cp->val.id) { /* Name of existing struct/union/enum. */
1190 sid = cp->val.id;
1191 ct = cp->ct;
1192 if ((ct->info ^ info) & (CTMASK_NUM|CTF_UNION)) /* Wrong type. */
1193 cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(gco2str(gcref(ct->name))));
1194 } else { /* Create named, incomplete struct/union/enum. */
1195 if ((cp->mode & CPARSE_MODE_NOIMPLICIT))
1196 cp_errmsg(cp, 0, LJ_ERR_FFI_BADTAG, strdata(cp->str));
1197 sid = lj_ctype_new(cp->cts, &ct);
1198 ct->info = info;
1199 ct->size = CTSIZE_INVALID;
1200 ctype_setname(ct, cp->str);
1201 lj_ctype_addname(cp->cts, ct, sid);
1203 cp_next(cp);
1204 } else { /* Create anonymous, incomplete struct/union/enum. */
1205 sid = lj_ctype_new(cp->cts, &ct);
1206 ct->info = info;
1207 ct->size = CTSIZE_INVALID;
1209 if (cp->tok == '{') {
1210 if (ct->size != CTSIZE_INVALID || ct->sib)
1211 cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(gco2str(gcref(ct->name))));
1212 ct->sib = 1; /* Indicate the type is currently being defined. */
1214 return sid;
1217 /* Determine field alignment. */
1218 static CTSize cp_field_align(CPState *cp, CType *ct, CTInfo info)
1220 CTSize align = ctype_align(info);
1221 UNUSED(cp); UNUSED(ct);
1222 #if (LJ_TARGET_X86 && !LJ_ABI_WIN) || (LJ_TARGET_ARM && __APPLE__)
1223 /* The SYSV i386 and iOS ABIs limit alignment of non-vector fields to 2^2. */
1224 if (align > 2 && !(info & CTFP_ALIGNED)) {
1225 if (ctype_isarray(info) && !(info & CTF_VECTOR)) {
1226 do {
1227 ct = ctype_rawchild(cp->cts, ct);
1228 info = ct->info;
1229 } while (ctype_isarray(info) && !(info & CTF_VECTOR));
1231 if (ctype_isnum(info) || ctype_isenum(info))
1232 align = 2;
1234 #endif
1235 return align;
1238 /* Layout struct/union fields. */
1239 static void cp_struct_layout(CPState *cp, CTypeID sid, CTInfo sattr)
1241 CTSize bofs = 0, bmaxofs = 0; /* Bit offset and max. bit offset. */
1242 CTSize maxalign = ctype_align(sattr);
1243 CType *sct = ctype_get(cp->cts, sid);
1244 CTInfo sinfo = sct->info;
1245 CTypeID fieldid = sct->sib;
1246 while (fieldid) {
1247 CType *ct = ctype_get(cp->cts, fieldid);
1248 CTInfo attr = ct->size; /* Field declaration attributes (temp.). */
1250 if (ctype_isfield(ct->info) ||
1251 (ctype_isxattrib(ct->info, CTA_SUBTYPE) && attr)) {
1252 CTSize align, amask; /* Alignment (pow2) and alignment mask (bits). */
1253 CTSize sz;
1254 CTInfo info = lj_ctype_info(cp->cts, ctype_cid(ct->info), &sz);
1255 CTSize bsz, csz = 8*sz; /* Field size and container size (in bits). */
1256 sinfo |= (info & (CTF_QUAL|CTF_VLA)); /* Merge pseudo-qualifiers. */
1258 /* Check for size overflow and determine alignment. */
1259 if (sz >= 0x20000000u || bofs + csz < bofs) {
1260 if (!(sz == CTSIZE_INVALID && ctype_isarray(info) &&
1261 !(sinfo & CTF_UNION)))
1262 cp_err(cp, LJ_ERR_FFI_INVSIZE);
1263 csz = sz = 0; /* Treat a[] and a[?] as zero-sized. */
1265 align = cp_field_align(cp, ct, info);
1266 if (((attr|sattr) & CTFP_PACKED) ||
1267 ((attr & CTFP_ALIGNED) && ctype_align(attr) > align))
1268 align = ctype_align(attr);
1269 if (cp->packstack[cp->curpack] < align)
1270 align = cp->packstack[cp->curpack];
1271 if (align > maxalign) maxalign = align;
1272 amask = (8u << align) - 1;
1274 bsz = ctype_bitcsz(ct->info); /* Bitfield size (temp.). */
1275 if (bsz == CTBSZ_FIELD || !ctype_isfield(ct->info)) {
1276 bsz = csz; /* Regular fields or subtypes always fill the container. */
1277 bofs = (bofs + amask) & ~amask; /* Start new aligned field. */
1278 ct->size = (bofs >> 3); /* Store field offset. */
1279 } else { /* Bitfield. */
1280 if (bsz == 0 || (attr & CTFP_ALIGNED) ||
1281 (!((attr|sattr) & CTFP_PACKED) && (bofs & amask) + bsz > csz))
1282 bofs = (bofs + amask) & ~amask; /* Start new aligned field. */
1284 /* Prefer regular field over bitfield. */
1285 if (bsz == csz && (bofs & amask) == 0) {
1286 ct->info = CTINFO(CT_FIELD, ctype_cid(ct->info));
1287 ct->size = (bofs >> 3); /* Store field offset. */
1288 } else {
1289 ct->info = CTINFO(CT_BITFIELD,
1290 (info & (CTF_QUAL|CTF_UNSIGNED|CTF_BOOL)) +
1291 (csz << (CTSHIFT_BITCSZ-3)) + (bsz << CTSHIFT_BITBSZ));
1292 #if LJ_BE
1293 ct->info += ((csz - (bofs & (csz-1)) - bsz) << CTSHIFT_BITPOS);
1294 #else
1295 ct->info += ((bofs & (csz-1)) << CTSHIFT_BITPOS);
1296 #endif
1297 ct->size = ((bofs & ~(csz-1)) >> 3); /* Store container offset. */
1301 /* Determine next offset or max. offset. */
1302 if ((sinfo & CTF_UNION)) {
1303 if (bsz > bmaxofs) bmaxofs = bsz;
1304 } else {
1305 bofs += bsz;
1307 } /* All other fields in the chain are already set up. */
1309 fieldid = ct->sib;
1312 /* Complete struct/union. */
1313 sct->info = sinfo + CTALIGN(maxalign);
1314 bofs = (sinfo & CTF_UNION) ? bmaxofs : bofs;
1315 maxalign = (8u << maxalign) - 1;
1316 sct->size = (((bofs + maxalign) & ~maxalign) >> 3);
1319 /* Parse struct/union declaration. */
1320 static CTypeID cp_decl_struct(CPState *cp, CPDecl *sdecl, CTInfo sinfo)
1322 CTypeID sid = cp_struct_name(cp, sdecl, sinfo);
1323 if (cp_opt(cp, '{')) { /* Struct/union definition. */
1324 CTypeID lastid = sid;
1325 int lastdecl = 0;
1326 while (cp->tok != '}') {
1327 CPDecl decl;
1328 CPscl scl = cp_decl_spec(cp, &decl, CDF_STATIC);
1329 decl.mode = scl ? CPARSE_MODE_DIRECT :
1330 CPARSE_MODE_DIRECT|CPARSE_MODE_ABSTRACT|CPARSE_MODE_FIELD;
1332 for (;;) {
1333 CTypeID ctypeid;
1335 if (lastdecl) cp_err_token(cp, '}');
1337 /* Parse field declarator. */
1338 decl.bits = CTSIZE_INVALID;
1339 cp_declarator(cp, &decl);
1340 ctypeid = cp_decl_intern(cp, &decl);
1342 if ((scl & CDF_STATIC)) { /* Static constant in struct namespace. */
1343 CType *ct;
1344 CTypeID fieldid = cp_decl_constinit(cp, &ct, ctypeid);
1345 ctype_get(cp->cts, lastid)->sib = fieldid;
1346 lastid = fieldid;
1347 ctype_setname(ct, decl.name);
1348 } else {
1349 CTSize bsz = CTBSZ_FIELD; /* Temp. for layout phase. */
1350 CType *ct;
1351 CTypeID fieldid = lj_ctype_new(cp->cts, &ct); /* Do this first. */
1352 CType *tct = ctype_raw(cp->cts, ctypeid);
1354 if (decl.bits == CTSIZE_INVALID) { /* Regular field. */
1355 if (ctype_isarray(tct->info) && tct->size == CTSIZE_INVALID)
1356 lastdecl = 1; /* a[] or a[?] must be the last declared field. */
1358 /* Accept transparent struct/union/enum. */
1359 if (!decl.name) {
1360 if (!((ctype_isstruct(tct->info) && !(tct->info & CTF_VLA)) ||
1361 ctype_isenum(tct->info)))
1362 cp_err_token(cp, CTOK_IDENT);
1363 ct->info = CTINFO(CT_ATTRIB, CTATTRIB(CTA_SUBTYPE) + ctypeid);
1364 ct->size = ctype_isstruct(tct->info) ?
1365 (decl.attr|0x80000000u) : 0; /* For layout phase. */
1366 goto add_field;
1368 } else { /* Bitfield. */
1369 bsz = decl.bits;
1370 if (!ctype_isinteger_or_bool(tct->info) ||
1371 (bsz == 0 && decl.name) || 8*tct->size > CTBSZ_MAX ||
1372 bsz > ((tct->info & CTF_BOOL) ? 1 : 8*tct->size))
1373 cp_errmsg(cp, ':', LJ_ERR_BADVAL);
1376 /* Create temporary field for layout phase. */
1377 ct->info = CTINFO(CT_FIELD, ctypeid + (bsz << CTSHIFT_BITCSZ));
1378 ct->size = decl.attr;
1379 if (decl.name) ctype_setname(ct, decl.name);
1381 add_field:
1382 ctype_get(cp->cts, lastid)->sib = fieldid;
1383 lastid = fieldid;
1385 if (!cp_opt(cp, ',')) break;
1386 cp_decl_reset(&decl);
1388 cp_check(cp, ';');
1390 cp_check(cp, '}');
1391 ctype_get(cp->cts, lastid)->sib = 0; /* Drop sib = 1 for empty structs. */
1392 cp_decl_attributes(cp, sdecl); /* Layout phase needs postfix attributes. */
1393 cp_struct_layout(cp, sid, sdecl->attr);
1395 return sid;
1398 /* Parse enum declaration. */
1399 static CTypeID cp_decl_enum(CPState *cp, CPDecl *sdecl)
1401 CTypeID eid = cp_struct_name(cp, sdecl, CTINFO(CT_ENUM, CTID_VOID));
1402 CTInfo einfo = CTINFO(CT_ENUM, CTALIGN(2) + CTID_UINT32);
1403 CTSize esize = 4; /* Only 32 bit enums are supported. */
1404 if (cp_opt(cp, '{')) { /* Enum definition. */
1405 CPValue k;
1406 CTypeID lastid = eid;
1407 k.u32 = 0;
1408 k.id = CTID_INT32;
1409 do {
1410 GCstr *name = cp->str;
1411 if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
1412 if (cp->val.id) cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(name));
1413 cp_next(cp);
1414 if (cp_opt(cp, '=')) {
1415 cp_expr_kint(cp, &k);
1416 if (k.id == CTID_UINT32) {
1417 /* C99 says that enum constants are always (signed) integers.
1418 ** But since unsigned constants like 0x80000000 are quite common,
1419 ** those are left as uint32_t.
1421 if (k.i32 >= 0) k.id = CTID_INT32;
1422 } else {
1423 /* OTOH it's common practice and even mandated by some ABIs
1424 ** that the enum type itself is unsigned, unless there are any
1425 ** negative constants.
1427 k.id = CTID_INT32;
1428 if (k.i32 < 0) einfo = CTINFO(CT_ENUM, CTALIGN(2) + CTID_INT32);
1431 /* Add named enum constant. */
1433 CType *ct;
1434 CTypeID constid = lj_ctype_new(cp->cts, &ct);
1435 ctype_get(cp->cts, lastid)->sib = constid;
1436 lastid = constid;
1437 ctype_setname(ct, name);
1438 ct->info = CTINFO(CT_CONSTVAL, CTF_CONST|k.id);
1439 ct->size = k.u32++;
1440 if (k.u32 == 0x80000000u) k.id = CTID_UINT32;
1441 lj_ctype_addname(cp->cts, ct, constid);
1443 if (!cp_opt(cp, ',')) break;
1444 } while (cp->tok != '}'); /* Trailing ',' is ok. */
1445 cp_check(cp, '}');
1446 /* Complete enum. */
1447 ctype_get(cp->cts, eid)->info = einfo;
1448 ctype_get(cp->cts, eid)->size = esize;
1450 return eid;
1453 /* Parse declaration specifiers. */
1454 static CPscl cp_decl_spec(CPState *cp, CPDecl *decl, CPscl scl)
1456 uint32_t cds = 0, sz = 0;
1457 CTypeID tdef = 0;
1459 decl->cp = cp;
1460 decl->mode = cp->mode;
1461 decl->name = NULL;
1462 decl->redir = NULL;
1463 decl->attr = 0;
1464 decl->fattr = 0;
1465 decl->pos = decl->top = 0;
1466 decl->stack[0].next = 0;
1468 for (;;) { /* Parse basic types. */
1469 cp_decl_attributes(cp, decl);
1470 switch (cp->tok) {
1471 case CTOK_STRUCT:
1472 tdef = cp_decl_struct(cp, decl, CTINFO(CT_STRUCT, 0));
1473 break;
1474 case CTOK_UNION:
1475 tdef = cp_decl_struct(cp, decl, CTINFO(CT_STRUCT, CTF_UNION));
1476 break;
1477 case CTOK_ENUM:
1478 tdef = cp_decl_enum(cp, decl);
1479 break;
1480 case CTOK_IDENT:
1481 if (!ctype_istypedef(cp->ct->info) || sz || tdef ||
1482 (cds & (CDF_SHORT|CDF_LONG|CDF_SIGNED|CDF_UNSIGNED|CDF_COMPLEX)))
1483 goto end_decl;
1484 tdef = ctype_cid(cp->ct->info); /* Get typedef. */
1485 cp_next(cp);
1486 break;
1487 case '$':
1488 tdef = cp->val.id;
1489 cp_next(cp);
1490 break;
1491 default:
1492 if (cp->tok >= CTOK_FIRSTDECL && cp->tok <= CTOK_LASTDECLFLAG) {
1493 uint32_t cbit;
1494 if (cp->ct->size) {
1495 if (sz) goto end_decl;
1496 sz = cp->ct->size;
1498 cbit = (1u << (cp->tok - CTOK_FIRSTDECL));
1499 cds = cds | cbit | ((cbit & cds & CDF_LONG) << 1);
1500 if (cp->tok >= CTOK_FIRSTSCL && !(scl & cbit))
1501 cp_errmsg(cp, cp->tok, LJ_ERR_FFI_BADSCL);
1502 cp_next(cp);
1503 break;
1505 goto end_decl;
1508 end_decl:
1510 if ((cds & CDF_COMPLEX)) /* Use predefined complex types. */
1511 tdef = sz == 4 ? CTID_COMPLEX_FLOAT : CTID_COMPLEX_DOUBLE;
1513 if (tdef) {
1514 cp_push_type(decl, tdef);
1515 } else if ((cds & CDF_VOID)) {
1516 cp_push(decl, CTINFO(CT_VOID, (decl->attr & CTF_QUAL)), CTSIZE_INVALID);
1517 decl->attr &= ~CTF_QUAL;
1518 } else {
1519 /* Determine type info and size. */
1520 CTInfo info = CTINFO(CT_NUM, (cds & CDF_UNSIGNED) ? CTF_UNSIGNED : 0);
1521 if ((cds & CDF_BOOL)) {
1522 if ((cds & ~(CDF_SCL|CDF_BOOL|CDF_INT|CDF_SIGNED|CDF_UNSIGNED)))
1523 cp_errmsg(cp, 0, LJ_ERR_FFI_INVTYPE);
1524 info |= CTF_BOOL;
1525 if (!sz) {
1526 if (!(cds & CDF_SIGNED)) info |= CTF_UNSIGNED;
1527 sz = 1;
1529 } else if ((cds & CDF_FP)) {
1530 info = CTINFO(CT_NUM, CTF_FP);
1531 if ((cds & CDF_LONG)) sz = sizeof(long double);
1532 } else if ((cds & CDF_CHAR)) {
1533 if ((cds & (CDF_CHAR|CDF_SIGNED|CDF_UNSIGNED)) == CDF_CHAR)
1534 info |= CTF_UCHAR; /* Handle platforms where char is unsigned. */
1535 } else if ((cds & CDF_SHORT)) {
1536 sz = sizeof(short);
1537 } else if ((cds & CDF_LONGLONG)) {
1538 sz = 8;
1539 } else if ((cds & CDF_LONG)) {
1540 info |= CTF_LONG;
1541 sz = sizeof(long);
1542 } else if (!sz) {
1543 if (!(cds & (CDF_SIGNED|CDF_UNSIGNED)))
1544 cp_errmsg(cp, cp->tok, LJ_ERR_FFI_DECLSPEC);
1545 sz = sizeof(int);
1547 lua_assert(sz != 0);
1548 info += CTALIGN(lj_fls(sz)); /* Use natural alignment. */
1549 info += (decl->attr & CTF_QUAL); /* Merge qualifiers. */
1550 cp_push(decl, info, sz);
1551 decl->attr &= ~CTF_QUAL;
1553 decl->specpos = decl->pos;
1554 decl->specattr = decl->attr;
1555 decl->specfattr = decl->fattr;
1556 return (cds & CDF_SCL); /* Return storage class. */
1559 /* Parse array declaration. */
1560 static void cp_decl_array(CPState *cp, CPDecl *decl)
1562 CTInfo info = CTINFO(CT_ARRAY, 0);
1563 CTSize nelem = CTSIZE_INVALID; /* Default size for a[] or a[?]. */
1564 cp_decl_attributes(cp, decl);
1565 if (cp_opt(cp, '?'))
1566 info |= CTF_VLA; /* Create variable-length array a[?]. */
1567 else if (cp->tok != ']')
1568 nelem = cp_expr_ksize(cp);
1569 cp_check(cp, ']');
1570 cp_add(decl, info, nelem);
1573 /* Parse function declaration. */
1574 static void cp_decl_func(CPState *cp, CPDecl *fdecl)
1576 CTSize nargs = 0;
1577 CTInfo info = CTINFO(CT_FUNC, 0);
1578 CTypeID lastid = 0, anchor = 0;
1579 if (cp->tok != ')') {
1580 do {
1581 CPDecl decl;
1582 CTypeID ctypeid, fieldid;
1583 CType *ct;
1584 if (cp_opt(cp, '.')) { /* Vararg function. */
1585 cp_check(cp, '.'); /* Workaround for the minimalistic lexer. */
1586 cp_check(cp, '.');
1587 info |= CTF_VARARG;
1588 break;
1590 cp_decl_spec(cp, &decl, CDF_REGISTER);
1591 decl.mode = CPARSE_MODE_DIRECT|CPARSE_MODE_ABSTRACT;
1592 cp_declarator(cp, &decl);
1593 ctypeid = cp_decl_intern(cp, &decl);
1594 ct = ctype_raw(cp->cts, ctypeid);
1595 if (ctype_isvoid(ct->info))
1596 break;
1597 else if (ctype_isrefarray(ct->info))
1598 ctypeid = lj_ctype_intern(cp->cts,
1599 CTINFO(CT_PTR, CTALIGN_PTR|ctype_cid(ct->info)), CTSIZE_PTR);
1600 else if (ctype_isfunc(ct->info))
1601 ctypeid = lj_ctype_intern(cp->cts,
1602 CTINFO(CT_PTR, CTALIGN_PTR|ctypeid), CTSIZE_PTR);
1603 /* Add new parameter. */
1604 fieldid = lj_ctype_new(cp->cts, &ct);
1605 if (anchor)
1606 ctype_get(cp->cts, lastid)->sib = fieldid;
1607 else
1608 anchor = fieldid;
1609 lastid = fieldid;
1610 if (decl.name) ctype_setname(ct, decl.name);
1611 ct->info = CTINFO(CT_FIELD, ctypeid);
1612 ct->size = nargs++;
1613 } while (cp_opt(cp, ','));
1615 cp_check(cp, ')');
1616 if (cp_opt(cp, '{')) { /* Skip function definition. */
1617 int level = 1;
1618 cp->mode |= CPARSE_MODE_SKIP;
1619 for (;;) {
1620 if (cp->tok == '{') level++;
1621 else if (cp->tok == '}' && --level == 0) break;
1622 else if (cp->tok == CTOK_EOF) cp_err_token(cp, '}');
1623 cp_next(cp);
1625 cp->mode &= ~CPARSE_MODE_SKIP;
1626 cp->tok = ';'; /* Ok for cp_decl_multi(), error in cp_decl_single(). */
1628 info |= (fdecl->fattr & ~CTMASK_CID);
1629 fdecl->fattr = 0;
1630 fdecl->stack[cp_add(fdecl, info, nargs)].sib = anchor;
1633 /* Parse declarator. */
1634 static void cp_declarator(CPState *cp, CPDecl *decl)
1636 if (++cp->depth > CPARSE_MAX_DECLDEPTH) cp_err(cp, LJ_ERR_XLEVELS);
1638 for (;;) { /* Head of declarator. */
1639 if (cp_opt(cp, '*')) { /* Pointer. */
1640 CTSize sz;
1641 CTInfo info;
1642 cp_decl_attributes(cp, decl);
1643 sz = CTSIZE_PTR;
1644 info = CTINFO(CT_PTR, CTALIGN_PTR);
1645 #if LJ_64
1646 if (ctype_msizeP(decl->attr) == 4) {
1647 sz = 4;
1648 info = CTINFO(CT_PTR, CTALIGN(2));
1650 #endif
1651 info += (decl->attr & (CTF_QUAL|CTF_REF));
1652 decl->attr &= ~(CTF_QUAL|(CTMASK_MSIZEP<<CTSHIFT_MSIZEP));
1653 cp_push(decl, info, sz);
1654 } else if (cp_opt(cp, '&') || cp_opt(cp, CTOK_ANDAND)) { /* Reference. */
1655 decl->attr &= ~(CTF_QUAL|(CTMASK_MSIZEP<<CTSHIFT_MSIZEP));
1656 cp_push(decl, CTINFO_REF(0), CTSIZE_PTR);
1657 } else {
1658 break;
1662 if (cp_opt(cp, '(')) { /* Inner declarator. */
1663 CPDeclIdx pos;
1664 cp_decl_attributes(cp, decl);
1665 /* Resolve ambiguity between inner declarator and 1st function parameter. */
1666 if ((decl->mode & CPARSE_MODE_ABSTRACT) &&
1667 (cp->tok == ')' || cp_istypedecl(cp))) goto func_decl;
1668 pos = decl->pos;
1669 cp_declarator(cp, decl);
1670 cp_check(cp, ')');
1671 decl->pos = pos;
1672 } else if (cp->tok == CTOK_IDENT) { /* Direct declarator. */
1673 if (!(decl->mode & CPARSE_MODE_DIRECT)) cp_err_token(cp, CTOK_EOF);
1674 decl->name = cp->str;
1675 decl->nameid = cp->val.id;
1676 cp_next(cp);
1677 } else { /* Abstract declarator. */
1678 if (!(decl->mode & CPARSE_MODE_ABSTRACT)) cp_err_token(cp, CTOK_IDENT);
1681 for (;;) { /* Tail of declarator. */
1682 if (cp_opt(cp, '[')) { /* Array. */
1683 cp_decl_array(cp, decl);
1684 } else if (cp_opt(cp, '(')) { /* Function. */
1685 func_decl:
1686 cp_decl_func(cp, decl);
1687 } else {
1688 break;
1692 if ((decl->mode & CPARSE_MODE_FIELD) && cp_opt(cp, ':')) /* Field width. */
1693 decl->bits = cp_expr_ksize(cp);
1695 /* Process postfix attributes. */
1696 cp_decl_attributes(cp, decl);
1697 cp_push_attributes(decl);
1699 cp->depth--;
1702 /* Parse an abstract type declaration and return it's C type ID. */
1703 static CTypeID cp_decl_abstract(CPState *cp)
1705 CPDecl decl;
1706 cp_decl_spec(cp, &decl, 0);
1707 decl.mode = CPARSE_MODE_ABSTRACT;
1708 cp_declarator(cp, &decl);
1709 return cp_decl_intern(cp, &decl);
1712 /* Handle pragmas. */
1713 static void cp_pragma(CPState *cp, BCLine pragmaline)
1715 cp_next(cp);
1716 if (cp->tok == CTOK_IDENT &&
1717 cp->str->hash == H_(e79b999f,42ca3e85)) { /* pack */
1718 cp_next(cp);
1719 cp_check(cp, '(');
1720 if (cp->tok == CTOK_IDENT) {
1721 if (cp->str->hash == H_(738e923c,a1b65954)) { /* push */
1722 if (cp->curpack < CPARSE_MAX_PACKSTACK) {
1723 cp->packstack[cp->curpack+1] = cp->packstack[cp->curpack];
1724 cp->curpack++;
1726 } else if (cp->str->hash == H_(6c71cf27,6c71cf27)) { /* pop */
1727 if (cp->curpack > 0) cp->curpack--;
1728 } else {
1729 cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
1731 cp_next(cp);
1732 if (!cp_opt(cp, ',')) goto end_pack;
1734 if (cp->tok == CTOK_INTEGER) {
1735 cp->packstack[cp->curpack] = cp->val.u32 ? lj_fls(cp->val.u32) : 0;
1736 cp_next(cp);
1737 } else {
1738 cp->packstack[cp->curpack] = 255;
1740 end_pack:
1741 cp_check(cp, ')');
1742 } else { /* Ignore all other pragmas. */
1743 while (cp->tok != CTOK_EOF && cp->linenumber == pragmaline)
1744 cp_next(cp);
1748 /* Parse multiple C declarations of types or extern identifiers. */
1749 static void cp_decl_multi(CPState *cp)
1751 int first = 1;
1752 while (cp->tok != CTOK_EOF) {
1753 CPDecl decl;
1754 CPscl scl;
1755 if (cp_opt(cp, ';')) { /* Skip empty statements. */
1756 first = 0;
1757 continue;
1759 if (cp->tok == '#') { /* Workaround, since we have no preprocessor, yet. */
1760 BCLine pragmaline = cp->linenumber;
1761 if (!(cp_next(cp) == CTOK_IDENT &&
1762 cp->str->hash == H_(f5e6b4f8,1d509107))) /* pragma */
1763 cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
1764 cp_pragma(cp, pragmaline);
1765 continue;
1767 scl = cp_decl_spec(cp, &decl, CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC);
1768 if ((cp->tok == ';' || cp->tok == CTOK_EOF) &&
1769 ctype_istypedef(decl.stack[0].info)) {
1770 CTInfo info = ctype_rawchild(cp->cts, &decl.stack[0])->info;
1771 if (ctype_isstruct(info) || ctype_isenum(info))
1772 goto decl_end; /* Accept empty declaration of struct/union/enum. */
1774 for (;;) {
1775 CTypeID ctypeid;
1776 cp_declarator(cp, &decl);
1777 ctypeid = cp_decl_intern(cp, &decl);
1778 if (decl.name && !decl.nameid) { /* NYI: redeclarations are ignored. */
1779 CType *ct;
1780 CTypeID id;
1781 if ((scl & CDF_TYPEDEF)) { /* Create new typedef. */
1782 id = lj_ctype_new(cp->cts, &ct);
1783 ct->info = CTINFO(CT_TYPEDEF, ctypeid);
1784 goto noredir;
1785 } else if (ctype_isfunc(ctype_get(cp->cts, ctypeid)->info)) {
1786 /* Treat both static and extern function declarations as extern. */
1787 ct = ctype_get(cp->cts, ctypeid);
1788 /* We always get new anonymous functions (typedefs are copied). */
1789 lua_assert(gcref(ct->name) == NULL);
1790 id = ctypeid; /* Just name it. */
1791 } else if ((scl & CDF_STATIC)) { /* Accept static constants. */
1792 id = cp_decl_constinit(cp, &ct, ctypeid);
1793 goto noredir;
1794 } else { /* External references have extern or no storage class. */
1795 id = lj_ctype_new(cp->cts, &ct);
1796 ct->info = CTINFO(CT_EXTERN, ctypeid);
1798 if (decl.redir) { /* Add attribute for redirected symbol name. */
1799 CType *cta;
1800 CTypeID aid = lj_ctype_new(cp->cts, &cta);
1801 ct = ctype_get(cp->cts, id); /* Table may have been reallocated. */
1802 cta->info = CTINFO(CT_ATTRIB, CTATTRIB(CTA_REDIR));
1803 cta->sib = ct->sib;
1804 ct->sib = aid;
1805 ctype_setname(cta, decl.redir);
1807 noredir:
1808 ctype_setname(ct, decl.name);
1809 lj_ctype_addname(cp->cts, ct, id);
1811 if (!cp_opt(cp, ',')) break;
1812 cp_decl_reset(&decl);
1814 decl_end:
1815 if (cp->tok == CTOK_EOF && first) break; /* May omit ';' for 1 decl. */
1816 first = 0;
1817 cp_check(cp, ';');
1821 /* Parse a single C type declaration. */
1822 static void cp_decl_single(CPState *cp)
1824 CPDecl decl;
1825 cp_decl_spec(cp, &decl, 0);
1826 cp_declarator(cp, &decl);
1827 cp->val.id = cp_decl_intern(cp, &decl);
1828 if (cp->tok != CTOK_EOF) cp_err_token(cp, CTOK_EOF);
1831 #undef H_
1833 /* ------------------------------------------------------------------------ */
1835 /* Protected callback for C parser. */
1836 static TValue *cpcparser(lua_State *L, lua_CFunction dummy, void *ud)
1838 CPState *cp = (CPState *)ud;
1839 UNUSED(dummy);
1840 cframe_errfunc(L->cframe) = -1; /* Inherit error function. */
1841 cp_init(cp);
1842 if ((cp->mode & CPARSE_MODE_MULTI))
1843 cp_decl_multi(cp);
1844 else
1845 cp_decl_single(cp);
1846 if (cp->param && cp->param != cp->L->top)
1847 cp_err(cp, LJ_ERR_FFI_NUMPARAM);
1848 lua_assert(cp->depth == 0);
1849 return NULL;
1852 /* C parser. */
1853 int lj_cparse(CPState *cp)
1855 LJ_CTYPE_SAVE(cp->cts);
1856 int errcode = lj_vm_cpcall(cp->L, NULL, cp, cpcparser);
1857 if (errcode)
1858 LJ_CTYPE_RESTORE(cp->cts);
1859 cp_cleanup(cp);
1860 return errcode;
1863 #endif