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