2
0

lj_cparse.c 57 KB

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