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