]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
More cleanup
[xonotic/gmqcc.git] / ftepp.c
1 /*
2  * Copyright (C) 2012, 2013, 2014, 2015
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <string.h>
25 #include <stdlib.h>
26 #include <sys/stat.h>
27
28 #include "gmqcc.h"
29 #include "lexer.h"
30
31 #define HT_MACROS 1024
32
33 typedef struct {
34     bool on;
35     bool was_on;
36     bool had_else;
37 } ppcondition;
38
39 typedef struct {
40     int   token;
41     char *value;
42     /* a copy from the lexer */
43     union {
44         vec3_t v;
45         int    i;
46         double f;
47         int    t; /* type */
48     } constval;
49 } pptoken;
50
51 typedef struct {
52     lex_ctx_t ctx;
53
54     char   *name;
55     char  **params;
56     /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
57     bool    has_params;
58     bool    variadic;
59
60     pptoken **output;
61 } ppmacro;
62
63 typedef struct ftepp_s {
64     lex_file    *lex;
65     int          token;
66     unsigned int errors;
67
68     bool         output_on;
69     ppcondition *conditions;
70     /*ppmacro    **macros;*/
71     ht           macros;  /* hashtable<string, ppmacro*> */
72     char        *output_string;
73
74     char        *itemname;
75     char        *includename;
76     bool         in_macro;
77
78     uint32_t predef_countval;
79     uint32_t predef_randval;
80 } ftepp_t;
81
82 /* __DATE__ */
83 static char *ftepp_predef_date(ftepp_t *context) {
84     const struct tm *itime = NULL;
85     char            *value = (char*)mem_a(82);
86     time_t           rtime;
87
88     (void)context;
89
90     time (&rtime);
91     itime = util_localtime(&rtime);
92     strftime(value, 82, "\"%b %d %Y\"", itime);
93
94     return value;
95 }
96
97 /* __TIME__ */
98 static char *ftepp_predef_time(ftepp_t *context) {
99     const struct tm *itime = NULL;
100     char            *value = (char*)mem_a(82);
101     time_t           rtime;
102
103     (void)context;
104
105     time (&rtime);
106     itime = util_localtime(&rtime);
107     strftime(value, 82, "\"%X\"", itime);
108
109     return value;
110 }
111
112 /* __LINE__ */
113 static char *ftepp_predef_line(ftepp_t *context) {
114     char *value;
115
116     util_asprintf(&value, "%d", (int)context->lex->line);
117     return value;
118 }
119 /* __FILE__ */
120 static char *ftepp_predef_file(ftepp_t *context) {
121     size_t length = strlen(context->lex->name) + 3; /* two quotes and a terminator */
122     char  *value  = (char*)mem_a(length);
123
124     util_snprintf(value, length, "\"%s\"", context->lex->name);
125     return value;
126 }
127 /* __COUNTER_LAST__ */
128 static char *ftepp_predef_counterlast(ftepp_t *context) {
129     char *value;
130     util_asprintf(&value, "%u", context->predef_countval);
131     return value;
132 }
133 /* __COUNTER__ */
134 static char *ftepp_predef_counter(ftepp_t *context) {
135     char *value;
136
137     context->predef_countval ++;
138     util_asprintf(&value, "%u", context->predef_countval);
139
140     return value;
141 }
142 /* __RANDOM__ */
143 static char *ftepp_predef_random(ftepp_t *context) {
144     char *value;
145
146     context->predef_randval = (util_rand() % 0xFF) + 1;
147     util_asprintf(&value, "%u", context->predef_randval);
148     return value;
149 }
150 /* __RANDOM_LAST__ */
151 static char *ftepp_predef_randomlast(ftepp_t *context) {
152     char *value;
153
154     util_asprintf(&value, "%u", context->predef_randval);
155     return value;
156 }
157 /* __TIMESTAMP__ */
158 static char *ftepp_predef_timestamp(ftepp_t *context) {
159     struct stat finfo;
160     const char *find;
161     char       *value;
162     size_t      size;
163
164     if (stat(context->lex->name, &finfo))
165         return util_strdup("\"<failed to determine timestamp>\"");
166
167     find = util_ctime(&finfo.st_mtime);
168     value = (char*)mem_a(strlen(find) + 1);
169     memcpy(&value[1], find, (size = strlen(find)) - 1);
170
171     value[0]    = '"';
172     value[size] = '"';
173
174     return value;
175 }
176
177 typedef struct {
178     const char   *name;
179     char       *(*func)(ftepp_t *);
180 } ftepp_predef_t;
181
182 static const ftepp_predef_t ftepp_predefs[] = {
183     { "__LINE__",         &ftepp_predef_line        },
184     { "__FILE__",         &ftepp_predef_file        },
185     { "__COUNTER__",      &ftepp_predef_counter     },
186     { "__COUNTER_LAST__", &ftepp_predef_counterlast },
187     { "__RANDOM__",       &ftepp_predef_random      },
188     { "__RANDOM_LAST__",  &ftepp_predef_randomlast  },
189     { "__DATE__",         &ftepp_predef_date        },
190     { "__TIME__",         &ftepp_predef_time        },
191     { "__TIME_STAMP__",   &ftepp_predef_timestamp   }
192 };
193
194 static GMQCC_INLINE size_t ftepp_predef_index(const char *name) {
195     /* no hashtable here, we simply check for one to exist the naive way */
196     size_t i;
197     for(i = 1; i < GMQCC_ARRAY_COUNT(ftepp_predefs) + 1; i++)
198         if (!strcmp(ftepp_predefs[i-1].name, name))
199             return i;
200     return 0;
201 }
202
203 bool ftepp_predef_exists(const char *name);
204 bool ftepp_predef_exists(const char *name) {
205     return ftepp_predef_index(name) != 0;
206 }
207
208 /* singleton because we're allowed */
209 static GMQCC_INLINE char *(*ftepp_predef(const char *name))(ftepp_t *context) {
210     size_t i = ftepp_predef_index(name);
211     return (i != 0) ? ftepp_predefs[i-1].func : NULL;
212 }
213
214 #define ftepp_tokval(f) ((f)->lex->tok.value)
215 #define ftepp_ctx(f)    ((f)->lex->tok.ctx)
216
217 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx_t ctx, const char *fmt, ...)
218 {
219     va_list ap;
220
221     ftepp->errors++;
222
223     va_start(ap, fmt);
224     con_cvprintmsg(ctx, LVL_ERROR, "error", fmt, ap);
225     va_end(ap);
226 }
227
228 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
229 {
230     va_list ap;
231
232     ftepp->errors++;
233
234     va_start(ap, fmt);
235     con_cvprintmsg(ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
236     va_end(ap);
237 }
238
239 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
240 {
241     bool    r;
242     va_list ap;
243
244     va_start(ap, fmt);
245     r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
246     va_end(ap);
247     return r;
248 }
249
250 static pptoken *pptoken_make(ftepp_t *ftepp)
251 {
252     pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
253     token->token = ftepp->token;
254     token->value = util_strdup(ftepp_tokval(ftepp));
255     memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
256     return token;
257 }
258
259 static GMQCC_INLINE void pptoken_delete(pptoken *self)
260 {
261     mem_d(self->value);
262     mem_d(self);
263 }
264
265 static ppmacro *ppmacro_new(lex_ctx_t ctx, const char *name)
266 {
267     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
268
269     (void)ctx;
270     memset(macro, 0, sizeof(*macro));
271     macro->name = util_strdup(name);
272     return macro;
273 }
274
275 static void ppmacro_delete(ppmacro *self)
276 {
277     size_t i;
278     for (i = 0; i < vec_size(self->params); ++i)
279         mem_d(self->params[i]);
280     vec_free(self->params);
281     for (i = 0; i < vec_size(self->output); ++i)
282         pptoken_delete(self->output[i]);
283     vec_free(self->output);
284     mem_d(self->name);
285     mem_d(self);
286 }
287
288 static ftepp_t* ftepp_new(void)
289 {
290     ftepp_t *ftepp;
291
292     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
293     memset(ftepp, 0, sizeof(*ftepp));
294
295     ftepp->macros          = util_htnew(HT_MACROS);
296     ftepp->output_on       = true;
297     ftepp->predef_countval = 0;
298     ftepp->predef_randval  = 0;
299
300     return ftepp;
301 }
302
303 static GMQCC_INLINE void ftepp_flush_do(ftepp_t *self)
304 {
305     vec_free(self->output_string);
306 }
307
308 static void ftepp_delete(ftepp_t *self)
309 {
310     ftepp_flush_do(self);
311     if (self->itemname)
312         mem_d(self->itemname);
313     if (self->includename)
314         vec_free(self->includename);
315
316     util_htrem(self->macros, (void (*)(void*))&ppmacro_delete);
317
318     vec_free(self->conditions);
319     if (self->lex)
320         lex_close(self->lex);
321     mem_d(self);
322 }
323
324 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
325 {
326     if (ignore_cond || ftepp->output_on)
327     {
328         size_t len;
329         char  *data;
330         len = strlen(str);
331         data = vec_add(ftepp->output_string, len);
332         memcpy(data, str, len);
333     }
334 }
335
336 static GMQCC_INLINE void ftepp_update_output_condition(ftepp_t *ftepp)
337 {
338     size_t i;
339     ftepp->output_on = true;
340     for (i = 0; i < vec_size(ftepp->conditions); ++i)
341         ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
342 }
343
344 static GMQCC_INLINE ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
345 {
346     return (ppmacro*)util_htget(ftepp->macros, name);
347 }
348
349 static GMQCC_INLINE void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
350 {
351     util_htrm(ftepp->macros, name, (void (*)(void*))&ppmacro_delete);
352 }
353
354 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
355 {
356     return (ftepp->token = lex_do(ftepp->lex));
357 }
358
359 /* Important: this does not skip newlines! */
360 static bool ftepp_skipspace(ftepp_t *ftepp)
361 {
362     if (ftepp->token != TOKEN_WHITE)
363         return true;
364     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
365     if (ftepp->token >= TOKEN_EOF) {
366         ftepp_error(ftepp, "unexpected end of preprocessor directive");
367         return false;
368     }
369     return true;
370 }
371
372 /* this one skips EOLs as well */
373 static bool ftepp_skipallwhite(ftepp_t *ftepp)
374 {
375     if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
376         return true;
377     do {
378         ftepp_next(ftepp);
379     } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
380     if (ftepp->token >= TOKEN_EOF) {
381         ftepp_error(ftepp, "unexpected end of preprocessor directive");
382         return false;
383     }
384     return true;
385 }
386
387 /**
388  * The huge macro parsing code...
389  */
390 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
391 {
392     do {
393         ftepp_next(ftepp);
394         if (!ftepp_skipspace(ftepp))
395             return false;
396         if (ftepp->token == ')')
397             break;
398         switch (ftepp->token) {
399             case TOKEN_IDENT:
400             case TOKEN_TYPENAME:
401             case TOKEN_KEYWORD:
402                 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
403                 break;
404             case TOKEN_DOTS:
405                 macro->variadic = true;
406                 break;
407             default:
408                 ftepp_error(ftepp, "unexpected token in parameter list");
409                 return false;
410         }
411         ftepp_next(ftepp);
412         if (!ftepp_skipspace(ftepp))
413             return false;
414         if (macro->variadic && ftepp->token != ')') {
415             ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
416             return false;
417         }
418     } while (ftepp->token == ',');
419
420     if (ftepp->token != ')') {
421         ftepp_error(ftepp, "expected closing paren after macro parameter list");
422         return false;
423     }
424     ftepp_next(ftepp);
425     /* skipspace happens in ftepp_define */
426     return true;
427 }
428
429 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
430 {
431     pptoken *ptok;
432     while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
433         bool   subscript = false;
434         size_t index     = 0;
435         if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
436             subscript = !!(ftepp_next(ftepp) == '#');
437
438             if (subscript && ftepp_next(ftepp) != '#') {
439                 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
440                 return false;
441             } else if (subscript) {
442                 if (ftepp_next(ftepp) == '[') {
443                     if (ftepp_next(ftepp) != TOKEN_INTCONST) {
444                         ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
445                         return false;
446                     }
447
448                     index = (int)strtol(ftepp_tokval(ftepp), NULL, 10);
449
450                     if (ftepp_next(ftepp) != ']') {
451                         ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
452                         return false;
453                     }
454
455                     /*
456                      * mark it as an array to be handled later as such and not
457                      * as traditional __VA_ARGS__
458                      */
459                     ftepp->token = TOKEN_VA_ARGS_ARRAY;
460                     ptok = pptoken_make(ftepp);
461                     ptok->constval.i = index;
462                     vec_push(macro->output, ptok);
463                     ftepp_next(ftepp);
464                 } else {
465                     ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
466                     return false;
467                 }
468             } else {
469                 int old = ftepp->token;
470                 ftepp->token = TOKEN_VA_ARGS;
471                 ptok = pptoken_make(ftepp);
472                 vec_push(macro->output, ptok);
473                 ftepp->token = old;
474             }
475         }
476         else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
477             ftepp->token = TOKEN_VA_COUNT;
478             ptok         = pptoken_make(ftepp);
479             vec_push(macro->output, ptok);
480             ftepp_next(ftepp);
481         } else {
482             ptok = pptoken_make(ftepp);
483             vec_push(macro->output, ptok);
484             ftepp_next(ftepp);
485         }
486     }
487     /* recursive expansion can cause EOFs here */
488     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
489         ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
490         return false;
491     }
492     return true;
493 }
494
495 static const char *ftepp_math_constants[][2] = {
496     { "M_E",        "2.7182818284590452354"  }, /* e          */
497     { "M_LOG2E",    "1.4426950408889634074"  }, /* log_2 e    */
498     { "M_LOG10E",   "0.43429448190325182765" }, /* log_10 e   */
499     { "M_LN2",      "0.69314718055994530942" }, /* log_e 2    */
500     { "M_LN10",     "2.30258509299404568402" }, /* log_e 10   */
501     { "M_PI",       "3.14159265358979323846" }, /* pi         */
502     { "M_PI_2",     "1.57079632679489661923" }, /* pi/2       */
503     { "M_PI_4",     "0.78539816339744830962" }, /* pi/4       */
504     { "M_1_PI",     "0.31830988618379067154" }, /* 1/pi       */
505     { "M_2_PI",     "0.63661977236758134308" }, /* 2/pi       */
506     { "M_2_SQRTPI", "1.12837916709551257390" }, /* 2/sqrt(pi) */
507     { "M_SQRT2",    "1.41421356237309504880" }, /* sqrt(2)    */
508     { "M_SQRT1_2",  "0.70710678118654752440" }, /* 1/sqrt(2)  */
509     { "M_TAU",      "6.28318530717958647692" }  /* pi*2       */
510 };
511
512 static bool ftepp_define(ftepp_t *ftepp)
513 {
514     ppmacro *macro = NULL;
515     size_t l = ftepp_ctx(ftepp).line;
516     size_t i;
517     bool   mathconstant = false;
518
519     (void)ftepp_next(ftepp);
520     if (!ftepp_skipspace(ftepp))
521         return false;
522
523     switch (ftepp->token) {
524         case TOKEN_IDENT:
525         case TOKEN_TYPENAME:
526         case TOKEN_KEYWORD:
527             if (OPTS_FLAG(FTEPP_MATHDEFS)) {
528                 for (i = 0; i < GMQCC_ARRAY_COUNT(ftepp_math_constants); i++) {
529                     if (!strcmp(ftepp_math_constants[i][0], ftepp_tokval(ftepp))) {
530                         mathconstant = true;
531                         break;
532                     }
533                 }
534             }
535
536             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
537
538             if (OPTS_FLAG(FTEPP_MATHDEFS)) {
539                 /* user defined ones take precedence */
540                 if (macro && mathconstant) {
541                     ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
542                     macro = NULL;
543                 }
544             }
545
546             if (macro && ftepp->output_on) {
547                 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
548                     return false;
549                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
550             }
551             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
552             break;
553         default:
554             ftepp_error(ftepp, "expected macro name");
555             return false;
556     }
557
558     (void)ftepp_next(ftepp);
559
560     if (ftepp->token == '(') {
561         macro->has_params = true;
562         if (!ftepp_define_params(ftepp, macro)) {
563             ppmacro_delete(macro);
564             return false;
565         }
566     }
567
568     if (!ftepp_skipspace(ftepp)) {
569         ppmacro_delete(macro);
570         return false;
571     }
572
573     if (!ftepp_define_body(ftepp, macro)) {
574         ppmacro_delete(macro);
575         return false;
576     }
577
578     if (ftepp->output_on)
579         util_htset(ftepp->macros, macro->name, (void*)macro);
580     else {
581         ppmacro_delete(macro);
582     }
583
584     for (; l < ftepp_ctx(ftepp).line; ++l)
585         ftepp_out(ftepp, "\n", true);
586     return true;
587 }
588
589 /**
590  * When a macro is used we have to handle parameters as well
591  * as special-concatenation via ## or stringification via #
592  *
593  * Note: parenthesis can nest, so FOO((a),b) is valid, but only
594  * this kind of parens. Curly braces or [] don't count towards the
595  * paren-level.
596  */
597 typedef struct {
598     pptoken **tokens;
599 } macroparam;
600
601 static void macroparam_clean(macroparam *self)
602 {
603     size_t i;
604     for (i = 0; i < vec_size(self->tokens); ++i)
605         pptoken_delete(self->tokens[i]);
606     vec_free(self->tokens);
607 }
608
609 /* need to leave the last token up */
610 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
611 {
612     macroparam *params = NULL;
613     pptoken    *ptok;
614     macroparam  mp;
615     size_t      parens = 0;
616     size_t      i;
617
618     if (!ftepp_skipallwhite(ftepp))
619         return false;
620     while (ftepp->token != ')') {
621         mp.tokens = NULL;
622         if (!ftepp_skipallwhite(ftepp))
623             return false;
624         while (parens || ftepp->token != ',') {
625             if (ftepp->token == '(')
626                 ++parens;
627             else if (ftepp->token == ')') {
628                 if (!parens)
629                     break;
630                 --parens;
631             }
632             ptok = pptoken_make(ftepp);
633             vec_push(mp.tokens, ptok);
634             if (ftepp_next(ftepp) >= TOKEN_EOF) {
635                 ftepp_error(ftepp, "unexpected end of file in macro call");
636                 goto on_error;
637             }
638         }
639         vec_push(params, mp);
640         mp.tokens = NULL;
641         if (ftepp->token == ')')
642             break;
643         if (ftepp->token != ',') {
644             ftepp_error(ftepp, "expected closing paren or comma in macro call");
645             goto on_error;
646         }
647         if (ftepp_next(ftepp) >= TOKEN_EOF) {
648             ftepp_error(ftepp, "unexpected end of file in macro call");
649             goto on_error;
650         }
651     }
652     *out_params = params;
653     return true;
654
655 on_error:
656     if (mp.tokens)
657         macroparam_clean(&mp);
658     for (i = 0; i < vec_size(params); ++i)
659         macroparam_clean(&params[i]);
660     vec_free(params);
661     return false;
662 }
663
664 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
665 {
666     size_t i;
667     for (i = 0; i < vec_size(macro->params); ++i) {
668         if (!strcmp(macro->params[i], name)) {
669             *idx = i;
670             return true;
671         }
672     }
673     return false;
674 }
675
676 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
677 {
678     char        chs[2];
679     const char *ch;
680     chs[1] = 0;
681     switch (token->token) {
682         case TOKEN_STRINGCONST:
683             ch = token->value;
684             while (*ch) {
685                 /* in preprocessor mode strings already are string,
686                  * so we don't get actual newline bytes here.
687                  * Still need to escape backslashes and quotes.
688                  */
689                 switch (*ch) {
690                     case '\\': ftepp_out(ftepp, "\\\\", false); break;
691                     case '"':  ftepp_out(ftepp, "\\\"", false); break;
692                     default:
693                         chs[0] = *ch;
694                         ftepp_out(ftepp, chs, false);
695                         break;
696                 }
697                 ++ch;
698             }
699             break;
700         /*case TOKEN_WHITE:
701             ftepp_out(ftepp, " ", false);
702             break;*/
703         case TOKEN_EOL:
704             ftepp_out(ftepp, "\\n", false);
705             break;
706         default:
707             ftepp_out(ftepp, token->value, false);
708             break;
709     }
710 }
711
712 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
713 {
714     size_t i;
715     ftepp_out(ftepp, "\"", false);
716     for (i = 0; i < vec_size(param->tokens); ++i)
717         ftepp_stringify_token(ftepp, param->tokens[i]);
718     ftepp_out(ftepp, "\"", false);
719 }
720
721 static void ftepp_recursion_header(ftepp_t *ftepp)
722 {
723     ftepp_out(ftepp, "\n#pragma push(line)\n", false);
724 }
725
726 static void ftepp_recursion_footer(ftepp_t *ftepp)
727 {
728     ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
729 }
730
731 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline);
732 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
733 {
734     size_t   i;
735     pptoken *out;
736     for (i = 0; i < vec_size(param->tokens); ++i) {
737         out = param->tokens[i];
738         if (out->token == TOKEN_EOL)
739             ftepp_out(ftepp, "\n", false);
740         else {
741             ppmacro *find = ftepp_macro_find(ftepp, out->value);
742             if (OPTS_FLAG(FTEPP_INDIRECT_EXPANSION) && find && !find->has_params)
743                 ftepp_macro_expand(ftepp, find, NULL, false);
744             else
745                 ftepp_out(ftepp, out->value, false);
746         }
747     }
748 }
749
750 static bool ftepp_preprocess(ftepp_t *ftepp);
751 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
752 {
753     char     *buffer       = NULL;
754     char     *old_string   = ftepp->output_string;
755     char     *inner_string;
756     lex_file *old_lexer    = ftepp->lex;
757     size_t    vararg_start = vec_size(macro->params);
758     bool      retval       = true;
759     bool      has_newlines;
760     size_t    varargs;
761
762     size_t    o, pi;
763     lex_file *inlex;
764
765     bool      old_inmacro;
766     bool      strip = false;
767
768     int nextok;
769
770     if (vararg_start < vec_size(params))
771         varargs = vec_size(params) - vararg_start;
772     else
773         varargs = 0;
774
775     /* really ... */
776     if (!vec_size(macro->output))
777         return true;
778
779     ftepp->output_string = NULL;
780     for (o = 0; o < vec_size(macro->output); ++o) {
781         pptoken *out = macro->output[o];
782         switch (out->token) {
783             case TOKEN_VA_ARGS:
784                 if (!macro->variadic) {
785                     ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
786                     vec_free(old_string);
787                     return false;
788                 }
789                 if (!varargs)
790                     break;
791
792                 pi = 0;
793                 ftepp_param_out(ftepp, &params[pi + vararg_start]);
794                 for (++pi; pi < varargs; ++pi) {
795                     ftepp_out(ftepp, ", ", false);
796                     ftepp_param_out(ftepp, &params[pi + vararg_start]);
797                 }
798                 break;
799
800             case TOKEN_VA_ARGS_ARRAY:
801                 if ((size_t)out->constval.i >= varargs) {
802                     ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
803                     vec_free(old_string);
804                     return false;
805                 }
806
807                 ftepp_param_out(ftepp, &params[out->constval.i + vararg_start]);
808                 break;
809
810             case TOKEN_VA_COUNT:
811                 util_asprintf(&buffer, "%d", varargs);
812                 ftepp_out(ftepp, buffer, false);
813                 mem_d(buffer);
814                 break;
815
816             case TOKEN_IDENT:
817             case TOKEN_TYPENAME:
818             case TOKEN_KEYWORD:
819                 if (!macro_params_find(macro, out->value, &pi)) {
820                     ftepp_out(ftepp, out->value, false);
821                     break;
822                 } else
823                     ftepp_param_out(ftepp, &params[pi]);
824                 break;
825             case '#':
826                 if (o + 1 < vec_size(macro->output)) {
827                     nextok = macro->output[o+1]->token;
828                     if (nextok == '#') {
829                         /* raw concatenation */
830                         ++o;
831                         strip = true;
832                         break;
833                     }
834                     if ( (nextok == TOKEN_IDENT    ||
835                           nextok == TOKEN_KEYWORD  ||
836                           nextok == TOKEN_TYPENAME) &&
837                         macro_params_find(macro, macro->output[o+1]->value, &pi))
838                     {
839                         ++o;
840
841                         ftepp_stringify(ftepp, &params[pi]);
842                         break;
843                     }
844                 }
845                 ftepp_out(ftepp, "#", false);
846                 break;
847             case TOKEN_EOL:
848                 ftepp_out(ftepp, "\n", false);
849                 break;
850             default:
851                 buffer = out->value;
852                 #define buffer_stripable(X) ((X) == ' ' || (X) == '\t')
853                 if (vec_size(macro->output) > o + 1 && macro->output[o+1]->token == '#' && buffer_stripable(*buffer))
854                     buffer++;
855                 if (strip) {
856                     while (buffer_stripable(*buffer)) buffer++;
857                     strip = false;
858                 }
859                 ftepp_out(ftepp, buffer, false);
860                 break;
861         }
862     }
863     vec_push(ftepp->output_string, 0);
864     /* Now run the preprocessor recursively on this string buffer */
865     /*
866     printf("__________\n%s\n=========\n", ftepp->output_string);
867     */
868     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
869     if (!inlex) {
870         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
871         retval = false;
872         goto cleanup;
873     }
874
875     inlex->line  = ftepp->lex->line;
876     inlex->sline = ftepp->lex->sline;
877     ftepp->lex   = inlex;
878
879     old_inmacro     = ftepp->in_macro;
880     ftepp->in_macro = true;
881     ftepp->output_string = NULL;
882     if (!ftepp_preprocess(ftepp)) {
883         ftepp->in_macro = old_inmacro;
884         vec_free(ftepp->lex->open_string);
885         vec_free(ftepp->output_string);
886         lex_close(ftepp->lex);
887         retval = false;
888         goto cleanup;
889     }
890     ftepp->in_macro = old_inmacro;
891     vec_free(ftepp->lex->open_string);
892     lex_close(ftepp->lex);
893
894     inner_string = ftepp->output_string;
895     ftepp->output_string = old_string;
896
897     has_newlines = (strchr(inner_string, '\n') != NULL);
898
899     if (has_newlines && !old_inmacro)
900         ftepp_recursion_header(ftepp);
901
902     vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
903     vec_free(inner_string);
904
905     if (has_newlines && !old_inmacro)
906         ftepp_recursion_footer(ftepp);
907
908     if (resetline && !ftepp->in_macro) {
909         char lineno[128];
910         util_snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
911         ftepp_out(ftepp, lineno, false);
912     }
913
914     old_string = ftepp->output_string;
915 cleanup:
916     ftepp->lex           = old_lexer;
917     ftepp->output_string = old_string;
918     return retval;
919 }
920
921 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
922 {
923     size_t     o;
924     macroparam *params = NULL;
925     bool        retval = true;
926     size_t      paramline;
927
928     if (!macro->has_params) {
929         if (!ftepp_macro_expand(ftepp, macro, NULL, false))
930             return false;
931         ftepp_next(ftepp);
932         return true;
933     }
934     ftepp_next(ftepp);
935
936     if (!ftepp_skipallwhite(ftepp))
937         return false;
938
939     if (ftepp->token != '(') {
940         ftepp_error(ftepp, "expected macro parameters in parenthesis");
941         return false;
942     }
943
944     ftepp_next(ftepp);
945     paramline = ftepp->lex->sline;
946     if (!ftepp_macro_call_params(ftepp, &params))
947         return false;
948
949     if ( vec_size(params) < vec_size(macro->params) ||
950         (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
951     {
952         ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
953                     (macro->variadic ? " at least" : ""),
954                     (unsigned int)vec_size(macro->params),
955                     (unsigned int)vec_size(params));
956         retval = false;
957         goto cleanup;
958     }
959
960     if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
961         retval = false;
962     ftepp_next(ftepp);
963
964 cleanup:
965     for (o = 0; o < vec_size(params); ++o)
966         macroparam_clean(&params[o]);
967     vec_free(params);
968     return retval;
969 }
970
971 /**
972  * #if - the FTEQCC way:
973  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
974  *    <numbers>    => True if the number is not 0
975  *    !<factor>    => True if the factor yields false
976  *    !!<factor>   => ERROR on 2 or more unary nots
977  *    <macro>      => becomes the macro's FIRST token regardless of parameters
978  *    <e> && <e>   => True if both expressions are true
979  *    <e> || <e>   => True if either expression is true
980  *    <string>     => False
981  *    <ident>      => False (remember for macros the <macro> rule applies instead)
982  * Unary + and - are weird and wrong in fteqcc so we don't allow them
983  * parenthesis in expressions are allowed
984  * parameter lists on macros are errors
985  * No mathematical calculations are executed
986  */
987 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
988 static bool ftepp_if_op(ftepp_t *ftepp)
989 {
990     ftepp->lex->flags.noops = false;
991     ftepp_next(ftepp);
992     if (!ftepp_skipspace(ftepp))
993         return false;
994     ftepp->lex->flags.noops = true;
995     return true;
996 }
997 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
998 {
999     ppmacro *macro;
1000     bool     wasnot = false;
1001     bool     wasneg = false;
1002
1003     if (!ftepp_skipspace(ftepp))
1004         return false;
1005
1006     while (ftepp->token == '!') {
1007         wasnot = true;
1008         ftepp_next(ftepp);
1009         if (!ftepp_skipspace(ftepp))
1010             return false;
1011     }
1012
1013     if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
1014     {
1015         wasneg = true;
1016         ftepp_next(ftepp);
1017         if (!ftepp_skipspace(ftepp))
1018             return false;
1019     }
1020
1021     switch (ftepp->token) {
1022         case TOKEN_IDENT:
1023         case TOKEN_TYPENAME:
1024         case TOKEN_KEYWORD:
1025             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
1026                 ftepp_next(ftepp);
1027                 if (!ftepp_skipspace(ftepp))
1028                     return false;
1029                 if (ftepp->token != '(') {
1030                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
1031                     return false;
1032                 }
1033                 ftepp_next(ftepp);
1034                 if (!ftepp_skipspace(ftepp))
1035                     return false;
1036                 if (ftepp->token != TOKEN_IDENT &&
1037                     ftepp->token != TOKEN_TYPENAME &&
1038                     ftepp->token != TOKEN_KEYWORD)
1039                 {
1040                     ftepp_error(ftepp, "defined() used on an unexpected token type");
1041                     return false;
1042                 }
1043                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1044                 *out = !!macro;
1045                 ftepp_next(ftepp);
1046                 if (!ftepp_skipspace(ftepp))
1047                     return false;
1048                 if (ftepp->token != ')') {
1049                     ftepp_error(ftepp, "expected closing paren");
1050                     return false;
1051                 }
1052                 break;
1053             }
1054
1055             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1056             if (!macro || !vec_size(macro->output)) {
1057                 *out = false;
1058                 *value_out = 0;
1059             } else {
1060                 /* This does not expand recursively! */
1061                 switch (macro->output[0]->token) {
1062                     case TOKEN_INTCONST:
1063                         *value_out = macro->output[0]->constval.i;
1064                         *out = !!(macro->output[0]->constval.i);
1065                         break;
1066                     case TOKEN_FLOATCONST:
1067                         *value_out = macro->output[0]->constval.f;
1068                         *out = !!(macro->output[0]->constval.f);
1069                         break;
1070                     default:
1071                         *out = false;
1072                         break;
1073                 }
1074             }
1075             break;
1076         case TOKEN_STRINGCONST:
1077             *value_out = 0;
1078             *out = false;
1079             break;
1080         case TOKEN_INTCONST:
1081             *value_out = ftepp->lex->tok.constval.i;
1082             *out = !!(ftepp->lex->tok.constval.i);
1083             break;
1084         case TOKEN_FLOATCONST:
1085             *value_out = ftepp->lex->tok.constval.f;
1086             *out = !!(ftepp->lex->tok.constval.f);
1087             break;
1088
1089         case '(':
1090             ftepp_next(ftepp);
1091             if (!ftepp_if_expr(ftepp, out, value_out))
1092                 return false;
1093             if (ftepp->token != ')') {
1094                 ftepp_error(ftepp, "expected closing paren in #if expression");
1095                 return false;
1096             }
1097             break;
1098
1099         default:
1100             ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1101             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1102                 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1103             return false;
1104     }
1105     if (wasneg)
1106         *value_out = -*value_out;
1107     if (wasnot) {
1108         *out = !*out;
1109         *value_out = (*out ? 1 : 0);
1110     }
1111     return true;
1112 }
1113
1114 /*
1115 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1116 {
1117     if (!ftepp_next(ftepp))
1118         return false;
1119     return ftepp_if_value(ftepp, out, value_out);
1120 }
1121 */
1122
1123 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1124 {
1125     if (!ftepp_if_value(ftepp, out, value_out))
1126         return false;
1127
1128     if (!ftepp_if_op(ftepp))
1129         return false;
1130
1131     if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1132         return true;
1133
1134     /* FTEQCC is all right-associative and no precedence here */
1135     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1136         !strcmp(ftepp_tokval(ftepp), "||"))
1137     {
1138         bool next = false;
1139         char opc  = ftepp_tokval(ftepp)[0];
1140         double nextvalue;
1141
1142         (void)nextvalue;
1143         if (!ftepp_next(ftepp))
1144             return false;
1145         if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1146             return false;
1147
1148         if (opc == '&')
1149             *out = *out && next;
1150         else
1151             *out = *out || next;
1152
1153         *value_out = (*out ? 1 : 0);
1154         return true;
1155     }
1156     else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1157              !strcmp(ftepp_tokval(ftepp), "!=") ||
1158              !strcmp(ftepp_tokval(ftepp), ">=") ||
1159              !strcmp(ftepp_tokval(ftepp), "<=") ||
1160              !strcmp(ftepp_tokval(ftepp), ">") ||
1161              !strcmp(ftepp_tokval(ftepp), "<"))
1162     {
1163         bool next = false;
1164         const char opc0 = ftepp_tokval(ftepp)[0];
1165         const char opc1 = ftepp_tokval(ftepp)[1];
1166         double other;
1167
1168         if (!ftepp_next(ftepp))
1169             return false;
1170         if (!ftepp_if_expr(ftepp, &next, &other))
1171             return false;
1172
1173         if (opc0 == '=')
1174             *out = (*value_out == other);
1175         else if (opc0 == '!')
1176             *out = (*value_out != other);
1177         else if (opc0 == '>') {
1178             if (opc1 == '=') *out = (*value_out >= other);
1179             else             *out = (*value_out > other);
1180         }
1181         else if (opc0 == '<') {
1182             if (opc1 == '=') *out = (*value_out <= other);
1183             else             *out = (*value_out < other);
1184         }
1185         *value_out = (*out ? 1 : 0);
1186
1187         return true;
1188     }
1189     else {
1190         ftepp_error(ftepp, "junk after #if");
1191         return false;
1192     }
1193 }
1194
1195 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1196 {
1197     bool result = false;
1198     double dummy = 0;
1199
1200     memset(cond, 0, sizeof(*cond));
1201     (void)ftepp_next(ftepp);
1202
1203     if (!ftepp_skipspace(ftepp))
1204         return false;
1205     if (ftepp->token == TOKEN_EOL) {
1206         ftepp_error(ftepp, "expected expression for #if-directive");
1207         return false;
1208     }
1209
1210     if (!ftepp_if_expr(ftepp, &result, &dummy))
1211         return false;
1212
1213     cond->on = result;
1214     return true;
1215 }
1216
1217 /**
1218  * ifdef is rather simple
1219  */
1220 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1221 {
1222     ppmacro *macro;
1223     memset(cond, 0, sizeof(*cond));
1224     (void)ftepp_next(ftepp);
1225     if (!ftepp_skipspace(ftepp))
1226         return false;
1227
1228     switch (ftepp->token) {
1229         case TOKEN_IDENT:
1230         case TOKEN_TYPENAME:
1231         case TOKEN_KEYWORD:
1232             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1233             break;
1234         default:
1235             ftepp_error(ftepp, "expected macro name");
1236             return false;
1237     }
1238
1239     (void)ftepp_next(ftepp);
1240     if (!ftepp_skipspace(ftepp))
1241         return false;
1242     /* relaxing this condition
1243     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1244         ftepp_error(ftepp, "stray tokens after #ifdef");
1245         return false;
1246     }
1247     */
1248     cond->on = !!macro;
1249     return true;
1250 }
1251
1252 /**
1253  * undef is also simple
1254  */
1255 static bool ftepp_undef(ftepp_t *ftepp)
1256 {
1257     (void)ftepp_next(ftepp);
1258     if (!ftepp_skipspace(ftepp))
1259         return false;
1260
1261     if (ftepp->output_on) {
1262         switch (ftepp->token) {
1263             case TOKEN_IDENT:
1264             case TOKEN_TYPENAME:
1265             case TOKEN_KEYWORD:
1266                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1267                 break;
1268             default:
1269                 ftepp_error(ftepp, "expected macro name");
1270                 return false;
1271         }
1272     }
1273
1274     (void)ftepp_next(ftepp);
1275     if (!ftepp_skipspace(ftepp))
1276         return false;
1277     /* relaxing this condition
1278     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1279         ftepp_error(ftepp, "stray tokens after #ifdef");
1280         return false;
1281     }
1282     */
1283     return true;
1284 }
1285
1286 /* Special unescape-string function which skips a leading quote
1287  * and stops at a quote, not just at \0
1288  */
1289 static void unescape(const char *str, char *out) {
1290     ++str;
1291     while (*str && *str != '"') {
1292         if (*str == '\\') {
1293             ++str;
1294             switch (*str) {
1295                 case '\\': *out++ = *str; break;
1296                 case '"':  *out++ = *str; break;
1297                 case 'a':  *out++ = '\a'; break;
1298                 case 'b':  *out++ = '\b'; break;
1299                 case 'r':  *out++ = '\r'; break;
1300                 case 'n':  *out++ = '\n'; break;
1301                 case 't':  *out++ = '\t'; break;
1302                 case 'f':  *out++ = '\f'; break;
1303                 case 'v':  *out++ = '\v'; break;
1304                 default:
1305                     *out++ = '\\';
1306                     *out++ = *str;
1307                     break;
1308             }
1309             ++str;
1310             continue;
1311         }
1312
1313         *out++ = *str++;
1314     }
1315     *out = 0;
1316 }
1317
1318 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1319 {
1320     FILE *fp;
1321     char       *filename = NULL;
1322     const char *last_slash;
1323     size_t      len;
1324
1325     if (!pathfile)
1326         return NULL;
1327
1328     last_slash = strrchr(pathfile, '/');
1329
1330     if (last_slash) {
1331         len = last_slash - pathfile;
1332         memcpy(vec_add(filename, len), pathfile, len);
1333         vec_push(filename, '/');
1334     }
1335
1336     len = strlen(file);
1337     memcpy(vec_add(filename, len+1), file, len);
1338     vec_last(filename) = 0;
1339
1340     fp = fopen(filename, "rb");
1341     if (fp) {
1342         fclose(fp);
1343         return filename;
1344     }
1345     vec_free(filename);
1346     return NULL;
1347 }
1348
1349 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1350 {
1351     char *filename = NULL;
1352
1353     filename = ftepp_include_find_path(file, ftepp->includename);
1354     if (!filename)
1355         filename = ftepp_include_find_path(file, ftepp->itemname);
1356     return filename;
1357 }
1358
1359 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1360     char *message = NULL;
1361
1362     if (!ftepp_skipspace(ftepp))
1363         return false;
1364
1365     /* handle the odd non string constant case so it works like C */
1366     if (ftepp->token != TOKEN_STRINGCONST) {
1367         bool  store   = false;
1368         vec_append(message, 8, "#warning");
1369         ftepp_next(ftepp);
1370         while (ftepp->token != TOKEN_EOL) {
1371             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1372             ftepp_next(ftepp);
1373         }
1374         vec_push(message, '\0');
1375         if (ftepp->output_on)
1376             store = ftepp_warn(ftepp, WARN_CPP, message);
1377         else
1378             store = false;
1379         vec_free(message);
1380         return store;
1381     }
1382
1383     if (!ftepp->output_on)
1384         return false;
1385
1386     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1387     return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1388 }
1389
1390 static void ftepp_directive_error(ftepp_t *ftepp) {
1391     char *message = NULL;
1392
1393     if (!ftepp_skipspace(ftepp))
1394         return;
1395
1396     /* handle the odd non string constant case so it works like C */
1397     if (ftepp->token != TOKEN_STRINGCONST) {
1398         vec_append(message, 6, "#error");
1399         ftepp_next(ftepp);
1400         while (ftepp->token != TOKEN_EOL) {
1401             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1402             ftepp_next(ftepp);
1403         }
1404         vec_push(message, '\0');
1405         if (ftepp->output_on)
1406             ftepp_error(ftepp, message);
1407         vec_free(message);
1408         return;
1409     }
1410
1411     if (!ftepp->output_on)
1412         return;
1413
1414     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1415     ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1416 }
1417
1418 static void ftepp_directive_message(ftepp_t *ftepp) {
1419     char *message = NULL;
1420
1421     if (!ftepp_skipspace(ftepp))
1422         return;
1423
1424     /* handle the odd non string constant case so it works like C */
1425     if (ftepp->token != TOKEN_STRINGCONST) {
1426         vec_append(message, 8, "#message");
1427         ftepp_next(ftepp);
1428         while (ftepp->token != TOKEN_EOL) {
1429             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1430             ftepp_next(ftepp);
1431         }
1432         vec_push(message, '\0');
1433         if (ftepp->output_on)
1434             con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1435         vec_free(message);
1436         return;
1437     }
1438
1439     if (!ftepp->output_on)
1440         return;
1441
1442     unescape     (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1443     con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message",  ftepp_tokval(ftepp));
1444 }
1445
1446 /**
1447  * Include a file.
1448  * FIXME: do we need/want a -I option?
1449  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1450  */
1451 static bool ftepp_include(ftepp_t *ftepp)
1452 {
1453     lex_file *old_lexer = ftepp->lex;
1454     lex_file *inlex;
1455     lex_ctx_t ctx;
1456     char     lineno[128];
1457     char     *filename;
1458     char     *parsename = NULL;
1459     char     *old_includename;
1460
1461     (void)ftepp_next(ftepp);
1462     if (!ftepp_skipspace(ftepp))
1463         return false;
1464
1465     if (ftepp->token != TOKEN_STRINGCONST) {
1466         ppmacro *macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1467         if (macro) {
1468             char *backup = ftepp->output_string;
1469             ftepp->output_string = NULL;
1470             if (ftepp_macro_expand(ftepp, macro, NULL, true)) {
1471                 parsename = util_strdup(ftepp->output_string);
1472                 vec_free(ftepp->output_string);
1473                 ftepp->output_string = backup;
1474             } else {
1475                 ftepp->output_string = backup;
1476                 ftepp_error(ftepp, "expected filename to include");
1477                 return false;
1478             }
1479         } else if (OPTS_FLAG(FTEPP_PREDEFS)) {
1480             /* Well it could be a predefine like __LINE__ */
1481             char *(*predef)(ftepp_t*) = ftepp_predef(ftepp_tokval(ftepp));
1482             if (predef) {
1483                 parsename = predef(ftepp);
1484             } else {
1485                 ftepp_error(ftepp, "expected filename to include");
1486                 return false;
1487             }
1488         }
1489     }
1490
1491     if (!ftepp->output_on) {
1492         (void)ftepp_next(ftepp);
1493         return true;
1494     }
1495
1496     if (parsename)
1497         unescape(parsename, parsename);
1498     else {
1499         char *tokval = ftepp_tokval(ftepp);
1500         unescape(tokval, tokval);
1501         parsename = util_strdup(tokval);
1502     }
1503
1504     ctx = ftepp_ctx(ftepp);
1505     ftepp_out(ftepp, "\n#pragma file(", false);
1506     ftepp_out(ftepp, parsename, false);
1507     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1508
1509     filename = ftepp_include_find(ftepp, parsename);
1510     if (!filename) {
1511         ftepp_error(ftepp, "failed to open include file `%s`", parsename);
1512         mem_d(parsename);
1513         return false;
1514     }
1515     mem_d(parsename);
1516     inlex = lex_open(filename);
1517     if (!inlex) {
1518         ftepp_error(ftepp, "open failed on include file `%s`", filename);
1519         vec_free(filename);
1520         return false;
1521     }
1522     ftepp->lex = inlex;
1523     old_includename = ftepp->includename;
1524     ftepp->includename = filename;
1525     if (!ftepp_preprocess(ftepp)) {
1526         vec_free(ftepp->includename);
1527         ftepp->includename = old_includename;
1528         lex_close(ftepp->lex);
1529         ftepp->lex = old_lexer;
1530         return false;
1531     }
1532     vec_free(ftepp->includename);
1533     ftepp->includename = old_includename;
1534     lex_close(ftepp->lex);
1535     ftepp->lex = old_lexer;
1536
1537     ftepp_out(ftepp, "\n#pragma file(", false);
1538     ftepp_out(ftepp, ctx.file, false);
1539     util_snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1540     ftepp_out(ftepp, lineno, false);
1541
1542     /* skip the line */
1543     (void)ftepp_next(ftepp);
1544     if (!ftepp_skipspace(ftepp))
1545         return false;
1546     if (ftepp->token != TOKEN_EOL) {
1547         ftepp_error(ftepp, "stray tokens after #include");
1548         return false;
1549     }
1550     (void)ftepp_next(ftepp);
1551
1552     return true;
1553 }
1554
1555 /* Basic structure handlers */
1556 static bool ftepp_else_allowed(ftepp_t *ftepp)
1557 {
1558     if (!vec_size(ftepp->conditions)) {
1559         ftepp_error(ftepp, "#else without #if");
1560         return false;
1561     }
1562     if (vec_last(ftepp->conditions).had_else) {
1563         ftepp_error(ftepp, "multiple #else for a single #if");
1564         return false;
1565     }
1566     return true;
1567 }
1568
1569 static GMQCC_INLINE void ftepp_inmacro(ftepp_t *ftepp, const char *hash) {
1570     if (ftepp->in_macro)
1571         (void)!ftepp_warn(ftepp, WARN_DIRECTIVE_INMACRO, "`#%s` directive in macro", hash);
1572 }
1573
1574 static bool ftepp_hash(ftepp_t *ftepp)
1575 {
1576     ppcondition cond;
1577     ppcondition *pc;
1578
1579     lex_ctx_t ctx = ftepp_ctx(ftepp);
1580
1581     if (!ftepp_skipspace(ftepp))
1582         return false;
1583
1584     switch (ftepp->token) {
1585         case TOKEN_KEYWORD:
1586         case TOKEN_IDENT:
1587         case TOKEN_TYPENAME:
1588             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1589                 ftepp_inmacro(ftepp, "define");
1590                 return ftepp_define(ftepp);
1591             }
1592             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1593                 ftepp_inmacro(ftepp, "undef");
1594                 return ftepp_undef(ftepp);
1595             }
1596             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1597                 ftepp_inmacro(ftepp, "ifdef");
1598                 if (!ftepp_ifdef(ftepp, &cond))
1599                     return false;
1600                 cond.was_on = cond.on;
1601                 vec_push(ftepp->conditions, cond);
1602                 ftepp->output_on = ftepp->output_on && cond.on;
1603                 break;
1604             }
1605             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1606                 ftepp_inmacro(ftepp, "ifndef");
1607                 if (!ftepp_ifdef(ftepp, &cond))
1608                     return false;
1609                 cond.on = !cond.on;
1610                 cond.was_on = cond.on;
1611                 vec_push(ftepp->conditions, cond);
1612                 ftepp->output_on = ftepp->output_on && cond.on;
1613                 break;
1614             }
1615             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1616                 ftepp_inmacro(ftepp, "elifdef");
1617                 if (!ftepp_else_allowed(ftepp))
1618                     return false;
1619                 if (!ftepp_ifdef(ftepp, &cond))
1620                     return false;
1621                 pc = &vec_last(ftepp->conditions);
1622                 pc->on     = !pc->was_on && cond.on;
1623                 pc->was_on = pc->was_on || pc->on;
1624                 ftepp_update_output_condition(ftepp);
1625                 break;
1626             }
1627             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1628                 ftepp_inmacro(ftepp, "elifndef");
1629                 if (!ftepp_else_allowed(ftepp))
1630                     return false;
1631                 if (!ftepp_ifdef(ftepp, &cond))
1632                     return false;
1633                 cond.on = !cond.on;
1634                 pc = &vec_last(ftepp->conditions);
1635                 pc->on     = !pc->was_on && cond.on;
1636                 pc->was_on = pc->was_on || pc->on;
1637                 ftepp_update_output_condition(ftepp);
1638                 break;
1639             }
1640             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1641                 ftepp_inmacro(ftepp, "elif");
1642                 if (!ftepp_else_allowed(ftepp))
1643                     return false;
1644                 if (!ftepp_if(ftepp, &cond))
1645                     return false;
1646                 pc = &vec_last(ftepp->conditions);
1647                 pc->on     = !pc->was_on && cond.on;
1648                 pc->was_on = pc->was_on  || pc->on;
1649                 ftepp_update_output_condition(ftepp);
1650                 break;
1651             }
1652             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1653                 ftepp_inmacro(ftepp, "if");
1654                 if (!ftepp_if(ftepp, &cond))
1655                     return false;
1656                 cond.was_on = cond.on;
1657                 vec_push(ftepp->conditions, cond);
1658                 ftepp->output_on = ftepp->output_on && cond.on;
1659                 break;
1660             }
1661             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1662                 ftepp_inmacro(ftepp, "else");
1663                 if (!ftepp_else_allowed(ftepp))
1664                     return false;
1665                 pc = &vec_last(ftepp->conditions);
1666                 pc->on = !pc->was_on;
1667                 pc->had_else = true;
1668                 ftepp_next(ftepp);
1669                 ftepp_update_output_condition(ftepp);
1670                 break;
1671             }
1672             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1673                 ftepp_inmacro(ftepp, "endif");
1674                 if (!vec_size(ftepp->conditions)) {
1675                     ftepp_error(ftepp, "#endif without #if");
1676                     return false;
1677                 }
1678                 vec_pop(ftepp->conditions);
1679                 ftepp_next(ftepp);
1680                 ftepp_update_output_condition(ftepp);
1681                 break;
1682             }
1683             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1684                 ftepp_inmacro(ftepp, "include");
1685                 return ftepp_include(ftepp);
1686             }
1687             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1688                 ftepp_out(ftepp, "#", false);
1689                 break;
1690             }
1691             else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1692                 ftepp_directive_warning(ftepp);
1693                 break;
1694             }
1695             else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1696                 ftepp_directive_error(ftepp);
1697                 break;
1698             }
1699             else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1700                 ftepp_directive_message(ftepp);
1701                 break;
1702             }
1703             else {
1704                 if (ftepp->output_on) {
1705                     ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1706                     return false;
1707                 } else {
1708                     ftepp_next(ftepp);
1709                     break;
1710                 }
1711             }
1712             /* break; never reached */
1713         default:
1714             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1715             return false;
1716         case TOKEN_EOL:
1717             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1718             return false;
1719         case TOKEN_EOF:
1720             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1721             return false;
1722
1723         /* Builtins! Don't forget the builtins! */
1724         case TOKEN_INTCONST:
1725         case TOKEN_FLOATCONST:
1726             ftepp_out(ftepp, "#", false);
1727             return true;
1728     }
1729     if (!ftepp_skipspace(ftepp))
1730         return false;
1731     return true;
1732 }
1733
1734 static bool ftepp_preprocess(ftepp_t *ftepp)
1735 {
1736     ppmacro *macro;
1737     bool     newline = true;
1738
1739     /* predef stuff */
1740     char    *expand  = NULL;
1741
1742     ftepp->lex->flags.preprocessing = true;
1743     ftepp->lex->flags.mergelines    = false;
1744     ftepp->lex->flags.noops         = true;
1745
1746     ftepp_next(ftepp);
1747     do
1748     {
1749         if (ftepp->token >= TOKEN_EOF)
1750             break;
1751         switch (ftepp->token) {
1752             case TOKEN_KEYWORD:
1753             case TOKEN_IDENT:
1754             case TOKEN_TYPENAME:
1755                 /* is it a predef? */
1756                 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1757                     char *(*predef)(ftepp_t*) = ftepp_predef(ftepp_tokval(ftepp));
1758                     if (predef) {
1759                         expand = predef(ftepp);
1760                         ftepp_out (ftepp, expand, false);
1761                         ftepp_next(ftepp);
1762
1763                         mem_d(expand);
1764                         break;
1765                     }
1766                 }
1767
1768                 if (ftepp->output_on)
1769                     macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1770                 else
1771                     macro = NULL;
1772
1773                 if (!macro) {
1774                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1775                     ftepp_next(ftepp);
1776                     break;
1777                 }
1778                 if (!ftepp_macro_call(ftepp, macro))
1779                     ftepp->token = TOKEN_ERROR;
1780                 break;
1781             case '#':
1782                 if (!newline) {
1783                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1784                     ftepp_next(ftepp);
1785                     break;
1786                 }
1787                 ftepp->lex->flags.mergelines = true;
1788                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1789                     ftepp_error(ftepp, "error in preprocessor directive");
1790                     ftepp->token = TOKEN_ERROR;
1791                     break;
1792                 }
1793                 if (!ftepp_hash(ftepp))
1794                     ftepp->token = TOKEN_ERROR;
1795                 ftepp->lex->flags.mergelines = false;
1796                 break;
1797             case TOKEN_EOL:
1798                 newline = true;
1799                 ftepp_out(ftepp, "\n", true);
1800                 ftepp_next(ftepp);
1801                 break;
1802             case TOKEN_WHITE:
1803                 /* same as default but don't set newline=false */
1804                 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1805                 ftepp_next(ftepp);
1806                 break;
1807             default:
1808                 newline = false;
1809                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1810                 ftepp_next(ftepp);
1811                 break;
1812         }
1813     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1814
1815     /* force a 0 at the end but don't count it as added to the output */
1816     vec_push(ftepp->output_string, 0);
1817     vec_shrinkby(ftepp->output_string, 1);
1818
1819     return (ftepp->token == TOKEN_EOF);
1820 }
1821
1822 /* Like in parser.c - files keep the previous state so we have one global
1823  * preprocessor. Except here we will want to warn about dangling #ifs.
1824  */
1825 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1826 {
1827     bool retval = true;
1828     if (vec_size(ftepp->conditions)) {
1829         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1830             retval = false;
1831     }
1832     lex_close(ftepp->lex);
1833     ftepp->lex = NULL;
1834     if (ftepp->itemname) {
1835         mem_d(ftepp->itemname);
1836         ftepp->itemname = NULL;
1837     }
1838     return retval;
1839 }
1840
1841 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1842 {
1843     ftepp->lex = lex_open(filename);
1844     ftepp->itemname = util_strdup(filename);
1845     if (!ftepp->lex) {
1846         con_out("failed to open file \"%s\"\n", filename);
1847         return false;
1848     }
1849     if (!ftepp_preprocess(ftepp))
1850         return false;
1851     return ftepp_preprocess_done(ftepp);
1852 }
1853
1854 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1855 {
1856     ftepp->lex = lex_open_string(str, strlen(str), name);
1857     ftepp->itemname = util_strdup(name);
1858     if (!ftepp->lex) {
1859         con_out("failed to create lexer for string \"%s\"\n", name);
1860         return false;
1861     }
1862     if (!ftepp_preprocess(ftepp))
1863         return false;
1864     return ftepp_preprocess_done(ftepp);
1865 }
1866
1867
1868 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1869     char *create = NULL;
1870
1871     /* use saner path for empty macros */
1872     if (!value) {
1873         ftepp_add_define(ftepp, "__builtin__", name);
1874         return;
1875     }
1876
1877     vec_append(create, 8,           "#define ");
1878     vec_append(create, strlen(name), name);
1879     vec_push  (create, ' ');
1880     vec_append(create, strlen(value), value);
1881     vec_push  (create, 0);
1882
1883     ftepp_preprocess_string(ftepp, "__builtin__", create);
1884     vec_free  (create);
1885 }
1886
1887 ftepp_t *ftepp_create()
1888 {
1889     ftepp_t *ftepp;
1890     char minor[32];
1891     char major[32];
1892     size_t i;
1893
1894     ftepp = ftepp_new();
1895     if (!ftepp)
1896         return NULL;
1897
1898     memset(minor, 0, sizeof(minor));
1899     memset(major, 0, sizeof(major));
1900
1901     /* set the right macro based on the selected standard */
1902     ftepp_add_define(ftepp, NULL, "GMQCC");
1903     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1904         ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1905         /* 1.00 */
1906         major[0] = '"';
1907         major[1] = '1';
1908         major[2] = '"';
1909
1910         minor[0] = '"';
1911         minor[1] = '0';
1912         minor[2] = '"';
1913     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1914         ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1915         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1916         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1917     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1918         ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1919         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1920         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1921     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1922         ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1923         /* 1.0 */
1924         major[0] = '"';
1925         major[1] = '1';
1926         major[2] = '"';
1927
1928         minor[0] = '"';
1929         minor[1] = '0';
1930         minor[2] = '"';
1931     }
1932
1933     ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1934     ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1935
1936     /*
1937      * We're going to just make __NULL__ nil, which works for 60% of the
1938      * cases of __NULL_ for fteqcc.
1939      */
1940     ftepp_add_macro(ftepp, "__NULL__", "nil");
1941
1942     /* add all the math constants if they can be */
1943     if (OPTS_FLAG(FTEPP_MATHDEFS)) {
1944         for (i = 0; i < GMQCC_ARRAY_COUNT(ftepp_math_constants); i++)
1945             if (!ftepp_macro_find(ftepp, ftepp_math_constants[i][0]))
1946                 ftepp_add_macro(ftepp, ftepp_math_constants[i][0], ftepp_math_constants[i][1]);
1947     }
1948
1949     return ftepp;
1950 }
1951
1952 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1953 {
1954     ppmacro *macro;
1955     lex_ctx_t ctx = { "__builtin__", 0, 0 };
1956     ctx.file = source;
1957     macro = ppmacro_new(ctx, name);
1958     /*vec_push(ftepp->macros, macro);*/
1959     util_htset(ftepp->macros, name, macro);
1960 }
1961
1962 const char *ftepp_get(ftepp_t *ftepp)
1963 {
1964     return ftepp->output_string;
1965 }
1966
1967 void ftepp_flush(ftepp_t *ftepp)
1968 {
1969     ftepp_flush_do(ftepp);
1970 }
1971
1972 void ftepp_finish(ftepp_t *ftepp)
1973 {
1974     if (!ftepp)
1975         return;
1976     ftepp_delete(ftepp);
1977 }