aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

pp.c (29501B)


      1 #include <assert.h>
      2 #include <stdarg.h>
      3 #include <stdbool.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <string.h>
      7 #include <unistd.h>
      8 #include "util.h"
      9 #include "cc.h"
     10 #include "proc.h"
     11 
     12 struct macroparam {
     13   char *name;
     14   enum {
     15     PARAMTOK = 1 << 0, /* the parameter is used normally */
     16     PARAMSTR = 1 << 1, /* the parameter is used with the '#' operator */
     17     PARAMVAR = 1 << 2, /* the parameter is __VA_ARGS__ */
     18   } flags;
     19 };
     20 
     21 struct macroarg {
     22   struct token *token;
     23   size_t        ntoken;
     24   /* stringized argument */
     25   struct token str;
     26 };
     27 
     28 struct macro {
     29   enum {
     30     MACROOBJ,
     31     MACROFUNC,
     32   } kind;
     33   char *name;
     34   /* whether or not this macro is ineligible for expansion */
     35   bool hide;
     36   /* parameters of function-like macro */
     37   struct macroparam *param;
     38   size_t             nparam;
     39   /* argument tokens of macro invocation */
     40   struct macroarg *arg;
     41   /* replacement list */
     42   struct token *token;
     43   size_t        ntoken;
     44 };
     45 
     46 struct frame {
     47   struct token *token;
     48   size_t        ntoken;
     49   struct macro *macro;
     50   struct token *alloc;
     51   bool          is_substituted;
     52 };
     53 
     54 enum ppflags ppflags;
     55 
     56 static struct array ctx;
     57 static struct array macros;
     58 /* number of macros currently undergoing expansion */
     59 static size_t        macrodepth;
     60 static struct macro *macroget(enum tokenkind);
     61 
     62 static bool disexpand;
     63 static int  cppoff;
     64 static struct condstate {
     65   int enabled;
     66   int done;
     67   int iselse;
     68 } condstack[64];
     69 static int conddepth;
     70 
     71 static const char **incdirs;
     72 static size_t       nincdirs;
     73 
     74 void
     75 addincdir(const char *dir)
     76 {
     77   incdirs             = xreallocarray(incdirs, nincdirs + 1, sizeof(*incdirs));
     78   incdirs[nincdirs++] = dir;
     79 }
     80 
     81 static char *
     82 strdup_internal(const char *s)
     83 {
     84   size_t len = strlen(s);
     85   char  *d   = xmalloc(len + 1);
     86   memcpy(d, s, len + 1);
     87   return d;
     88 }
     89 
     90 static void
     91 include(void)
     92 {
     93   bool  is_system;
     94   char *name = scaninclude(&is_system);
     95   if (!name) {
     96     error(&tok.loc, "expected filename after #include");
     97     return;
     98   }
     99 
    100   char  path[FILENAME_MAX];
    101   FILE *f = NULL;
    102 
    103   if (!is_system) {
    104     const char *curfile = tok.loc.file;
    105     const char *slash   = strrchr(curfile, '/');
    106     if (slash) {
    107       size_t len = slash - curfile;
    108       if (len + 1 + strlen(name) < sizeof(path)) {
    109         memcpy(path, curfile, len);
    110         path[len] = '/';
    111         strcpy(path + len + 1, name);
    112         f = fopen(path, "r");
    113       }
    114     } else {
    115       if (strlen(name) < sizeof(path)) {
    116         strcpy(path, name);
    117         f = fopen(path, "r");
    118       }
    119     }
    120   }
    121 
    122   if (!f) {
    123     for (size_t i = 0; i < nincdirs; i++) {
    124       if (strlen(incdirs[i]) + 1 + strlen(name) < sizeof(path)) {
    125         sprintf(path, "%s/%s", incdirs[i], name);
    126         f = fopen(path, "r");
    127         if (f)
    128           break;
    129       }
    130     }
    131   }
    132 
    133   /* freestanding headers (stddef.h etc) the libc may not ship: an include/
    134      dir next to the compiler in a source tree, lib/aruu/include in a
    135      system whose binaries are in bin/, or beside a lib/aruu/bin they sit in */
    136   if (!f) {
    137     static const char *const rel[] = {"include", "../lib/aruu/include", "../include"};
    138     char                     self[FILENAME_MAX];
    139     ssize_t                  n = proc_selfexe(self, sizeof(self) - 1);
    140     if (n == -1) {
    141       n = strlen(argv0);
    142       if (n > (ssize_t)sizeof(self) - 1)
    143         n = sizeof(self) - 1;
    144       memcpy(self, argv0, n);
    145     }
    146     self[n] = '\0';
    147 
    148     char *dir = strrchr(self, '/');
    149     if (dir) {
    150       *dir = '\0';
    151       for (size_t i = 0; !f && i < sizeof(rel) / sizeof(*rel); i++) {
    152         if (strlen(self) + 1 + strlen(rel[i]) + 1 + strlen(name) < sizeof(path)) {
    153           snprintf(path, sizeof(path), "%s/%s/%s", self, rel[i], name);
    154           f = fopen(path, "r");
    155         }
    156       }
    157     }
    158   }
    159 
    160   if (!f) {
    161     error(&tok.loc, "included file '%s' not found", name);
    162     free(name);
    163     return;
    164   }
    165 
    166   while (tok.kind != TNEWLINE && tok.kind != TEOF)
    167     scan(&tok);
    168 
    169   scanfrom(strdup_internal(path), f);
    170   free(name);
    171 }
    172 
    173 struct PPVal {
    174   enum tokenkind kind;
    175   long long      val;
    176 };
    177 
    178 static struct PPVal *ppvals;
    179 static size_t        nppvals, capppvals;
    180 static size_t        validx;
    181 
    182 static void
    183 addval(enum tokenkind kind, long long val)
    184 {
    185   if (nppvals >= capppvals) {
    186     capppvals = capppvals ? capppvals * 2 : 16;
    187     ppvals    = xreallocarray(ppvals, capppvals, sizeof(*ppvals));
    188   }
    189   ppvals[nppvals].kind = kind;
    190   ppvals[nppvals].val  = val;
    191   nppvals++;
    192 }
    193 
    194 static long long eval_cond_expr(void);
    195 
    196 static long long
    197 eval_primary(void)
    198 {
    199   if (validx >= nppvals)
    200     return 0;
    201   struct PPVal p = ppvals[validx++];
    202   if (p.kind == TNUMBER) {
    203     return p.val;
    204   }
    205   if (p.kind == TLPAREN) {
    206     long long val = eval_cond_expr();
    207     if (validx < nppvals && ppvals[validx].kind == TRPAREN) {
    208       validx++;
    209     }
    210     return val;
    211   }
    212   if (p.kind == TADD) {
    213     return eval_primary();
    214   }
    215   if (p.kind == TSUB) {
    216     return -eval_primary();
    217   }
    218   if (p.kind == TLNOT) {
    219     return !eval_primary();
    220   }
    221   if (p.kind == TBNOT) {
    222     return ~eval_primary();
    223   }
    224   return 0;
    225 }
    226 
    227 static long long
    228 eval_mul(void)
    229 {
    230   long long val = eval_primary();
    231   while (validx < nppvals) {
    232     enum tokenkind op = ppvals[validx].kind;
    233     if (op == TMUL || op == TDIV || op == TMOD) {
    234       validx++;
    235       long long rhs = eval_primary();
    236       if (op == TMUL)
    237         val *= rhs;
    238       else if (op == TDIV)
    239         val = rhs ? val / rhs : 0;
    240       else
    241         val = rhs ? val % rhs : 0;
    242     } else {
    243       break;
    244     }
    245   }
    246   return val;
    247 }
    248 
    249 static long long
    250 eval_add(void)
    251 {
    252   long long val = eval_mul();
    253   while (validx < nppvals) {
    254     enum tokenkind op = ppvals[validx].kind;
    255     if (op == TADD || op == TSUB) {
    256       validx++;
    257       long long rhs = eval_mul();
    258       if (op == TADD)
    259         val += rhs;
    260       else
    261         val -= rhs;
    262     } else {
    263       break;
    264     }
    265   }
    266   return val;
    267 }
    268 
    269 static long long
    270 eval_shift(void)
    271 {
    272   long long val = eval_add();
    273   while (validx < nppvals) {
    274     enum tokenkind op = ppvals[validx].kind;
    275     if (op == TSHL || op == TSHR) {
    276       validx++;
    277       long long rhs = eval_add();
    278       if (op == TSHL)
    279         val <<= rhs;
    280       else
    281         val >>= rhs;
    282     } else {
    283       break;
    284     }
    285   }
    286   return val;
    287 }
    288 
    289 static long long
    290 eval_rel(void)
    291 {
    292   long long val = eval_shift();
    293   while (validx < nppvals) {
    294     enum tokenkind op = ppvals[validx].kind;
    295     if (op == TLESS || op == TGREATER || op == TLEQ || op == TGEQ) {
    296       validx++;
    297       long long rhs = eval_shift();
    298       if (op == TLESS)
    299         val = val < rhs;
    300       else if (op == TGREATER)
    301         val = val > rhs;
    302       else if (op == TLEQ)
    303         val = val <= rhs;
    304       else
    305         val = val >= rhs;
    306     } else {
    307       break;
    308     }
    309   }
    310   return val;
    311 }
    312 
    313 static long long
    314 eval_eq(void)
    315 {
    316   long long val = eval_rel();
    317   while (validx < nppvals) {
    318     enum tokenkind op = ppvals[validx].kind;
    319     if (op == TEQL || op == TNEQ) {
    320       validx++;
    321       long long rhs = eval_rel();
    322       if (op == TEQL)
    323         val = val == rhs;
    324       else
    325         val = val != rhs;
    326     } else {
    327       break;
    328     }
    329   }
    330   return val;
    331 }
    332 
    333 static long long
    334 eval_band(void)
    335 {
    336   long long val = eval_eq();
    337   while (validx < nppvals) {
    338     enum tokenkind op = ppvals[validx].kind;
    339     if (op == TBAND) {
    340       validx++;
    341       long long rhs = eval_eq();
    342       val &= rhs;
    343     } else {
    344       break;
    345     }
    346   }
    347   return val;
    348 }
    349 
    350 static long long
    351 eval_bxor(void)
    352 {
    353   long long val = eval_band();
    354   while (validx < nppvals) {
    355     enum tokenkind op = ppvals[validx].kind;
    356     if (op == TXOR) {
    357       validx++;
    358       long long rhs = eval_band();
    359       val ^= rhs;
    360     } else {
    361       break;
    362     }
    363   }
    364   return val;
    365 }
    366 
    367 static long long
    368 eval_bor(void)
    369 {
    370   long long val = eval_bxor();
    371   while (validx < nppvals) {
    372     enum tokenkind op = ppvals[validx].kind;
    373     if (op == TBOR) {
    374       validx++;
    375       long long rhs = eval_bxor();
    376       val |= rhs;
    377     } else {
    378       break;
    379     }
    380   }
    381   return val;
    382 }
    383 
    384 static long long
    385 eval_and(void)
    386 {
    387   long long val = eval_bor();
    388   while (validx < nppvals) {
    389     enum tokenkind op = ppvals[validx].kind;
    390     if (op == TLAND) {
    391       validx++;
    392       long long rhs = eval_bor();
    393       val           = val && rhs;
    394     } else {
    395       break;
    396     }
    397   }
    398   return val;
    399 }
    400 
    401 static long long
    402 eval_or(void)
    403 {
    404   long long val = eval_and();
    405   while (validx < nppvals) {
    406     enum tokenkind op = ppvals[validx].kind;
    407     if (op == TLOR) {
    408       validx++;
    409       long long rhs = eval_and();
    410       val           = val || rhs;
    411     } else {
    412       break;
    413     }
    414   }
    415   return val;
    416 }
    417 
    418 static long long
    419 eval_cond_expr(void)
    420 {
    421   long long val = eval_or();
    422   if (validx < nppvals && ppvals[validx].kind == TQUESTION) {
    423     validx++;
    424     long long true_val = eval_cond_expr();
    425     if (validx < nppvals && ppvals[validx].kind == TCOLON) {
    426       validx++;
    427     }
    428     long long false_val = eval_cond_expr();
    429     val                 = val ? true_val : false_val;
    430   }
    431   return val;
    432 }
    433 
    434 static long long
    435 eval_if_expr(void)
    436 {
    437   enum ppflags old_flags  = ppflags;
    438   int          old_cppoff = cppoff;
    439   cppoff                  = 0;
    440   ppflags |= PPNEWLINE;
    441   nppvals = 0;
    442   next();
    443   while (tok.kind != TNEWLINE && tok.kind != TEOF) {
    444     if (tok.kind >= TPPIDENT && strcmp(tokenstr(tok.kind), "defined") == 0) {
    445       bool paren = false;
    446       disexpand  = true;
    447       next();
    448       if (tok.kind == TLPAREN) {
    449         paren = true;
    450         next();
    451       }
    452       if (tok.kind < TPPIDENT) {
    453         error(
    454             &tok.loc,
    455             "operator 'defined' requires "
    456             "an identifier"
    457         );
    458       }
    459       struct macro *m   = macroget(tok.kind);
    460       long long     res = (m != NULL);
    461       if (paren) {
    462         next();
    463         if (tok.kind != TRPAREN)
    464           error(&tok.loc, "expected ')' in defined()");
    465       }
    466       disexpand = false;
    467       addval(TNUMBER, res);
    468       next();
    469     } else if (tok.kind >= TPPIDENT) {
    470       addval(TNUMBER, 0);
    471       next();
    472     } else if (tok.kind == TNUMBER) {
    473       long long v = strtoull(tok.lit, NULL, 0);
    474       addval(TNUMBER, v);
    475       next();
    476     } else {
    477       addval(tok.kind, 0);
    478       next();
    479     }
    480   }
    481   cppoff  = old_cppoff;
    482   ppflags = old_flags;
    483   validx  = 0;
    484   return eval_cond_expr();
    485 }
    486 
    487 void
    488 ppinit(void)
    489 {
    490   next();
    491 }
    492 
    493 static void
    494 macrodel(struct macro *m)
    495 {
    496   free(m->param);
    497   free(m->token);
    498   free(m);
    499 }
    500 
    501 /* check if two macro definitions are equal, as in C11 6.10.3p2 */
    502 static bool
    503 macroequal(struct macro *m1, struct macro *m2)
    504 {
    505   struct macroparam *p1, *p2;
    506   struct token      *t1, *t2;
    507 
    508   if (m1->kind != m2->kind)
    509     return false;
    510   if (m1->kind == MACROFUNC) {
    511     if (m1->nparam != m2->nparam)
    512       return false;
    513     for (p1 = m1->param, p2 = m2->param; p1 < m1->param + m1->nparam; ++p1, ++p2) {
    514       if (strcmp(p1->name, p2->name) != 0 || p1->flags != p2->flags)
    515         return false;
    516     }
    517   }
    518   if (m1->ntoken != m2->ntoken)
    519     return false;
    520   for (t1 = m1->token, t2 = m2->token; t1 < m1->token + m1->ntoken; ++t1, ++t2) {
    521     if (t1->kind != t2->kind)
    522       return false;
    523     if (t1->lit && strcmp(t1->lit, t2->lit) != 0)
    524       return false;
    525   }
    526   return true;
    527 }
    528 
    529 /* find the index of a macro parameter with the given name */
    530 static size_t
    531 macroparam(struct macro *m, struct token *t)
    532 {
    533   size_t i;
    534 
    535   if (t->kind >= TPPIDENT) {
    536     for (i = 0; i < m->nparam; ++i) {
    537       if (strcmp(m->param[i].name, tokenstr(t->kind)) == 0)
    538         return i;
    539     }
    540   }
    541   return -1;
    542 }
    543 
    544 /* lookup a macro by name */
    545 static struct macro *
    546 macroget(enum tokenkind ident)
    547 {
    548   return arraygetptr(&macros, ident - TPPIDENT);
    549 }
    550 
    551 static void
    552 macrodone(struct macro *m)
    553 {
    554   m->hide = false;
    555   if (m->kind == MACROFUNC && m->nparam > 0) {
    556     free(m->arg[0].token);
    557     free(m->arg);
    558   }
    559   --macrodepth;
    560 }
    561 
    562 static bool
    563 macrovarargs(struct macro *m)
    564 {
    565   return m->kind == MACROFUNC && m->nparam > 0 && m->param[m->nparam - 1].flags & PARAMVAR;
    566 }
    567 
    568 static struct token *
    569 framenext(struct frame *f)
    570 {
    571   return f->ntoken--, f->token++;
    572 }
    573 
    574 /* push a new context frame */
    575 static struct frame *
    576 ctxpush(struct token *t, size_t n, struct macro *m, bool space)
    577 {
    578   struct frame *f;
    579 
    580   f                 = arrayadd(&ctx, sizeof(*f));
    581   f->token          = t;
    582   f->ntoken         = n;
    583   f->macro          = m;
    584   f->alloc          = NULL;
    585   f->is_substituted = false;
    586   if (n > 0)
    587     t[0].space = space;
    588   return f;
    589 }
    590 
    591 static struct frame *
    592 ctxpush_alloc(struct token *t, size_t n, struct macro *m, bool space, struct token *alloc)
    593 {
    594   struct frame *f;
    595 
    596   f                 = arrayadd(&ctx, sizeof(*f));
    597   f->token          = t;
    598   f->ntoken         = n;
    599   f->macro          = m;
    600   f->alloc          = alloc;
    601   f->is_substituted = true;
    602   if (n > 0)
    603     t[0].space = space;
    604   return f;
    605 }
    606 
    607 /* get the next token from the context */
    608 static struct token *
    609 ctxnext(void)
    610 {
    611   struct frame *f;
    612   struct token *t;
    613   struct macro *m;
    614   bool          space;
    615   size_t        i;
    616 
    617 again:
    618   for (f = arraylast(&ctx, sizeof(*f)); ctx.len; --f, ctx.len -= sizeof(*f)) {
    619     if (f->ntoken)
    620       break;
    621     if (f->macro)
    622       macrodone(f->macro);
    623     if (f->alloc)
    624       free(f->alloc);
    625   }
    626   if (ctx.len == 0)
    627     return NULL;
    628   m = f->macro;
    629   if (m && m->kind == MACROFUNC && !f->is_substituted) {
    630     /* try to expand macro parameter */
    631     space = f->token->space;
    632     switch (f->token->kind) {
    633       case THASH:
    634         framenext(f);
    635         t = framenext(f);
    636         assert(t);
    637         i = macroparam(m, t);
    638         assert(i != (size_t)-1);
    639         f = ctxpush(&m->arg[i].str, 1, NULL, space);
    640         break;
    641       default:
    642         if (f->token->kind >= TPPIDENT) {
    643           i = macroparam(m, f->token);
    644           if (i == (size_t)-1)
    645             break;
    646           framenext(f);
    647           if (m->arg[i].ntoken == 0)
    648             goto again;
    649           f = ctxpush(m->arg[i].token, m->arg[i].ntoken, NULL, space);
    650         }
    651         break;
    652     }
    653     /* XXX: token concatenation */
    654   }
    655   return framenext(f);
    656 }
    657 
    658 static void
    659 define(void)
    660 {
    661   struct token      *t;
    662   enum tokenkind     ident, prev;
    663   struct macro      *m, *other;
    664   struct macroparam *p;
    665   struct array       params = {0}, repl = {0};
    666   size_t             i;
    667 
    668   m       = xmalloc(sizeof(*m));
    669   ident   = tok.kind;
    670   m->name = tokencheck(&tok, TPPIDENT, "after #define");
    671   m->hide = false;
    672   t       = arrayadd(&repl, sizeof(*t));
    673   scan(t);
    674   if (t->kind == TLPAREN && !t->space) {
    675     m->kind = MACROFUNC;
    676     /* read macro parameter names */
    677     p = NULL;
    678     while (scan(&tok), tok.kind != TRPAREN) {
    679       if (p) {
    680         if (p->flags & PARAMVAR)
    681           tokencheck(&tok, TRPAREN, "after '...'");
    682         tokencheck(&tok, TCOMMA, "or ')' after macro parameter");
    683         scan(&tok);
    684       }
    685       p        = arrayadd(&params, sizeof(*p));
    686       p->flags = 0;
    687       if (tok.kind == TELLIPSIS) {
    688         p->name = "__VA_ARGS__";
    689         p->flags |= PARAMVAR;
    690       } else {
    691         p->name = tokencheck(&tok, TPPIDENT, "of macro parameter name or '...'");
    692       }
    693     }
    694     scan(t); /* first token in replacement list */
    695   } else {
    696     m->kind = MACROOBJ;
    697   }
    698   m->param  = params.val;
    699   m->nparam = params.len / sizeof(m->param[0]);
    700 
    701   /* read macro body */
    702   i = macroparam(m, t);
    703   while (t->kind != TNEWLINE && t->kind != TEOF) {
    704     prev = t->kind;
    705     t    = arrayadd(&repl, sizeof(*t));
    706     scan(t);
    707     if (t->kind == T__VA_ARGS__ && !macrovarargs(m))
    708       error(
    709           &t->loc,
    710           "__VA_ARGS__ can only be used in "
    711           "variadic function-like macros"
    712       );
    713     if (m->kind != MACROFUNC)
    714       continue;
    715     if (i != (size_t)-1)
    716       m->param[i].flags |= PARAMTOK;
    717     i = macroparam(m, t);
    718     if (prev == THASH) {
    719       tokencheck(t, TPPIDENT, "after '#' operator");
    720       if (i == (size_t)-1)
    721         error(&t->loc, "'%s' is not a macro parameter name", t->lit);
    722       m->param[i].flags |= PARAMSTR;
    723       i = -1;
    724     }
    725   }
    726   m->token  = repl.val;
    727   m->ntoken = repl.len / sizeof(*t) - 1;
    728   tok       = *t;
    729 
    730   i     = ident - TPPIDENT;
    731   other = arraysetptr(&macros, i, m);
    732   if (other) {
    733     if (!macroequal(m, other))
    734       error(&tok.loc, "redefinition of macro '%s'", m->name);
    735     macrodel(other);
    736   }
    737 }
    738 
    739 static void
    740 undef(void)
    741 {
    742   enum tokenkind ident;
    743   struct macro  *m;
    744 
    745   ident = tok.kind;
    746   tokencheck(&tok, TPPIDENT, "after #undef");
    747   m = macroget(ident);
    748   if (m) {
    749     macrodel(m);
    750     ((void **)macros.val)[ident - TPPIDENT] = NULL;
    751   }
    752   scan(&tok);
    753 }
    754 
    755 static void
    756 directive(void)
    757 {
    758   struct location newloc;
    759   enum ppflags    oldflags;
    760   enum tokenkind  kind;
    761 
    762   scan(&tok);
    763   if (tok.kind == TNEWLINE)
    764     return; /* empty directive */
    765   oldflags = ppflags;
    766   ppflags |= PPNEWLINE;
    767   kind = tok.kind;
    768   switch (kind) {
    769     case TNUMBER:
    770       goto line; /* gcc line markers */
    771     case TIF: {
    772       int enabled = 0;
    773       if (!cppoff) {
    774         enabled = (eval_if_expr() != 0);
    775       } else {
    776         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    777           scan(&tok);
    778       }
    779       if (conddepth >= 64)
    780         error(&tok.loc, "too many nested #if");
    781       condstack[conddepth].iselse  = 0;
    782       condstack[conddepth].done    = enabled || cppoff;
    783       condstack[conddepth].enabled = enabled && !cppoff;
    784       if (!condstack[conddepth].enabled)
    785         cppoff++;
    786       conddepth++;
    787       break;
    788     }
    789     case TIFDEF:
    790     case TIFNDEF: {
    791       int enabled = 0;
    792       if (!cppoff) {
    793         scan(&tok);
    794         struct macro *m = macroget(tok.kind);
    795         enabled         = (m != NULL);
    796         if (kind == TIFNDEF)
    797           enabled = !enabled;
    798       }
    799       if (conddepth >= 64)
    800         error(&tok.loc, "too many nested #if");
    801       condstack[conddepth].iselse  = 0;
    802       condstack[conddepth].done    = enabled || cppoff;
    803       condstack[conddepth].enabled = enabled && !cppoff;
    804       if (!condstack[conddepth].enabled)
    805         cppoff++;
    806       conddepth++;
    807       while (tok.kind != TNEWLINE && tok.kind != TEOF)
    808         scan(&tok);
    809       break;
    810     }
    811     case TELIF: {
    812       if (conddepth == 0)
    813         error(&tok.loc, "#elif without #if");
    814       if (condstack[conddepth - 1].iselse)
    815         error(&tok.loc, "#elif after #else");
    816       int enabled = 0;
    817       if (cppoff == 1 && !condstack[conddepth - 1].enabled && !condstack[conddepth - 1].done) {
    818         enabled = (eval_if_expr() != 0);
    819         if (enabled) {
    820           condstack[conddepth - 1].enabled = 1;
    821           condstack[conddepth - 1].done    = 1;
    822           cppoff                           = 0;
    823         }
    824       } else {
    825         if (cppoff == 0) {
    826           condstack[conddepth - 1].enabled = 0;
    827           cppoff                           = 1;
    828         }
    829         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    830           scan(&tok);
    831       }
    832       break;
    833     }
    834     case TELSE:
    835       if (conddepth == 0)
    836         error(&tok.loc, "#else without #if");
    837       if (condstack[conddepth - 1].iselse)
    838         error(&tok.loc, "multiple #else");
    839       condstack[conddepth - 1].iselse = 1;
    840       if (cppoff == 1 && !condstack[conddepth - 1].enabled && !condstack[conddepth - 1].done) {
    841         condstack[conddepth - 1].enabled = 1;
    842         condstack[conddepth - 1].done    = 1;
    843         cppoff                           = 0;
    844       } else if (cppoff == 0) {
    845         condstack[conddepth - 1].enabled = 0;
    846         cppoff                           = 1;
    847       }
    848       while (tok.kind != TNEWLINE && tok.kind != TEOF)
    849         scan(&tok);
    850       break;
    851     case TENDIF:
    852       if (conddepth == 0)
    853         error(&tok.loc, "#endif without #if");
    854       conddepth--;
    855       if (!condstack[conddepth].enabled) {
    856         cppoff--;
    857       }
    858       while (tok.kind != TNEWLINE && tok.kind != TEOF)
    859         scan(&tok);
    860       break;
    861     case TINCLUDE: {
    862       if (cppoff) {
    863         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    864           scan(&tok);
    865         break;
    866       }
    867       include();
    868       break;
    869     }
    870     case TDEFINE:
    871       if (cppoff) {
    872         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    873           scan(&tok);
    874         break;
    875       }
    876       scan(&tok);
    877       define();
    878       break;
    879     case TUNDEF:
    880       if (cppoff) {
    881         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    882           scan(&tok);
    883         break;
    884       }
    885       scan(&tok);
    886       undef();
    887       break;
    888     case TLINE:
    889       if (cppoff) {
    890         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    891           scan(&tok);
    892         break;
    893       }
    894       scan(&tok);
    895       tokencheck(&tok, TNUMBER, "after #line");
    896     line:
    897       newloc.line = strtoull(tok.lit, NULL, 0);
    898       newloc.col  = 1;
    899       scan(&tok);
    900       newloc.file = tok.loc.file;
    901       if (tok.kind == TSTRINGLIT) {
    902         char *quote;
    903 
    904         /* XXX: handle escape sequences (reuse string decoding
    905          * from expr.c) */
    906         quote = strchr(tok.lit, '"');
    907         assert(quote);
    908         newloc.file = quote + 1;
    909         quote       = strchr(quote + 1, '"');
    910         assert(quote);
    911         *quote = '\0';
    912         scan(&tok);
    913       }
    914       while (tok.kind == TNUMBER)
    915         scan(&tok);
    916       scansetloc(newloc);
    917       break;
    918     case TERROR:
    919     case TWARNING:
    920       if (cppoff) {
    921         while (tok.kind != TNEWLINE && tok.kind != TEOF)
    922           scan(&tok);
    923         break;
    924       }
    925       diagloc(&tok.loc);
    926       fprintf(stderr, "%s directive:", kind == TERROR ? "#error" : "#warning");
    927       scan(&tok);
    928       while (tok.kind != TNEWLINE && tok.kind != TEOF) {
    929         tokenprint(&tok, stderr);
    930         scan(&tok);
    931       }
    932       fputc('\n', stderr);
    933       if (kind == TERROR)
    934         exit(1);
    935       break;
    936     case TPRAGMA:
    937       while (tok.kind != TNEWLINE && tok.kind != TEOF)
    938         scan(&tok);
    939       break;
    940     default:
    941       error(&tok.loc, "invalid preprocessor directive #%s", tokenstr(tok.kind));
    942   }
    943   tokencheck(&tok, TNEWLINE, "after preprocessing directive");
    944   ppflags = oldflags;
    945 }
    946 
    947 /* get the next token without expanding it */
    948 static void
    949 nextinto(struct token *t)
    950 {
    951   static bool newline = true;
    952 
    953   for (;;) {
    954     scan(t);
    955     if (newline && t->kind == THASH) {
    956       directive();
    957       if (cppoff) {
    958         newline = true;
    959         continue;
    960       }
    961     } else {
    962       newline = tok.kind == TNEWLINE;
    963       if (cppoff) {
    964         continue;
    965       }
    966       break;
    967     }
    968   }
    969 }
    970 
    971 static struct token *
    972 rawnext(void)
    973 {
    974   struct token *t;
    975 
    976   t = ctxnext();
    977   if (!t) {
    978     t = &tok;
    979     nextinto(t);
    980   }
    981   return t;
    982 }
    983 
    984 static bool
    985 peekparen(void)
    986 {
    987   static struct array pending;
    988   struct token       *t;
    989   struct frame       *f;
    990 
    991   t = ctxnext();
    992   if (t) {
    993     if (t->kind == TLPAREN)
    994       return true;
    995     f = arraylast(&ctx, sizeof(*f));
    996     --f->token;
    997     ++f->ntoken;
    998     return false;
    999   }
   1000   pending.len = 0;
   1001   do
   1002     t = arrayadd(&pending, sizeof(*t)), nextinto(t);
   1003   while (t->kind == TNEWLINE);
   1004   if (t->kind == TLPAREN)
   1005     return true;
   1006   t = pending.val;
   1007   ctxpush(t, pending.len / sizeof(*t), NULL, t[0].space);
   1008   return false;
   1009 }
   1010 
   1011 static void
   1012 stringize(struct array *buf, struct token *t)
   1013 {
   1014   const char *lit;
   1015 
   1016   if ((t->space || t->kind == TNEWLINE) && buf->len > 1 && ((char *)buf->val)[buf->len - 1] != ' ')
   1017     arrayaddbuf(buf, " ", 1);
   1018   lit = t->lit ? t->lit : tokenstr(t->kind);
   1019   if (t->kind == TSTRINGLIT || t->kind == TCHARCONST) {
   1020     for (; *lit; ++lit) {
   1021       if (*lit == '\\' || *lit == '"')
   1022         arrayaddbuf(buf, "\\", 1);
   1023       arrayaddbuf(buf, lit, 1);
   1024     }
   1025   } else if (lit) {
   1026     arrayaddbuf(buf, lit, strlen(lit));
   1027   }
   1028 }
   1029 
   1030 static void expandfunc(struct macro *);
   1031 
   1032 static void
   1033 macroexpand(struct macro *m, bool space)
   1034 {
   1035   struct array  repl = {0};
   1036   size_t        i, j;
   1037   struct token *t;
   1038   int           param_idx;
   1039 
   1040   for (i = 0; i < m->ntoken; ++i) {
   1041     t = &m->token[i];
   1042     if (t->kind == THASH && m->kind == MACROFUNC && i + 1 < m->ntoken) {
   1043       struct token stringized;
   1044       struct array str = {0};
   1045       t                = &m->token[++i];
   1046       param_idx        = macroparam(m, t);
   1047       assert(param_idx != -1);
   1048       arrayaddbuf(&str, "\"", 1);
   1049       for (j = 0; j < m->arg[param_idx].ntoken; ++j)
   1050         stringize(&str, &m->arg[param_idx].token[j]);
   1051       arrayaddbuf(&str, "\"", 2);
   1052       stringized = (struct token){
   1053           .kind  = TSTRINGLIT,
   1054           .lit   = str.val,
   1055           .space = t->space,
   1056       };
   1057       arrayaddbuf(&repl, &stringized, sizeof(stringized));
   1058     } else if (m->kind == MACROFUNC && (param_idx = macroparam(m, t)) != -1) {
   1059       struct macroarg *arg = &m->arg[param_idx];
   1060       for (j = 0; j < arg->ntoken; ++j) {
   1061         struct token arg_t = arg->token[j];
   1062         if (j == 0)
   1063           arg_t.space = t->space;
   1064         arrayaddbuf(&repl, &arg_t, sizeof(arg_t));
   1065       }
   1066     } else {
   1067       arrayaddbuf(&repl, t, sizeof(*t));
   1068     }
   1069   }
   1070 
   1071   struct array clean = {0};
   1072   t                  = repl.val;
   1073   size_t n           = repl.len / sizeof(*t);
   1074   for (i = 0; i < n; ++i) {
   1075     if (i + 1 < n && t[i + 1].kind == THASHHASH) {
   1076       struct token pasted = t[i];
   1077       if (i + 2 < n) {
   1078         struct token *right = &t[i + 2];
   1079         char         *s1    = pasted.lit ? pasted.lit : tokenstr(pasted.kind);
   1080         char         *s2    = right->lit ? right->lit : tokenstr(right->kind);
   1081         size_t        len1  = strlen(s1);
   1082         size_t        len2  = strlen(s2);
   1083         char         *s     = xmalloc(len1 + len2 + 1);
   1084         memcpy(s, s1, len1);
   1085         memcpy(s + len1, s2, len2);
   1086         s[len1 + len2] = '\0';
   1087 
   1088         pasted.lit = s;
   1089         if (s[0] >= '0' && s[0] <= '9') {
   1090           pasted.kind = TNUMBER;
   1091         } else {
   1092           pasted.kind = tokenget(s, len1 + len2);
   1093         }
   1094         i += 2;
   1095       } else {
   1096         i += 1;
   1097       }
   1098       t[i] = pasted;
   1099       --i;
   1100     } else if (t[i].kind != THASHHASH) {
   1101       arrayaddbuf(&clean, &t[i], sizeof(t[i]));
   1102     }
   1103   }
   1104   free(repl.val);
   1105 
   1106   struct token *allocated = clean.val;
   1107   size_t        n_clean   = clean.len / sizeof(*allocated);
   1108   ctxpush_alloc(allocated, n_clean, m, space, allocated);
   1109 }
   1110 
   1111 static bool
   1112 expand(struct token *t)
   1113 {
   1114   struct macro *m;
   1115   bool          space;
   1116 
   1117   if (disexpand)
   1118     return false;
   1119 
   1120   if (t->kind < TPPIDENT)
   1121     return false;
   1122   m = macroget(t->kind);
   1123   if (!m || m->hide)
   1124     t->hide = true;
   1125   if (t->hide)
   1126     return false;
   1127   space = t->space;
   1128   if (m->kind == MACROFUNC) {
   1129     if (!peekparen())
   1130       return false;
   1131     expandfunc(m);
   1132   }
   1133   macroexpand(m, space);
   1134   m->hide = true;
   1135   ++macrodepth;
   1136   return true;
   1137 }
   1138 
   1139 static void
   1140 expandfunc(struct macro *m)
   1141 {
   1142   struct macroparam *p;
   1143   struct macroarg   *arg;
   1144   struct array       str, tok;
   1145   size_t             i, depth, paren;
   1146   struct token      *t;
   1147 
   1148   /* read macro arguments */
   1149   paren = 0;
   1150   depth = macrodepth;
   1151   tok   = (struct array){0};
   1152   arg   = xreallocarray(NULL, m->nparam, sizeof(*arg));
   1153   t     = rawnext();
   1154   for (i = 0; i < m->nparam; ++i) {
   1155     p = &m->param[i];
   1156     if (p->flags & PARAMSTR) {
   1157       str = (struct array){0};
   1158       arrayaddbuf(&str, "\"", 1);
   1159     }
   1160     arg[i].ntoken = 0;
   1161     for (;;) {
   1162       if (t->kind == TEOF)
   1163         error(&t->loc, "EOF when reading macro parameters");
   1164       if (macrodepth <= depth) {
   1165         /* adjust current macro depth, in case it got
   1166          * shallower */
   1167         depth = macrodepth;
   1168         if (paren == 0 && (t->kind == TRPAREN || (t->kind == TCOMMA && !(p->flags & PARAMVAR))))
   1169           break;
   1170         switch (t->kind) {
   1171           case TLPAREN:
   1172             ++paren;
   1173             break;
   1174           case TRPAREN:
   1175             --paren;
   1176             break;
   1177           default:
   1178             break;
   1179         }
   1180         if (p->flags & PARAMSTR)
   1181           stringize(&str, t);
   1182       }
   1183       if (p->flags & PARAMTOK && !expand(t)) {
   1184         arrayaddbuf(&tok, t, sizeof(*t));
   1185         ++arg[i].ntoken;
   1186       }
   1187       t = rawnext();
   1188     }
   1189     if (p->flags & PARAMSTR) {
   1190       arrayaddbuf(&str, "\"", 2);
   1191       arg[i].str = (struct token){
   1192           .kind = TSTRINGLIT,
   1193           .lit  = str.val,
   1194       };
   1195     }
   1196     if (t->kind == TRPAREN)
   1197       break;
   1198     t = rawnext();
   1199   }
   1200   if (i + 1 < m->nparam)
   1201     error(&t->loc, "not enough arguments for macro '%s'", m->name);
   1202   if (t->kind != TRPAREN)
   1203     error(&t->loc, "too many arguments for macro '%s'", m->name);
   1204   for (i = 0, t = tok.val; i < m->nparam; ++i) {
   1205     arg[i].token = t;
   1206     t += arg[i].ntoken;
   1207   }
   1208   m->arg = arg;
   1209 }
   1210 
   1211 void
   1212 next(void)
   1213 {
   1214   struct token *t;
   1215 
   1216   do
   1217     t = rawnext();
   1218   while (expand(t) || (t->kind == TNEWLINE && !(ppflags & PPNEWLINE)));
   1219   tok = *t;
   1220 
   1221   /* keyword aliases */
   1222   switch (tok.kind) {
   1223     case ALIAS_ALIGNAS:
   1224       tok.kind = TALIGNAS;
   1225       break;
   1226     case ALIAS_ALIGNOF:
   1227       tok.kind = TALIGNOF;
   1228       break;
   1229     case ALIAS_BOOL:
   1230       tok.kind = TBOOL;
   1231       break;
   1232     case ALIAS__INLINE:
   1233     case ALIAS__INLINE__:
   1234       tok.kind = TINLINE;
   1235       break;
   1236     case ALIAS__SIGNED:
   1237     case ALIAS__SIGNED__:
   1238       tok.kind = TSIGNED;
   1239       break;
   1240     case ALIAS_STATIC_ASSERT:
   1241       tok.kind = TSTATIC_ASSERT;
   1242       break;
   1243     case ALIAS_THREAD_LOCAL:
   1244     case ALIAS__THREAD:
   1245       tok.kind = TTHREAD_LOCAL;
   1246       break;
   1247     case ALIAS__TYPEOF:
   1248     case ALIAS__TYPEOF__:
   1249       tok.kind = TTYPEOF;
   1250       break;
   1251     case ALIAS__VOLATILE__:
   1252       tok.kind = TVOLATILE;
   1253       break;
   1254     case ALIAS__ASM:
   1255       tok.kind = T__ASM__;
   1256       break;
   1257     default:
   1258       break;
   1259   }
   1260 }
   1261 
   1262 bool
   1263 peek(enum tokenkind kind)
   1264 {
   1265   static struct token pending;
   1266   struct token        old;
   1267 
   1268   old = tok;
   1269   next();
   1270   if (tok.kind == kind) {
   1271     next();
   1272     return true;
   1273   }
   1274   pending = tok;
   1275   tok     = old;
   1276   ctxpush(&pending, 1, NULL, pending.space);
   1277   return false;
   1278 }
   1279 
   1280 char *
   1281 expect(enum tokenkind kind, const char *msg)
   1282 {
   1283   char *lit;
   1284 
   1285   lit = tokencheck(&tok, kind, msg);
   1286   next();
   1287 
   1288   return lit;
   1289 }
   1290 
   1291 bool
   1292 consume(enum tokenkind kind)
   1293 {
   1294   if (tok.kind != kind)
   1295     return false;
   1296   next();
   1297   return true;
   1298 }