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