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