]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Ignore emitting implicit math constants in the preprocessor if they exist.
[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 #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 #if 0
255     if (token->token == TOKEN_WHITE)
256         token->value = util_strdup(" ");
257     else
258 #else
259         token->value = util_strdup(ftepp_tokval(ftepp));
260 #endif
261     memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
262     return token;
263 }
264
265 static GMQCC_INLINE void pptoken_delete(pptoken *self)
266 {
267     mem_d(self->value);
268     mem_d(self);
269 }
270
271 static ppmacro *ppmacro_new(lex_ctx_t ctx, const char *name)
272 {
273     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
274
275     (void)ctx;
276     memset(macro, 0, sizeof(*macro));
277     macro->name = util_strdup(name);
278     return macro;
279 }
280
281 static void ppmacro_delete(ppmacro *self)
282 {
283     size_t i;
284     for (i = 0; i < vec_size(self->params); ++i)
285         mem_d(self->params[i]);
286     vec_free(self->params);
287     for (i = 0; i < vec_size(self->output); ++i)
288         pptoken_delete(self->output[i]);
289     vec_free(self->output);
290     mem_d(self->name);
291     mem_d(self);
292 }
293
294 static ftepp_t* ftepp_new(void)
295 {
296     ftepp_t *ftepp;
297
298     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
299     memset(ftepp, 0, sizeof(*ftepp));
300
301     ftepp->macros          = util_htnew(HT_MACROS);
302     ftepp->output_on       = true;
303     ftepp->predef_countval = 0;
304     ftepp->predef_randval  = 0;
305
306     return ftepp;
307 }
308
309 static GMQCC_INLINE void ftepp_flush_do(ftepp_t *self)
310 {
311     vec_free(self->output_string);
312 }
313
314 static void ftepp_delete(ftepp_t *self)
315 {
316     ftepp_flush_do(self);
317     if (self->itemname)
318         mem_d(self->itemname);
319     if (self->includename)
320         vec_free(self->includename);
321
322     util_htrem(self->macros, (void (*)(void*))&ppmacro_delete);
323
324     vec_free(self->conditions);
325     if (self->lex)
326         lex_close(self->lex);
327     mem_d(self);
328 }
329
330 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
331 {
332     if (ignore_cond || ftepp->output_on)
333     {
334         size_t len;
335         char  *data;
336         len = strlen(str);
337         data = vec_add(ftepp->output_string, len);
338         memcpy(data, str, len);
339     }
340 }
341
342 static GMQCC_INLINE void ftepp_update_output_condition(ftepp_t *ftepp)
343 {
344     size_t i;
345     ftepp->output_on = true;
346     for (i = 0; i < vec_size(ftepp->conditions); ++i)
347         ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
348 }
349
350 static GMQCC_INLINE ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
351 {
352     return (ppmacro*)util_htget(ftepp->macros, name);
353 }
354
355 static GMQCC_INLINE void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
356 {
357     util_htrm(ftepp->macros, name, (void (*)(void*))&ppmacro_delete);
358 }
359
360 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
361 {
362     return (ftepp->token = lex_do(ftepp->lex));
363 }
364
365 /* Important: this does not skip newlines! */
366 static bool ftepp_skipspace(ftepp_t *ftepp)
367 {
368     if (ftepp->token != TOKEN_WHITE)
369         return true;
370     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
371     if (ftepp->token >= TOKEN_EOF) {
372         ftepp_error(ftepp, "unexpected end of preprocessor directive");
373         return false;
374     }
375     return true;
376 }
377
378 /* this one skips EOLs as well */
379 static bool ftepp_skipallwhite(ftepp_t *ftepp)
380 {
381     if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
382         return true;
383     do {
384         ftepp_next(ftepp);
385     } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
386     if (ftepp->token >= TOKEN_EOF) {
387         ftepp_error(ftepp, "unexpected end of preprocessor directive");
388         return false;
389     }
390     return true;
391 }
392
393 /**
394  * The huge macro parsing code...
395  */
396 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
397 {
398     do {
399         ftepp_next(ftepp);
400         if (!ftepp_skipspace(ftepp))
401             return false;
402         if (ftepp->token == ')')
403             break;
404         switch (ftepp->token) {
405             case TOKEN_IDENT:
406             case TOKEN_TYPENAME:
407             case TOKEN_KEYWORD:
408                 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
409                 break;
410             case TOKEN_DOTS:
411                 macro->variadic = true;
412                 break;
413             default:
414                 ftepp_error(ftepp, "unexpected token in parameter list");
415                 return false;
416         }
417         ftepp_next(ftepp);
418         if (!ftepp_skipspace(ftepp))
419             return false;
420         if (macro->variadic && ftepp->token != ')') {
421             ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
422             return false;
423         }
424     } while (ftepp->token == ',');
425
426     if (ftepp->token != ')') {
427         ftepp_error(ftepp, "expected closing paren after macro parameter list");
428         return false;
429     }
430     ftepp_next(ftepp);
431     /* skipspace happens in ftepp_define */
432     return true;
433 }
434
435 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
436 {
437     pptoken *ptok;
438     while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
439         bool   subscript = false;
440         size_t index     = 0;
441         if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
442             subscript = !!(ftepp_next(ftepp) == '#');
443
444             if (subscript && ftepp_next(ftepp) != '#') {
445                 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
446                 return false;
447             } else if (subscript) {
448                 if (ftepp_next(ftepp) == '[') {
449                     if (ftepp_next(ftepp) != TOKEN_INTCONST) {
450                         ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
451                         return false;
452                     }
453
454                     index = (int)strtol(ftepp_tokval(ftepp), NULL, 10);
455
456                     if (ftepp_next(ftepp) != ']') {
457                         ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
458                         return false;
459                     }
460
461                     /*
462                      * mark it as an array to be handled later as such and not
463                      * as traditional __VA_ARGS__
464                      */
465                     ftepp->token = TOKEN_VA_ARGS_ARRAY;
466                     ptok = pptoken_make(ftepp);
467                     ptok->constval.i = index;
468                     vec_push(macro->output, ptok);
469                     ftepp_next(ftepp);
470                 } else {
471                     ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
472                     return false;
473                 }
474             } else {
475                 int old = ftepp->token;
476                 ftepp->token = TOKEN_VA_ARGS;
477                 ptok = pptoken_make(ftepp);
478                 vec_push(macro->output, ptok);
479                 ftepp->token = old;
480             }
481         }
482         else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
483             ftepp->token = TOKEN_VA_COUNT;
484             ptok         = pptoken_make(ftepp);
485             vec_push(macro->output, ptok);
486             ftepp_next(ftepp);
487         } else {
488             ptok = pptoken_make(ftepp);
489             vec_push(macro->output, ptok);
490             ftepp_next(ftepp);
491         }
492     }
493     /* recursive expansion can cause EOFs here */
494     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
495         ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
496         return false;
497     }
498     return true;
499 }
500
501 static const char *ftepp_math_constants[][2] = {
502     { "M_E",        "2.7182818284590452354"  }, /* e          */
503     { "M_LOG2E",    "1.4426950408889634074"  }, /* log_2 e    */
504     { "M_LOG10E",   "0.43429448190325182765" }, /* log_10 e   */
505     { "M_LN2",      "0.69314718055994530942" }, /* log_e 2    */
506     { "M_LN10",     "2.30258509299404568402" }, /* log_e 10   */
507     { "M_PI",       "3.14159265358979323846" }, /* pi         */
508     { "M_PI_2",     "1.57079632679489661923" }, /* pi/2       */
509     { "M_PI_4",     "0.78539816339744830962" }, /* pi/4       */
510     { "M_1_PI",     "0.31830988618379067154" }, /* 1/pi       */
511     { "M_2_PI",     "0.63661977236758134308" }, /* 2/pi       */
512     { "M_2_SQRTPI", "1.12837916709551257390" }, /* 2/sqrt(pi) */
513     { "M_SQRT2",    "1.41421356237309504880" }, /* sqrt(2)    */
514     { "M_SQRT1_2",  "0.70710678118654752440" }, /* 1/sqrt(2)  */
515     { "M_TAU",      "6.28318530717958647692" }  /* pi*2       */
516 };
517
518 static bool ftepp_define(ftepp_t *ftepp)
519 {
520     ppmacro *macro = NULL;
521     size_t l = ftepp_ctx(ftepp).line;
522     size_t i;
523     bool   mathconstant = false;
524
525     (void)ftepp_next(ftepp);
526     if (!ftepp_skipspace(ftepp))
527         return false;
528
529     switch (ftepp->token) {
530         case TOKEN_IDENT:
531         case TOKEN_TYPENAME:
532         case TOKEN_KEYWORD:
533             for (i = 0; i < GMQCC_ARRAY_COUNT(ftepp_math_constants); i++) {
534                 if (!strcmp(ftepp_math_constants[i][0], ftepp_tokval(ftepp))) {
535                     mathconstant = true;
536                     break;
537                 }
538             }
539
540             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
541
542             /* ignore creating a math macro if one is already present */
543             if (macro && mathconstant)
544                 break;
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 void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
732 {
733     size_t   i;
734     pptoken *out;
735     for (i = 0; i < vec_size(param->tokens); ++i) {
736         out = param->tokens[i];
737         if (out->token == TOKEN_EOL)
738             ftepp_out(ftepp, "\n", false);
739         else
740             ftepp_out(ftepp, out->value, false);
741     }
742 }
743
744 static bool ftepp_preprocess(ftepp_t *ftepp);
745 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
746 {
747     char     *buffer       = NULL;
748     char     *old_string   = ftepp->output_string;
749     char     *inner_string;
750     lex_file *old_lexer    = ftepp->lex;
751     size_t    vararg_start = vec_size(macro->params);
752     bool      retval       = true;
753     bool      has_newlines;
754     size_t    varargs;
755
756     size_t    o, pi;
757     lex_file *inlex;
758
759     bool      old_inmacro;
760
761     int nextok;
762
763     if (vararg_start < vec_size(params))
764         varargs = vec_size(params) - vararg_start;
765     else
766         varargs = 0;
767
768     /* really ... */
769     if (!vec_size(macro->output))
770         return true;
771
772     ftepp->output_string = NULL;
773     for (o = 0; o < vec_size(macro->output); ++o) {
774         pptoken *out = macro->output[o];
775         switch (out->token) {
776             case TOKEN_VA_ARGS:
777                 if (!macro->variadic) {
778                     ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
779                     vec_free(old_string);
780                     return false;
781                 }
782                 if (!varargs)
783                     break;
784
785                 pi = 0;
786                 ftepp_param_out(ftepp, &params[pi + vararg_start]);
787                 for (++pi; pi < varargs; ++pi) {
788                     ftepp_out(ftepp, ", ", false);
789                     ftepp_param_out(ftepp, &params[pi + vararg_start]);
790                 }
791                 break;
792
793             case TOKEN_VA_ARGS_ARRAY:
794                 if ((size_t)out->constval.i >= varargs) {
795                     ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
796                     vec_free(old_string);
797                     return false;
798                 }
799
800                 ftepp_param_out(ftepp, &params[out->constval.i + vararg_start]);
801                 break;
802
803             case TOKEN_VA_COUNT:
804                 util_asprintf(&buffer, "%d", varargs);
805                 ftepp_out(ftepp, buffer, false);
806                 mem_d(buffer);
807                 break;
808
809             case TOKEN_IDENT:
810             case TOKEN_TYPENAME:
811             case TOKEN_KEYWORD:
812                 if (!macro_params_find(macro, out->value, &pi)) {
813                     ftepp_out(ftepp, out->value, false);
814                     break;
815                 } else
816                     ftepp_param_out(ftepp, &params[pi]);
817                 break;
818             case '#':
819                 if (o + 1 < vec_size(macro->output)) {
820                     nextok = macro->output[o+1]->token;
821                     if (nextok == '#') {
822                         /* raw concatenation */
823                         ++o;
824                         break;
825                     }
826                     if ( (nextok == TOKEN_IDENT    ||
827                           nextok == TOKEN_KEYWORD  ||
828                           nextok == TOKEN_TYPENAME) &&
829                         macro_params_find(macro, macro->output[o+1]->value, &pi))
830                     {
831                         ++o;
832                         ftepp_stringify(ftepp, &params[pi]);
833                         break;
834                     }
835                 }
836                 ftepp_out(ftepp, "#", false);
837                 break;
838             case TOKEN_EOL:
839                 ftepp_out(ftepp, "\n", false);
840                 break;
841             default:
842                 ftepp_out(ftepp, out->value, false);
843                 break;
844         }
845     }
846     vec_push(ftepp->output_string, 0);
847     /* Now run the preprocessor recursively on this string buffer */
848     /*
849     printf("__________\n%s\n=========\n", ftepp->output_string);
850     */
851     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
852     if (!inlex) {
853         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
854         retval = false;
855         goto cleanup;
856     }
857
858     inlex->line  = ftepp->lex->line;
859     inlex->sline = ftepp->lex->sline;
860     ftepp->lex   = inlex;
861
862     old_inmacro     = ftepp->in_macro;
863     ftepp->in_macro = true;
864     ftepp->output_string = NULL;
865     if (!ftepp_preprocess(ftepp)) {
866         ftepp->in_macro = old_inmacro;
867         vec_free(ftepp->lex->open_string);
868         vec_free(ftepp->output_string);
869         lex_close(ftepp->lex);
870         retval = false;
871         goto cleanup;
872     }
873     ftepp->in_macro = old_inmacro;
874     vec_free(ftepp->lex->open_string);
875     lex_close(ftepp->lex);
876
877     inner_string = ftepp->output_string;
878     ftepp->output_string = old_string;
879
880     has_newlines = (strchr(inner_string, '\n') != NULL);
881
882     if (has_newlines && !old_inmacro)
883         ftepp_recursion_header(ftepp);
884
885     vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
886     vec_free(inner_string);
887
888     if (has_newlines && !old_inmacro)
889         ftepp_recursion_footer(ftepp);
890
891     if (resetline && !ftepp->in_macro) {
892         char lineno[128];
893         util_snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
894         ftepp_out(ftepp, lineno, false);
895     }
896
897     old_string = ftepp->output_string;
898 cleanup:
899     ftepp->lex           = old_lexer;
900     ftepp->output_string = old_string;
901     return retval;
902 }
903
904 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
905 {
906     size_t     o;
907     macroparam *params = NULL;
908     bool        retval = true;
909     size_t      paramline;
910
911     if (!macro->has_params) {
912         if (!ftepp_macro_expand(ftepp, macro, NULL, false))
913             return false;
914         ftepp_next(ftepp);
915         return true;
916     }
917     ftepp_next(ftepp);
918
919     if (!ftepp_skipallwhite(ftepp))
920         return false;
921
922     if (ftepp->token != '(') {
923         ftepp_error(ftepp, "expected macro parameters in parenthesis");
924         return false;
925     }
926
927     ftepp_next(ftepp);
928     paramline = ftepp->lex->sline;
929     if (!ftepp_macro_call_params(ftepp, &params))
930         return false;
931
932     if ( vec_size(params) < vec_size(macro->params) ||
933         (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
934     {
935         ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
936                     (macro->variadic ? " at least" : ""),
937                     (unsigned int)vec_size(macro->params),
938                     (unsigned int)vec_size(params));
939         retval = false;
940         goto cleanup;
941     }
942
943     if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
944         retval = false;
945     ftepp_next(ftepp);
946
947 cleanup:
948     for (o = 0; o < vec_size(params); ++o)
949         macroparam_clean(&params[o]);
950     vec_free(params);
951     return retval;
952 }
953
954 /**
955  * #if - the FTEQCC way:
956  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
957  *    <numbers>    => True if the number is not 0
958  *    !<factor>    => True if the factor yields false
959  *    !!<factor>   => ERROR on 2 or more unary nots
960  *    <macro>      => becomes the macro's FIRST token regardless of parameters
961  *    <e> && <e>   => True if both expressions are true
962  *    <e> || <e>   => True if either expression is true
963  *    <string>     => False
964  *    <ident>      => False (remember for macros the <macro> rule applies instead)
965  * Unary + and - are weird and wrong in fteqcc so we don't allow them
966  * parenthesis in expressions are allowed
967  * parameter lists on macros are errors
968  * No mathematical calculations are executed
969  */
970 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
971 static bool ftepp_if_op(ftepp_t *ftepp)
972 {
973     ftepp->lex->flags.noops = false;
974     ftepp_next(ftepp);
975     if (!ftepp_skipspace(ftepp))
976         return false;
977     ftepp->lex->flags.noops = true;
978     return true;
979 }
980 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
981 {
982     ppmacro *macro;
983     bool     wasnot = false;
984     bool     wasneg = false;
985
986     if (!ftepp_skipspace(ftepp))
987         return false;
988
989     while (ftepp->token == '!') {
990         wasnot = true;
991         ftepp_next(ftepp);
992         if (!ftepp_skipspace(ftepp))
993             return false;
994     }
995
996     if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
997     {
998         wasneg = true;
999         ftepp_next(ftepp);
1000         if (!ftepp_skipspace(ftepp))
1001             return false;
1002     }
1003
1004     switch (ftepp->token) {
1005         case TOKEN_IDENT:
1006         case TOKEN_TYPENAME:
1007         case TOKEN_KEYWORD:
1008             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
1009                 ftepp_next(ftepp);
1010                 if (!ftepp_skipspace(ftepp))
1011                     return false;
1012                 if (ftepp->token != '(') {
1013                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
1014                     return false;
1015                 }
1016                 ftepp_next(ftepp);
1017                 if (!ftepp_skipspace(ftepp))
1018                     return false;
1019                 if (ftepp->token != TOKEN_IDENT &&
1020                     ftepp->token != TOKEN_TYPENAME &&
1021                     ftepp->token != TOKEN_KEYWORD)
1022                 {
1023                     ftepp_error(ftepp, "defined() used on an unexpected token type");
1024                     return false;
1025                 }
1026                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1027                 *out = !!macro;
1028                 ftepp_next(ftepp);
1029                 if (!ftepp_skipspace(ftepp))
1030                     return false;
1031                 if (ftepp->token != ')') {
1032                     ftepp_error(ftepp, "expected closing paren");
1033                     return false;
1034                 }
1035                 break;
1036             }
1037
1038             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1039             if (!macro || !vec_size(macro->output)) {
1040                 *out = false;
1041                 *value_out = 0;
1042             } else {
1043                 /* This does not expand recursively! */
1044                 switch (macro->output[0]->token) {
1045                     case TOKEN_INTCONST:
1046                         *value_out = macro->output[0]->constval.i;
1047                         *out = !!(macro->output[0]->constval.i);
1048                         break;
1049                     case TOKEN_FLOATCONST:
1050                         *value_out = macro->output[0]->constval.f;
1051                         *out = !!(macro->output[0]->constval.f);
1052                         break;
1053                     default:
1054                         *out = false;
1055                         break;
1056                 }
1057             }
1058             break;
1059         case TOKEN_STRINGCONST:
1060             *value_out = 0;
1061             *out = false;
1062             break;
1063         case TOKEN_INTCONST:
1064             *value_out = ftepp->lex->tok.constval.i;
1065             *out = !!(ftepp->lex->tok.constval.i);
1066             break;
1067         case TOKEN_FLOATCONST:
1068             *value_out = ftepp->lex->tok.constval.f;
1069             *out = !!(ftepp->lex->tok.constval.f);
1070             break;
1071
1072         case '(':
1073             ftepp_next(ftepp);
1074             if (!ftepp_if_expr(ftepp, out, value_out))
1075                 return false;
1076             if (ftepp->token != ')') {
1077                 ftepp_error(ftepp, "expected closing paren in #if expression");
1078                 return false;
1079             }
1080             break;
1081
1082         default:
1083             ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1084             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1085                 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1086             return false;
1087     }
1088     if (wasneg)
1089         *value_out = -*value_out;
1090     if (wasnot) {
1091         *out = !*out;
1092         *value_out = (*out ? 1 : 0);
1093     }
1094     return true;
1095 }
1096
1097 /*
1098 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1099 {
1100     if (!ftepp_next(ftepp))
1101         return false;
1102     return ftepp_if_value(ftepp, out, value_out);
1103 }
1104 */
1105
1106 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1107 {
1108     if (!ftepp_if_value(ftepp, out, value_out))
1109         return false;
1110
1111     if (!ftepp_if_op(ftepp))
1112         return false;
1113
1114     if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1115         return true;
1116
1117     /* FTEQCC is all right-associative and no precedence here */
1118     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1119         !strcmp(ftepp_tokval(ftepp), "||"))
1120     {
1121         bool next = false;
1122         char opc  = ftepp_tokval(ftepp)[0];
1123         double nextvalue;
1124
1125         (void)nextvalue;
1126         if (!ftepp_next(ftepp))
1127             return false;
1128         if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1129             return false;
1130
1131         if (opc == '&')
1132             *out = *out && next;
1133         else
1134             *out = *out || next;
1135
1136         *value_out = (*out ? 1 : 0);
1137         return true;
1138     }
1139     else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1140              !strcmp(ftepp_tokval(ftepp), "!=") ||
1141              !strcmp(ftepp_tokval(ftepp), ">=") ||
1142              !strcmp(ftepp_tokval(ftepp), "<=") ||
1143              !strcmp(ftepp_tokval(ftepp), ">") ||
1144              !strcmp(ftepp_tokval(ftepp), "<"))
1145     {
1146         bool next = false;
1147         const char opc0 = ftepp_tokval(ftepp)[0];
1148         const char opc1 = ftepp_tokval(ftepp)[1];
1149         double other;
1150
1151         if (!ftepp_next(ftepp))
1152             return false;
1153         if (!ftepp_if_expr(ftepp, &next, &other))
1154             return false;
1155
1156         if (opc0 == '=')
1157             *out = (*value_out == other);
1158         else if (opc0 == '!')
1159             *out = (*value_out != other);
1160         else if (opc0 == '>') {
1161             if (opc1 == '=') *out = (*value_out >= other);
1162             else             *out = (*value_out > other);
1163         }
1164         else if (opc0 == '<') {
1165             if (opc1 == '=') *out = (*value_out <= other);
1166             else             *out = (*value_out < other);
1167         }
1168         *value_out = (*out ? 1 : 0);
1169
1170         return true;
1171     }
1172     else {
1173         ftepp_error(ftepp, "junk after #if");
1174         return false;
1175     }
1176 }
1177
1178 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1179 {
1180     bool result = false;
1181     double dummy = 0;
1182
1183     memset(cond, 0, sizeof(*cond));
1184     (void)ftepp_next(ftepp);
1185
1186     if (!ftepp_skipspace(ftepp))
1187         return false;
1188     if (ftepp->token == TOKEN_EOL) {
1189         ftepp_error(ftepp, "expected expression for #if-directive");
1190         return false;
1191     }
1192
1193     if (!ftepp_if_expr(ftepp, &result, &dummy))
1194         return false;
1195
1196     cond->on = result;
1197     return true;
1198 }
1199
1200 /**
1201  * ifdef is rather simple
1202  */
1203 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1204 {
1205     ppmacro *macro;
1206     memset(cond, 0, sizeof(*cond));
1207     (void)ftepp_next(ftepp);
1208     if (!ftepp_skipspace(ftepp))
1209         return false;
1210
1211     switch (ftepp->token) {
1212         case TOKEN_IDENT:
1213         case TOKEN_TYPENAME:
1214         case TOKEN_KEYWORD:
1215             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1216             break;
1217         default:
1218             ftepp_error(ftepp, "expected macro name");
1219             return false;
1220     }
1221
1222     (void)ftepp_next(ftepp);
1223     if (!ftepp_skipspace(ftepp))
1224         return false;
1225     /* relaxing this condition
1226     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1227         ftepp_error(ftepp, "stray tokens after #ifdef");
1228         return false;
1229     }
1230     */
1231     cond->on = !!macro;
1232     return true;
1233 }
1234
1235 /**
1236  * undef is also simple
1237  */
1238 static bool ftepp_undef(ftepp_t *ftepp)
1239 {
1240     (void)ftepp_next(ftepp);
1241     if (!ftepp_skipspace(ftepp))
1242         return false;
1243
1244     if (ftepp->output_on) {
1245         switch (ftepp->token) {
1246             case TOKEN_IDENT:
1247             case TOKEN_TYPENAME:
1248             case TOKEN_KEYWORD:
1249                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1250                 break;
1251             default:
1252                 ftepp_error(ftepp, "expected macro name");
1253                 return false;
1254         }
1255     }
1256
1257     (void)ftepp_next(ftepp);
1258     if (!ftepp_skipspace(ftepp))
1259         return false;
1260     /* relaxing this condition
1261     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1262         ftepp_error(ftepp, "stray tokens after #ifdef");
1263         return false;
1264     }
1265     */
1266     return true;
1267 }
1268
1269 /* Special unescape-string function which skips a leading quote
1270  * and stops at a quote, not just at \0
1271  */
1272 static void unescape(const char *str, char *out) {
1273     ++str;
1274     while (*str && *str != '"') {
1275         if (*str == '\\') {
1276             ++str;
1277             switch (*str) {
1278                 case '\\': *out++ = *str; break;
1279                 case '"':  *out++ = *str; break;
1280                 case 'a':  *out++ = '\a'; break;
1281                 case 'b':  *out++ = '\b'; break;
1282                 case 'r':  *out++ = '\r'; break;
1283                 case 'n':  *out++ = '\n'; break;
1284                 case 't':  *out++ = '\t'; break;
1285                 case 'f':  *out++ = '\f'; break;
1286                 case 'v':  *out++ = '\v'; break;
1287                 default:
1288                     *out++ = '\\';
1289                     *out++ = *str;
1290                     break;
1291             }
1292             ++str;
1293             continue;
1294         }
1295
1296         *out++ = *str++;
1297     }
1298     *out = 0;
1299 }
1300
1301 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1302 {
1303     fs_file_t  *fp;
1304     char       *filename = NULL;
1305     const char *last_slash;
1306     size_t      len;
1307
1308     if (!pathfile)
1309         return NULL;
1310
1311     last_slash = strrchr(pathfile, '/');
1312
1313     if (last_slash) {
1314         len = last_slash - pathfile;
1315         memcpy(vec_add(filename, len), pathfile, len);
1316         vec_push(filename, '/');
1317     }
1318
1319     len = strlen(file);
1320     memcpy(vec_add(filename, len+1), file, len);
1321     vec_last(filename) = 0;
1322
1323     fp = fs_file_open(filename, "rb");
1324     if (fp) {
1325         fs_file_close(fp);
1326         return filename;
1327     }
1328     vec_free(filename);
1329     return NULL;
1330 }
1331
1332 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1333 {
1334     char *filename = NULL;
1335
1336     filename = ftepp_include_find_path(file, ftepp->includename);
1337     if (!filename)
1338         filename = ftepp_include_find_path(file, ftepp->itemname);
1339     return filename;
1340 }
1341
1342 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1343     char *message = NULL;
1344
1345     if (!ftepp_skipspace(ftepp))
1346         return false;
1347
1348     /* handle the odd non string constant case so it works like C */
1349     if (ftepp->token != TOKEN_STRINGCONST) {
1350         bool  store   = false;
1351         vec_append(message, 8, "#warning");
1352         ftepp_next(ftepp);
1353         while (ftepp->token != TOKEN_EOL) {
1354             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1355             ftepp_next(ftepp);
1356         }
1357         vec_push(message, '\0');
1358         if (ftepp->output_on)
1359             store = ftepp_warn(ftepp, WARN_CPP, message);
1360         else
1361             store = false;
1362         vec_free(message);
1363         return store;
1364     }
1365
1366     if (!ftepp->output_on)
1367         return false;
1368
1369     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1370     return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1371 }
1372
1373 static void ftepp_directive_error(ftepp_t *ftepp) {
1374     char *message = NULL;
1375
1376     if (!ftepp_skipspace(ftepp))
1377         return;
1378
1379     /* handle the odd non string constant case so it works like C */
1380     if (ftepp->token != TOKEN_STRINGCONST) {
1381         vec_append(message, 6, "#error");
1382         ftepp_next(ftepp);
1383         while (ftepp->token != TOKEN_EOL) {
1384             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1385             ftepp_next(ftepp);
1386         }
1387         vec_push(message, '\0');
1388         if (ftepp->output_on)
1389             ftepp_error(ftepp, message);
1390         vec_free(message);
1391         return;
1392     }
1393
1394     if (!ftepp->output_on)
1395         return;
1396
1397     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1398     ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1399 }
1400
1401 static void ftepp_directive_message(ftepp_t *ftepp) {
1402     char *message = NULL;
1403
1404     if (!ftepp_skipspace(ftepp))
1405         return;
1406
1407     /* handle the odd non string constant case so it works like C */
1408     if (ftepp->token != TOKEN_STRINGCONST) {
1409         vec_append(message, 8, "#message");
1410         ftepp_next(ftepp);
1411         while (ftepp->token != TOKEN_EOL) {
1412             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1413             ftepp_next(ftepp);
1414         }
1415         vec_push(message, '\0');
1416         if (ftepp->output_on)
1417             con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1418         vec_free(message);
1419         return;
1420     }
1421
1422     if (!ftepp->output_on)
1423         return;
1424
1425     unescape     (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1426     con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message",  ftepp_tokval(ftepp));
1427 }
1428
1429 /**
1430  * Include a file.
1431  * FIXME: do we need/want a -I option?
1432  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1433  */
1434 static bool ftepp_include(ftepp_t *ftepp)
1435 {
1436     lex_file *old_lexer = ftepp->lex;
1437     lex_file *inlex;
1438     lex_ctx_t ctx;
1439     char     lineno[128];
1440     char     *filename;
1441     char     *old_includename;
1442
1443     (void)ftepp_next(ftepp);
1444     if (!ftepp_skipspace(ftepp))
1445         return false;
1446
1447     if (ftepp->token != TOKEN_STRINGCONST) {
1448         ftepp_error(ftepp, "expected filename to include");
1449         return false;
1450     }
1451
1452     if (!ftepp->output_on) {
1453         ftepp_next(ftepp);
1454         return true;
1455     }
1456
1457     ctx = ftepp_ctx(ftepp);
1458
1459     unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1460
1461     ftepp_out(ftepp, "\n#pragma file(", false);
1462     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1463     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1464
1465     filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1466     if (!filename) {
1467         ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1468         return false;
1469     }
1470     inlex = lex_open(filename);
1471     if (!inlex) {
1472         ftepp_error(ftepp, "open failed on include file `%s`", filename);
1473         vec_free(filename);
1474         return false;
1475     }
1476     ftepp->lex = inlex;
1477     old_includename = ftepp->includename;
1478     ftepp->includename = filename;
1479     if (!ftepp_preprocess(ftepp)) {
1480         vec_free(ftepp->includename);
1481         ftepp->includename = old_includename;
1482         lex_close(ftepp->lex);
1483         ftepp->lex = old_lexer;
1484         return false;
1485     }
1486     vec_free(ftepp->includename);
1487     ftepp->includename = old_includename;
1488     lex_close(ftepp->lex);
1489     ftepp->lex = old_lexer;
1490
1491     ftepp_out(ftepp, "\n#pragma file(", false);
1492     ftepp_out(ftepp, ctx.file, false);
1493     util_snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1494     ftepp_out(ftepp, lineno, false);
1495
1496     /* skip the line */
1497     (void)ftepp_next(ftepp);
1498     if (!ftepp_skipspace(ftepp))
1499         return false;
1500     if (ftepp->token != TOKEN_EOL) {
1501         ftepp_error(ftepp, "stray tokens after #include");
1502         return false;
1503     }
1504     (void)ftepp_next(ftepp);
1505
1506     return true;
1507 }
1508
1509 /* Basic structure handlers */
1510 static bool ftepp_else_allowed(ftepp_t *ftepp)
1511 {
1512     if (!vec_size(ftepp->conditions)) {
1513         ftepp_error(ftepp, "#else without #if");
1514         return false;
1515     }
1516     if (vec_last(ftepp->conditions).had_else) {
1517         ftepp_error(ftepp, "multiple #else for a single #if");
1518         return false;
1519     }
1520     return true;
1521 }
1522
1523 static GMQCC_INLINE void ftepp_inmacro(ftepp_t *ftepp, const char *hash) {
1524     if (ftepp->in_macro)
1525         (void)!ftepp_warn(ftepp, WARN_DIRECTIVE_INMACRO, "`#%s` directive in macro", hash);
1526 }
1527
1528 static bool ftepp_hash(ftepp_t *ftepp)
1529 {
1530     ppcondition cond;
1531     ppcondition *pc;
1532
1533     lex_ctx_t ctx = ftepp_ctx(ftepp);
1534
1535     if (!ftepp_skipspace(ftepp))
1536         return false;
1537
1538     switch (ftepp->token) {
1539         case TOKEN_KEYWORD:
1540         case TOKEN_IDENT:
1541         case TOKEN_TYPENAME:
1542             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1543                 ftepp_inmacro(ftepp, "define");
1544                 return ftepp_define(ftepp);
1545             }
1546             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1547                 ftepp_inmacro(ftepp, "undef");
1548                 return ftepp_undef(ftepp);
1549             }
1550             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1551                 ftepp_inmacro(ftepp, "ifdef");
1552                 if (!ftepp_ifdef(ftepp, &cond))
1553                     return false;
1554                 cond.was_on = cond.on;
1555                 vec_push(ftepp->conditions, cond);
1556                 ftepp->output_on = ftepp->output_on && cond.on;
1557                 break;
1558             }
1559             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1560                 ftepp_inmacro(ftepp, "ifndef");
1561                 if (!ftepp_ifdef(ftepp, &cond))
1562                     return false;
1563                 cond.on = !cond.on;
1564                 cond.was_on = cond.on;
1565                 vec_push(ftepp->conditions, cond);
1566                 ftepp->output_on = ftepp->output_on && cond.on;
1567                 break;
1568             }
1569             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1570                 ftepp_inmacro(ftepp, "elifdef");
1571                 if (!ftepp_else_allowed(ftepp))
1572                     return false;
1573                 if (!ftepp_ifdef(ftepp, &cond))
1574                     return false;
1575                 pc = &vec_last(ftepp->conditions);
1576                 pc->on     = !pc->was_on && cond.on;
1577                 pc->was_on = pc->was_on || pc->on;
1578                 ftepp_update_output_condition(ftepp);
1579                 break;
1580             }
1581             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1582                 ftepp_inmacro(ftepp, "elifndef");
1583                 if (!ftepp_else_allowed(ftepp))
1584                     return false;
1585                 if (!ftepp_ifdef(ftepp, &cond))
1586                     return false;
1587                 cond.on = !cond.on;
1588                 pc = &vec_last(ftepp->conditions);
1589                 pc->on     = !pc->was_on && cond.on;
1590                 pc->was_on = pc->was_on || pc->on;
1591                 ftepp_update_output_condition(ftepp);
1592                 break;
1593             }
1594             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1595                 ftepp_inmacro(ftepp, "elif");
1596                 if (!ftepp_else_allowed(ftepp))
1597                     return false;
1598                 if (!ftepp_if(ftepp, &cond))
1599                     return false;
1600                 pc = &vec_last(ftepp->conditions);
1601                 pc->on     = !pc->was_on && cond.on;
1602                 pc->was_on = pc->was_on  || pc->on;
1603                 ftepp_update_output_condition(ftepp);
1604                 break;
1605             }
1606             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1607                 ftepp_inmacro(ftepp, "if");
1608                 if (!ftepp_if(ftepp, &cond))
1609                     return false;
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), "else")) {
1616                 ftepp_inmacro(ftepp, "else");
1617                 if (!ftepp_else_allowed(ftepp))
1618                     return false;
1619                 pc = &vec_last(ftepp->conditions);
1620                 pc->on = !pc->was_on;
1621                 pc->had_else = true;
1622                 ftepp_next(ftepp);
1623                 ftepp_update_output_condition(ftepp);
1624                 break;
1625             }
1626             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1627                 ftepp_inmacro(ftepp, "endif");
1628                 if (!vec_size(ftepp->conditions)) {
1629                     ftepp_error(ftepp, "#endif without #if");
1630                     return false;
1631                 }
1632                 vec_pop(ftepp->conditions);
1633                 ftepp_next(ftepp);
1634                 ftepp_update_output_condition(ftepp);
1635                 break;
1636             }
1637             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1638                 ftepp_inmacro(ftepp, "include");
1639                 return ftepp_include(ftepp);
1640             }
1641             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1642                 ftepp_out(ftepp, "#", false);
1643                 break;
1644             }
1645             else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1646                 ftepp_directive_warning(ftepp);
1647                 break;
1648             }
1649             else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1650                 ftepp_directive_error(ftepp);
1651                 break;
1652             }
1653             else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1654                 ftepp_directive_message(ftepp);
1655                 break;
1656             }
1657             else {
1658                 if (ftepp->output_on) {
1659                     ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1660                     return false;
1661                 } else {
1662                     ftepp_next(ftepp);
1663                     break;
1664                 }
1665             }
1666             /* break; never reached */
1667         default:
1668             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1669             return false;
1670         case TOKEN_EOL:
1671             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1672             return false;
1673         case TOKEN_EOF:
1674             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1675             return false;
1676
1677         /* Builtins! Don't forget the builtins! */
1678         case TOKEN_INTCONST:
1679         case TOKEN_FLOATCONST:
1680             ftepp_out(ftepp, "#", false);
1681             return true;
1682     }
1683     if (!ftepp_skipspace(ftepp))
1684         return false;
1685     return true;
1686 }
1687
1688 static bool ftepp_preprocess(ftepp_t *ftepp)
1689 {
1690     ppmacro *macro;
1691     bool     newline = true;
1692
1693     /* predef stuff */
1694     char    *expand  = NULL;
1695
1696     ftepp->lex->flags.preprocessing = true;
1697     ftepp->lex->flags.mergelines    = false;
1698     ftepp->lex->flags.noops         = true;
1699
1700     ftepp_next(ftepp);
1701     do
1702     {
1703         if (ftepp->token >= TOKEN_EOF)
1704             break;
1705 #if 0
1706         newline = true;
1707 #endif
1708
1709         switch (ftepp->token) {
1710             case TOKEN_KEYWORD:
1711             case TOKEN_IDENT:
1712             case TOKEN_TYPENAME:
1713                 /* is it a predef? */
1714                 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1715                     char *(*predef)(ftepp_t*) = ftepp_predef(ftepp_tokval(ftepp));
1716                     if (predef) {
1717                         expand = predef(ftepp);
1718                         ftepp_out (ftepp, expand, false);
1719                         ftepp_next(ftepp);
1720
1721                         mem_d(expand);
1722                         break;
1723                     }
1724                 }
1725
1726                 if (ftepp->output_on)
1727                     macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1728                 else
1729                     macro = NULL;
1730
1731                 if (!macro) {
1732                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1733                     ftepp_next(ftepp);
1734                     break;
1735                 }
1736                 if (!ftepp_macro_call(ftepp, macro))
1737                     ftepp->token = TOKEN_ERROR;
1738                 break;
1739             case '#':
1740                 if (!newline) {
1741                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1742                     ftepp_next(ftepp);
1743                     break;
1744                 }
1745                 ftepp->lex->flags.mergelines = true;
1746                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1747                     ftepp_error(ftepp, "error in preprocessor directive");
1748                     ftepp->token = TOKEN_ERROR;
1749                     break;
1750                 }
1751                 if (!ftepp_hash(ftepp))
1752                     ftepp->token = TOKEN_ERROR;
1753                 ftepp->lex->flags.mergelines = false;
1754                 break;
1755             case TOKEN_EOL:
1756                 newline = true;
1757                 ftepp_out(ftepp, "\n", true);
1758                 ftepp_next(ftepp);
1759                 break;
1760             case TOKEN_WHITE:
1761                 /* same as default but don't set newline=false */
1762                 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1763                 ftepp_next(ftepp);
1764                 break;
1765             default:
1766                 newline = false;
1767                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1768                 ftepp_next(ftepp);
1769                 break;
1770         }
1771     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1772
1773     /* force a 0 at the end but don't count it as added to the output */
1774     vec_push(ftepp->output_string, 0);
1775     vec_shrinkby(ftepp->output_string, 1);
1776
1777     return (ftepp->token == TOKEN_EOF);
1778 }
1779
1780 /* Like in parser.c - files keep the previous state so we have one global
1781  * preprocessor. Except here we will want to warn about dangling #ifs.
1782  */
1783 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1784 {
1785     bool retval = true;
1786     if (vec_size(ftepp->conditions)) {
1787         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1788             retval = false;
1789     }
1790     lex_close(ftepp->lex);
1791     ftepp->lex = NULL;
1792     if (ftepp->itemname) {
1793         mem_d(ftepp->itemname);
1794         ftepp->itemname = NULL;
1795     }
1796     return retval;
1797 }
1798
1799 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1800 {
1801     ftepp->lex = lex_open(filename);
1802     ftepp->itemname = util_strdup(filename);
1803     if (!ftepp->lex) {
1804         con_out("failed to open file \"%s\"\n", filename);
1805         return false;
1806     }
1807     if (!ftepp_preprocess(ftepp))
1808         return false;
1809     return ftepp_preprocess_done(ftepp);
1810 }
1811
1812 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1813 {
1814     ftepp->lex = lex_open_string(str, strlen(str), name);
1815     ftepp->itemname = util_strdup(name);
1816     if (!ftepp->lex) {
1817         con_out("failed to create lexer for string \"%s\"\n", name);
1818         return false;
1819     }
1820     if (!ftepp_preprocess(ftepp))
1821         return false;
1822     return ftepp_preprocess_done(ftepp);
1823 }
1824
1825
1826 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1827     char *create = NULL;
1828
1829     /* use saner path for empty macros */
1830     if (!value) {
1831         ftepp_add_define(ftepp, "__builtin__", name);
1832         return;
1833     }
1834
1835     vec_append(create, 8,           "#define ");
1836     vec_append(create, strlen(name), name);
1837     vec_push  (create, ' ');
1838     vec_append(create, strlen(value), value);
1839     vec_push  (create, 0);
1840
1841     ftepp_preprocess_string(ftepp, "__builtin__", create);
1842     vec_free  (create);
1843 }
1844
1845 ftepp_t *ftepp_create()
1846 {
1847     ftepp_t *ftepp;
1848     char minor[32];
1849     char major[32];
1850     size_t i;
1851
1852     ftepp = ftepp_new();
1853     if (!ftepp)
1854         return NULL;
1855
1856     memset(minor, 0, sizeof(minor));
1857     memset(major, 0, sizeof(major));
1858
1859     /* set the right macro based on the selected standard */
1860     ftepp_add_define(ftepp, NULL, "GMQCC");
1861     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1862         ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1863         /* 1.00 */
1864         major[0] = '"';
1865         major[1] = '1';
1866         major[2] = '"';
1867
1868         minor[0] = '"';
1869         minor[1] = '0';
1870         minor[2] = '"';
1871     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1872         ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1873         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1874         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1875     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1876         ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1877         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1878         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1879     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1880         ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1881         /* 1.0 */
1882         major[0] = '"';
1883         major[1] = '1';
1884         major[2] = '"';
1885
1886         minor[0] = '"';
1887         minor[1] = '0';
1888         minor[2] = '"';
1889     }
1890
1891     ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1892     ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1893
1894     /*
1895      * We're going to just make __NULL__ nil, which works for 60% of the
1896      * cases of __NULL_ for fteqcc.
1897      */
1898     ftepp_add_macro(ftepp, "__NULL__", "nil");
1899
1900     /* add all the math constants if they can be */
1901     for (i = 0; i < GMQCC_ARRAY_COUNT(ftepp_math_constants); i++)
1902         if (!ftepp_macro_find(ftepp, ftepp_math_constants[i][0]))
1903             ftepp_add_macro(ftepp, ftepp_math_constants[i][0], ftepp_math_constants[i][1]);
1904
1905     return ftepp;
1906 }
1907
1908 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1909 {
1910     ppmacro *macro;
1911     lex_ctx_t ctx = { "__builtin__", 0, 0 };
1912     ctx.file = source;
1913     macro = ppmacro_new(ctx, name);
1914     /*vec_push(ftepp->macros, macro);*/
1915     util_htset(ftepp->macros, name, macro);
1916 }
1917
1918 const char *ftepp_get(ftepp_t *ftepp)
1919 {
1920     return ftepp->output_string;
1921 }
1922
1923 void ftepp_flush(ftepp_t *ftepp)
1924 {
1925     ftepp_flush_do(ftepp);
1926 }
1927
1928 void ftepp_finish(ftepp_t *ftepp)
1929 {
1930     if (!ftepp)
1931         return;
1932     ftepp_delete(ftepp);
1933 }