]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
call ftepp_recursion_header/footer only when there are newlines in the expanded macro
[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     bool      has_newlines;
644     size_t    varargs;
645
646     size_t    o, pi;
647     lex_file *inlex;
648
649     int nextok;
650
651     if (vararg_start < vec_size(params))
652         varargs = vec_size(params) - vararg_start;
653     else
654         varargs = 0;
655
656     /* really ... */
657     if (!vec_size(macro->output))
658         return true;
659
660     ftepp->output_string = NULL;
661     for (o = 0; o < vec_size(macro->output); ++o) {
662         pptoken *out = macro->output[o];
663         switch (out->token) {
664             case TOKEN_VA_ARGS:
665                 if (!macro->variadic) {
666                     ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
667                     return false;
668                 }
669                 if (!varargs)
670                     break;
671                 pi = 0;
672                 ftepp_param_out(ftepp, &params[pi + vararg_start]);
673                 for (++pi; pi < varargs; ++pi) {
674                     ftepp_out(ftepp, ", ", false);
675                     ftepp_param_out(ftepp, &params[pi + vararg_start]);
676                 }
677                 break;
678             case TOKEN_IDENT:
679             case TOKEN_TYPENAME:
680             case TOKEN_KEYWORD:
681                 if (!macro_params_find(macro, out->value, &pi)) {
682                     ftepp_out(ftepp, out->value, false);
683                     break;
684                 } else
685                     ftepp_param_out(ftepp, &params[pi]);
686                 break;
687             case '#':
688                 if (o + 1 < vec_size(macro->output)) {
689                     nextok = macro->output[o+1]->token;
690                     if (nextok == '#') {
691                         /* raw concatenation */
692                         ++o;
693                         break;
694                     }
695                     if ( (nextok == TOKEN_IDENT    ||
696                           nextok == TOKEN_KEYWORD  ||
697                           nextok == TOKEN_TYPENAME) &&
698                         macro_params_find(macro, macro->output[o+1]->value, &pi))
699                     {
700                         ++o;
701                         ftepp_stringify(ftepp, &params[pi]);
702                         break;
703                     }
704                 }
705                 ftepp_out(ftepp, "#", false);
706                 break;
707             case TOKEN_EOL:
708                 ftepp_out(ftepp, "\n", false);
709                 break;
710             default:
711                 ftepp_out(ftepp, out->value, false);
712                 break;
713         }
714     }
715     vec_push(ftepp->output_string, 0);
716     has_newlines = (strchr(ftepp->output_string, '\n') != NULL);
717     /* Now run the preprocessor recursively on this string buffer */
718     /*
719     printf("__________\n%s\n=========\n", ftepp->output_string);
720     */
721     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
722     if (!inlex) {
723         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
724         retval = false;
725         goto cleanup;
726     }
727     ftepp->output_string = old_string;
728     inlex->line = ftepp->lex->line;
729     inlex->sline = ftepp->lex->sline;
730     ftepp->lex = inlex;
731     if (has_newlines)
732         ftepp_recursion_header(ftepp);
733     if (!ftepp_preprocess(ftepp)) {
734         vec_free(ftepp->lex->open_string);
735         old_string = ftepp->output_string;
736         lex_close(ftepp->lex);
737         retval = false;
738         goto cleanup;
739     }
740     vec_free(ftepp->lex->open_string);
741     if (has_newlines)
742         ftepp_recursion_footer(ftepp);
743     old_string = ftepp->output_string;
744
745 cleanup:
746     ftepp->lex           = old_lexer;
747     ftepp->output_string = old_string;
748     return retval;
749 }
750
751 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
752 {
753     size_t     o;
754     macroparam *params = NULL;
755     bool        retval = true;
756
757     if (!macro->has_params) {
758         if (!ftepp_macro_expand(ftepp, macro, NULL))
759             return false;
760         ftepp_next(ftepp);
761         return true;
762     }
763     ftepp_next(ftepp);
764
765     if (!ftepp_skipallwhite(ftepp))
766         return false;
767
768     if (ftepp->token != '(') {
769         ftepp_error(ftepp, "expected macro parameters in parenthesis");
770         return false;
771     }
772
773     ftepp_next(ftepp);
774     if (!ftepp_macro_call_params(ftepp, &params))
775         return false;
776
777     if ( vec_size(params) < vec_size(macro->params) ||
778         (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
779     {
780         ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
781                     (macro->variadic ? " at least" : ""),
782                     (unsigned int)vec_size(macro->params),
783                     (unsigned int)vec_size(params));
784         retval = false;
785         goto cleanup;
786     }
787
788     if (!ftepp_macro_expand(ftepp, macro, params))
789         retval = false;
790     ftepp_next(ftepp);
791
792 cleanup:
793     for (o = 0; o < vec_size(params); ++o)
794         macroparam_clean(&params[o]);
795     vec_free(params);
796     return retval;
797 }
798
799 /**
800  * #if - the FTEQCC way:
801  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
802  *    <numbers>    => True if the number is not 0
803  *    !<factor>    => True if the factor yields false
804  *    !!<factor>   => ERROR on 2 or more unary nots
805  *    <macro>      => becomes the macro's FIRST token regardless of parameters
806  *    <e> && <e>   => True if both expressions are true
807  *    <e> || <e>   => True if either expression is true
808  *    <string>     => False
809  *    <ident>      => False (remember for macros the <macro> rule applies instead)
810  * Unary + and - are weird and wrong in fteqcc so we don't allow them
811  * parenthesis in expressions are allowed
812  * parameter lists on macros are errors
813  * No mathematical calculations are executed
814  */
815 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
816 static bool ftepp_if_op(ftepp_t *ftepp)
817 {
818     ftepp->lex->flags.noops = false;
819     ftepp_next(ftepp);
820     if (!ftepp_skipspace(ftepp))
821         return false;
822     ftepp->lex->flags.noops = true;
823     return true;
824 }
825 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
826 {
827     ppmacro *macro;
828     bool     wasnot = false;
829     bool     wasneg = 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     if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
842     {
843         wasneg = true;
844         ftepp_next(ftepp);
845         if (!ftepp_skipspace(ftepp))
846             return false;
847     }
848
849     switch (ftepp->token) {
850         case TOKEN_IDENT:
851         case TOKEN_TYPENAME:
852         case TOKEN_KEYWORD:
853             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
854                 ftepp_next(ftepp);
855                 if (!ftepp_skipspace(ftepp))
856                     return false;
857                 if (ftepp->token != '(') {
858                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
859                     return false;
860                 }
861                 ftepp_next(ftepp);
862                 if (!ftepp_skipspace(ftepp))
863                     return false;
864                 if (ftepp->token != TOKEN_IDENT &&
865                     ftepp->token != TOKEN_TYPENAME &&
866                     ftepp->token != TOKEN_KEYWORD)
867                 {
868                     ftepp_error(ftepp, "defined() used on an unexpected token type");
869                     return false;
870                 }
871                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
872                 *out = !!macro;
873                 ftepp_next(ftepp);
874                 if (!ftepp_skipspace(ftepp))
875                     return false;
876                 if (ftepp->token != ')') {
877                     ftepp_error(ftepp, "expected closing paren");
878                     return false;
879                 }
880                 break;
881             }
882
883             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
884             if (!macro || !vec_size(macro->output)) {
885                 *out = false;
886                 *value_out = 0;
887             } else {
888                 /* This does not expand recursively! */
889                 switch (macro->output[0]->token) {
890                     case TOKEN_INTCONST:
891                         *value_out = macro->output[0]->constval.i;
892                         *out = !!(macro->output[0]->constval.i);
893                         break;
894                     case TOKEN_FLOATCONST:
895                         *value_out = macro->output[0]->constval.f;
896                         *out = !!(macro->output[0]->constval.f);
897                         break;
898                     default:
899                         *out = false;
900                         break;
901                 }
902             }
903             break;
904         case TOKEN_STRINGCONST:
905             *value_out = 0;
906             *out = false;
907             break;
908         case TOKEN_INTCONST:
909             *value_out = ftepp->lex->tok.constval.i;
910             *out = !!(ftepp->lex->tok.constval.i);
911             break;
912         case TOKEN_FLOATCONST:
913             *value_out = ftepp->lex->tok.constval.f;
914             *out = !!(ftepp->lex->tok.constval.f);
915             break;
916
917         case '(':
918             ftepp_next(ftepp);
919             if (!ftepp_if_expr(ftepp, out, value_out))
920                 return false;
921             if (ftepp->token != ')') {
922                 ftepp_error(ftepp, "expected closing paren in #if expression");
923                 return false;
924             }
925             break;
926
927         default:
928             ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
929             if (opts.debug)
930                 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
931             return false;
932     }
933     if (wasneg)
934         *value_out = -*value_out;
935     if (wasnot) {
936         *out = !*out;
937         *value_out = (*out ? 1 : 0);
938     }
939     return true;
940 }
941
942 /*
943 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
944 {
945     if (!ftepp_next(ftepp))
946         return false;
947     return ftepp_if_value(ftepp, out, value_out);
948 }
949 */
950
951 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
952 {
953     if (!ftepp_if_value(ftepp, out, value_out))
954         return false;
955
956     if (!ftepp_if_op(ftepp))
957         return false;
958
959     if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
960         return true;
961
962     /* FTEQCC is all right-associative and no precedence here */
963     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
964         !strcmp(ftepp_tokval(ftepp), "||"))
965     {
966         bool next = false;
967         char opc  = ftepp_tokval(ftepp)[0];
968         double nextvalue;
969
970         (void)nextvalue;
971         if (!ftepp_next(ftepp))
972             return false;
973         if (!ftepp_if_expr(ftepp, &next, &nextvalue))
974             return false;
975
976         if (opc == '&')
977             *out = *out && next;
978         else
979             *out = *out || next;
980
981         *value_out = (*out ? 1 : 0);
982         return true;
983     }
984     else if (!strcmp(ftepp_tokval(ftepp), "==") ||
985              !strcmp(ftepp_tokval(ftepp), "!=") ||
986              !strcmp(ftepp_tokval(ftepp), ">=") ||
987              !strcmp(ftepp_tokval(ftepp), "<=") ||
988              !strcmp(ftepp_tokval(ftepp), ">") ||
989              !strcmp(ftepp_tokval(ftepp), "<"))
990     {
991         bool next = false;
992         const char opc0 = ftepp_tokval(ftepp)[0];
993         const char opc1 = ftepp_tokval(ftepp)[1];
994         double other;
995
996         if (!ftepp_next(ftepp))
997             return false;
998         if (!ftepp_if_expr(ftepp, &next, &other))
999             return false;
1000
1001         if (opc0 == '=')
1002             *out = (*value_out == other);
1003         else if (opc0 == '!')
1004             *out = (*value_out != other);
1005         else if (opc0 == '>') {
1006             if (opc1 == '=') *out = (*value_out >= other);
1007             else             *out = (*value_out > other);
1008         }
1009         else if (opc0 == '<') {
1010             if (opc1 == '=') *out = (*value_out <= other);
1011             else             *out = (*value_out < other);
1012         }
1013         *value_out = (*out ? 1 : 0);
1014
1015         return true;
1016     }
1017     else {
1018         ftepp_error(ftepp, "junk after #if");
1019         return false;
1020     }
1021 }
1022
1023 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1024 {
1025     bool result = false;
1026     double dummy = 0;
1027
1028     memset(cond, 0, sizeof(*cond));
1029     (void)ftepp_next(ftepp);
1030
1031     if (!ftepp_skipspace(ftepp))
1032         return false;
1033     if (ftepp->token == TOKEN_EOL) {
1034         ftepp_error(ftepp, "expected expression for #if-directive");
1035         return false;
1036     }
1037
1038     if (!ftepp_if_expr(ftepp, &result, &dummy))
1039         return false;
1040
1041     cond->on = result;
1042     return true;
1043 }
1044
1045 /**
1046  * ifdef is rather simple
1047  */
1048 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1049 {
1050     ppmacro *macro;
1051     memset(cond, 0, sizeof(*cond));
1052     (void)ftepp_next(ftepp);
1053     if (!ftepp_skipspace(ftepp))
1054         return false;
1055
1056     switch (ftepp->token) {
1057         case TOKEN_IDENT:
1058         case TOKEN_TYPENAME:
1059         case TOKEN_KEYWORD:
1060             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1061             break;
1062         default:
1063             ftepp_error(ftepp, "expected macro name");
1064             return false;
1065     }
1066
1067     (void)ftepp_next(ftepp);
1068     if (!ftepp_skipspace(ftepp))
1069         return false;
1070     /* relaxing this condition
1071     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1072         ftepp_error(ftepp, "stray tokens after #ifdef");
1073         return false;
1074     }
1075     */
1076     cond->on = !!macro;
1077     return true;
1078 }
1079
1080 /**
1081  * undef is also simple
1082  */
1083 static bool ftepp_undef(ftepp_t *ftepp)
1084 {
1085     (void)ftepp_next(ftepp);
1086     if (!ftepp_skipspace(ftepp))
1087         return false;
1088
1089     if (ftepp->output_on) {
1090         switch (ftepp->token) {
1091             case TOKEN_IDENT:
1092             case TOKEN_TYPENAME:
1093             case TOKEN_KEYWORD:
1094                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1095                 break;
1096             default:
1097                 ftepp_error(ftepp, "expected macro name");
1098                 return false;
1099         }
1100     }
1101
1102     (void)ftepp_next(ftepp);
1103     if (!ftepp_skipspace(ftepp))
1104         return false;
1105     /* relaxing this condition
1106     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1107         ftepp_error(ftepp, "stray tokens after #ifdef");
1108         return false;
1109     }
1110     */
1111     return true;
1112 }
1113
1114 /* Special unescape-string function which skips a leading quote
1115  * and stops at a quote, not just at \0
1116  */
1117 static void unescape(const char *str, char *out) {
1118     ++str;
1119     while (*str && *str != '"') {
1120         if (*str == '\\') {
1121             ++str;
1122             switch (*str) {
1123                 case '\\': *out++ = *str; break;
1124                 case '"':  *out++ = *str; break;
1125                 case 'a':  *out++ = '\a'; break;
1126                 case 'b':  *out++ = '\b'; break;
1127                 case 'r':  *out++ = '\r'; break;
1128                 case 'n':  *out++ = '\n'; break;
1129                 case 't':  *out++ = '\t'; break;
1130                 case 'f':  *out++ = '\f'; break;
1131                 case 'v':  *out++ = '\v'; break;
1132                 default:
1133                     *out++ = '\\';
1134                     *out++ = *str;
1135                     break;
1136             }
1137             ++str;
1138             continue;
1139         }
1140
1141         *out++ = *str++;
1142     }
1143     *out = 0;
1144 }
1145
1146 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1147 {
1148     FILE       *fp;
1149     char       *filename = NULL;
1150     const char *last_slash;
1151     size_t      len;
1152
1153     if (!pathfile)
1154         return NULL;
1155
1156     last_slash = strrchr(pathfile, '/');
1157
1158     if (last_slash) {
1159         len = last_slash - pathfile;
1160         memcpy(vec_add(filename, len), pathfile, len);
1161         vec_push(filename, '/');
1162     }
1163
1164     len = strlen(file);
1165     memcpy(vec_add(filename, len+1), file, len);
1166     vec_last(filename) = 0;
1167
1168     fp = file_open(filename, "rb");
1169     if (fp) {
1170         file_close(fp);
1171         return filename;
1172     }
1173     vec_free(filename);
1174     return NULL;
1175 }
1176
1177 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1178 {
1179     char *filename = NULL;
1180
1181     filename = ftepp_include_find_path(file, ftepp->includename);
1182     if (!filename)
1183         filename = ftepp_include_find_path(file, ftepp->itemname);
1184     return filename;
1185 }
1186
1187 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1188     char *message = NULL;
1189
1190     if (!ftepp_skipspace(ftepp))
1191         return false;
1192
1193     /* handle the odd non string constant case so it works like C */
1194     if (ftepp->token != TOKEN_STRINGCONST) {
1195         bool  store   = false;
1196         vec_upload(message, "#warning", 8);
1197         ftepp_next(ftepp);
1198         while (ftepp->token != TOKEN_EOL) {
1199             vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1200             ftepp_next(ftepp);
1201         }
1202         vec_push(message, '\0');
1203         store = ftepp_warn(ftepp, WARN_CPP, message);
1204         vec_free(message);
1205         return store;
1206     }
1207
1208     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1209     return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1210 }
1211
1212 static void ftepp_directive_error(ftepp_t *ftepp) {
1213     char *message = NULL;
1214
1215     if (!ftepp_skipspace(ftepp))
1216         return;
1217
1218     /* handle the odd non string constant case so it works like C */
1219     if (ftepp->token != TOKEN_STRINGCONST) {
1220         vec_upload(message, "#error", 6);
1221         ftepp_next(ftepp);
1222         while (ftepp->token != TOKEN_EOL) {
1223             vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1224             ftepp_next(ftepp);
1225         }
1226         vec_push(message, '\0');
1227         ftepp_error(ftepp, message);
1228         vec_free(message);
1229         return;
1230     }
1231
1232     unescape  (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1233     ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1234 }
1235
1236 /**
1237  * Include a file.
1238  * FIXME: do we need/want a -I option?
1239  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1240  */
1241 static bool ftepp_include(ftepp_t *ftepp)
1242 {
1243     lex_file *old_lexer = ftepp->lex;
1244     lex_file *inlex;
1245     lex_ctx  ctx;
1246     char     lineno[128];
1247     char     *filename;
1248     char     *old_includename;
1249
1250     (void)ftepp_next(ftepp);
1251     if (!ftepp_skipspace(ftepp))
1252         return false;
1253
1254     if (ftepp->token != TOKEN_STRINGCONST) {
1255         ftepp_error(ftepp, "expected filename to include");
1256         return false;
1257     }
1258
1259     ctx = ftepp_ctx(ftepp);
1260
1261     unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1262
1263     ftepp_out(ftepp, "\n#pragma file(", false);
1264     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1265     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1266
1267     filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1268     if (!filename) {
1269         ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1270         return false;
1271     }
1272     inlex = lex_open(filename);
1273     if (!inlex) {
1274         ftepp_error(ftepp, "open failed on include file `%s`", filename);
1275         vec_free(filename);
1276         return false;
1277     }
1278     ftepp->lex = inlex;
1279     old_includename = ftepp->includename;
1280     ftepp->includename = filename;
1281     if (!ftepp_preprocess(ftepp)) {
1282         vec_free(ftepp->includename);
1283         ftepp->includename = old_includename;
1284         lex_close(ftepp->lex);
1285         ftepp->lex = old_lexer;
1286         return false;
1287     }
1288     vec_free(ftepp->includename);
1289     ftepp->includename = old_includename;
1290     lex_close(ftepp->lex);
1291     ftepp->lex = old_lexer;
1292
1293     ftepp_out(ftepp, "\n#pragma file(", false);
1294     ftepp_out(ftepp, ctx.file, false);
1295     snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1296     ftepp_out(ftepp, lineno, false);
1297
1298     /* skip the line */
1299     (void)ftepp_next(ftepp);
1300     if (!ftepp_skipspace(ftepp))
1301         return false;
1302     if (ftepp->token != TOKEN_EOL) {
1303         ftepp_error(ftepp, "stray tokens after #include");
1304         return false;
1305     }
1306     (void)ftepp_next(ftepp);
1307
1308     return true;
1309 }
1310
1311 /* Basic structure handlers */
1312 static bool ftepp_else_allowed(ftepp_t *ftepp)
1313 {
1314     if (!vec_size(ftepp->conditions)) {
1315         ftepp_error(ftepp, "#else without #if");
1316         return false;
1317     }
1318     if (vec_last(ftepp->conditions).had_else) {
1319         ftepp_error(ftepp, "multiple #else for a single #if");
1320         return false;
1321     }
1322     return true;
1323 }
1324
1325 static bool ftepp_hash(ftepp_t *ftepp)
1326 {
1327     ppcondition cond;
1328     ppcondition *pc;
1329
1330     lex_ctx ctx = ftepp_ctx(ftepp);
1331
1332     if (!ftepp_skipspace(ftepp))
1333         return false;
1334
1335     switch (ftepp->token) {
1336         case TOKEN_KEYWORD:
1337         case TOKEN_IDENT:
1338         case TOKEN_TYPENAME:
1339             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1340                 return ftepp_define(ftepp);
1341             }
1342             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1343                 return ftepp_undef(ftepp);
1344             }
1345             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1346                 if (!ftepp_ifdef(ftepp, &cond))
1347                     return false;
1348                 cond.was_on = cond.on;
1349                 vec_push(ftepp->conditions, cond);
1350                 ftepp->output_on = ftepp->output_on && cond.on;
1351                 break;
1352             }
1353             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1354                 if (!ftepp_ifdef(ftepp, &cond))
1355                     return false;
1356                 cond.on = !cond.on;
1357                 cond.was_on = cond.on;
1358                 vec_push(ftepp->conditions, cond);
1359                 ftepp->output_on = ftepp->output_on && cond.on;
1360                 break;
1361             }
1362             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1363                 if (!ftepp_else_allowed(ftepp))
1364                     return false;
1365                 if (!ftepp_ifdef(ftepp, &cond))
1366                     return false;
1367                 pc = &vec_last(ftepp->conditions);
1368                 pc->on     = !pc->was_on && cond.on;
1369                 pc->was_on = pc->was_on || pc->on;
1370                 ftepp_update_output_condition(ftepp);
1371                 break;
1372             }
1373             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1374                 if (!ftepp_else_allowed(ftepp))
1375                     return false;
1376                 if (!ftepp_ifdef(ftepp, &cond))
1377                     return false;
1378                 cond.on = !cond.on;
1379                 pc = &vec_last(ftepp->conditions);
1380                 pc->on     = !pc->was_on && cond.on;
1381                 pc->was_on = pc->was_on || pc->on;
1382                 ftepp_update_output_condition(ftepp);
1383                 break;
1384             }
1385             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1386                 if (!ftepp_else_allowed(ftepp))
1387                     return false;
1388                 if (!ftepp_if(ftepp, &cond))
1389                     return false;
1390                 pc = &vec_last(ftepp->conditions);
1391                 pc->on     = !pc->was_on && cond.on;
1392                 pc->was_on = pc->was_on  || pc->on;
1393                 ftepp_update_output_condition(ftepp);
1394                 break;
1395             }
1396             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1397                 if (!ftepp_if(ftepp, &cond))
1398                     return false;
1399                 cond.was_on = cond.on;
1400                 vec_push(ftepp->conditions, cond);
1401                 ftepp->output_on = ftepp->output_on && cond.on;
1402                 break;
1403             }
1404             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1405                 if (!ftepp_else_allowed(ftepp))
1406                     return false;
1407                 pc = &vec_last(ftepp->conditions);
1408                 pc->on = !pc->was_on;
1409                 pc->had_else = true;
1410                 ftepp_next(ftepp);
1411                 ftepp_update_output_condition(ftepp);
1412                 break;
1413             }
1414             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1415                 if (!vec_size(ftepp->conditions)) {
1416                     ftepp_error(ftepp, "#endif without #if");
1417                     return false;
1418                 }
1419                 vec_pop(ftepp->conditions);
1420                 ftepp_next(ftepp);
1421                 ftepp_update_output_condition(ftepp);
1422                 break;
1423             }
1424             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1425                 return ftepp_include(ftepp);
1426             }
1427             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1428                 ftepp_out(ftepp, "#", false);
1429                 break;
1430             }
1431             else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1432                 ftepp_directive_warning(ftepp);
1433                 break;
1434             }
1435             else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1436                 ftepp_directive_error(ftepp);
1437                 break;
1438             }
1439             else {
1440                 if (ftepp->output_on) {
1441                     ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1442                     return false;
1443                 } else {
1444                     ftepp_next(ftepp);
1445                     break;
1446                 }
1447             }
1448             /* break; never reached */
1449         default:
1450             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1451             return false;
1452         case TOKEN_EOL:
1453             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1454             return false;
1455         case TOKEN_EOF:
1456             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1457             return false;
1458
1459         /* Builtins! Don't forget the builtins! */
1460         case TOKEN_INTCONST:
1461         case TOKEN_FLOATCONST:
1462             ftepp_out(ftepp, "#", false);
1463             return true;
1464     }
1465     if (!ftepp_skipspace(ftepp))
1466         return false;
1467     return true;
1468 }
1469
1470 static bool ftepp_preprocess(ftepp_t *ftepp)
1471 {
1472     ppmacro *macro;
1473     bool     newline = true;
1474
1475     /* predef stuff */
1476     char    *expand  = NULL;
1477     size_t   i;
1478
1479     ftepp->lex->flags.preprocessing = true;
1480     ftepp->lex->flags.mergelines    = false;
1481     ftepp->lex->flags.noops         = true;
1482
1483     ftepp_next(ftepp);
1484     do
1485     {
1486         if (ftepp->token >= TOKEN_EOF)
1487             break;
1488 #if 0
1489         newline = true;
1490 #endif
1491
1492         switch (ftepp->token) {
1493             case TOKEN_KEYWORD:
1494             case TOKEN_IDENT:
1495             case TOKEN_TYPENAME:
1496                 /* is it a predef? */
1497                 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1498                     for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1499                         if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1500                             expand = ftepp_predefs[i].func(ftepp->lex);
1501                             ftepp_out(ftepp, expand, false);
1502                             ftepp_next(ftepp); /* skip */
1503
1504                             mem_d(expand); /* free memory */
1505                             break;
1506                         }
1507                     }
1508                 }
1509
1510                 if (ftepp->output_on)
1511                     macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1512                 else
1513                     macro = NULL;
1514
1515                 if (!macro) {
1516                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1517                     ftepp_next(ftepp);
1518                     break;
1519                 }
1520                 if (!ftepp_macro_call(ftepp, macro))
1521                     ftepp->token = TOKEN_ERROR;
1522                 break;
1523             case '#':
1524                 if (!newline) {
1525                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1526                     ftepp_next(ftepp);
1527                     break;
1528                 }
1529                 ftepp->lex->flags.mergelines = true;
1530                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1531                     ftepp_error(ftepp, "error in preprocessor directive");
1532                     ftepp->token = TOKEN_ERROR;
1533                     break;
1534                 }
1535                 if (!ftepp_hash(ftepp))
1536                     ftepp->token = TOKEN_ERROR;
1537                 ftepp->lex->flags.mergelines = false;
1538                 break;
1539             case TOKEN_EOL:
1540                 newline = true;
1541                 ftepp_out(ftepp, "\n", true);
1542                 ftepp_next(ftepp);
1543                 break;
1544             case TOKEN_WHITE:
1545                 /* same as default but don't set newline=false */
1546                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1547                 ftepp_next(ftepp);
1548                 break;
1549             default:
1550                 newline = false;
1551                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1552                 ftepp_next(ftepp);
1553                 break;
1554         }
1555     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1556
1557     /* force a 0 at the end but don't count it as added to the output */
1558     vec_push(ftepp->output_string, 0);
1559     vec_shrinkby(ftepp->output_string, 1);
1560
1561     return (ftepp->token == TOKEN_EOF);
1562 }
1563
1564 /* Like in parser.c - files keep the previous state so we have one global
1565  * preprocessor. Except here we will want to warn about dangling #ifs.
1566  */
1567 static ftepp_t *ftepp;
1568
1569 static bool ftepp_preprocess_done()
1570 {
1571     bool retval = true;
1572     if (vec_size(ftepp->conditions)) {
1573         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1574             retval = false;
1575     }
1576     lex_close(ftepp->lex);
1577     ftepp->lex = NULL;
1578     if (ftepp->itemname) {
1579         mem_d(ftepp->itemname);
1580         ftepp->itemname = NULL;
1581     }
1582     return retval;
1583 }
1584
1585 bool ftepp_preprocess_file(const char *filename)
1586 {
1587     ftepp->lex = lex_open(filename);
1588     ftepp->itemname = util_strdup(filename);
1589     if (!ftepp->lex) {
1590         con_out("failed to open file \"%s\"\n", filename);
1591         return false;
1592     }
1593     if (!ftepp_preprocess(ftepp))
1594         return false;
1595     return ftepp_preprocess_done();
1596 }
1597
1598 bool ftepp_preprocess_string(const char *name, const char *str)
1599 {
1600     ftepp->lex = lex_open_string(str, strlen(str), name);
1601     ftepp->itemname = util_strdup(name);
1602     if (!ftepp->lex) {
1603         con_out("failed to create lexer for string \"%s\"\n", name);
1604         return false;
1605     }
1606     if (!ftepp_preprocess(ftepp))
1607         return false;
1608     return ftepp_preprocess_done();
1609 }
1610
1611
1612 void ftepp_add_macro(const char *name, const char *value) {
1613     char *create = NULL;
1614
1615     /* use saner path for empty macros */
1616     if (!value) {
1617         ftepp_add_define("__builtin__", name);
1618         return;
1619     }
1620
1621     vec_upload(create, "#define ", 8);
1622     vec_upload(create, name,  strlen(name));
1623     vec_push  (create, ' ');
1624     vec_upload(create, value, strlen(value));
1625     vec_push  (create, 0);
1626
1627     ftepp_preprocess_string("__builtin__", create);
1628     vec_free  (create);
1629 }
1630
1631 bool ftepp_init()
1632 {
1633     char minor[32];
1634     char major[32];
1635
1636     ftepp = ftepp_new();
1637     if (!ftepp)
1638         return false;
1639
1640     memset(minor, 0, sizeof(minor));
1641     memset(major, 0, sizeof(major));
1642
1643     /* set the right macro based on the selected standard */
1644     ftepp_add_define(NULL, "GMQCC");
1645     if (opts.standard == COMPILER_FTEQCC) {
1646         ftepp_add_define(NULL, "__STD_FTEQCC__");
1647         /* 1.00 */
1648         major[0] = '"';
1649         major[1] = '1';
1650         major[2] = '"';
1651
1652         minor[0] = '"';
1653         minor[1] = '0';
1654         minor[2] = '"';
1655     } else if (opts.standard == COMPILER_GMQCC) {
1656         ftepp_add_define(NULL, "__STD_GMQCC__");
1657         sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1658         sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1659     } else if (opts.standard == COMPILER_QCCX) {
1660         ftepp_add_define(NULL, "__STD_QCCX__");
1661         sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1662         sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1663     } else if (opts.standard == COMPILER_QCC) {
1664         ftepp_add_define(NULL, "__STD_QCC__");
1665         /* 1.0 */
1666         major[0] = '"';
1667         major[1] = '1';
1668         major[2] = '"';
1669
1670         minor[0] = '"';
1671         minor[1] = '0';
1672         minor[2] = '"';
1673     }
1674
1675     ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1676     ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1677
1678     return true;
1679 }
1680
1681 void ftepp_add_define(const char *source, const char *name)
1682 {
1683     ppmacro *macro;
1684     lex_ctx ctx = { "__builtin__", 0 };
1685     ctx.file = source;
1686     macro = ppmacro_new(ctx, name);
1687     vec_push(ftepp->macros, macro);
1688 }
1689
1690 const char *ftepp_get()
1691 {
1692     return ftepp->output_string;
1693 }
1694
1695 void ftepp_flush()
1696 {
1697     ftepp_flush_do(ftepp);
1698 }
1699
1700 void ftepp_finish()
1701 {
1702     if (!ftepp)
1703         return;
1704     ftepp_delete(ftepp);
1705     ftepp = NULL;
1706 }