lj_cparse.c 55 KB

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