src/lj_cparse.c - luajit-2.0-src

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** C declaration parser.
  3. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
  4. */

  5. #include "lj_obj.h"

  6. #if LJ_HASFFI

  7. #include "lj_gc.h"
  8. #include "lj_err.h"
  9. #include "lj_buf.h"
  10. #include "lj_ctype.h"
  11. #include "lj_cparse.h"
  12. #include "lj_frame.h"
  13. #include "lj_vm.h"
  14. #include "lj_char.h"
  15. #include "lj_strscan.h"
  16. #include "lj_strfmt.h"

  17. /*
  18. ** Important note: this is NOT a validating C parser! This is a minimal
  19. ** C declaration parser, solely for use by the LuaJIT FFI.
  20. **
  21. ** It ought to return correct results for properly formed C declarations,
  22. ** but it may accept some invalid declarations, too (and return nonsense).
  23. ** Also, it shows rather generic error messages to avoid unnecessary bloat.
  24. ** If in doubt, please check the input against your favorite C compiler.
  25. */

  26. /* -- C lexer ------------------------------------------------------------- */

  27. /* C lexer token names. */
  28. static const char *const ctoknames[] = {
  29. #define CTOKSTR(name, str)        str,
  30. CTOKDEF(CTOKSTR)
  31. #undef CTOKSTR
  32.   NULL
  33. };

  34. /* Forward declaration. */
  35. LJ_NORET static void cp_err(CPState *cp, ErrMsg em);

  36. static const char *cp_tok2str(CPState *cp, CPToken tok)
  37. {
  38.   lua_assert(tok < CTOK_FIRSTDECL);
  39.   if (tok > CTOK_OFS)
  40.     return ctoknames[tok-CTOK_OFS-1];
  41.   else if (!lj_char_iscntrl(tok))
  42.     return lj_strfmt_pushf(cp->L, "%c", tok);
  43.   else
  44.     return lj_strfmt_pushf(cp->L, "char(%d)", tok);
  45. }

  46. /* End-of-line? */
  47. static LJ_AINLINE int cp_iseol(CPChar c)
  48. {
  49.   return (c == '\n' || c == '\r');
  50. }

  51. /* Peek next raw character. */
  52. static LJ_AINLINE CPChar cp_rawpeek(CPState *cp)
  53. {
  54.   return (CPChar)(uint8_t)(*cp->p);
  55. }

  56. static LJ_NOINLINE CPChar cp_get_bs(CPState *cp);

  57. /* Get next character. */
  58. static LJ_AINLINE CPChar cp_get(CPState *cp)
  59. {
  60.   cp->c = (CPChar)(uint8_t)(*cp->p++);
  61.   if (LJ_LIKELY(cp->c != '\\')) return cp->c;
  62.   return cp_get_bs(cp);
  63. }

  64. /* Transparently skip backslash-escaped line breaks. */
  65. static LJ_NOINLINE CPChar cp_get_bs(CPState *cp)
  66. {
  67.   CPChar c2, c = cp_rawpeek(cp);
  68.   if (!cp_iseol(c)) return cp->c;
  69.   cp->p++;
  70.   c2 = cp_rawpeek(cp);
  71.   if (cp_iseol(c2) && c2 != c) cp->p++;
  72.   cp->linenumber++;
  73.   return cp_get(cp);
  74. }

  75. /* Save character in buffer. */
  76. static LJ_AINLINE void cp_save(CPState *cp, CPChar c)
  77. {
  78.   lj_buf_putb(&cp->sb, c);
  79. }

  80. /* Skip line break. Handles "\n", "\r", "\r\n" or "\n\r". */
  81. static void cp_newline(CPState *cp)
  82. {
  83.   CPChar c = cp_rawpeek(cp);
  84.   if (cp_iseol(c) && c != cp->c) cp->p++;
  85.   cp->linenumber++;
  86. }

  87. LJ_NORET static void cp_errmsg(CPState *cp, CPToken tok, ErrMsg em, ...)
  88. {
  89.   const char *msg, *tokstr;
  90.   lua_State *L;
  91.   va_list argp;
  92.   if (tok == 0) {
  93.     tokstr = NULL;
  94.   } else if (tok == CTOK_IDENT || tok == CTOK_INTEGER || tok == CTOK_STRING ||
  95.              tok >= CTOK_FIRSTDECL) {
  96.     if (sbufP(&cp->sb) == sbufB(&cp->sb)) cp_save(cp, '$');
  97.     cp_save(cp, '\0');
  98.     tokstr = sbufB(&cp->sb);
  99.   } else {
  100.     tokstr = cp_tok2str(cp, tok);
  101.   }
  102.   L = cp->L;
  103.   va_start(argp, em);
  104.   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  105.   va_end(argp);
  106.   if (tokstr)
  107.     msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tokstr);
  108.   if (cp->linenumber > 1)
  109.     msg = lj_strfmt_pushf(L, "%s at line %d", msg, cp->linenumber);
  110.   lj_err_callermsg(L, msg);
  111. }

  112. LJ_NORET LJ_NOINLINE static void cp_err_token(CPState *cp, CPToken tok)
  113. {
  114.   cp_errmsg(cp, cp->tok, LJ_ERR_XTOKEN, cp_tok2str(cp, tok));
  115. }

  116. LJ_NORET LJ_NOINLINE static void cp_err_badidx(CPState *cp, CType *ct)
  117. {
  118.   GCstr *s = lj_ctype_repr(cp->cts->L, ctype_typeid(cp->cts, ct), NULL);
  119.   cp_errmsg(cp, 0, LJ_ERR_FFI_BADIDX, strdata(s));
  120. }

  121. LJ_NORET LJ_NOINLINE static void cp_err(CPState *cp, ErrMsg em)
  122. {
  123.   cp_errmsg(cp, 0, em);
  124. }

  125. /* -- Main lexical scanner ------------------------------------------------ */

  126. /* Parse number literal. Only handles int32_t/uint32_t right now. */
  127. static CPToken cp_number(CPState *cp)
  128. {
  129.   StrScanFmt fmt;
  130.   TValue o;
  131.   do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
  132.   cp_save(cp, '\0');
  133.   fmt = lj_strscan_scan((const uint8_t *)sbufB(&cp->sb), &o, STRSCAN_OPT_C);
  134.   if (fmt == STRSCAN_INT) cp->val.id = CTID_INT32;
  135.   else if (fmt == STRSCAN_U32) cp->val.id = CTID_UINT32;
  136.   else if (!(cp->mode & CPARSE_MODE_SKIP))
  137.     cp_errmsg(cp, CTOK_INTEGER, LJ_ERR_XNUMBER);
  138.   cp->val.u32 = (uint32_t)o.i;
  139.   return CTOK_INTEGER;
  140. }

  141. /* Parse identifier or keyword. */
  142. static CPToken cp_ident(CPState *cp)
  143. {
  144.   do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
  145.   cp->str = lj_buf_str(cp->L, &cp->sb);
  146.   cp->val.id = lj_ctype_getname(cp->cts, &cp->ct, cp->str, cp->tmask);
  147.   if (ctype_type(cp->ct->info) == CT_KW)
  148.     return ctype_cid(cp->ct->info);
  149.   return CTOK_IDENT;
  150. }

  151. /* Parse parameter. */
  152. static CPToken cp_param(CPState *cp)
  153. {
  154.   CPChar c = cp_get(cp);
  155.   TValue *o = cp->param;
  156.   if (lj_char_isident(c) || c == '$'/* Reserve $xyz for future extensions. */
  157.     cp_errmsg(cp, c, LJ_ERR_XSYNTAX);
  158.   if (!o || o >= cp->L->top)
  159.     cp_err(cp, LJ_ERR_FFI_NUMPARAM);
  160.   cp->param = o+1;
  161.   if (tvisstr(o)) {
  162.     cp->str = strV(o);
  163.     cp->val.id = 0;
  164.     cp->ct = &cp->cts->tab[0];
  165.     return CTOK_IDENT;
  166.   } else if (tvisnumber(o)) {
  167.     cp->val.i32 = numberVint(o);
  168.     cp->val.id = CTID_INT32;
  169.     return CTOK_INTEGER;
  170.   } else {
  171.     GCcdata *cd;
  172.     if (!tviscdata(o))
  173.       lj_err_argtype(cp->L, (int)(o-cp->L->base)+1, "type parameter");
  174.     cd = cdataV(o);
  175.     if (cd->ctypeid == CTID_CTYPEID)
  176.       cp->val.id = *(CTypeID *)cdataptr(cd);
  177.     else
  178.       cp->val.id = cd->ctypeid;
  179.     return '$';
  180.   }
  181. }

  182. /* Parse string or character constant. */
  183. static CPToken cp_string(CPState *cp)
  184. {
  185.   CPChar delim = cp->c;
  186.   cp_get(cp);
  187.   while (cp->c != delim) {
  188.     CPChar c = cp->c;
  189.     if (c == '\0') cp_errmsg(cp, CTOK_EOF, LJ_ERR_XSTR);
  190.     if (c == '\\') {
  191.       c = cp_get(cp);
  192.       switch (c) {
  193.       case '\0': cp_errmsg(cp, CTOK_EOF, LJ_ERR_XSTR); break;
  194.       case 'a': c = '\a'; break;
  195.       case 'b': c = '\b'; break;
  196.       case 'f': c = '\f'; break;
  197.       case 'n': c = '\n'; break;
  198.       case 'r': c = '\r'; break;
  199.       case 't': c = '\t'; break;
  200.       case 'v': c = '\v'; break;
  201.       case 'e': c = 27; break;
  202.       case 'x':
  203.         c = 0;
  204.         while (lj_char_isxdigit(cp_get(cp)))
  205.           c = (c<<4) + (lj_char_isdigit(cp->c) ? cp->c-'0' : (cp->c&15)+9);
  206.         cp_save(cp, (c & 0xff));
  207.         continue;
  208.       default:
  209.         if (lj_char_isdigit(c)) {
  210.           c -= '0';
  211.           if (lj_char_isdigit(cp_get(cp))) {
  212.             c = c*8 + (cp->c - '0');
  213.             if (lj_char_isdigit(cp_get(cp))) {
  214.               c = c*8 + (cp->c - '0');
  215.               cp_get(cp);
  216.             }
  217.           }
  218.           cp_save(cp, (c & 0xff));
  219.           continue;
  220.         }
  221.         break;
  222.       }
  223.     }
  224.     cp_save(cp, c);
  225.     cp_get(cp);
  226.   }
  227.   cp_get(cp);
  228.   if (delim == '"') {
  229.     cp->str = lj_buf_str(cp->L, &cp->sb);
  230.     return CTOK_STRING;
  231.   } else {
  232.     if (sbuflen(&cp->sb) != 1) cp_err_token(cp, '\'');
  233.     cp->val.i32 = (int32_t)(char)*sbufB(&cp->sb);
  234.     cp->val.id = CTID_INT32;
  235.     return CTOK_INTEGER;
  236.   }
  237. }

  238. /* Skip C comment. */
  239. static void cp_comment_c(CPState *cp)
  240. {
  241.   do {
  242.     if (cp_get(cp) == '*') {
  243.       do {
  244.         if (cp_get(cp) == '/') { cp_get(cp); return; }
  245.       } while (cp->c == '*');
  246.     }
  247.     if (cp_iseol(cp->c)) cp_newline(cp);
  248.   } while (cp->c != '\0');
  249. }

  250. /* Skip C++ comment. */
  251. static void cp_comment_cpp(CPState *cp)
  252. {
  253.   while (!cp_iseol(cp_get(cp)) && cp->c != '\0')
  254.     ;
  255. }

  256. /* Lexical scanner for C. Only a minimal subset is implemented. */
  257. static CPToken cp_next_(CPState *cp)
  258. {
  259.   lj_buf_reset(&cp->sb);
  260.   for (;;) {
  261.     if (lj_char_isident(cp->c))
  262.       return lj_char_isdigit(cp->c) ? cp_number(cp) : cp_ident(cp);
  263.     switch (cp->c) {
  264.     case '\n': case '\r': cp_newline(cp);  /* fallthrough. */
  265.     case ' ': case '\t': case '\v': case '\f': cp_get(cp); break;
  266.     case '"': case '\'': return cp_string(cp);
  267.     case '/':
  268.       if (cp_get(cp) == '*') cp_comment_c(cp);
  269.       else if (cp->c == '/') cp_comment_cpp(cp);
  270.       else return '/';
  271.       break;
  272.     case '|':
  273.       if (cp_get(cp) != '|') return '|'; cp_get(cp); return CTOK_OROR;
  274.     case '&':
  275.       if (cp_get(cp) != '&') return '&'; cp_get(cp); return CTOK_ANDAND;
  276.     case '=':
  277.       if (cp_get(cp) != '=') return '='; cp_get(cp); return CTOK_EQ;
  278.     case '!':
  279.       if (cp_get(cp) != '=') return '!'; cp_get(cp); return CTOK_NE;
  280.     case '<':
  281.       if (cp_get(cp) == '=') { cp_get(cp); return CTOK_LE; }
  282.       else if (cp->c == '<') { cp_get(cp); return CTOK_SHL; }
  283.       return '<';
  284.     case '>':
  285.       if (cp_get(cp) == '=') { cp_get(cp); return CTOK_GE; }
  286.       else if (cp->c == '>') { cp_get(cp); return CTOK_SHR; }
  287.       return '>';
  288.     case '-':
  289.       if (cp_get(cp) != '>') return '-'; cp_get(cp); return CTOK_DEREF;
  290.     case '$':
  291.       return cp_param(cp);
  292.     case '\0': return CTOK_EOF;
  293.     default: { CPToken c = cp->c; cp_get(cp); return c; }
  294.     }
  295.   }
  296. }

  297. static LJ_NOINLINE CPToken cp_next(CPState *cp)
  298. {
  299.   return (cp->tok = cp_next_(cp));
  300. }

  301. /* -- C parser ------------------------------------------------------------ */

  302. /* Namespaces for resolving identifiers. */
  303. #define CPNS_DEFAULT \
  304.   ((1u<<CT_KW)|(1u<<CT_TYPEDEF)|(1u<<CT_FUNC)|(1u<<CT_EXTERN)|(1u<<CT_CONSTVAL))
  305. #define CPNS_STRUCT        ((1u<<CT_KW)|(1u<<CT_STRUCT)|(1u<<CT_ENUM))

  306. typedef CTypeID CPDeclIdx;        /* Index into declaration stack. */
  307. typedef uint32_t CPscl;                /* Storage class flags. */

  308. /* Type declaration context. */
  309. typedef struct CPDecl {
  310.   CPDeclIdx top;        /* Top of declaration stack. */
  311.   CPDeclIdx pos;        /* Insertion position in declaration chain. */
  312.   CPDeclIdx specpos;        /* Saved position for declaration specifier. */
  313.   uint32_t mode;        /* Declarator mode. */
  314.   CPState *cp;                /* C parser state. */
  315.   GCstr *name;                /* Name of declared identifier (if direct). */
  316.   GCstr *redir;                /* Redirected symbol name. */
  317.   CTypeID nameid;        /* Existing typedef for declared identifier. */
  318.   CTInfo attr;                /* Attributes. */
  319.   CTInfo fattr;                /* Function attributes. */
  320.   CTInfo specattr;        /* Saved attributes. */
  321.   CTInfo specfattr;        /* Saved function attributes. */
  322.   CTSize bits;                /* Field size in bits (if any). */
  323.   CType stack[CPARSE_MAX_DECLSTACK];  /* Type declaration stack. */
  324. } CPDecl;

  325. /* Forward declarations. */
  326. static CPscl cp_decl_spec(CPState *cp, CPDecl *decl, CPscl scl);
  327. static void cp_declarator(CPState *cp, CPDecl *decl);
  328. static CTypeID cp_decl_abstract(CPState *cp);

  329. /* Initialize C parser state. Caller must set up: L, p, srcname, mode. */
  330. static void cp_init(CPState *cp)
  331. {
  332.   cp->linenumber = 1;
  333.   cp->depth = 0;
  334.   cp->curpack = 0;
  335.   cp->packstack[0] = 255;
  336.   lj_buf_init(cp->L, &cp->sb);
  337.   lua_assert(cp->p != NULL);
  338.   cp_get(cp);  /* Read-ahead first char. */
  339.   cp->tok = 0;
  340.   cp->tmask = CPNS_DEFAULT;
  341.   cp_next(cp);  /* Read-ahead first token. */
  342. }

  343. /* Cleanup C parser state. */
  344. static void cp_cleanup(CPState *cp)
  345. {
  346.   global_State *g = G(cp->L);
  347.   lj_buf_free(g, &cp->sb);
  348. }

  349. /* Check and consume optional token. */
  350. static int cp_opt(CPState *cp, CPToken tok)
  351. {
  352.   if (cp->tok == tok) { cp_next(cp); return 1; }
  353.   return 0;
  354. }

  355. /* Check and consume token. */
  356. static void cp_check(CPState *cp, CPToken tok)
  357. {
  358.   if (cp->tok != tok) cp_err_token(cp, tok);
  359.   cp_next(cp);
  360. }

  361. /* Check if the next token may start a type declaration. */
  362. static int cp_istypedecl(CPState *cp)
  363. {
  364.   if (cp->tok >= CTOK_FIRSTDECL && cp->tok <= CTOK_LASTDECL) return 1;
  365.   if (cp->tok == CTOK_IDENT && ctype_istypedef(cp->ct->info)) return 1;
  366.   if (cp->tok == '$') return 1;
  367.   return 0;
  368. }

  369. /* -- Constant expression evaluator --------------------------------------- */

  370. /* Forward declarations. */
  371. static void cp_expr_unary(CPState *cp, CPValue *k);
  372. static void cp_expr_sub(CPState *cp, CPValue *k, int pri);

  373. /* Please note that type handling is very weak here. Most ops simply
  374. ** assume integer operands. Accessors are only needed to compute types and
  375. ** return synthetic values. The only purpose of the expression evaluator
  376. ** is to compute the values of constant expressions one would typically
  377. ** find in C header files. And again: this is NOT a validating C parser!
  378. */

  379. /* Parse comma separated expression and return last result. */
  380. static void cp_expr_comma(CPState *cp, CPValue *k)
  381. {
  382.   do { cp_expr_sub(cp, k, 0); } while (cp_opt(cp, ','));
  383. }

  384. /* Parse sizeof/alignof operator. */
  385. static void cp_expr_sizeof(CPState *cp, CPValue *k, int wantsz)
  386. {
  387.   CTSize sz;
  388.   CTInfo info;
  389.   if (cp_opt(cp, '(')) {
  390.     if (cp_istypedecl(cp))
  391.       k->id = cp_decl_abstract(cp);
  392.     else
  393.       cp_expr_comma(cp, k);
  394.     cp_check(cp, ')');
  395.   } else {
  396.     cp_expr_unary(cp, k);
  397.   }
  398.   info = lj_ctype_info(cp->cts, k->id, &sz);
  399.   if (wantsz) {
  400.     if (sz != CTSIZE_INVALID)
  401.       k->u32 = sz;
  402.     else if (k->id != CTID_A_CCHAR)  /* Special case for sizeof("string"). */
  403.       cp_err(cp, LJ_ERR_FFI_INVSIZE);
  404.   } else {
  405.     k->u32 = 1u << ctype_align(info);
  406.   }
  407.   k->id = CTID_UINT32;  /* Really size_t. */
  408. }

  409. /* Parse prefix operators. */
  410. static void cp_expr_prefix(CPState *cp, CPValue *k)
  411. {
  412.   if (cp->tok == CTOK_INTEGER) {
  413.     *k = cp->val; cp_next(cp);
  414.   } else if (cp_opt(cp, '+')) {
  415.     cp_expr_unary(cp, k);  /* Nothing to do (well, integer promotion). */
  416.   } else if (cp_opt(cp, '-')) {
  417.     cp_expr_unary(cp, k); k->i32 = -k->i32;
  418.   } else if (cp_opt(cp, '~')) {
  419.     cp_expr_unary(cp, k); k->i32 = ~k->i32;
  420.   } else if (cp_opt(cp, '!')) {
  421.     cp_expr_unary(cp, k); k->i32 = !k->i32; k->id = CTID_INT32;
  422.   } else if (cp_opt(cp, '(')) {
  423.     if (cp_istypedecl(cp)) {  /* Cast operator. */
  424.       CTypeID id = cp_decl_abstract(cp);
  425.       cp_check(cp, ')');
  426.       cp_expr_unary(cp, k);
  427.       k->id = id;  /* No conversion performed. */
  428.     } else/* Sub-expression. */
  429.       cp_expr_comma(cp, k);
  430.       cp_check(cp, ')');
  431.     }
  432.   } else if (cp_opt(cp, '*')) {  /* Indirection. */
  433.     CType *ct;
  434.     cp_expr_unary(cp, k);
  435.     ct = lj_ctype_rawref(cp->cts, k->id);
  436.     if (!ctype_ispointer(ct->info))
  437.       cp_err_badidx(cp, ct);
  438.     k->u32 = 0; k->id = ctype_cid(ct->info);
  439.   } else if (cp_opt(cp, '&')) {  /* Address operator. */
  440.     cp_expr_unary(cp, k);
  441.     k->id = lj_ctype_intern(cp->cts, CTINFO(CT_PTR, CTALIGN_PTR+k->id),
  442.                             CTSIZE_PTR);
  443.   } else if (cp_opt(cp, CTOK_SIZEOF)) {
  444.     cp_expr_sizeof(cp, k, 1);
  445.   } else if (cp_opt(cp, CTOK_ALIGNOF)) {
  446.     cp_expr_sizeof(cp, k, 0);
  447.   } else if (cp->tok == CTOK_IDENT) {
  448.     if (ctype_type(cp->ct->info) == CT_CONSTVAL) {
  449.       k->u32 = cp->ct->size; k->id = ctype_cid(cp->ct->info);
  450.     } else if (ctype_type(cp->ct->info) == CT_EXTERN) {
  451.       k->u32 = cp->val.id; k->id = ctype_cid(cp->ct->info);
  452.     } else if (ctype_type(cp->ct->info) == CT_FUNC) {
  453.       k->u32 = cp->val.id; k->id = cp->val.id;
  454.     } else {
  455.       goto err_expr;
  456.     }
  457.     cp_next(cp);
  458.   } else if (cp->tok == CTOK_STRING) {
  459.     CTSize sz = cp->str->len;
  460.     while (cp_next(cp) == CTOK_STRING)
  461.       sz += cp->str->len;
  462.     k->u32 = sz + 1;
  463.     k->id = CTID_A_CCHAR;
  464.   } else {
  465.   err_expr:
  466.     cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
  467.   }
  468. }

  469. /* Parse postfix operators. */
  470. static void cp_expr_postfix(CPState *cp, CPValue *k)
  471. {
  472.   for (;;) {
  473.     CType *ct;
  474.     if (cp_opt(cp, '[')) {  /* Array/pointer index. */
  475.       CPValue k2;
  476.       cp_expr_comma(cp, &k2);
  477.       ct = lj_ctype_rawref(cp->cts, k->id);
  478.       if (!ctype_ispointer(ct->info)) {
  479.         ct = lj_ctype_rawref(cp->cts, k2.id);
  480.         if (!ctype_ispointer(ct->info))
  481.           cp_err_badidx(cp, ct);
  482.       }
  483.       cp_check(cp, ']');
  484.       k->u32 = 0;
  485.     } else if (cp->tok == '.' || cp->tok == CTOK_DEREF) {  /* Struct deref. */
  486.       CTSize ofs;
  487.       CType *fct;
  488.       ct = lj_ctype_rawref(cp->cts, k->id);
  489.       if (cp->tok == CTOK_DEREF) {
  490.         if (!ctype_ispointer(ct->info))
  491.           cp_err_badidx(cp, ct);
  492.         ct = lj_ctype_rawref(cp->cts, ctype_cid(ct->info));
  493.       }
  494.       cp_next(cp);
  495.       if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
  496.       if (!ctype_isstruct(ct->info) || ct->size == CTSIZE_INVALID ||
  497.           !(fct = lj_ctype_getfield(cp->cts, ct, cp->str, &ofs)) ||
  498.           ctype_isbitfield(fct->info)) {
  499.         GCstr *s = lj_ctype_repr(cp->cts->L, ctype_typeid(cp->cts, ct), NULL);
  500.         cp_errmsg(cp, 0, LJ_ERR_FFI_BADMEMBER, strdata(s), strdata(cp->str));
  501.       }
  502.       ct = fct;
  503.       k->u32 = ctype_isconstval(ct->info) ? ct->size : 0;
  504.       cp_next(cp);
  505.     } else {
  506.       return;
  507.     }
  508.     k->id = ctype_cid(ct->info);
  509.   }
  510. }

  511. /* Parse infix operators. */
  512. static void cp_expr_infix(CPState *cp, CPValue *k, int pri)
  513. {
  514.   CPValue k2;
  515.   k2.u32 = 0; k2.id = 0/* Silence the compiler. */
  516.   for (;;) {
  517.     switch (pri) {
  518.     case 0:
  519.       if (cp_opt(cp, '?')) {
  520.         CPValue k3;
  521.         cp_expr_comma(cp, &k2);  /* Right-associative. */
  522.         cp_check(cp, ':');
  523.         cp_expr_sub(cp, &k3, 0);
  524.         k->u32 = k->u32 ? k2.u32 : k3.u32;
  525.         k->id = k2.id > k3.id ? k2.id : k3.id;
  526.         continue;
  527.       }
  528.     case 1:
  529.       if (cp_opt(cp, CTOK_OROR)) {
  530.         cp_expr_sub(cp, &k2, 2); k->i32 = k->u32 || k2.u32; k->id = CTID_INT32;
  531.         continue;
  532.       }
  533.     case 2:
  534.       if (cp_opt(cp, CTOK_ANDAND)) {
  535.         cp_expr_sub(cp, &k2, 3); k->i32 = k->u32 && k2.u32; k->id = CTID_INT32;
  536.         continue;
  537.       }
  538.     case 3:
  539.       if (cp_opt(cp, '|')) {
  540.         cp_expr_sub(cp, &k2, 4); k->u32 = k->u32 | k2.u32; goto arith_result;
  541.       }
  542.     case 4:
  543.       if (cp_opt(cp, '^')) {
  544.         cp_expr_sub(cp, &k2, 5); k->u32 = k->u32 ^ k2.u32; goto arith_result;
  545.       }
  546.     case 5:
  547.       if (cp_opt(cp, '&')) {
  548.         cp_expr_sub(cp, &k2, 6); k->u32 = k->u32 & k2.u32; goto arith_result;
  549.       }
  550.     case 6:
  551.       if (cp_opt(cp, CTOK_EQ)) {
  552.         cp_expr_sub(cp, &k2, 7); k->i32 = k->u32 == k2.u32; k->id = CTID_INT32;
  553.         continue;
  554.       } else if (cp_opt(cp, CTOK_NE)) {
  555.         cp_expr_sub(cp, &k2, 7); k->i32 = k->u32 != k2.u32; k->id = CTID_INT32;
  556.         continue;
  557.       }
  558.     case 7:
  559.       if (cp_opt(cp, '<')) {
  560.         cp_expr_sub(cp, &k2, 8);
  561.         if (k->id == CTID_INT32 && k2.id == CTID_INT32)
  562.           k->i32 = k->i32 < k2.i32;
  563.         else
  564.           k->i32 = k->u32 < k2.u32;
  565.         k->id = CTID_INT32;
  566.         continue;
  567.       } else if (cp_opt(cp, '>')) {
  568.         cp_expr_sub(cp, &k2, 8);
  569.         if (k->id == CTID_INT32 && k2.id == CTID_INT32)
  570.           k->i32 = k->i32 > k2.i32;
  571.         else
  572.           k->i32 = k->u32 > k2.u32;
  573.         k->id = CTID_INT32;
  574.         continue;
  575.       } else if (cp_opt(cp, CTOK_LE)) {
  576.         cp_expr_sub(cp, &k2, 8);
  577.         if (k->id == CTID_INT32 && k2.id == CTID_INT32)
  578.           k->i32 = k->i32 <= k2.i32;
  579.         else
  580.           k->i32 = k->u32 <= k2.u32;
  581.         k->id = CTID_INT32;
  582.         continue;
  583.       } else if (cp_opt(cp, CTOK_GE)) {
  584.         cp_expr_sub(cp, &k2, 8);
  585.         if (k->id == CTID_INT32 && k2.id == CTID_INT32)
  586.           k->i32 = k->i32 >= k2.i32;
  587.         else
  588.           k->i32 = k->u32 >= k2.u32;
  589.         k->id = CTID_INT32;
  590.         continue;
  591.       }
  592.     case 8:
  593.       if (cp_opt(cp, CTOK_SHL)) {
  594.         cp_expr_sub(cp, &k2, 9); k->u32 = k->u32 << k2.u32;
  595.         continue;
  596.       } else if (cp_opt(cp, CTOK_SHR)) {
  597.         cp_expr_sub(cp, &k2, 9);
  598.         if (k->id == CTID_INT32)
  599.           k->i32 = k->i32 >> k2.i32;
  600.         else
  601.           k->u32 = k->u32 >> k2.u32;
  602.         continue;
  603.       }
  604.     case 9:
  605.       if (cp_opt(cp, '+')) {
  606.         cp_expr_sub(cp, &k2, 10); k->u32 = k->u32 + k2.u32;
  607.       arith_result:
  608.         if (k2.id > k->id) k->id = k2.id;  /* Trivial promotion to unsigned. */
  609.         continue;
  610.       } else if (cp_opt(cp, '-')) {
  611.         cp_expr_sub(cp, &k2, 10); k->u32 = k->u32 - k2.u32; goto arith_result;
  612.       }
  613.     case 10:
  614.       if (cp_opt(cp, '*')) {
  615.         cp_expr_unary(cp, &k2); k->u32 = k->u32 * k2.u32; goto arith_result;
  616.       } else if (cp_opt(cp, '/')) {
  617.         cp_expr_unary(cp, &k2);
  618.         if (k2.id > k->id) k->id = k2.id;  /* Trivial promotion to unsigned. */
  619.         if (k2.u32 == 0 ||
  620.             (k->id == CTID_INT32 && k->u32 == 0x80000000u && k2.i32 == -1))
  621.           cp_err(cp, LJ_ERR_BADVAL);
  622.         if (k->id == CTID_INT32)
  623.           k->i32 = k->i32 / k2.i32;
  624.         else
  625.           k->u32 = k->u32 / k2.u32;
  626.         continue;
  627.       } else if (cp_opt(cp, '%')) {
  628.         cp_expr_unary(cp, &k2);
  629.         if (k2.id > k->id) k->id = k2.id;  /* Trivial promotion to unsigned. */
  630.         if (k2.u32 == 0 ||
  631.             (k->id == CTID_INT32 && k->u32 == 0x80000000u && k2.i32 == -1))
  632.           cp_err(cp, LJ_ERR_BADVAL);
  633.         if (k->id == CTID_INT32)
  634.           k->i32 = k->i32 % k2.i32;
  635.         else
  636.           k->u32 = k->u32 % k2.u32;
  637.         continue;
  638.       }
  639.     default:
  640.       return;
  641.     }
  642.   }
  643. }

  644. /* Parse and evaluate unary expression. */
  645. static void cp_expr_unary(CPState *cp, CPValue *k)
  646. {
  647.   if (++cp->depth > CPARSE_MAX_DECLDEPTH) cp_err(cp, LJ_ERR_XLEVELS);
  648.   cp_expr_prefix(cp, k);
  649.   cp_expr_postfix(cp, k);
  650.   cp->depth--;
  651. }

  652. /* Parse and evaluate sub-expression. */
  653. static void cp_expr_sub(CPState *cp, CPValue *k, int pri)
  654. {
  655.   cp_expr_unary(cp, k);
  656.   cp_expr_infix(cp, k, pri);
  657. }

  658. /* Parse constant integer expression. */
  659. static void cp_expr_kint(CPState *cp, CPValue *k)
  660. {
  661.   CType *ct;
  662.   cp_expr_sub(cp, k, 0);
  663.   ct = ctype_raw(cp->cts, k->id);
  664.   if (!ctype_isinteger(ct->info)) cp_err(cp, LJ_ERR_BADVAL);
  665. }

  666. /* Parse (non-negative) size expression. */
  667. static CTSize cp_expr_ksize(CPState *cp)
  668. {
  669.   CPValue k;
  670.   cp_expr_kint(cp, &k);
  671.   if (k.u32 >= 0x80000000u) cp_err(cp, LJ_ERR_FFI_INVSIZE);
  672.   return k.u32;
  673. }

  674. /* -- Type declaration stack management ----------------------------------- */

  675. /* Add declaration element behind the insertion position. */
  676. static CPDeclIdx cp_add(CPDecl *decl, CTInfo info, CTSize size)
  677. {
  678.   CPDeclIdx top = decl->top;
  679.   if (top >= CPARSE_MAX_DECLSTACK) cp_err(decl->cp, LJ_ERR_XLEVELS);
  680.   decl->stack[top].info = info;
  681.   decl->stack[top].size = size;
  682.   decl->stack[top].sib = 0;
  683.   setgcrefnull(decl->stack[top].name);
  684.   decl->stack[top].next = decl->stack[decl->pos].next;
  685.   decl->stack[decl->pos].next = (CTypeID1)top;
  686.   decl->top = top+1;
  687.   return top;
  688. }

  689. /* Push declaration element before the insertion position. */
  690. static CPDeclIdx cp_push(CPDecl *decl, CTInfo info, CTSize size)
  691. {
  692.   return (decl->pos = cp_add(decl, info, size));
  693. }

  694. /* Push or merge attributes. */
  695. static void cp_push_attributes(CPDecl *decl)
  696. {
  697.   CType *ct = &decl->stack[decl->pos];
  698.   if (ctype_isfunc(ct->info)) {  /* Ok to modify in-place. */
  699. #if LJ_TARGET_X86
  700.     if ((decl->fattr & CTFP_CCONV))
  701.       ct->info = (ct->info & (CTMASK_NUM|CTF_VARARG|CTMASK_CID)) +
  702.                  (decl->fattr & ~CTMASK_CID);
  703. #endif
  704.   } else {
  705.     if ((decl->attr & CTFP_ALIGNED) && !(decl->mode & CPARSE_MODE_FIELD))
  706.       cp_push(decl, CTINFO(CT_ATTRIB, CTATTRIB(CTA_ALIGN)),
  707.               ctype_align(decl->attr));
  708.   }
  709. }

  710. /* Push unrolled type to declaration stack and merge qualifiers. */
  711. static void cp_push_type(CPDecl *decl, CTypeID id)
  712. {
  713.   CType *ct = ctype_get(decl->cp->cts, id);
  714.   CTInfo info = ct->info;
  715.   CTSize size = ct->size;
  716.   switch (ctype_type(info)) {
  717.   case CT_STRUCT: case CT_ENUM:
  718.     cp_push(decl, CTINFO(CT_TYPEDEF, id), 0);  /* Don't copy unique types. */
  719.     if ((decl->attr & CTF_QUAL)) {  /* Push unmerged qualifiers. */
  720.       cp_push(decl, CTINFO(CT_ATTRIB, CTATTRIB(CTA_QUAL)),
  721.               (decl->attr & CTF_QUAL));
  722.       decl->attr &= ~CTF_QUAL;
  723.     }
  724.     break;
  725.   case CT_ATTRIB:
  726.     if (ctype_isxattrib(info, CTA_QUAL))
  727.       decl->attr &= ~size;  /* Remove redundant qualifiers. */
  728.     cp_push_type(decl, ctype_cid(info));  /* Unroll. */
  729.     cp_push(decl, info & ~CTMASK_CID, size);  /* Copy type. */
  730.     break;
  731.   case CT_ARRAY:
  732.     cp_push_type(decl, ctype_cid(info));  /* Unroll. */
  733.     cp_push(decl, info & ~CTMASK_CID, size);  /* Copy type. */
  734.     decl->stack[decl->pos].sib = 1/* Mark as already checked and sized. */
  735.     /* Note: this is not copied to the ct->sib in the C type table. */
  736.     break;
  737.   case CT_FUNC:
  738.     /* Copy type, link parameters (shared). */
  739.     decl->stack[cp_push(decl, info, size)].sib = ct->sib;
  740.     break;
  741.   default:
  742.     /* Copy type, merge common qualifiers. */
  743.     cp_push(decl, info|(decl->attr & CTF_QUAL), size);
  744.     decl->attr &= ~CTF_QUAL;
  745.     break;
  746.   }
  747. }

  748. /* Consume the declaration element chain and intern the C type. */
  749. static CTypeID cp_decl_intern(CPState *cp, CPDecl *decl)
  750. {
  751.   CTypeID id = 0;
  752.   CPDeclIdx idx = 0;
  753.   CTSize csize = CTSIZE_INVALID;
  754.   CTSize cinfo = 0;
  755.   do {
  756.     CType *ct = &decl->stack[idx];
  757.     CTInfo info = ct->info;
  758.     CTInfo size = ct->size;
  759.     /* The cid is already part of info for copies of pointers/functions. */
  760.     idx = ct->next;
  761.     if (ctype_istypedef(info)) {
  762.       lua_assert(id == 0);
  763.       id = ctype_cid(info);
  764.       /* Always refetch info/size, since struct/enum may have been completed. */
  765.       cinfo = ctype_get(cp->cts, id)->info;
  766.       csize = ctype_get(cp->cts, id)->size;
  767.       lua_assert(ctype_isstruct(cinfo) || ctype_isenum(cinfo));
  768.     } else if (ctype_isfunc(info)) {  /* Intern function. */
  769.       CType *fct;
  770.       CTypeID fid;
  771.       CTypeID sib;
  772.       if (id) {
  773.         CType *refct = ctype_raw(cp->cts, id);
  774.         /* Reject function or refarray return types. */
  775.         if (ctype_isfunc(refct->info) || ctype_isrefarray(refct->info))
  776.           cp_err(cp, LJ_ERR_FFI_INVTYPE);
  777.       }
  778.       /* No intervening attributes allowed, skip forward. */
  779.       while (idx) {
  780.         CType *ctn = &decl->stack[idx];
  781.         if (!ctype_isattrib(ctn->info)) break;
  782.         idx = ctn->next/* Skip attribute. */
  783.       }
  784.       sib = ct->sib;  /* Next line may reallocate the C type table. */
  785.       fid = lj_ctype_new(cp->cts, &fct);
  786.       csize = CTSIZE_INVALID;
  787.       fct->info = cinfo = info + id;
  788.       fct->size = size;
  789.       fct->sib = sib;
  790.       id = fid;
  791.     } else if (ctype_isattrib(info)) {
  792.       if (ctype_isxattrib(info, CTA_QUAL))
  793.         cinfo |= size;
  794.       else if (ctype_isxattrib(info, CTA_ALIGN))
  795.         CTF_INSERT(cinfo, ALIGN, size);
  796.       id = lj_ctype_intern(cp->cts, info+id, size);
  797.       /* Inherit csize/cinfo from original type. */
  798.     } else {
  799.       if (ctype_isnum(info)) {  /* Handle mode/vector-size attributes. */
  800.         lua_assert(id == 0);
  801.         if (!(info & CTF_BOOL)) {
  802.           CTSize msize = ctype_msizeP(decl->attr);
  803.           CTSize vsize = ctype_vsizeP(decl->attr);
  804.           if (msize && (!(info & CTF_FP) || (msize == 4 || msize == 8))) {
  805.             CTSize malign = lj_fls(msize);
  806.             if (malign > 4) malign = 4/* Limit alignment. */
  807.             CTF_INSERT(info, ALIGN, malign);
  808.             size = msize;  /* Override size via mode. */
  809.           }
  810.           if (vsize) {  /* Vector size set? */
  811.             CTSize esize = lj_fls(size);
  812.             if (vsize >= esize) {
  813.               /* Intern the element type first. */
  814.               id = lj_ctype_intern(cp->cts, info, size);
  815.               /* Then create a vector (array) with vsize alignment. */
  816.               size = (1u << vsize);
  817.               if (vsize > 4) vsize = 4/* Limit alignment. */
  818.               if (ctype_align(info) > vsize) vsize = ctype_align(info);
  819.               info = CTINFO(CT_ARRAY, (info & CTF_QUAL) + CTF_VECTOR +
  820.                                       CTALIGN(vsize));
  821.             }
  822.           }
  823.         }
  824.       } else if (ctype_isptr(info)) {
  825.         /* Reject pointer/ref to ref. */
  826.         if (id && ctype_isref(ctype_raw(cp->cts, id)->info))
  827.           cp_err(cp, LJ_ERR_FFI_INVTYPE);
  828.         if (ctype_isref(info)) {
  829.           info &= ~CTF_VOLATILE/* Refs are always const, never volatile. */
  830.           /* No intervening attributes allowed, skip forward. */
  831.           while (idx) {
  832.             CType *ctn = &decl->stack[idx];
  833.             if (!ctype_isattrib(ctn->info)) break;
  834.             idx = ctn->next/* Skip attribute. */
  835.           }
  836.         }
  837.       } else if (ctype_isarray(info)) {  /* Check for valid array size etc. */
  838.         if (ct->sib == 0) {  /* Only check/size arrays not copied by unroll. */
  839.           if (ctype_isref(cinfo))  /* Reject arrays of refs. */
  840.             cp_err(cp, LJ_ERR_FFI_INVTYPE);
  841.           /* Reject VLS or unknown-sized types. */
  842.           if (ctype_isvltype(cinfo) || csize == CTSIZE_INVALID)
  843.             cp_err(cp, LJ_ERR_FFI_INVSIZE);
  844.           /* a[] and a[?] keep their invalid size. */
  845.           if (size != CTSIZE_INVALID) {
  846.             uint64_t xsz = (uint64_t)size * csize;
  847.             if (xsz >= 0x80000000u) cp_err(cp, LJ_ERR_FFI_INVSIZE);
  848.             size = (CTSize)xsz;
  849.           }
  850.         }
  851.         if ((cinfo & CTF_ALIGN) > (info & CTF_ALIGN))  /* Find max. align. */
  852.           info = (info & ~CTF_ALIGN) | (cinfo & CTF_ALIGN);
  853.         info |= (cinfo & CTF_QUAL);  /* Inherit qual. */
  854.       } else {
  855.         lua_assert(ctype_isvoid(info));
  856.       }
  857.       csize = size;
  858.       cinfo = info+id;
  859.       id = lj_ctype_intern(cp->cts, info+id, size);
  860.     }
  861.   } while (idx);
  862.   return id;
  863. }

  864. /* -- C declaration parser ------------------------------------------------ */

  865. #define H_(le, be)        LJ_ENDIAN_SELECT(0x##le, 0x##be)

  866. /* Reset declaration state to declaration specifier. */
  867. static void cp_decl_reset(CPDecl *decl)
  868. {
  869.   decl->pos = decl->specpos;
  870.   decl->top = decl->specpos+1;
  871.   decl->stack[decl->specpos].next = 0;
  872.   decl->attr = decl->specattr;
  873.   decl->fattr = decl->specfattr;
  874.   decl->name = NULL;
  875.   decl->redir = NULL;
  876. }

  877. /* Parse constant initializer. */
  878. /* NYI: FP constants and strings as initializers. */
  879. static CTypeID cp_decl_constinit(CPState *cp, CType **ctp, CTypeID ctypeid)
  880. {
  881.   CType *ctt = ctype_get(cp->cts, ctypeid);
  882.   CTInfo info;
  883.   CTSize size;
  884.   CPValue k;
  885.   CTypeID constid;
  886.   while (ctype_isattrib(ctt->info)) {  /* Skip attributes. */
  887.     ctypeid = ctype_cid(ctt->info);  /* Update ID, too. */
  888.     ctt = ctype_get(cp->cts, ctypeid);
  889.   }
  890.   info = ctt->info;
  891.   size = ctt->size;
  892.   if (!ctype_isinteger(info) || !(info & CTF_CONST) || size > 4)
  893.     cp_err(cp, LJ_ERR_FFI_INVTYPE);
  894.   cp_check(cp, '=');
  895.   cp_expr_sub(cp, &k, 0);
  896.   constid = lj_ctype_new(cp->cts, ctp);
  897.   (*ctp)->info = CTINFO(CT_CONSTVAL, CTF_CONST|ctypeid);
  898.   k.u32 <<= 8*(4-size);
  899.   if ((info & CTF_UNSIGNED))
  900.     k.u32 >>= 8*(4-size);
  901.   else
  902.     k.u32 = (uint32_t)((int32_t)k.u32 >> 8*(4-size));
  903.   (*ctp)->size = k.u32;
  904.   return constid;
  905. }

  906. /* Parse size in parentheses as part of attribute. */
  907. static CTSize cp_decl_sizeattr(CPState *cp)
  908. {
  909.   CTSize sz;
  910.   uint32_t oldtmask = cp->tmask;
  911.   cp->tmask = CPNS_DEFAULT/* Required for expression evaluator. */
  912.   cp_check(cp, '(');
  913.   sz = cp_expr_ksize(cp);
  914.   cp->tmask = oldtmask;
  915.   cp_check(cp, ')');
  916.   return sz;
  917. }

  918. /* Parse alignment attribute. */
  919. static void cp_decl_align(CPState *cp, CPDecl *decl)
  920. {
  921.   CTSize al = 4/* Unspecified alignment is 16 bytes. */
  922.   if (cp->tok == '(') {
  923.     al = cp_decl_sizeattr(cp);
  924.     al = al ? lj_fls(al) : 0;
  925.   }
  926.   CTF_INSERT(decl->attr, ALIGN, al);
  927.   decl->attr |= CTFP_ALIGNED;
  928. }

  929. /* Parse GCC asm("name") redirect. */
  930. static void cp_decl_asm(CPState *cp, CPDecl *decl)
  931. {
  932.   UNUSED(decl);
  933.   cp_next(cp);
  934.   cp_check(cp, '(');
  935.   if (cp->tok == CTOK_STRING) {
  936.     GCstr *str = cp->str;
  937.     while (cp_next(cp) == CTOK_STRING) {
  938.       lj_strfmt_pushf(cp->L, "%s%s", strdata(str), strdata(cp->str));
  939.       cp->L->top--;
  940.       str = strV(cp->L->top);
  941.     }
  942.     decl->redir = str;
  943.   }
  944.   cp_check(cp, ')');
  945. }

  946. /* Parse GCC __attribute__((mode(...))). */
  947. static void cp_decl_mode(CPState *cp, CPDecl *decl)
  948. {
  949.   cp_check(cp, '(');
  950.   if (cp->tok == CTOK_IDENT) {
  951.     const char *s = strdata(cp->str);
  952.     CTSize sz = 0, vlen = 0;
  953.     if (s[0] == '_' && s[1] == '_') s += 2;
  954.     if (*s == 'V') {
  955.       s++;
  956.       vlen = *s++ - '0';
  957.       if (*s >= '0' && *s <= '9')
  958.         vlen = vlen*10 + (*s++ - '0');
  959.     }
  960.     switch (*s++) {
  961.     case 'Q': sz = 1; break;
  962.     case 'H': sz = 2; break;
  963.     case 'S': sz = 4; break;
  964.     case 'D': sz = 8; break;
  965.     case 'T': sz = 16; break;
  966.     case 'O': sz = 32; break;
  967.     default: goto bad_size;
  968.     }
  969.     if (*s == 'I' || *s == 'F') {
  970.       CTF_INSERT(decl->attr, MSIZEP, sz);
  971.       if (vlen) CTF_INSERT(decl->attr, VSIZEP, lj_fls(vlen*sz));
  972.     }
  973.   bad_size:
  974.     cp_next(cp);
  975.   }
  976.   cp_check(cp, ')');
  977. }

  978. /* Parse GCC __attribute__((...)). */
  979. static void cp_decl_gccattribute(CPState *cp, CPDecl *decl)
  980. {
  981.   cp_next(cp);
  982.   cp_check(cp, '(');
  983.   cp_check(cp, '(');
  984.   while (cp->tok != ')') {
  985.     if (cp->tok == CTOK_IDENT) {
  986.       GCstr *attrstr = cp->str;
  987.       cp_next(cp);
  988.       switch (attrstr->hash) {
  989.       case H_(64a9208e,8ce14319): case H_(8e6331b2,95a282af):  /* aligned */
  990.         cp_decl_align(cp, decl);
  991.         break;
  992.       case H_(42eb47de,f0ede26c): case H_(29f48a09,cf383e0c):  /* packed */
  993.         decl->attr |= CTFP_PACKED;
  994.         break;
  995.       case H_(0a84eef6,8dfab04c): case H_(995cf92c,d5696591):  /* mode */
  996.         cp_decl_mode(cp, decl);
  997.         break;
  998.       case H_(0ab31997,2d5213fa): case H_(bf875611,200e9990):  /* vector_size */
  999.         {
  1000.           CTSize vsize = cp_decl_sizeattr(cp);
  1001.           if (vsize) CTF_INSERT(decl->attr, VSIZEP, lj_fls(vsize));
  1002.         }
  1003.         break;
  1004. #if LJ_TARGET_X86
  1005.       case H_(5ad22db8,c689b848): case H_(439150fa,65ea78cb):  /* regparm */
  1006.         CTF_INSERT(decl->fattr, REGPARM, cp_decl_sizeattr(cp));
  1007.         decl->fattr |= CTFP_CCONV;
  1008.         break;
  1009.       case H_(18fc0b98,7ff4c074): case H_(4e62abed,0a747424):  /* cdecl */
  1010.         CTF_INSERT(decl->fattr, CCONV, CTCC_CDECL);
  1011.         decl->fattr |= CTFP_CCONV;
  1012.         break;
  1013.       case H_(72b2e41b,494c5a44): case H_(f2356d59,f25fc9bd):  /* thiscall */
  1014.         CTF_INSERT(decl->fattr, CCONV, CTCC_THISCALL);
  1015.         decl->fattr |= CTFP_CCONV;
  1016.         break;
  1017.       case H_(0d0ffc42,ab746f88): case H_(21c54ba1,7f0ca7e3):  /* fastcall */
  1018.         CTF_INSERT(decl->fattr, CCONV, CTCC_FASTCALL);
  1019.         decl->fattr |= CTFP_CCONV;
  1020.         break;
  1021.       case H_(ef76b040,9412e06a): case H_(de56697b,c750e6e1):  /* stdcall */
  1022.         CTF_INSERT(decl->fattr, CCONV, CTCC_STDCALL);
  1023.         decl->fattr |= CTFP_CCONV;
  1024.         break;
  1025.       case H_(ea78b622,f234bd8e): case H_(252ffb06,8d50f34b):  /* sseregparm */
  1026.         decl->fattr |= CTF_SSEREGPARM;
  1027.         decl->fattr |= CTFP_CCONV;
  1028.         break;
  1029. #endif
  1030.       default:  /* Skip all other attributes. */
  1031.         goto skip_attr;
  1032.       }
  1033.     } else if (cp->tok >= CTOK_FIRSTDECL) {  /* For __attribute((const)) etc. */
  1034.       cp_next(cp);
  1035.     skip_attr:
  1036.       if (cp_opt(cp, '(')) {
  1037.         while (cp->tok != ')' && cp->tok != CTOK_EOF) cp_next(cp);
  1038.         cp_check(cp, ')');
  1039.       }
  1040.     } else {
  1041.       break;
  1042.     }
  1043.     if (!cp_opt(cp, ',')) break;
  1044.   }
  1045.   cp_check(cp, ')');
  1046.   cp_check(cp, ')');
  1047. }

  1048. /* Parse MSVC __declspec(...). */
  1049. static void cp_decl_msvcattribute(CPState *cp, CPDecl *decl)
  1050. {
  1051.   cp_next(cp);
  1052.   cp_check(cp, '(');
  1053.   while (cp->tok == CTOK_IDENT) {
  1054.     GCstr *attrstr = cp->str;
  1055.     cp_next(cp);
  1056.     switch (attrstr->hash) {
  1057.     case H_(bc2395fa,98f267f8):  /* align */
  1058.       cp_decl_align(cp, decl);
  1059.       break;
  1060.     default:  /* Ignore all other attributes. */
  1061.       if (cp_opt(cp, '(')) {
  1062.         while (cp->tok != ')' && cp->tok != CTOK_EOF) cp_next(cp);
  1063.         cp_check(cp, ')');
  1064.       }
  1065.       break;
  1066.     }
  1067.   }
  1068.   cp_check(cp, ')');
  1069. }

  1070. /* Parse declaration attributes (and common qualifiers). */
  1071. static void cp_decl_attributes(CPState *cp, CPDecl *decl)
  1072. {
  1073.   for (;;) {
  1074.     switch (cp->tok) {
  1075.     case CTOK_CONST: decl->attr |= CTF_CONST; break;
  1076.     case CTOK_VOLATILE: decl->attr |= CTF_VOLATILE; break;
  1077.     case CTOK_RESTRICT: break/* Ignore. */
  1078.     case CTOK_EXTENSION: break/* Ignore. */
  1079.     case CTOK_ATTRIBUTE: cp_decl_gccattribute(cp, decl); continue;
  1080.     case CTOK_ASM: cp_decl_asm(cp, decl); continue;
  1081.     case CTOK_DECLSPEC: cp_decl_msvcattribute(cp, decl); continue;
  1082.     case CTOK_CCDECL:
  1083. #if LJ_TARGET_X86
  1084.       CTF_INSERT(decl->fattr, CCONV, cp->ct->size);
  1085.       decl->fattr |= CTFP_CCONV;
  1086. #endif
  1087.       break;
  1088.     case CTOK_PTRSZ:
  1089. #if LJ_64
  1090.       CTF_INSERT(decl->attr, MSIZEP, cp->ct->size);
  1091. #endif
  1092.       break;
  1093.     default: return;
  1094.     }
  1095.     cp_next(cp);
  1096.   }
  1097. }

  1098. /* Parse struct/union/enum name. */
  1099. static CTypeID cp_struct_name(CPState *cp, CPDecl *sdecl, CTInfo info)
  1100. {
  1101.   CTypeID sid;
  1102.   CType *ct;
  1103.   cp->tmask = CPNS_STRUCT;
  1104.   cp_next(cp);
  1105.   cp_decl_attributes(cp, sdecl);
  1106.   cp->tmask = CPNS_DEFAULT;
  1107.   if (cp->tok != '{') {
  1108.     if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
  1109.     if (cp->val.id) {  /* Name of existing struct/union/enum. */
  1110.       sid = cp->val.id;
  1111.       ct = cp->ct;
  1112.       if ((ct->info ^ info) & (CTMASK_NUM|CTF_UNION))  /* Wrong type. */
  1113.         cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(gco2str(gcref(ct->name))));
  1114.     } else/* Create named, incomplete struct/union/enum. */
  1115.       if ((cp->mode & CPARSE_MODE_NOIMPLICIT))
  1116.         cp_errmsg(cp, 0, LJ_ERR_FFI_BADTAG, strdata(cp->str));
  1117.       sid = lj_ctype_new(cp->cts, &ct);
  1118.       ct->info = info;
  1119.       ct->size = CTSIZE_INVALID;
  1120.       ctype_setname(ct, cp->str);
  1121.       lj_ctype_addname(cp->cts, ct, sid);
  1122.     }
  1123.     cp_next(cp);
  1124.   } else/* Create anonymous, incomplete struct/union/enum. */
  1125.     sid = lj_ctype_new(cp->cts, &ct);
  1126.     ct->info = info;
  1127.     ct->size = CTSIZE_INVALID;
  1128.   }
  1129.   if (cp->tok == '{') {
  1130.     if (ct->size != CTSIZE_INVALID || ct->sib)
  1131.       cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(gco2str(gcref(ct->name))));
  1132.     ct->sib = 1/* Indicate the type is currently being defined. */
  1133.   }
  1134.   return sid;
  1135. }

  1136. /* Determine field alignment. */
  1137. static CTSize cp_field_align(CPState *cp, CType *ct, CTInfo info)
  1138. {
  1139.   CTSize align = ctype_align(info);
  1140.   UNUSED(cp); UNUSED(ct);
  1141. #if (LJ_TARGET_X86 && !LJ_ABI_WIN) || (LJ_TARGET_ARM && __APPLE__)
  1142.   /* The SYSV i386 and iOS ABIs limit alignment of non-vector fields to 2^2. */
  1143.   if (align > 2 && !(info & CTFP_ALIGNED)) {
  1144.     if (ctype_isarray(info) && !(info & CTF_VECTOR)) {
  1145.       do {
  1146.         ct = ctype_rawchild(cp->cts, ct);
  1147.         info = ct->info;
  1148.       } while (ctype_isarray(info) && !(info & CTF_VECTOR));
  1149.     }
  1150.     if (ctype_isnum(info) || ctype_isenum(info))
  1151.       align = 2;
  1152.   }
  1153. #endif
  1154.   return align;
  1155. }

  1156. /* Layout struct/union fields. */
  1157. static void cp_struct_layout(CPState *cp, CTypeID sid, CTInfo sattr)
  1158. {
  1159.   CTSize bofs = 0, bmaxofs = 0/* Bit offset and max. bit offset. */
  1160.   CTSize maxalign = ctype_align(sattr);
  1161.   CType *sct = ctype_get(cp->cts, sid);
  1162.   CTInfo sinfo = sct->info;
  1163.   CTypeID fieldid = sct->sib;
  1164.   while (fieldid) {
  1165.     CType *ct = ctype_get(cp->cts, fieldid);
  1166.     CTInfo attr = ct->size;  /* Field declaration attributes (temp.). */

  1167.     if (ctype_isfield(ct->info) ||
  1168.         (ctype_isxattrib(ct->info, CTA_SUBTYPE) && attr)) {
  1169.       CTSize align, amask;  /* Alignment (pow2) and alignment mask (bits). */
  1170.       CTSize sz;
  1171.       CTInfo info = lj_ctype_info(cp->cts, ctype_cid(ct->info), &sz);
  1172.       CTSize bsz, csz = 8*sz;  /* Field size and container size (in bits). */
  1173.       sinfo |= (info & (CTF_QUAL|CTF_VLA));  /* Merge pseudo-qualifiers. */

  1174.       /* Check for size overflow and determine alignment. */
  1175.       if (sz >= 0x20000000u || bofs + csz < bofs || (info & CTF_VLA)) {
  1176.         if (!(sz == CTSIZE_INVALID && ctype_isarray(info) &&
  1177.               !(sinfo & CTF_UNION)))
  1178.           cp_err(cp, LJ_ERR_FFI_INVSIZE);
  1179.         csz = sz = 0/* Treat a[] and a[?] as zero-sized. */
  1180.       }
  1181.       align = cp_field_align(cp, ct, info);
  1182.       if (((attr|sattr) & CTFP_PACKED) ||
  1183.           ((attr & CTFP_ALIGNED) && ctype_align(attr) > align))
  1184.         align = ctype_align(attr);
  1185.       if (cp->packstack[cp->curpack] < align)
  1186.         align = cp->packstack[cp->curpack];
  1187.       if (align > maxalign) maxalign = align;
  1188.       amask = (8u << align) - 1;

  1189.       bsz = ctype_bitcsz(ct->info);  /* Bitfield size (temp.). */
  1190.       if (bsz == CTBSZ_FIELD || !ctype_isfield(ct->info)) {
  1191.         bsz = csz;  /* Regular fields or subtypes always fill the container. */
  1192.         bofs = (bofs + amask) & ~amask;  /* Start new aligned field. */
  1193.         ct->size = (bofs >> 3);  /* Store field offset. */
  1194.       } else/* Bitfield. */
  1195.         if (bsz == 0 || (attr & CTFP_ALIGNED) ||
  1196.             (!((attr|sattr) & CTFP_PACKED) && (bofs & amask) + bsz > csz))
  1197.           bofs = (bofs + amask) & ~amask;  /* Start new aligned field. */

  1198.         /* Prefer regular field over bitfield. */
  1199.         if (bsz == csz && (bofs & amask) == 0) {
  1200.           ct->info = CTINFO(CT_FIELD, ctype_cid(ct->info));
  1201.           ct->size = (bofs >> 3);  /* Store field offset. */
  1202.         } else {
  1203.           ct->info = CTINFO(CT_BITFIELD,
  1204.             (info & (CTF_QUAL|CTF_UNSIGNED|CTF_BOOL)) +
  1205.             (csz << (CTSHIFT_BITCSZ-3)) + (bsz << CTSHIFT_BITBSZ));
  1206. #if LJ_BE
  1207.           ct->info += ((csz - (bofs & (csz-1)) - bsz) << CTSHIFT_BITPOS);
  1208. #else
  1209.           ct->info += ((bofs & (csz-1)) << CTSHIFT_BITPOS);
  1210. #endif
  1211.           ct->size = ((bofs & ~(csz-1)) >> 3);  /* Store container offset. */
  1212.         }
  1213.       }

  1214.       /* Determine next offset or max. offset. */
  1215.       if ((sinfo & CTF_UNION)) {
  1216.         if (bsz > bmaxofs) bmaxofs = bsz;
  1217.       } else {
  1218.         bofs += bsz;
  1219.       }
  1220.     }  /* All other fields in the chain are already set up. */

  1221.     fieldid = ct->sib;
  1222.   }

  1223.   /* Complete struct/union. */
  1224.   sct->info = sinfo + CTALIGN(maxalign);
  1225.   bofs = (sinfo & CTF_UNION) ? bmaxofs : bofs;
  1226.   maxalign = (8u << maxalign) - 1;
  1227.   sct->size = (((bofs + maxalign) & ~maxalign) >> 3);
  1228. }

  1229. /* Parse struct/union declaration. */
  1230. static CTypeID cp_decl_struct(CPState *cp, CPDecl *sdecl, CTInfo sinfo)
  1231. {
  1232.   CTypeID sid = cp_struct_name(cp, sdecl, sinfo);
  1233.   if (cp_opt(cp, '{')) {  /* Struct/union definition. */
  1234.     CTypeID lastid = sid;
  1235.     int lastdecl = 0;
  1236.     while (cp->tok != '}') {
  1237.       CPDecl decl;
  1238.       CPscl scl = cp_decl_spec(cp, &decl, CDF_STATIC);
  1239.       decl.mode = scl ? CPARSE_MODE_DIRECT :
  1240.         CPARSE_MODE_DIRECT|CPARSE_MODE_ABSTRACT|CPARSE_MODE_FIELD;

  1241.       for (;;) {
  1242.         CTypeID ctypeid;

  1243.         if (lastdecl) cp_err_token(cp, '}');

  1244.         /* Parse field declarator. */
  1245.         decl.bits = CTSIZE_INVALID;
  1246.         cp_declarator(cp, &decl);
  1247.         ctypeid = cp_decl_intern(cp, &decl);

  1248.         if ((scl & CDF_STATIC)) {  /* Static constant in struct namespace. */
  1249.           CType *ct;
  1250.           CTypeID fieldid = cp_decl_constinit(cp, &ct, ctypeid);
  1251.           ctype_get(cp->cts, lastid)->sib = fieldid;
  1252.           lastid = fieldid;
  1253.           ctype_setname(ct, decl.name);
  1254.         } else {
  1255.           CTSize bsz = CTBSZ_FIELD/* Temp. for layout phase. */
  1256.           CType *ct;
  1257.           CTypeID fieldid = lj_ctype_new(cp->cts, &ct);  /* Do this first. */
  1258.           CType *tct = ctype_raw(cp->cts, ctypeid);

  1259.           if (decl.bits == CTSIZE_INVALID) {  /* Regular field. */
  1260.             if (ctype_isarray(tct->info) && tct->size == CTSIZE_INVALID)
  1261.               lastdecl = 1/* a[] or a[?] must be the last declared field. */

  1262.             /* Accept transparent struct/union/enum. */
  1263.             if (!decl.name) {
  1264.               if (!((ctype_isstruct(tct->info) && !(tct->info & CTF_VLA)) ||
  1265.                     ctype_isenum(tct->info)))
  1266.                 cp_err_token(cp, CTOK_IDENT);
  1267.               ct->info = CTINFO(CT_ATTRIB, CTATTRIB(CTA_SUBTYPE) + ctypeid);
  1268.               ct->size = ctype_isstruct(tct->info) ?
  1269.                          (decl.attr|0x80000000u) : 0/* For layout phase. */
  1270.               goto add_field;
  1271.             }
  1272.           } else/* Bitfield. */
  1273.             bsz = decl.bits;
  1274.             if (!ctype_isinteger_or_bool(tct->info) ||
  1275.                 (bsz == 0 && decl.name) || 8*tct->size > CTBSZ_MAX ||
  1276.                 bsz > ((tct->info & CTF_BOOL) ? 1 : 8*tct->size))
  1277.               cp_errmsg(cp, ':', LJ_ERR_BADVAL);
  1278.           }

  1279.           /* Create temporary field for layout phase. */
  1280.           ct->info = CTINFO(CT_FIELD, ctypeid + (bsz << CTSHIFT_BITCSZ));
  1281.           ct->size = decl.attr;
  1282.           if (decl.name) ctype_setname(ct, decl.name);

  1283.         add_field:
  1284.           ctype_get(cp->cts, lastid)->sib = fieldid;
  1285.           lastid = fieldid;
  1286.         }
  1287.         if (!cp_opt(cp, ',')) break;
  1288.         cp_decl_reset(&decl);
  1289.       }
  1290.       cp_check(cp, ';');
  1291.     }
  1292.     cp_check(cp, '}');
  1293.     ctype_get(cp->cts, lastid)->sib = 0/* Drop sib = 1 for empty structs. */
  1294.     cp_decl_attributes(cp, sdecl);  /* Layout phase needs postfix attributes. */
  1295.     cp_struct_layout(cp, sid, sdecl->attr);
  1296.   }
  1297.   return sid;
  1298. }

  1299. /* Parse enum declaration. */
  1300. static CTypeID cp_decl_enum(CPState *cp, CPDecl *sdecl)
  1301. {
  1302.   CTypeID eid = cp_struct_name(cp, sdecl, CTINFO(CT_ENUM, CTID_VOID));
  1303.   CTInfo einfo = CTINFO(CT_ENUM, CTALIGN(2) + CTID_UINT32);
  1304.   CTSize esize = 4/* Only 32 bit enums are supported. */
  1305.   if (cp_opt(cp, '{')) {  /* Enum definition. */
  1306.     CPValue k;
  1307.     CTypeID lastid = eid;
  1308.     k.u32 = 0;
  1309.     k.id = CTID_INT32;
  1310.     do {
  1311.       GCstr *name = cp->str;
  1312.       if (cp->tok != CTOK_IDENT) cp_err_token(cp, CTOK_IDENT);
  1313.       if (cp->val.id) cp_errmsg(cp, 0, LJ_ERR_FFI_REDEF, strdata(name));
  1314.       cp_next(cp);
  1315.       if (cp_opt(cp, '=')) {
  1316.         cp_expr_kint(cp, &k);
  1317.         if (k.id == CTID_UINT32) {
  1318.           /* C99 says that enum constants are always (signed) integers.
  1319.           ** But since unsigned constants like 0x80000000 are quite common,
  1320.           ** those are left as uint32_t.
  1321.           */
  1322.           if (k.i32 >= 0) k.id = CTID_INT32;
  1323.         } else {
  1324.           /* OTOH it's common practice and even mandated by some ABIs
  1325.           ** that the enum type itself is unsigned, unless there are any
  1326.           ** negative constants.
  1327.           */
  1328.           k.id = CTID_INT32;
  1329.           if (k.i32 < 0) einfo = CTINFO(CT_ENUM, CTALIGN(2) + CTID_INT32);
  1330.         }
  1331.       }
  1332.       /* Add named enum constant. */
  1333.       {
  1334.         CType *ct;
  1335.         CTypeID constid = lj_ctype_new(cp->cts, &ct);
  1336.         ctype_get(cp->cts, lastid)->sib = constid;
  1337.         lastid = constid;
  1338.         ctype_setname(ct, name);
  1339.         ct->info = CTINFO(CT_CONSTVAL, CTF_CONST|k.id);
  1340.         ct->size = k.u32++;
  1341.         if (k.u32 == 0x80000000u) k.id = CTID_UINT32;
  1342.         lj_ctype_addname(cp->cts, ct, constid);
  1343.       }
  1344.       if (!cp_opt(cp, ',')) break;
  1345.     } while (cp->tok != '}');  /* Trailing ',' is ok. */
  1346.     cp_check(cp, '}');
  1347.     /* Complete enum. */
  1348.     ctype_get(cp->cts, eid)->info = einfo;
  1349.     ctype_get(cp->cts, eid)->size = esize;
  1350.   }
  1351.   return eid;
  1352. }

  1353. /* Parse declaration specifiers. */
  1354. static CPscl cp_decl_spec(CPState *cp, CPDecl *decl, CPscl scl)
  1355. {
  1356.   uint32_t cds = 0, sz = 0;
  1357.   CTypeID tdef = 0;

  1358.   decl->cp = cp;
  1359.   decl->mode = cp->mode;
  1360.   decl->name = NULL;
  1361.   decl->redir = NULL;
  1362.   decl->attr = 0;
  1363.   decl->fattr = 0;
  1364.   decl->pos = decl->top = 0;
  1365.   decl->stack[0].next = 0;

  1366.   for (;;) {  /* Parse basic types. */
  1367.     cp_decl_attributes(cp, decl);
  1368.     if (cp->tok >= CTOK_FIRSTDECL && cp->tok <= CTOK_LASTDECLFLAG) {
  1369.       uint32_t cbit;
  1370.       if (cp->ct->size) {
  1371.         if (sz) goto end_decl;
  1372.         sz = cp->ct->size;
  1373.       }
  1374.       cbit = (1u << (cp->tok - CTOK_FIRSTDECL));
  1375.       cds = cds | cbit | ((cbit & cds & CDF_LONG) << 1);
  1376.       if (cp->tok >= CTOK_FIRSTSCL) {
  1377.         if (!(scl & cbit)) cp_errmsg(cp, cp->tok, LJ_ERR_FFI_BADSCL);
  1378.       } else if (tdef) {
  1379.         goto end_decl;
  1380.       }
  1381.       cp_next(cp);
  1382.       continue;
  1383.     }
  1384.     if (sz || tdef ||
  1385.         (cds & (CDF_SHORT|CDF_LONG|CDF_SIGNED|CDF_UNSIGNED|CDF_COMPLEX)))
  1386.       break;
  1387.     switch (cp->tok) {
  1388.     case CTOK_STRUCT:
  1389.       tdef = cp_decl_struct(cp, decl, CTINFO(CT_STRUCT, 0));
  1390.       continue;
  1391.     case CTOK_UNION:
  1392.       tdef = cp_decl_struct(cp, decl, CTINFO(CT_STRUCT, CTF_UNION));
  1393.       continue;
  1394.     case CTOK_ENUM:
  1395.       tdef = cp_decl_enum(cp, decl);
  1396.       continue;
  1397.     case CTOK_IDENT:
  1398.       if (ctype_istypedef(cp->ct->info)) {
  1399.         tdef = ctype_cid(cp->ct->info);  /* Get typedef. */
  1400.         cp_next(cp);
  1401.         continue;
  1402.       }
  1403.       break;
  1404.     case '$':
  1405.       tdef = cp->val.id;
  1406.       cp_next(cp);
  1407.       continue;
  1408.     default:
  1409.       break;
  1410.     }
  1411.     break;
  1412.   }
  1413. end_decl:

  1414.   if ((cds & CDF_COMPLEX))  /* Use predefined complex types. */
  1415.     tdef = sz == 4 ? CTID_COMPLEX_FLOAT : CTID_COMPLEX_DOUBLE;

  1416.   if (tdef) {
  1417.     cp_push_type(decl, tdef);
  1418.   } else if ((cds & CDF_VOID)) {
  1419.     cp_push(decl, CTINFO(CT_VOID, (decl->attr & CTF_QUAL)), CTSIZE_INVALID);
  1420.     decl->attr &= ~CTF_QUAL;
  1421.   } else {
  1422.     /* Determine type info and size. */
  1423.     CTInfo info = CTINFO(CT_NUM, (cds & CDF_UNSIGNED) ? CTF_UNSIGNED : 0);
  1424.     if ((cds & CDF_BOOL)) {
  1425.       if ((cds & ~(CDF_SCL|CDF_BOOL|CDF_INT|CDF_SIGNED|CDF_UNSIGNED)))
  1426.         cp_errmsg(cp, 0, LJ_ERR_FFI_INVTYPE);
  1427.       info |= CTF_BOOL;
  1428.       if (!(cds & CDF_SIGNED)) info |= CTF_UNSIGNED;
  1429.       if (!sz) {
  1430.         sz = 1;
  1431.       }
  1432.     } else if ((cds & CDF_FP)) {
  1433.       info = CTINFO(CT_NUM, CTF_FP);
  1434.       if ((cds & CDF_LONG)) sz = sizeof(long double);
  1435.     } else if ((cds & CDF_CHAR)) {
  1436.       if ((cds & (CDF_CHAR|CDF_SIGNED|CDF_UNSIGNED)) == CDF_CHAR)
  1437.         info |= CTF_UCHAR/* Handle platforms where char is unsigned. */
  1438.     } else if ((cds & CDF_SHORT)) {
  1439.       sz = sizeof(short);
  1440.     } else if ((cds & CDF_LONGLONG)) {
  1441.       sz = 8;
  1442.     } else if ((cds & CDF_LONG)) {
  1443.       info |= CTF_LONG;
  1444.       sz = sizeof(long);
  1445.     } else if (!sz) {
  1446.       if (!(cds & (CDF_SIGNED|CDF_UNSIGNED)))
  1447.         cp_errmsg(cp, cp->tok, LJ_ERR_FFI_DECLSPEC);
  1448.       sz = sizeof(int);
  1449.     }
  1450.     lua_assert(sz != 0);
  1451.     info += CTALIGN(lj_fls(sz));  /* Use natural alignment. */
  1452.     info += (decl->attr & CTF_QUAL);  /* Merge qualifiers. */
  1453.     cp_push(decl, info, sz);
  1454.     decl->attr &= ~CTF_QUAL;
  1455.   }
  1456.   decl->specpos = decl->pos;
  1457.   decl->specattr = decl->attr;
  1458.   decl->specfattr = decl->fattr;
  1459.   return (cds & CDF_SCL);  /* Return storage class. */
  1460. }

  1461. /* Parse array declaration. */
  1462. static void cp_decl_array(CPState *cp, CPDecl *decl)
  1463. {
  1464.   CTInfo info = CTINFO(CT_ARRAY, 0);
  1465.   CTSize nelem = CTSIZE_INVALID/* Default size for a[] or a[?]. */
  1466.   cp_decl_attributes(cp, decl);
  1467.   if (cp_opt(cp, '?'))
  1468.     info |= CTF_VLA/* Create variable-length array a[?]. */
  1469.   else if (cp->tok != ']')
  1470.     nelem = cp_expr_ksize(cp);
  1471.   cp_check(cp, ']');
  1472.   cp_add(decl, info, nelem);
  1473. }

  1474. /* Parse function declaration. */
  1475. static void cp_decl_func(CPState *cp, CPDecl *fdecl)
  1476. {
  1477.   CTSize nargs = 0;
  1478.   CTInfo info = CTINFO(CT_FUNC, 0);
  1479.   CTypeID lastid = 0, anchor = 0;
  1480.   if (cp->tok != ')') {
  1481.     do {
  1482.       CPDecl decl;
  1483.       CTypeID ctypeid, fieldid;
  1484.       CType *ct;
  1485.       if (cp_opt(cp, '.')) {  /* Vararg function. */
  1486.         cp_check(cp, '.');  /* Workaround for the minimalistic lexer. */
  1487.         cp_check(cp, '.');
  1488.         info |= CTF_VARARG;
  1489.         break;
  1490.       }
  1491.       cp_decl_spec(cp, &decl, CDF_REGISTER);
  1492.       decl.mode = CPARSE_MODE_DIRECT|CPARSE_MODE_ABSTRACT;
  1493.       cp_declarator(cp, &decl);
  1494.       ctypeid = cp_decl_intern(cp, &decl);
  1495.       ct = ctype_raw(cp->cts, ctypeid);
  1496.       if (ctype_isvoid(ct->info))
  1497.         break;
  1498.       else if (ctype_isrefarray(ct->info))
  1499.         ctypeid = lj_ctype_intern(cp->cts,
  1500.           CTINFO(CT_PTR, CTALIGN_PTR|ctype_cid(ct->info)), CTSIZE_PTR);
  1501.       else if (ctype_isfunc(ct->info))
  1502.         ctypeid = lj_ctype_intern(cp->cts,
  1503.           CTINFO(CT_PTR, CTALIGN_PTR|ctypeid), CTSIZE_PTR);
  1504.       /* Add new parameter. */
  1505.       fieldid = lj_ctype_new(cp->cts, &ct);
  1506.       if (anchor)
  1507.         ctype_get(cp->cts, lastid)->sib = fieldid;
  1508.       else
  1509.         anchor = fieldid;
  1510.       lastid = fieldid;
  1511.       if (decl.name) ctype_setname(ct, decl.name);
  1512.       ct->info = CTINFO(CT_FIELD, ctypeid);
  1513.       ct->size = nargs++;
  1514.     } while (cp_opt(cp, ','));
  1515.   }
  1516.   cp_check(cp, ')');
  1517.   if (cp_opt(cp, '{')) {  /* Skip function definition. */
  1518.     int level = 1;
  1519.     cp->mode |= CPARSE_MODE_SKIP;
  1520.     for (;;) {
  1521.       if (cp->tok == '{') level++;
  1522.       else if (cp->tok == '}' && --level == 0) break;
  1523.       else if (cp->tok == CTOK_EOF) cp_err_token(cp, '}');
  1524.       cp_next(cp);
  1525.     }
  1526.     cp->mode &= ~CPARSE_MODE_SKIP;
  1527.     cp->tok = ';'/* Ok for cp_decl_multi(), error in cp_decl_single(). */
  1528.   }
  1529.   info |= (fdecl->fattr & ~CTMASK_CID);
  1530.   fdecl->fattr = 0;
  1531.   fdecl->stack[cp_add(fdecl, info, nargs)].sib = anchor;
  1532. }

  1533. /* Parse declarator. */
  1534. static void cp_declarator(CPState *cp, CPDecl *decl)
  1535. {
  1536.   if (++cp->depth > CPARSE_MAX_DECLDEPTH) cp_err(cp, LJ_ERR_XLEVELS);

  1537.   for (;;) {  /* Head of declarator. */
  1538.     if (cp_opt(cp, '*')) {  /* Pointer. */
  1539.       CTSize sz;
  1540.       CTInfo info;
  1541.       cp_decl_attributes(cp, decl);
  1542.       sz = CTSIZE_PTR;
  1543.       info = CTINFO(CT_PTR, CTALIGN_PTR);
  1544. #if LJ_64
  1545.       if (ctype_msizeP(decl->attr) == 4) {
  1546.         sz = 4;
  1547.         info = CTINFO(CT_PTR, CTALIGN(2));
  1548.       }
  1549. #endif
  1550.       info += (decl->attr & (CTF_QUAL|CTF_REF));
  1551.       decl->attr &= ~(CTF_QUAL|(CTMASK_MSIZEP<<CTSHIFT_MSIZEP));
  1552.       cp_push(decl, info, sz);
  1553.     } else if (cp_opt(cp, '&') || cp_opt(cp, CTOK_ANDAND)) {  /* Reference. */
  1554.       decl->attr &= ~(CTF_QUAL|(CTMASK_MSIZEP<<CTSHIFT_MSIZEP));
  1555.       cp_push(decl, CTINFO_REF(0), CTSIZE_PTR);
  1556.     } else {
  1557.       break;
  1558.     }
  1559.   }

  1560.   if (cp_opt(cp, '(')) {  /* Inner declarator. */
  1561.     CPDeclIdx pos;
  1562.     cp_decl_attributes(cp, decl);
  1563.     /* Resolve ambiguity between inner declarator and 1st function parameter. */
  1564.     if ((decl->mode & CPARSE_MODE_ABSTRACT) &&
  1565.         (cp->tok == ')' || cp_istypedecl(cp))) goto func_decl;
  1566.     pos = decl->pos;
  1567.     cp_declarator(cp, decl);
  1568.     cp_check(cp, ')');
  1569.     decl->pos = pos;
  1570.   } else if (cp->tok == CTOK_IDENT) {  /* Direct declarator. */
  1571.     if (!(decl->mode & CPARSE_MODE_DIRECT)) cp_err_token(cp, CTOK_EOF);
  1572.     decl->name = cp->str;
  1573.     decl->nameid = cp->val.id;
  1574.     cp_next(cp);
  1575.   } else/* Abstract declarator. */
  1576.     if (!(decl->mode & CPARSE_MODE_ABSTRACT)) cp_err_token(cp, CTOK_IDENT);
  1577.   }

  1578.   for (;;) {  /* Tail of declarator. */
  1579.     if (cp_opt(cp, '[')) {  /* Array. */
  1580.       cp_decl_array(cp, decl);
  1581.     } else if (cp_opt(cp, '(')) {  /* Function. */
  1582.     func_decl:
  1583.       cp_decl_func(cp, decl);
  1584.     } else {
  1585.       break;
  1586.     }
  1587.   }

  1588.   if ((decl->mode & CPARSE_MODE_FIELD) && cp_opt(cp, ':'))  /* Field width. */
  1589.     decl->bits = cp_expr_ksize(cp);

  1590.   /* Process postfix attributes. */
  1591.   cp_decl_attributes(cp, decl);
  1592.   cp_push_attributes(decl);

  1593.   cp->depth--;
  1594. }

  1595. /* Parse an abstract type declaration and return it's C type ID. */
  1596. static CTypeID cp_decl_abstract(CPState *cp)
  1597. {
  1598.   CPDecl decl;
  1599.   cp_decl_spec(cp, &decl, 0);
  1600.   decl.mode = CPARSE_MODE_ABSTRACT;
  1601.   cp_declarator(cp, &decl);
  1602.   return cp_decl_intern(cp, &decl);
  1603. }

  1604. /* Handle pragmas. */
  1605. static void cp_pragma(CPState *cp, BCLine pragmaline)
  1606. {
  1607.   cp_next(cp);
  1608.   if (cp->tok == CTOK_IDENT &&
  1609.       cp->str->hash == H_(e79b999f,42ca3e85))  {  /* pack */
  1610.     cp_next(cp);
  1611.     cp_check(cp, '(');
  1612.     if (cp->tok == CTOK_IDENT) {
  1613.       if (cp->str->hash == H_(738e923c,a1b65954)) {  /* push */
  1614.         if (cp->curpack < CPARSE_MAX_PACKSTACK) {
  1615.           cp->packstack[cp->curpack+1] = cp->packstack[cp->curpack];
  1616.           cp->curpack++;
  1617.         }
  1618.       } else if (cp->str->hash == H_(6c71cf27,6c71cf27)) {  /* pop */
  1619.         if (cp->curpack > 0) cp->curpack--;
  1620.       } else {
  1621.         cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
  1622.       }
  1623.       cp_next(cp);
  1624.       if (!cp_opt(cp, ',')) goto end_pack;
  1625.     }
  1626.     if (cp->tok == CTOK_INTEGER) {
  1627.       cp->packstack[cp->curpack] = cp->val.u32 ? lj_fls(cp->val.u32) : 0;
  1628.       cp_next(cp);
  1629.     } else {
  1630.       cp->packstack[cp->curpack] = 255;
  1631.     }
  1632.   end_pack:
  1633.     cp_check(cp, ')');
  1634.   } else/* Ignore all other pragmas. */
  1635.     while (cp->tok != CTOK_EOF && cp->linenumber == pragmaline)
  1636.       cp_next(cp);
  1637.   }
  1638. }

  1639. /* Parse multiple C declarations of types or extern identifiers. */
  1640. static void cp_decl_multi(CPState *cp)
  1641. {
  1642.   int first = 1;
  1643.   while (cp->tok != CTOK_EOF) {
  1644.     CPDecl decl;
  1645.     CPscl scl;
  1646.     if (cp_opt(cp, ';')) {  /* Skip empty statements. */
  1647.       first = 0;
  1648.       continue;
  1649.     }
  1650.     if (cp->tok == '#') {  /* Workaround, since we have no preprocessor, yet. */
  1651.       BCLine pragmaline = cp->linenumber;
  1652.       if (!(cp_next(cp) == CTOK_IDENT &&
  1653.             cp->str->hash == H_(f5e6b4f8,1d509107)))  /* pragma */
  1654.         cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
  1655.       cp_pragma(cp, pragmaline);
  1656.       continue;
  1657.     }
  1658.     scl = cp_decl_spec(cp, &decl, CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC);
  1659.     if ((cp->tok == ';' || cp->tok == CTOK_EOF) &&
  1660.         ctype_istypedef(decl.stack[0].info)) {
  1661.       CTInfo info = ctype_rawchild(cp->cts, &decl.stack[0])->info;
  1662.       if (ctype_isstruct(info) || ctype_isenum(info))
  1663.         goto decl_end;  /* Accept empty declaration of struct/union/enum. */
  1664.     }
  1665.     for (;;) {
  1666.       CTypeID ctypeid;
  1667.       cp_declarator(cp, &decl);
  1668.       ctypeid = cp_decl_intern(cp, &decl);
  1669.       if (decl.name && !decl.nameid) {  /* NYI: redeclarations are ignored. */
  1670.         CType *ct;
  1671.         CTypeID id;
  1672.         if ((scl & CDF_TYPEDEF)) {  /* Create new typedef. */
  1673.           id = lj_ctype_new(cp->cts, &ct);
  1674.           ct->info = CTINFO(CT_TYPEDEF, ctypeid);
  1675.           goto noredir;
  1676.         } else if (ctype_isfunc(ctype_get(cp->cts, ctypeid)->info)) {
  1677.           /* Treat both static and extern function declarations as extern. */
  1678.           ct = ctype_get(cp->cts, ctypeid);
  1679.           /* We always get new anonymous functions (typedefs are copied). */
  1680.           lua_assert(gcref(ct->name) == NULL);
  1681.           id = ctypeid;  /* Just name it. */
  1682.         } else if ((scl & CDF_STATIC)) {  /* Accept static constants. */
  1683.           id = cp_decl_constinit(cp, &ct, ctypeid);
  1684.           goto noredir;
  1685.         } else/* External references have extern or no storage class. */
  1686.           id = lj_ctype_new(cp->cts, &ct);
  1687.           ct->info = CTINFO(CT_EXTERN, ctypeid);
  1688.         }
  1689.         if (decl.redir) {  /* Add attribute for redirected symbol name. */
  1690.           CType *cta;
  1691.           CTypeID aid = lj_ctype_new(cp->cts, &cta);
  1692.           ct = ctype_get(cp->cts, id);  /* Table may have been reallocated. */
  1693.           cta->info = CTINFO(CT_ATTRIB, CTATTRIB(CTA_REDIR));
  1694.           cta->sib = ct->sib;
  1695.           ct->sib = aid;
  1696.           ctype_setname(cta, decl.redir);
  1697.         }
  1698.       noredir:
  1699.         ctype_setname(ct, decl.name);
  1700.         lj_ctype_addname(cp->cts, ct, id);
  1701.       }
  1702.       if (!cp_opt(cp, ',')) break;
  1703.       cp_decl_reset(&decl);
  1704.     }
  1705.   decl_end:
  1706.     if (cp->tok == CTOK_EOF && first) break/* May omit ';' for 1 decl. */
  1707.     first = 0;
  1708.     cp_check(cp, ';');
  1709.   }
  1710. }

  1711. /* Parse a single C type declaration. */
  1712. static void cp_decl_single(CPState *cp)
  1713. {
  1714.   CPDecl decl;
  1715.   cp_decl_spec(cp, &decl, 0);
  1716.   cp_declarator(cp, &decl);
  1717.   cp->val.id = cp_decl_intern(cp, &decl);
  1718.   if (cp->tok != CTOK_EOF) cp_err_token(cp, CTOK_EOF);
  1719. }

  1720. #undef H_

  1721. /* ------------------------------------------------------------------------ */

  1722. /* Protected callback for C parser. */
  1723. static TValue *cpcparser(lua_State *L, lua_CFunction dummy, void *ud)
  1724. {
  1725.   CPState *cp = (CPState *)ud;
  1726.   UNUSED(dummy);
  1727.   cframe_errfunc(L->cframe) = -1/* Inherit error function. */
  1728.   cp_init(cp);
  1729.   if ((cp->mode & CPARSE_MODE_MULTI))
  1730.     cp_decl_multi(cp);
  1731.   else
  1732.     cp_decl_single(cp);
  1733.   if (cp->param && cp->param != cp->L->top)
  1734.     cp_err(cp, LJ_ERR_FFI_NUMPARAM);
  1735.   lua_assert(cp->depth == 0);
  1736.   return NULL;
  1737. }

  1738. /* C parser. */
  1739. int lj_cparse(CPState *cp)
  1740. {
  1741.   LJ_CTYPE_SAVE(cp->cts);
  1742.   int errcode = lj_vm_cpcall(cp->L, NULL, cp, cpcparser);
  1743.   if (errcode)
  1744.     LJ_CTYPE_RESTORE(cp->cts);
  1745.   cp_cleanup(cp);
  1746.   return errcode;
  1747. }

  1748. #endif