]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Add specialized diagnostics for when predefined macros are used and ftepp predefined...
[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
826     if (!ftepp_skipspace(ftepp))
827         return false;
828
829     while (ftepp->token == '!') {
830         wasnot = true;
831         ftepp_next(ftepp);
832         if (!ftepp_skipspace(ftepp))
833             return false;
834     }
835
836     switch (ftepp->token) {
837         case TOKEN_IDENT:
838         case TOKEN_TYPENAME:
839         case TOKEN_KEYWORD:
840             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
841                 ftepp_next(ftepp);
842                 if (!ftepp_skipspace(ftepp))
843                     return false;
844                 if (ftepp->token != '(') {
845                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
846                     return false;
847                 }
848                 ftepp_next(ftepp);
849                 if (!ftepp_skipspace(ftepp))
850                     return false;
851                 if (ftepp->token != TOKEN_IDENT &&
852                     ftepp->token != TOKEN_TYPENAME &&
853                     ftepp->token != TOKEN_KEYWORD)
854                 {
855                     ftepp_error(ftepp, "defined() used on an unexpected token type");
856                     return false;
857                 }
858                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
859                 *out = !!macro;
860                 ftepp_next(ftepp);
861                 if (!ftepp_skipspace(ftepp))
862                     return false;
863                 if (ftepp->token != ')') {
864                     ftepp_error(ftepp, "expected closing paren");
865                     return false;
866                 }
867                 break;
868             }
869
870             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
871             if (!macro || !vec_size(macro->output)) {
872                 *out = false;
873                 *value_out = 0;
874             } else {
875                 /* This does not expand recursively! */
876                 switch (macro->output[0]->token) {
877                     case TOKEN_INTCONST:
878                         *value_out = macro->output[0]->constval.i;
879                         *out = !!(macro->output[0]->constval.i);
880                         break;
881                     case TOKEN_FLOATCONST:
882                         *value_out = macro->output[0]->constval.f;
883                         *out = !!(macro->output[0]->constval.f);
884                         break;
885                     default:
886                         *out = false;
887                         break;
888                 }
889             }
890             break;
891         case TOKEN_STRINGCONST:
892             *out = false;
893             break;
894         case TOKEN_INTCONST:
895             *value_out = ftepp->lex->tok.constval.i;
896             *out = !!(ftepp->lex->tok.constval.i);
897             break;
898         case TOKEN_FLOATCONST:
899             *value_out = ftepp->lex->tok.constval.f;
900             *out = !!(ftepp->lex->tok.constval.f);
901             break;
902
903         case '(':
904             ftepp_next(ftepp);
905             if (!ftepp_if_expr(ftepp, out, value_out))
906                 return false;
907             if (ftepp->token != ')') {
908                 ftepp_error(ftepp, "expected closing paren in #if expression");
909                 return false;
910             }
911             break;
912
913         default:
914             ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
915             return false;
916     }
917     if (wasnot) {
918         *out = !*out;
919         *value_out = (*out ? 1 : 0);
920     }
921     return true;
922 }
923
924 /*
925 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
926 {
927     if (!ftepp_next(ftepp))
928         return false;
929     return ftepp_if_value(ftepp, out, value_out);
930 }
931 */
932
933 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
934 {
935     if (!ftepp_if_value(ftepp, out, value_out))
936         return false;
937
938     if (!ftepp_if_op(ftepp))
939         return false;
940
941     if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
942         return true;
943
944     /* FTEQCC is all right-associative and no precedence here */
945     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
946         !strcmp(ftepp_tokval(ftepp), "||"))
947     {
948         bool next = false;
949         char opc  = ftepp_tokval(ftepp)[0];
950         double nextvalue;
951
952         (void)nextvalue;
953         if (!ftepp_next(ftepp))
954             return false;
955         if (!ftepp_if_expr(ftepp, &next, &nextvalue))
956             return false;
957
958         if (opc == '&')
959             *out = *out && next;
960         else
961             *out = *out || next;
962
963         *value_out = (*out ? 1 : 0);
964         return true;
965     }
966     else if (!strcmp(ftepp_tokval(ftepp), "==") ||
967              !strcmp(ftepp_tokval(ftepp), "!=") ||
968              !strcmp(ftepp_tokval(ftepp), ">=") ||
969              !strcmp(ftepp_tokval(ftepp), "<=") ||
970              !strcmp(ftepp_tokval(ftepp), ">") ||
971              !strcmp(ftepp_tokval(ftepp), "<"))
972     {
973         bool next = false;
974         const char opc0 = ftepp_tokval(ftepp)[0];
975         const char opc1 = ftepp_tokval(ftepp)[1];
976         double other;
977
978         if (!ftepp_next(ftepp))
979             return false;
980         if (!ftepp_if_expr(ftepp, &next, &other))
981             return false;
982
983         if (opc0 == '=')
984             *out = (*value_out == other);
985         else if (opc0 == '!')
986             *out = (*value_out != other);
987         else if (opc0 == '>') {
988             if (opc1 == '=') *out = (*value_out >= other);
989             else             *out = (*value_out > other);
990         }
991         else if (opc0 == '<') {
992             if (opc1 == '=') *out = (*value_out <= other);
993             else             *out = (*value_out < other);
994         }
995         *value_out = (*out ? 1 : 0);
996
997         return true;
998     }
999     else {
1000         ftepp_error(ftepp, "junk after #if");
1001         return false;
1002     }
1003 }
1004
1005 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1006 {
1007     bool result = false;
1008     double dummy = 0;
1009
1010     memset(cond, 0, sizeof(*cond));
1011     (void)ftepp_next(ftepp);
1012
1013     if (!ftepp_skipspace(ftepp))
1014         return false;
1015     if (ftepp->token == TOKEN_EOL) {
1016         ftepp_error(ftepp, "expected expression for #if-directive");
1017         return false;
1018     }
1019
1020     if (!ftepp_if_expr(ftepp, &result, &dummy))
1021         return false;
1022
1023     cond->on = result;
1024     return true;
1025 }
1026
1027 /**
1028  * ifdef is rather simple
1029  */
1030 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1031 {
1032     ppmacro *macro;
1033     memset(cond, 0, sizeof(*cond));
1034     (void)ftepp_next(ftepp);
1035     if (!ftepp_skipspace(ftepp))
1036         return false;
1037
1038     switch (ftepp->token) {
1039         case TOKEN_IDENT:
1040         case TOKEN_TYPENAME:
1041         case TOKEN_KEYWORD:
1042             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1043             break;
1044         default:
1045             ftepp_error(ftepp, "expected macro name");
1046             return false;
1047     }
1048
1049     (void)ftepp_next(ftepp);
1050     if (!ftepp_skipspace(ftepp))
1051         return false;
1052     /* relaxing this condition
1053     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1054         ftepp_error(ftepp, "stray tokens after #ifdef");
1055         return false;
1056     }
1057     */
1058     cond->on = !!macro;
1059     return true;
1060 }
1061
1062 /**
1063  * undef is also simple
1064  */
1065 static bool ftepp_undef(ftepp_t *ftepp)
1066 {
1067     (void)ftepp_next(ftepp);
1068     if (!ftepp_skipspace(ftepp))
1069         return false;
1070
1071     if (ftepp->output_on) {
1072         switch (ftepp->token) {
1073             case TOKEN_IDENT:
1074             case TOKEN_TYPENAME:
1075             case TOKEN_KEYWORD:
1076                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1077                 break;
1078             default:
1079                 ftepp_error(ftepp, "expected macro name");
1080                 return false;
1081         }
1082     }
1083
1084     (void)ftepp_next(ftepp);
1085     if (!ftepp_skipspace(ftepp))
1086         return false;
1087     /* relaxing this condition
1088     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1089         ftepp_error(ftepp, "stray tokens after #ifdef");
1090         return false;
1091     }
1092     */
1093     return true;
1094 }
1095
1096 /* Special unescape-string function which skips a leading quote
1097  * and stops at a quote, not just at \0
1098  */
1099 static void unescape(const char *str, char *out) {
1100     ++str;
1101     while (*str && *str != '"') {
1102         if (*str == '\\') {
1103             ++str;
1104             switch (*str) {
1105                 case '\\': *out++ = *str; break;
1106                 case '"':  *out++ = *str; break;
1107                 case 'a':  *out++ = '\a'; break;
1108                 case 'b':  *out++ = '\b'; break;
1109                 case 'r':  *out++ = '\r'; break;
1110                 case 'n':  *out++ = '\n'; break;
1111                 case 't':  *out++ = '\t'; break;
1112                 case 'f':  *out++ = '\f'; break;
1113                 case 'v':  *out++ = '\v'; break;
1114                 default:
1115                     *out++ = '\\';
1116                     *out++ = *str;
1117                     break;
1118             }
1119             ++str;
1120             continue;
1121         }
1122
1123         *out++ = *str++;
1124     }
1125     *out = 0;
1126 }
1127
1128 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1129 {
1130     FILE       *fp;
1131     char       *filename = NULL;
1132     const char *last_slash;
1133     size_t      len;
1134
1135     if (!pathfile)
1136         return NULL;
1137
1138     last_slash = strrchr(pathfile, '/');
1139
1140     if (last_slash) {
1141         len = last_slash - pathfile;
1142         memcpy(vec_add(filename, len), pathfile, len);
1143         vec_push(filename, '/');
1144     }
1145
1146     len = strlen(file);
1147     memcpy(vec_add(filename, len+1), file, len);
1148     vec_last(filename) = 0;
1149
1150     fp = file_open(filename, "rb");
1151     if (fp) {
1152         file_close(fp);
1153         return filename;
1154     }
1155     vec_free(filename);
1156     return NULL;
1157 }
1158
1159 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1160 {
1161     char *filename = NULL;
1162
1163     filename = ftepp_include_find_path(file, ftepp->includename);
1164     if (!filename)
1165         filename = ftepp_include_find_path(file, ftepp->itemname);
1166     return filename;
1167 }
1168
1169 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1170     char *message = NULL;
1171
1172     if (!ftepp_skipspace(ftepp))
1173         return false;
1174
1175     /* handle the odd non string constant case so it works like C */
1176     if (ftepp->token != TOKEN_STRINGCONST) {
1177         bool  store   = false;
1178         vec_upload(message, "#warning", 8);
1179         ftepp_next(ftepp);
1180         while (ftepp->token != TOKEN_EOL) {
1181             vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1182             ftepp_next(ftepp);
1183         }
1184         vec_push(message, '\0');
1185         store = ftepp_warn(ftepp, WARN_CPP, message);
1186         vec_free(message);
1187         return store;
1188     }
1189
1190     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1191     return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1192 }
1193
1194 static void ftepp_directive_error(ftepp_t *ftepp) {
1195     char *message = NULL;
1196
1197     if (!ftepp_skipspace(ftepp))
1198         return;
1199
1200     /* handle the odd non string constant case so it works like C */
1201     if (ftepp->token != TOKEN_STRINGCONST) {
1202         vec_upload(message, "#error", 6);
1203         ftepp_next(ftepp);
1204         while (ftepp->token != TOKEN_EOL) {
1205             vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1206             ftepp_next(ftepp);
1207         }
1208         vec_push(message, '\0');
1209         ftepp_error(ftepp, message);
1210         vec_free(message);
1211         return;
1212     }
1213
1214     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1215     ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1216 }
1217
1218 /**
1219  * Include a file.
1220  * FIXME: do we need/want a -I option?
1221  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1222  */
1223 static bool ftepp_include(ftepp_t *ftepp)
1224 {
1225     lex_file *old_lexer = ftepp->lex;
1226     lex_file *inlex;
1227     lex_ctx  ctx;
1228     char     lineno[128];
1229     char     *filename;
1230     char     *old_includename;
1231
1232     (void)ftepp_next(ftepp);
1233     if (!ftepp_skipspace(ftepp))
1234         return false;
1235
1236     if (ftepp->token != TOKEN_STRINGCONST) {
1237         ftepp_error(ftepp, "expected filename to include");
1238         return false;
1239     }
1240
1241     ctx = ftepp_ctx(ftepp);
1242
1243     unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1244
1245     ftepp_out(ftepp, "\n#pragma file(", false);
1246     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1247     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1248
1249     filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1250     if (!filename) {
1251         ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1252         return false;
1253     }
1254     inlex = lex_open(filename);
1255     if (!inlex) {
1256         ftepp_error(ftepp, "open failed on include file `%s`", filename);
1257         vec_free(filename);
1258         return false;
1259     }
1260     ftepp->lex = inlex;
1261     old_includename = ftepp->includename;
1262     ftepp->includename = filename;
1263     if (!ftepp_preprocess(ftepp)) {
1264         vec_free(ftepp->includename);
1265         ftepp->includename = old_includename;
1266         lex_close(ftepp->lex);
1267         ftepp->lex = old_lexer;
1268         return false;
1269     }
1270     vec_free(ftepp->includename);
1271     ftepp->includename = old_includename;
1272     lex_close(ftepp->lex);
1273     ftepp->lex = old_lexer;
1274
1275     ftepp_out(ftepp, "\n#pragma file(", false);
1276     ftepp_out(ftepp, ctx.file, false);
1277     snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1278     ftepp_out(ftepp, lineno, false);
1279
1280     /* skip the line */
1281     (void)ftepp_next(ftepp);
1282     if (!ftepp_skipspace(ftepp))
1283         return false;
1284     if (ftepp->token != TOKEN_EOL) {
1285         ftepp_error(ftepp, "stray tokens after #include");
1286         return false;
1287     }
1288     (void)ftepp_next(ftepp);
1289
1290     return true;
1291 }
1292
1293 /* Basic structure handlers */
1294 static bool ftepp_else_allowed(ftepp_t *ftepp)
1295 {
1296     if (!vec_size(ftepp->conditions)) {
1297         ftepp_error(ftepp, "#else without #if");
1298         return false;
1299     }
1300     if (vec_last(ftepp->conditions).had_else) {
1301         ftepp_error(ftepp, "multiple #else for a single #if");
1302         return false;
1303     }
1304     return true;
1305 }
1306
1307 static bool ftepp_hash(ftepp_t *ftepp)
1308 {
1309     ppcondition cond;
1310     ppcondition *pc;
1311
1312     lex_ctx ctx = ftepp_ctx(ftepp);
1313
1314     if (!ftepp_skipspace(ftepp))
1315         return false;
1316
1317     switch (ftepp->token) {
1318         case TOKEN_KEYWORD:
1319         case TOKEN_IDENT:
1320         case TOKEN_TYPENAME:
1321             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1322                 return ftepp_define(ftepp);
1323             }
1324             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1325                 return ftepp_undef(ftepp);
1326             }
1327             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1328                 if (!ftepp_ifdef(ftepp, &cond))
1329                     return false;
1330                 cond.was_on = cond.on;
1331                 vec_push(ftepp->conditions, cond);
1332                 ftepp->output_on = ftepp->output_on && cond.on;
1333                 break;
1334             }
1335             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1336                 if (!ftepp_ifdef(ftepp, &cond))
1337                     return false;
1338                 cond.on = !cond.on;
1339                 cond.was_on = cond.on;
1340                 vec_push(ftepp->conditions, cond);
1341                 ftepp->output_on = ftepp->output_on && cond.on;
1342                 break;
1343             }
1344             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1345                 if (!ftepp_else_allowed(ftepp))
1346                     return false;
1347                 if (!ftepp_ifdef(ftepp, &cond))
1348                     return false;
1349                 pc = &vec_last(ftepp->conditions);
1350                 pc->on     = !pc->was_on && cond.on;
1351                 pc->was_on = pc->was_on || pc->on;
1352                 ftepp_update_output_condition(ftepp);
1353                 break;
1354             }
1355             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1356                 if (!ftepp_else_allowed(ftepp))
1357                     return false;
1358                 if (!ftepp_ifdef(ftepp, &cond))
1359                     return false;
1360                 cond.on = !cond.on;
1361                 pc = &vec_last(ftepp->conditions);
1362                 pc->on     = !pc->was_on && cond.on;
1363                 pc->was_on = pc->was_on || pc->on;
1364                 ftepp_update_output_condition(ftepp);
1365                 break;
1366             }
1367             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1368                 if (!ftepp_else_allowed(ftepp))
1369                     return false;
1370                 if (!ftepp_if(ftepp, &cond))
1371                     return false;
1372                 pc = &vec_last(ftepp->conditions);
1373                 pc->on     = !pc->was_on && cond.on;
1374                 pc->was_on = pc->was_on  || pc->on;
1375                 ftepp_update_output_condition(ftepp);
1376                 break;
1377             }
1378             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1379                 if (!ftepp_if(ftepp, &cond))
1380                     return false;
1381                 cond.was_on = cond.on;
1382                 vec_push(ftepp->conditions, cond);
1383                 ftepp->output_on = ftepp->output_on && cond.on;
1384                 break;
1385             }
1386             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1387                 if (!ftepp_else_allowed(ftepp))
1388                     return false;
1389                 pc = &vec_last(ftepp->conditions);
1390                 pc->on = !pc->was_on;
1391                 pc->had_else = true;
1392                 ftepp_next(ftepp);
1393                 ftepp_update_output_condition(ftepp);
1394                 break;
1395             }
1396             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1397                 if (!vec_size(ftepp->conditions)) {
1398                     ftepp_error(ftepp, "#endif without #if");
1399                     return false;
1400                 }
1401                 vec_pop(ftepp->conditions);
1402                 ftepp_next(ftepp);
1403                 ftepp_update_output_condition(ftepp);
1404                 break;
1405             }
1406             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1407                 return ftepp_include(ftepp);
1408             }
1409             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1410                 ftepp_out(ftepp, "#", false);
1411                 break;
1412             }
1413             else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1414                 ftepp_directive_warning(ftepp);
1415                 break;
1416             }
1417             else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1418                 ftepp_directive_error(ftepp);
1419                 break;
1420             }
1421             else {
1422                 if (ftepp->output_on) {
1423                     ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1424                     return false;
1425                 } else {
1426                     ftepp_next(ftepp);
1427                     break;
1428                 }
1429             }
1430             /* break; never reached */
1431         default:
1432             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1433             return false;
1434         case TOKEN_EOL:
1435             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1436             return false;
1437         case TOKEN_EOF:
1438             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1439             return false;
1440
1441         /* Builtins! Don't forget the builtins! */
1442         case TOKEN_INTCONST:
1443         case TOKEN_FLOATCONST:
1444             ftepp_out(ftepp, "#", false);
1445             return true;
1446     }
1447     if (!ftepp_skipspace(ftepp))
1448         return false;
1449     return true;
1450 }
1451
1452 static bool ftepp_preprocess(ftepp_t *ftepp)
1453 {
1454     ppmacro *macro;
1455     bool     newline = true;
1456
1457     /* predef stuff */
1458     char    *expand  = NULL;
1459     size_t   i;
1460
1461     ftepp->lex->flags.preprocessing = true;
1462     ftepp->lex->flags.mergelines    = false;
1463     ftepp->lex->flags.noops         = true;
1464
1465     ftepp_next(ftepp);
1466     do
1467     {
1468         if (ftepp->token >= TOKEN_EOF)
1469             break;
1470 #if 0
1471         newline = true;
1472 #endif
1473
1474         switch (ftepp->token) {
1475             case TOKEN_KEYWORD:
1476             case TOKEN_IDENT:
1477             case TOKEN_TYPENAME:
1478                 /* is it a predef? */
1479                 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1480                     for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1481                         if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1482                             expand = ftepp_predefs[i].func(ftepp->lex);
1483                             ftepp_out(ftepp, expand, false);
1484                             ftepp_next(ftepp); /* skip */
1485
1486                             mem_d(expand); /* free memory */
1487                             break;
1488                         }
1489                     }
1490                 }
1491
1492                 if (ftepp->output_on)
1493                     macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1494                 else
1495                     macro = NULL;
1496
1497                 if (!macro) {
1498                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1499                     ftepp_next(ftepp);
1500                     break;
1501                 }
1502                 if (!ftepp_macro_call(ftepp, macro))
1503                     ftepp->token = TOKEN_ERROR;
1504                 break;
1505             case '#':
1506                 if (!newline) {
1507                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1508                     ftepp_next(ftepp);
1509                     break;
1510                 }
1511                 ftepp->lex->flags.mergelines = true;
1512                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1513                     ftepp_error(ftepp, "error in preprocessor directive");
1514                     ftepp->token = TOKEN_ERROR;
1515                     break;
1516                 }
1517                 if (!ftepp_hash(ftepp))
1518                     ftepp->token = TOKEN_ERROR;
1519                 ftepp->lex->flags.mergelines = false;
1520                 break;
1521             case TOKEN_EOL:
1522                 newline = true;
1523                 ftepp_out(ftepp, "\n", true);
1524                 ftepp_next(ftepp);
1525                 break;
1526             case TOKEN_WHITE:
1527                 /* same as default but don't set newline=false */
1528                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1529                 ftepp_next(ftepp);
1530                 break;
1531             default:
1532                 newline = false;
1533                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1534                 ftepp_next(ftepp);
1535                 break;
1536         }
1537     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1538
1539     /* force a 0 at the end but don't count it as added to the output */
1540     vec_push(ftepp->output_string, 0);
1541     vec_shrinkby(ftepp->output_string, 1);
1542
1543     return (ftepp->token == TOKEN_EOF);
1544 }
1545
1546 /* Like in parser.c - files keep the previous state so we have one global
1547  * preprocessor. Except here we will want to warn about dangling #ifs.
1548  */
1549 static ftepp_t *ftepp;
1550
1551 static bool ftepp_preprocess_done()
1552 {
1553     bool retval = true;
1554     if (vec_size(ftepp->conditions)) {
1555         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1556             retval = false;
1557     }
1558     lex_close(ftepp->lex);
1559     ftepp->lex = NULL;
1560     if (ftepp->itemname) {
1561         mem_d(ftepp->itemname);
1562         ftepp->itemname = NULL;
1563     }
1564     return retval;
1565 }
1566
1567 bool ftepp_preprocess_file(const char *filename)
1568 {
1569     ftepp->lex = lex_open(filename);
1570     ftepp->itemname = util_strdup(filename);
1571     if (!ftepp->lex) {
1572         con_out("failed to open file \"%s\"\n", filename);
1573         return false;
1574     }
1575     if (!ftepp_preprocess(ftepp))
1576         return false;
1577     return ftepp_preprocess_done();
1578 }
1579
1580 bool ftepp_preprocess_string(const char *name, const char *str)
1581 {
1582     ftepp->lex = lex_open_string(str, strlen(str), name);
1583     ftepp->itemname = util_strdup(name);
1584     if (!ftepp->lex) {
1585         con_out("failed to create lexer for string \"%s\"\n", name);
1586         return false;
1587     }
1588     if (!ftepp_preprocess(ftepp))
1589         return false;
1590     return ftepp_preprocess_done();
1591 }
1592
1593
1594 void ftepp_add_macro(const char *name, const char *value) {
1595     char *create = NULL;
1596
1597     /* use saner path for empty macros */
1598     if (!value) {
1599         ftepp_add_define("__builtin__", name);
1600         return;
1601     }
1602
1603     vec_upload(create, "#define ", 8);
1604     vec_upload(create, name,  strlen(name));
1605     vec_push  (create, ' ');
1606     vec_upload(create, value, strlen(value));
1607     vec_push  (create, 0);
1608
1609     ftepp_preprocess_string("__builtin__", create);
1610     vec_free  (create);
1611 }
1612
1613 bool ftepp_init()
1614 {
1615     char minor[32];
1616     char major[32];
1617
1618     ftepp = ftepp_new();
1619     if (!ftepp)
1620         return false;
1621
1622     memset(minor, 0, sizeof(minor));
1623     memset(major, 0, sizeof(major));
1624
1625     /* set the right macro based on the selected standard */
1626     ftepp_add_define(NULL, "GMQCC");
1627     if (opts.standard == COMPILER_FTEQCC) {
1628         ftepp_add_define(NULL, "__STD_FTEQCC__");
1629         /* 1.00 */
1630         major[0] = '"';
1631         major[1] = '1';
1632         major[2] = '"';
1633
1634         minor[0] = '"';
1635         minor[1] = '0';
1636         minor[2] = '"';
1637     } else if (opts.standard == COMPILER_GMQCC) {
1638         ftepp_add_define(NULL, "__STD_GMQCC__");
1639         sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1640         sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1641     } else if (opts.standard == COMPILER_QCC) {
1642         ftepp_add_define(NULL, "__STD_QCC__");
1643         /* 1.0 */
1644         major[0] = '"';
1645         major[1] = '1';
1646         major[2] = '"';
1647
1648         minor[0] = '"';
1649         minor[1] = '0';
1650         minor[2] = '"';
1651     }
1652
1653     ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1654     ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1655
1656     return true;
1657 }
1658
1659 void ftepp_add_define(const char *source, const char *name)
1660 {
1661     ppmacro *macro;
1662     lex_ctx ctx = { "__builtin__", 0 };
1663     ctx.file = source;
1664     macro = ppmacro_new(ctx, name);
1665     vec_push(ftepp->macros, macro);
1666 }
1667
1668 const char *ftepp_get()
1669 {
1670     return ftepp->output_string;
1671 }
1672
1673 void ftepp_flush()
1674 {
1675     ftepp_flush_do(ftepp);
1676 }
1677
1678 void ftepp_finish()
1679 {
1680     if (!ftepp)
1681         return;
1682     ftepp_delete(ftepp);
1683     ftepp = NULL;
1684 }