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