]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Merge branch 'cooking'
[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 bool ftepp_define(ftepp_t *ftepp)
502 {
503     ppmacro *macro = NULL;
504     size_t l = ftepp_ctx(ftepp).line;
505
506     (void)ftepp_next(ftepp);
507     if (!ftepp_skipspace(ftepp))
508         return false;
509
510     switch (ftepp->token) {
511         case TOKEN_IDENT:
512         case TOKEN_TYPENAME:
513         case TOKEN_KEYWORD:
514             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
515             if (macro && ftepp->output_on) {
516                 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
517                     return false;
518                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
519             }
520             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
521             break;
522         default:
523             ftepp_error(ftepp, "expected macro name");
524             return false;
525     }
526
527     (void)ftepp_next(ftepp);
528
529     if (ftepp->token == '(') {
530         macro->has_params = true;
531         if (!ftepp_define_params(ftepp, macro)) {
532             ppmacro_delete(macro);
533             return false;
534         }
535     }
536
537     if (!ftepp_skipspace(ftepp)) {
538         ppmacro_delete(macro);
539         return false;
540     }
541
542     if (!ftepp_define_body(ftepp, macro)) {
543         ppmacro_delete(macro);
544         return false;
545     }
546
547     if (ftepp->output_on)
548         util_htset(ftepp->macros, macro->name, (void*)macro);
549     else {
550         ppmacro_delete(macro);
551     }
552
553     for (; l < ftepp_ctx(ftepp).line; ++l)
554         ftepp_out(ftepp, "\n", true);
555     return true;
556 }
557
558 /**
559  * When a macro is used we have to handle parameters as well
560  * as special-concatenation via ## or stringification via #
561  *
562  * Note: parenthesis can nest, so FOO((a),b) is valid, but only
563  * this kind of parens. Curly braces or [] don't count towards the
564  * paren-level.
565  */
566 typedef struct {
567     pptoken **tokens;
568 } macroparam;
569
570 static void macroparam_clean(macroparam *self)
571 {
572     size_t i;
573     for (i = 0; i < vec_size(self->tokens); ++i)
574         pptoken_delete(self->tokens[i]);
575     vec_free(self->tokens);
576 }
577
578 /* need to leave the last token up */
579 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
580 {
581     macroparam *params = NULL;
582     pptoken    *ptok;
583     macroparam  mp;
584     size_t      parens = 0;
585     size_t      i;
586
587     if (!ftepp_skipallwhite(ftepp))
588         return false;
589     while (ftepp->token != ')') {
590         mp.tokens = NULL;
591         if (!ftepp_skipallwhite(ftepp))
592             return false;
593         while (parens || ftepp->token != ',') {
594             if (ftepp->token == '(')
595                 ++parens;
596             else if (ftepp->token == ')') {
597                 if (!parens)
598                     break;
599                 --parens;
600             }
601             ptok = pptoken_make(ftepp);
602             vec_push(mp.tokens, ptok);
603             if (ftepp_next(ftepp) >= TOKEN_EOF) {
604                 ftepp_error(ftepp, "unexpected end of file in macro call");
605                 goto on_error;
606             }
607         }
608         vec_push(params, mp);
609         mp.tokens = NULL;
610         if (ftepp->token == ')')
611             break;
612         if (ftepp->token != ',') {
613             ftepp_error(ftepp, "expected closing paren or comma in macro call");
614             goto on_error;
615         }
616         if (ftepp_next(ftepp) >= TOKEN_EOF) {
617             ftepp_error(ftepp, "unexpected end of file in macro call");
618             goto on_error;
619         }
620     }
621     *out_params = params;
622     return true;
623
624 on_error:
625     if (mp.tokens)
626         macroparam_clean(&mp);
627     for (i = 0; i < vec_size(params); ++i)
628         macroparam_clean(&params[i]);
629     vec_free(params);
630     return false;
631 }
632
633 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
634 {
635     size_t i;
636     for (i = 0; i < vec_size(macro->params); ++i) {
637         if (!strcmp(macro->params[i], name)) {
638             *idx = i;
639             return true;
640         }
641     }
642     return false;
643 }
644
645 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
646 {
647     char        chs[2];
648     const char *ch;
649     chs[1] = 0;
650     switch (token->token) {
651         case TOKEN_STRINGCONST:
652             ch = token->value;
653             while (*ch) {
654                 /* in preprocessor mode strings already are string,
655                  * so we don't get actual newline bytes here.
656                  * Still need to escape backslashes and quotes.
657                  */
658                 switch (*ch) {
659                     case '\\': ftepp_out(ftepp, "\\\\", false); break;
660                     case '"':  ftepp_out(ftepp, "\\\"", false); break;
661                     default:
662                         chs[0] = *ch;
663                         ftepp_out(ftepp, chs, false);
664                         break;
665                 }
666                 ++ch;
667             }
668             break;
669         case TOKEN_WHITE:
670             ftepp_out(ftepp, " ", false);
671             break;
672         case TOKEN_EOL:
673             ftepp_out(ftepp, "\\n", false);
674             break;
675         default:
676             ftepp_out(ftepp, token->value, false);
677             break;
678     }
679 }
680
681 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
682 {
683     size_t i;
684     ftepp_out(ftepp, "\"", false);
685     for (i = 0; i < vec_size(param->tokens); ++i)
686         ftepp_stringify_token(ftepp, param->tokens[i]);
687     ftepp_out(ftepp, "\"", false);
688 }
689
690 static void ftepp_recursion_header(ftepp_t *ftepp)
691 {
692     ftepp_out(ftepp, "\n#pragma push(line)\n", false);
693 }
694
695 static void ftepp_recursion_footer(ftepp_t *ftepp)
696 {
697     ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
698 }
699
700 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
701 {
702     size_t   i;
703     pptoken *out;
704     for (i = 0; i < vec_size(param->tokens); ++i) {
705         out = param->tokens[i];
706         if (out->token == TOKEN_EOL)
707             ftepp_out(ftepp, "\n", false);
708         else
709             ftepp_out(ftepp, out->value, false);
710     }
711 }
712
713 static bool ftepp_preprocess(ftepp_t *ftepp);
714 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
715 {
716     char     *buffer       = NULL;
717     char     *old_string   = ftepp->output_string;
718     char     *inner_string;
719     lex_file *old_lexer    = ftepp->lex;
720     size_t    vararg_start = vec_size(macro->params);
721     bool      retval       = true;
722     bool      has_newlines;
723     size_t    varargs;
724
725     size_t    o, pi;
726     lex_file *inlex;
727
728     bool      old_inmacro;
729
730     int nextok;
731
732     if (vararg_start < vec_size(params))
733         varargs = vec_size(params) - vararg_start;
734     else
735         varargs = 0;
736
737     /* really ... */
738     if (!vec_size(macro->output))
739         return true;
740
741     ftepp->output_string = NULL;
742     for (o = 0; o < vec_size(macro->output); ++o) {
743         pptoken *out = macro->output[o];
744         switch (out->token) {
745             case TOKEN_VA_ARGS:
746                 if (!macro->variadic) {
747                     ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
748                     vec_free(old_string);
749                     return false;
750                 }
751                 if (!varargs)
752                     break;
753
754                 pi = 0;
755                 ftepp_param_out(ftepp, &params[pi + vararg_start]);
756                 for (++pi; pi < varargs; ++pi) {
757                     ftepp_out(ftepp, ", ", false);
758                     ftepp_param_out(ftepp, &params[pi + vararg_start]);
759                 }
760                 break;
761
762             case TOKEN_VA_ARGS_ARRAY:
763                 if ((size_t)out->constval.i >= varargs) {
764                     ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
765                     vec_free(old_string);
766                     return false;
767                 }
768
769                 ftepp_param_out(ftepp, &params[out->constval.i + vararg_start]);
770                 break;
771
772             case TOKEN_VA_COUNT:
773                 util_asprintf(&buffer, "%d", varargs);
774                 ftepp_out(ftepp, buffer, false);
775                 mem_d(buffer);
776                 break;
777
778             case TOKEN_IDENT:
779             case TOKEN_TYPENAME:
780             case TOKEN_KEYWORD:
781                 if (!macro_params_find(macro, out->value, &pi)) {
782                     ftepp_out(ftepp, out->value, false);
783                     break;
784                 } else
785                     ftepp_param_out(ftepp, &params[pi]);
786                 break;
787             case '#':
788                 if (o + 1 < vec_size(macro->output)) {
789                     nextok = macro->output[o+1]->token;
790                     if (nextok == '#') {
791                         /* raw concatenation */
792                         ++o;
793                         break;
794                     }
795                     if ( (nextok == TOKEN_IDENT    ||
796                           nextok == TOKEN_KEYWORD  ||
797                           nextok == TOKEN_TYPENAME) &&
798                         macro_params_find(macro, macro->output[o+1]->value, &pi))
799                     {
800                         ++o;
801                         ftepp_stringify(ftepp, &params[pi]);
802                         break;
803                     }
804                 }
805                 ftepp_out(ftepp, "#", false);
806                 break;
807             case TOKEN_EOL:
808                 ftepp_out(ftepp, "\n", false);
809                 break;
810             default:
811                 ftepp_out(ftepp, out->value, false);
812                 break;
813         }
814     }
815     vec_push(ftepp->output_string, 0);
816     /* Now run the preprocessor recursively on this string buffer */
817     /*
818     printf("__________\n%s\n=========\n", ftepp->output_string);
819     */
820     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
821     if (!inlex) {
822         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
823         retval = false;
824         goto cleanup;
825     }
826
827     inlex->line  = ftepp->lex->line;
828     inlex->sline = ftepp->lex->sline;
829     ftepp->lex   = inlex;
830
831     old_inmacro     = ftepp->in_macro;
832     ftepp->in_macro = true;
833     ftepp->output_string = NULL;
834     if (!ftepp_preprocess(ftepp)) {
835         ftepp->in_macro = old_inmacro;
836         vec_free(ftepp->lex->open_string);
837         vec_free(ftepp->output_string);
838         lex_close(ftepp->lex);
839         retval = false;
840         goto cleanup;
841     }
842     ftepp->in_macro = old_inmacro;
843     vec_free(ftepp->lex->open_string);
844     lex_close(ftepp->lex);
845
846     inner_string = ftepp->output_string;
847     ftepp->output_string = old_string;
848
849     has_newlines = (strchr(inner_string, '\n') != NULL);
850
851     if (has_newlines && !old_inmacro)
852         ftepp_recursion_header(ftepp);
853
854     vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
855     vec_free(inner_string);
856
857     if (has_newlines && !old_inmacro)
858         ftepp_recursion_footer(ftepp);
859
860     if (resetline && !ftepp->in_macro) {
861         char lineno[128];
862         util_snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
863         ftepp_out(ftepp, lineno, false);
864     }
865
866     old_string = ftepp->output_string;
867 cleanup:
868     ftepp->lex           = old_lexer;
869     ftepp->output_string = old_string;
870     return retval;
871 }
872
873 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
874 {
875     size_t     o;
876     macroparam *params = NULL;
877     bool        retval = true;
878     size_t      paramline;
879
880     if (!macro->has_params) {
881         if (!ftepp_macro_expand(ftepp, macro, NULL, false))
882             return false;
883         ftepp_next(ftepp);
884         return true;
885     }
886     ftepp_next(ftepp);
887
888     if (!ftepp_skipallwhite(ftepp))
889         return false;
890
891     if (ftepp->token != '(') {
892         ftepp_error(ftepp, "expected macro parameters in parenthesis");
893         return false;
894     }
895
896     ftepp_next(ftepp);
897     paramline = ftepp->lex->sline;
898     if (!ftepp_macro_call_params(ftepp, &params))
899         return false;
900
901     if ( vec_size(params) < vec_size(macro->params) ||
902         (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
903     {
904         ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
905                     (macro->variadic ? " at least" : ""),
906                     (unsigned int)vec_size(macro->params),
907                     (unsigned int)vec_size(params));
908         retval = false;
909         goto cleanup;
910     }
911
912     if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
913         retval = false;
914     ftepp_next(ftepp);
915
916 cleanup:
917     for (o = 0; o < vec_size(params); ++o)
918         macroparam_clean(&params[o]);
919     vec_free(params);
920     return retval;
921 }
922
923 /**
924  * #if - the FTEQCC way:
925  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
926  *    <numbers>    => True if the number is not 0
927  *    !<factor>    => True if the factor yields false
928  *    !!<factor>   => ERROR on 2 or more unary nots
929  *    <macro>      => becomes the macro's FIRST token regardless of parameters
930  *    <e> && <e>   => True if both expressions are true
931  *    <e> || <e>   => True if either expression is true
932  *    <string>     => False
933  *    <ident>      => False (remember for macros the <macro> rule applies instead)
934  * Unary + and - are weird and wrong in fteqcc so we don't allow them
935  * parenthesis in expressions are allowed
936  * parameter lists on macros are errors
937  * No mathematical calculations are executed
938  */
939 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
940 static bool ftepp_if_op(ftepp_t *ftepp)
941 {
942     ftepp->lex->flags.noops = false;
943     ftepp_next(ftepp);
944     if (!ftepp_skipspace(ftepp))
945         return false;
946     ftepp->lex->flags.noops = true;
947     return true;
948 }
949 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
950 {
951     ppmacro *macro;
952     bool     wasnot = false;
953     bool     wasneg = false;
954
955     if (!ftepp_skipspace(ftepp))
956         return false;
957
958     while (ftepp->token == '!') {
959         wasnot = true;
960         ftepp_next(ftepp);
961         if (!ftepp_skipspace(ftepp))
962             return false;
963     }
964
965     if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
966     {
967         wasneg = true;
968         ftepp_next(ftepp);
969         if (!ftepp_skipspace(ftepp))
970             return false;
971     }
972
973     switch (ftepp->token) {
974         case TOKEN_IDENT:
975         case TOKEN_TYPENAME:
976         case TOKEN_KEYWORD:
977             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
978                 ftepp_next(ftepp);
979                 if (!ftepp_skipspace(ftepp))
980                     return false;
981                 if (ftepp->token != '(') {
982                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
983                     return false;
984                 }
985                 ftepp_next(ftepp);
986                 if (!ftepp_skipspace(ftepp))
987                     return false;
988                 if (ftepp->token != TOKEN_IDENT &&
989                     ftepp->token != TOKEN_TYPENAME &&
990                     ftepp->token != TOKEN_KEYWORD)
991                 {
992                     ftepp_error(ftepp, "defined() used on an unexpected token type");
993                     return false;
994                 }
995                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
996                 *out = !!macro;
997                 ftepp_next(ftepp);
998                 if (!ftepp_skipspace(ftepp))
999                     return false;
1000                 if (ftepp->token != ')') {
1001                     ftepp_error(ftepp, "expected closing paren");
1002                     return false;
1003                 }
1004                 break;
1005             }
1006
1007             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1008             if (!macro || !vec_size(macro->output)) {
1009                 *out = false;
1010                 *value_out = 0;
1011             } else {
1012                 /* This does not expand recursively! */
1013                 switch (macro->output[0]->token) {
1014                     case TOKEN_INTCONST:
1015                         *value_out = macro->output[0]->constval.i;
1016                         *out = !!(macro->output[0]->constval.i);
1017                         break;
1018                     case TOKEN_FLOATCONST:
1019                         *value_out = macro->output[0]->constval.f;
1020                         *out = !!(macro->output[0]->constval.f);
1021                         break;
1022                     default:
1023                         *out = false;
1024                         break;
1025                 }
1026             }
1027             break;
1028         case TOKEN_STRINGCONST:
1029             *value_out = 0;
1030             *out = false;
1031             break;
1032         case TOKEN_INTCONST:
1033             *value_out = ftepp->lex->tok.constval.i;
1034             *out = !!(ftepp->lex->tok.constval.i);
1035             break;
1036         case TOKEN_FLOATCONST:
1037             *value_out = ftepp->lex->tok.constval.f;
1038             *out = !!(ftepp->lex->tok.constval.f);
1039             break;
1040
1041         case '(':
1042             ftepp_next(ftepp);
1043             if (!ftepp_if_expr(ftepp, out, value_out))
1044                 return false;
1045             if (ftepp->token != ')') {
1046                 ftepp_error(ftepp, "expected closing paren in #if expression");
1047                 return false;
1048             }
1049             break;
1050
1051         default:
1052             ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1053             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1054                 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1055             return false;
1056     }
1057     if (wasneg)
1058         *value_out = -*value_out;
1059     if (wasnot) {
1060         *out = !*out;
1061         *value_out = (*out ? 1 : 0);
1062     }
1063     return true;
1064 }
1065
1066 /*
1067 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1068 {
1069     if (!ftepp_next(ftepp))
1070         return false;
1071     return ftepp_if_value(ftepp, out, value_out);
1072 }
1073 */
1074
1075 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1076 {
1077     if (!ftepp_if_value(ftepp, out, value_out))
1078         return false;
1079
1080     if (!ftepp_if_op(ftepp))
1081         return false;
1082
1083     if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1084         return true;
1085
1086     /* FTEQCC is all right-associative and no precedence here */
1087     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1088         !strcmp(ftepp_tokval(ftepp), "||"))
1089     {
1090         bool next = false;
1091         char opc  = ftepp_tokval(ftepp)[0];
1092         double nextvalue;
1093
1094         (void)nextvalue;
1095         if (!ftepp_next(ftepp))
1096             return false;
1097         if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1098             return false;
1099
1100         if (opc == '&')
1101             *out = *out && next;
1102         else
1103             *out = *out || next;
1104
1105         *value_out = (*out ? 1 : 0);
1106         return true;
1107     }
1108     else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1109              !strcmp(ftepp_tokval(ftepp), "!=") ||
1110              !strcmp(ftepp_tokval(ftepp), ">=") ||
1111              !strcmp(ftepp_tokval(ftepp), "<=") ||
1112              !strcmp(ftepp_tokval(ftepp), ">") ||
1113              !strcmp(ftepp_tokval(ftepp), "<"))
1114     {
1115         bool next = false;
1116         const char opc0 = ftepp_tokval(ftepp)[0];
1117         const char opc1 = ftepp_tokval(ftepp)[1];
1118         double other;
1119
1120         if (!ftepp_next(ftepp))
1121             return false;
1122         if (!ftepp_if_expr(ftepp, &next, &other))
1123             return false;
1124
1125         if (opc0 == '=')
1126             *out = (*value_out == other);
1127         else if (opc0 == '!')
1128             *out = (*value_out != other);
1129         else if (opc0 == '>') {
1130             if (opc1 == '=') *out = (*value_out >= other);
1131             else             *out = (*value_out > other);
1132         }
1133         else if (opc0 == '<') {
1134             if (opc1 == '=') *out = (*value_out <= other);
1135             else             *out = (*value_out < other);
1136         }
1137         *value_out = (*out ? 1 : 0);
1138
1139         return true;
1140     }
1141     else {
1142         ftepp_error(ftepp, "junk after #if");
1143         return false;
1144     }
1145 }
1146
1147 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1148 {
1149     bool result = false;
1150     double dummy = 0;
1151
1152     memset(cond, 0, sizeof(*cond));
1153     (void)ftepp_next(ftepp);
1154
1155     if (!ftepp_skipspace(ftepp))
1156         return false;
1157     if (ftepp->token == TOKEN_EOL) {
1158         ftepp_error(ftepp, "expected expression for #if-directive");
1159         return false;
1160     }
1161
1162     if (!ftepp_if_expr(ftepp, &result, &dummy))
1163         return false;
1164
1165     cond->on = result;
1166     return true;
1167 }
1168
1169 /**
1170  * ifdef is rather simple
1171  */
1172 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1173 {
1174     ppmacro *macro;
1175     memset(cond, 0, sizeof(*cond));
1176     (void)ftepp_next(ftepp);
1177     if (!ftepp_skipspace(ftepp))
1178         return false;
1179
1180     switch (ftepp->token) {
1181         case TOKEN_IDENT:
1182         case TOKEN_TYPENAME:
1183         case TOKEN_KEYWORD:
1184             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1185             break;
1186         default:
1187             ftepp_error(ftepp, "expected macro name");
1188             return false;
1189     }
1190
1191     (void)ftepp_next(ftepp);
1192     if (!ftepp_skipspace(ftepp))
1193         return false;
1194     /* relaxing this condition
1195     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1196         ftepp_error(ftepp, "stray tokens after #ifdef");
1197         return false;
1198     }
1199     */
1200     cond->on = !!macro;
1201     return true;
1202 }
1203
1204 /**
1205  * undef is also simple
1206  */
1207 static bool ftepp_undef(ftepp_t *ftepp)
1208 {
1209     (void)ftepp_next(ftepp);
1210     if (!ftepp_skipspace(ftepp))
1211         return false;
1212
1213     if (ftepp->output_on) {
1214         switch (ftepp->token) {
1215             case TOKEN_IDENT:
1216             case TOKEN_TYPENAME:
1217             case TOKEN_KEYWORD:
1218                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1219                 break;
1220             default:
1221                 ftepp_error(ftepp, "expected macro name");
1222                 return false;
1223         }
1224     }
1225
1226     (void)ftepp_next(ftepp);
1227     if (!ftepp_skipspace(ftepp))
1228         return false;
1229     /* relaxing this condition
1230     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1231         ftepp_error(ftepp, "stray tokens after #ifdef");
1232         return false;
1233     }
1234     */
1235     return true;
1236 }
1237
1238 /* Special unescape-string function which skips a leading quote
1239  * and stops at a quote, not just at \0
1240  */
1241 static void unescape(const char *str, char *out) {
1242     ++str;
1243     while (*str && *str != '"') {
1244         if (*str == '\\') {
1245             ++str;
1246             switch (*str) {
1247                 case '\\': *out++ = *str; break;
1248                 case '"':  *out++ = *str; break;
1249                 case 'a':  *out++ = '\a'; break;
1250                 case 'b':  *out++ = '\b'; break;
1251                 case 'r':  *out++ = '\r'; break;
1252                 case 'n':  *out++ = '\n'; break;
1253                 case 't':  *out++ = '\t'; break;
1254                 case 'f':  *out++ = '\f'; break;
1255                 case 'v':  *out++ = '\v'; break;
1256                 default:
1257                     *out++ = '\\';
1258                     *out++ = *str;
1259                     break;
1260             }
1261             ++str;
1262             continue;
1263         }
1264
1265         *out++ = *str++;
1266     }
1267     *out = 0;
1268 }
1269
1270 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1271 {
1272     fs_file_t  *fp;
1273     char       *filename = NULL;
1274     const char *last_slash;
1275     size_t      len;
1276
1277     if (!pathfile)
1278         return NULL;
1279
1280     last_slash = strrchr(pathfile, '/');
1281
1282     if (last_slash) {
1283         len = last_slash - pathfile;
1284         memcpy(vec_add(filename, len), pathfile, len);
1285         vec_push(filename, '/');
1286     }
1287
1288     len = strlen(file);
1289     memcpy(vec_add(filename, len+1), file, len);
1290     vec_last(filename) = 0;
1291
1292     fp = fs_file_open(filename, "rb");
1293     if (fp) {
1294         fs_file_close(fp);
1295         return filename;
1296     }
1297     vec_free(filename);
1298     return NULL;
1299 }
1300
1301 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1302 {
1303     char *filename = NULL;
1304
1305     filename = ftepp_include_find_path(file, ftepp->includename);
1306     if (!filename)
1307         filename = ftepp_include_find_path(file, ftepp->itemname);
1308     return filename;
1309 }
1310
1311 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1312     char *message = NULL;
1313
1314     if (!ftepp_skipspace(ftepp))
1315         return false;
1316
1317     /* handle the odd non string constant case so it works like C */
1318     if (ftepp->token != TOKEN_STRINGCONST) {
1319         bool  store   = false;
1320         vec_append(message, 8, "#warning");
1321         ftepp_next(ftepp);
1322         while (ftepp->token != TOKEN_EOL) {
1323             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1324             ftepp_next(ftepp);
1325         }
1326         vec_push(message, '\0');
1327         if (ftepp->output_on)
1328             store = ftepp_warn(ftepp, WARN_CPP, message);
1329         else
1330             store = false;
1331         vec_free(message);
1332         return store;
1333     }
1334
1335     if (!ftepp->output_on)
1336         return false;
1337
1338     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1339     return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1340 }
1341
1342 static void ftepp_directive_error(ftepp_t *ftepp) {
1343     char *message = NULL;
1344
1345     if (!ftepp_skipspace(ftepp))
1346         return;
1347
1348     /* handle the odd non string constant case so it works like C */
1349     if (ftepp->token != TOKEN_STRINGCONST) {
1350         vec_append(message, 6, "#error");
1351         ftepp_next(ftepp);
1352         while (ftepp->token != TOKEN_EOL) {
1353             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1354             ftepp_next(ftepp);
1355         }
1356         vec_push(message, '\0');
1357         if (ftepp->output_on)
1358             ftepp_error(ftepp, message);
1359         vec_free(message);
1360         return;
1361     }
1362
1363     if (!ftepp->output_on)
1364         return;
1365
1366     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1367     ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1368 }
1369
1370 static void ftepp_directive_message(ftepp_t *ftepp) {
1371     char *message = NULL;
1372
1373     if (!ftepp_skipspace(ftepp))
1374         return;
1375
1376     /* handle the odd non string constant case so it works like C */
1377     if (ftepp->token != TOKEN_STRINGCONST) {
1378         vec_append(message, 8, "#message");
1379         ftepp_next(ftepp);
1380         while (ftepp->token != TOKEN_EOL) {
1381             vec_append(message, strlen(ftepp_tokval(ftepp)), ftepp_tokval(ftepp));
1382             ftepp_next(ftepp);
1383         }
1384         vec_push(message, '\0');
1385         if (ftepp->output_on)
1386             con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1387         vec_free(message);
1388         return;
1389     }
1390
1391     if (!ftepp->output_on)
1392         return;
1393
1394     unescape     (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1395     con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message",  ftepp_tokval(ftepp));
1396 }
1397
1398 /**
1399  * Include a file.
1400  * FIXME: do we need/want a -I option?
1401  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1402  */
1403 static bool ftepp_include(ftepp_t *ftepp)
1404 {
1405     lex_file *old_lexer = ftepp->lex;
1406     lex_file *inlex;
1407     lex_ctx_t ctx;
1408     char     lineno[128];
1409     char     *filename;
1410     char     *old_includename;
1411
1412     (void)ftepp_next(ftepp);
1413     if (!ftepp_skipspace(ftepp))
1414         return false;
1415
1416     if (ftepp->token != TOKEN_STRINGCONST) {
1417         ftepp_error(ftepp, "expected filename to include");
1418         return false;
1419     }
1420
1421     if (!ftepp->output_on) {
1422         ftepp_next(ftepp);
1423         return true;
1424     }
1425
1426     ctx = ftepp_ctx(ftepp);
1427
1428     unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1429
1430     ftepp_out(ftepp, "\n#pragma file(", false);
1431     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1432     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1433
1434     filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1435     if (!filename) {
1436         ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1437         return false;
1438     }
1439     inlex = lex_open(filename);
1440     if (!inlex) {
1441         ftepp_error(ftepp, "open failed on include file `%s`", filename);
1442         vec_free(filename);
1443         return false;
1444     }
1445     ftepp->lex = inlex;
1446     old_includename = ftepp->includename;
1447     ftepp->includename = filename;
1448     if (!ftepp_preprocess(ftepp)) {
1449         vec_free(ftepp->includename);
1450         ftepp->includename = old_includename;
1451         lex_close(ftepp->lex);
1452         ftepp->lex = old_lexer;
1453         return false;
1454     }
1455     vec_free(ftepp->includename);
1456     ftepp->includename = old_includename;
1457     lex_close(ftepp->lex);
1458     ftepp->lex = old_lexer;
1459
1460     ftepp_out(ftepp, "\n#pragma file(", false);
1461     ftepp_out(ftepp, ctx.file, false);
1462     util_snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1463     ftepp_out(ftepp, lineno, false);
1464
1465     /* skip the line */
1466     (void)ftepp_next(ftepp);
1467     if (!ftepp_skipspace(ftepp))
1468         return false;
1469     if (ftepp->token != TOKEN_EOL) {
1470         ftepp_error(ftepp, "stray tokens after #include");
1471         return false;
1472     }
1473     (void)ftepp_next(ftepp);
1474
1475     return true;
1476 }
1477
1478 /* Basic structure handlers */
1479 static bool ftepp_else_allowed(ftepp_t *ftepp)
1480 {
1481     if (!vec_size(ftepp->conditions)) {
1482         ftepp_error(ftepp, "#else without #if");
1483         return false;
1484     }
1485     if (vec_last(ftepp->conditions).had_else) {
1486         ftepp_error(ftepp, "multiple #else for a single #if");
1487         return false;
1488     }
1489     return true;
1490 }
1491
1492 static GMQCC_INLINE void ftepp_inmacro(ftepp_t *ftepp, const char *hash) {
1493     if (ftepp->in_macro)
1494         (void)!ftepp_warn(ftepp, WARN_DIRECTIVE_INMACRO, "`#%s` directive in macro", hash);
1495 }
1496
1497 static bool ftepp_hash(ftepp_t *ftepp)
1498 {
1499     ppcondition cond;
1500     ppcondition *pc;
1501
1502     lex_ctx_t ctx = ftepp_ctx(ftepp);
1503
1504     if (!ftepp_skipspace(ftepp))
1505         return false;
1506
1507     switch (ftepp->token) {
1508         case TOKEN_KEYWORD:
1509         case TOKEN_IDENT:
1510         case TOKEN_TYPENAME:
1511             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1512                 ftepp_inmacro(ftepp, "define");
1513                 return ftepp_define(ftepp);
1514             }
1515             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1516                 ftepp_inmacro(ftepp, "undef");
1517                 return ftepp_undef(ftepp);
1518             }
1519             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1520                 ftepp_inmacro(ftepp, "ifdef");
1521                 if (!ftepp_ifdef(ftepp, &cond))
1522                     return false;
1523                 cond.was_on = cond.on;
1524                 vec_push(ftepp->conditions, cond);
1525                 ftepp->output_on = ftepp->output_on && cond.on;
1526                 break;
1527             }
1528             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1529                 ftepp_inmacro(ftepp, "ifndef");
1530                 if (!ftepp_ifdef(ftepp, &cond))
1531                     return false;
1532                 cond.on = !cond.on;
1533                 cond.was_on = cond.on;
1534                 vec_push(ftepp->conditions, cond);
1535                 ftepp->output_on = ftepp->output_on && cond.on;
1536                 break;
1537             }
1538             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1539                 ftepp_inmacro(ftepp, "elifdef");
1540                 if (!ftepp_else_allowed(ftepp))
1541                     return false;
1542                 if (!ftepp_ifdef(ftepp, &cond))
1543                     return false;
1544                 pc = &vec_last(ftepp->conditions);
1545                 pc->on     = !pc->was_on && cond.on;
1546                 pc->was_on = pc->was_on || pc->on;
1547                 ftepp_update_output_condition(ftepp);
1548                 break;
1549             }
1550             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1551                 ftepp_inmacro(ftepp, "elifndef");
1552                 if (!ftepp_else_allowed(ftepp))
1553                     return false;
1554                 if (!ftepp_ifdef(ftepp, &cond))
1555                     return false;
1556                 cond.on = !cond.on;
1557                 pc = &vec_last(ftepp->conditions);
1558                 pc->on     = !pc->was_on && cond.on;
1559                 pc->was_on = pc->was_on || pc->on;
1560                 ftepp_update_output_condition(ftepp);
1561                 break;
1562             }
1563             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1564                 ftepp_inmacro(ftepp, "elif");
1565                 if (!ftepp_else_allowed(ftepp))
1566                     return false;
1567                 if (!ftepp_if(ftepp, &cond))
1568                     return false;
1569                 pc = &vec_last(ftepp->conditions);
1570                 pc->on     = !pc->was_on && cond.on;
1571                 pc->was_on = pc->was_on  || pc->on;
1572                 ftepp_update_output_condition(ftepp);
1573                 break;
1574             }
1575             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1576                 ftepp_inmacro(ftepp, "if");
1577                 if (!ftepp_if(ftepp, &cond))
1578                     return false;
1579                 cond.was_on = cond.on;
1580                 vec_push(ftepp->conditions, cond);
1581                 ftepp->output_on = ftepp->output_on && cond.on;
1582                 break;
1583             }
1584             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1585                 ftepp_inmacro(ftepp, "else");
1586                 if (!ftepp_else_allowed(ftepp))
1587                     return false;
1588                 pc = &vec_last(ftepp->conditions);
1589                 pc->on = !pc->was_on;
1590                 pc->had_else = true;
1591                 ftepp_next(ftepp);
1592                 ftepp_update_output_condition(ftepp);
1593                 break;
1594             }
1595             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1596                 ftepp_inmacro(ftepp, "endif");
1597                 if (!vec_size(ftepp->conditions)) {
1598                     ftepp_error(ftepp, "#endif without #if");
1599                     return false;
1600                 }
1601                 vec_pop(ftepp->conditions);
1602                 ftepp_next(ftepp);
1603                 ftepp_update_output_condition(ftepp);
1604                 break;
1605             }
1606             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1607                 ftepp_inmacro(ftepp, "include");
1608                 return ftepp_include(ftepp);
1609             }
1610             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1611                 ftepp_out(ftepp, "#", false);
1612                 break;
1613             }
1614             else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1615                 ftepp_directive_warning(ftepp);
1616                 break;
1617             }
1618             else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1619                 ftepp_directive_error(ftepp);
1620                 break;
1621             }
1622             else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1623                 ftepp_directive_message(ftepp);
1624                 break;
1625             }
1626             else {
1627                 if (ftepp->output_on) {
1628                     ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1629                     return false;
1630                 } else {
1631                     ftepp_next(ftepp);
1632                     break;
1633                 }
1634             }
1635             /* break; never reached */
1636         default:
1637             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1638             return false;
1639         case TOKEN_EOL:
1640             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1641             return false;
1642         case TOKEN_EOF:
1643             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1644             return false;
1645
1646         /* Builtins! Don't forget the builtins! */
1647         case TOKEN_INTCONST:
1648         case TOKEN_FLOATCONST:
1649             ftepp_out(ftepp, "#", false);
1650             return true;
1651     }
1652     if (!ftepp_skipspace(ftepp))
1653         return false;
1654     return true;
1655 }
1656
1657 static bool ftepp_preprocess(ftepp_t *ftepp)
1658 {
1659     ppmacro *macro;
1660     bool     newline = true;
1661
1662     /* predef stuff */
1663     char    *expand  = NULL;
1664
1665     ftepp->lex->flags.preprocessing = true;
1666     ftepp->lex->flags.mergelines    = false;
1667     ftepp->lex->flags.noops         = true;
1668
1669     ftepp_next(ftepp);
1670     do
1671     {
1672         if (ftepp->token >= TOKEN_EOF)
1673             break;
1674 #if 0
1675         newline = true;
1676 #endif
1677
1678         switch (ftepp->token) {
1679             case TOKEN_KEYWORD:
1680             case TOKEN_IDENT:
1681             case TOKEN_TYPENAME:
1682                 /* is it a predef? */
1683                 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1684                     char *(*predef)(ftepp_t*) = ftepp_predef(ftepp_tokval(ftepp));
1685                     if (predef) {
1686                         expand = predef(ftepp);
1687                         ftepp_out (ftepp, expand, false);
1688                         ftepp_next(ftepp);
1689
1690                         mem_d(expand);
1691                         break;
1692                     }
1693                 }
1694
1695                 if (ftepp->output_on)
1696                     macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1697                 else
1698                     macro = NULL;
1699
1700                 if (!macro) {
1701                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1702                     ftepp_next(ftepp);
1703                     break;
1704                 }
1705                 if (!ftepp_macro_call(ftepp, macro))
1706                     ftepp->token = TOKEN_ERROR;
1707                 break;
1708             case '#':
1709                 if (!newline) {
1710                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1711                     ftepp_next(ftepp);
1712                     break;
1713                 }
1714                 ftepp->lex->flags.mergelines = true;
1715                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1716                     ftepp_error(ftepp, "error in preprocessor directive");
1717                     ftepp->token = TOKEN_ERROR;
1718                     break;
1719                 }
1720                 if (!ftepp_hash(ftepp))
1721                     ftepp->token = TOKEN_ERROR;
1722                 ftepp->lex->flags.mergelines = false;
1723                 break;
1724             case TOKEN_EOL:
1725                 newline = true;
1726                 ftepp_out(ftepp, "\n", true);
1727                 ftepp_next(ftepp);
1728                 break;
1729             case TOKEN_WHITE:
1730                 /* same as default but don't set newline=false */
1731                 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1732                 ftepp_next(ftepp);
1733                 break;
1734             default:
1735                 newline = false;
1736                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1737                 ftepp_next(ftepp);
1738                 break;
1739         }
1740     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1741
1742     /* force a 0 at the end but don't count it as added to the output */
1743     vec_push(ftepp->output_string, 0);
1744     vec_shrinkby(ftepp->output_string, 1);
1745
1746     return (ftepp->token == TOKEN_EOF);
1747 }
1748
1749 /* Like in parser.c - files keep the previous state so we have one global
1750  * preprocessor. Except here we will want to warn about dangling #ifs.
1751  */
1752 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1753 {
1754     bool retval = true;
1755     if (vec_size(ftepp->conditions)) {
1756         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1757             retval = false;
1758     }
1759     lex_close(ftepp->lex);
1760     ftepp->lex = NULL;
1761     if (ftepp->itemname) {
1762         mem_d(ftepp->itemname);
1763         ftepp->itemname = NULL;
1764     }
1765     return retval;
1766 }
1767
1768 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1769 {
1770     ftepp->lex = lex_open(filename);
1771     ftepp->itemname = util_strdup(filename);
1772     if (!ftepp->lex) {
1773         con_out("failed to open file \"%s\"\n", filename);
1774         return false;
1775     }
1776     if (!ftepp_preprocess(ftepp))
1777         return false;
1778     return ftepp_preprocess_done(ftepp);
1779 }
1780
1781 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1782 {
1783     ftepp->lex = lex_open_string(str, strlen(str), name);
1784     ftepp->itemname = util_strdup(name);
1785     if (!ftepp->lex) {
1786         con_out("failed to create lexer for string \"%s\"\n", name);
1787         return false;
1788     }
1789     if (!ftepp_preprocess(ftepp))
1790         return false;
1791     return ftepp_preprocess_done(ftepp);
1792 }
1793
1794
1795 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1796     char *create = NULL;
1797
1798     /* use saner path for empty macros */
1799     if (!value) {
1800         ftepp_add_define(ftepp, "__builtin__", name);
1801         return;
1802     }
1803
1804     vec_append(create, 8,           "#define ");
1805     vec_append(create, strlen(name), name);
1806     vec_push  (create, ' ');
1807     vec_append(create, strlen(value), value);
1808     vec_push  (create, 0);
1809
1810     ftepp_preprocess_string(ftepp, "__builtin__", create);
1811     vec_free  (create);
1812 }
1813
1814 ftepp_t *ftepp_create()
1815 {
1816     ftepp_t *ftepp;
1817     char minor[32];
1818     char major[32];
1819
1820     ftepp = ftepp_new();
1821     if (!ftepp)
1822         return NULL;
1823
1824     memset(minor, 0, sizeof(minor));
1825     memset(major, 0, sizeof(major));
1826
1827     /* set the right macro based on the selected standard */
1828     ftepp_add_define(ftepp, NULL, "GMQCC");
1829     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1830         ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1831         /* 1.00 */
1832         major[0] = '"';
1833         major[1] = '1';
1834         major[2] = '"';
1835
1836         minor[0] = '"';
1837         minor[1] = '0';
1838         minor[2] = '"';
1839     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1840         ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1841         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1842         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1843     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1844         ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1845         util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1846         util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1847     } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1848         ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1849         /* 1.0 */
1850         major[0] = '"';
1851         major[1] = '1';
1852         major[2] = '"';
1853
1854         minor[0] = '"';
1855         minor[1] = '0';
1856         minor[2] = '"';
1857     }
1858
1859     ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1860     ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1861
1862     /*
1863      * We're going to just make __NULL__ nil, which works for 60% of the
1864      * cases of __NULL_ for fteqcc.
1865      */
1866     ftepp_add_macro(ftepp, "__NULL__", "nil");
1867
1868     return ftepp;
1869 }
1870
1871 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1872 {
1873     ppmacro *macro;
1874     lex_ctx_t ctx = { "__builtin__", 0, 0 };
1875     ctx.file = source;
1876     macro = ppmacro_new(ctx, name);
1877     /*vec_push(ftepp->macros, macro);*/
1878     util_htset(ftepp->macros, name, macro);
1879 }
1880
1881 const char *ftepp_get(ftepp_t *ftepp)
1882 {
1883     return ftepp->output_string;
1884 }
1885
1886 void ftepp_flush(ftepp_t *ftepp)
1887 {
1888     ftepp_flush_do(ftepp);
1889 }
1890
1891 void ftepp_finish(ftepp_t *ftepp)
1892 {
1893     if (!ftepp)
1894         return;
1895     ftepp_delete(ftepp);
1896 }