]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
update old_string after a recursive preprocess call so we don't reset to a free'd...
[xonotic/gmqcc.git] / ftepp.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include "gmqcc.h"
24 #include "lexer.h"
25
26 typedef struct {
27     bool on;
28     bool was_on;
29     bool had_else;
30 } ppcondition;
31
32 typedef struct {
33     int   token;
34     char *value;
35     /* a copy from the lexer */
36     union {
37         vector v;
38         int    i;
39         double f;
40         int    t; /* type */
41     } constval;
42 } pptoken;
43
44 typedef struct {
45     lex_ctx ctx;
46
47     char   *name;
48     char  **params;
49     /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
50     bool    has_params;
51
52     pptoken **output;
53 } ppmacro;
54
55 typedef struct {
56     lex_file    *lex;
57     int          token;
58     bool         newline;
59     unsigned int errors;
60
61     bool         output_on;
62     ppcondition *conditions;
63     ppmacro    **macros;
64
65     char        *output_string;
66 } ftepp_t;
67
68 #define ftepp_tokval(f) ((f)->lex->tok.value)
69 #define ftepp_ctx(f)    ((f)->lex->tok.ctx)
70
71 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
72 {
73     va_list ap;
74
75     ftepp->errors++;
76
77     va_start(ap, fmt);
78     con_vprintmsg(LVL_ERROR, ctx.file, ctx.line, "error", fmt, ap);
79     va_end(ap);
80 }
81
82 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
83 {
84     va_list ap;
85
86     ftepp->errors++;
87
88     va_start(ap, fmt);
89     con_vprintmsg(LVL_ERROR, ftepp->lex->tok.ctx.file, ftepp->lex->tok.ctx.line, "error", fmt, ap);
90     va_end(ap);
91 }
92
93 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
94 {
95     va_list ap;
96     int lvl = LVL_WARNING;
97
98     if (!OPTS_WARN(warntype))
99         return false;
100
101     if (opts_werror) {
102             lvl = LVL_ERROR;
103         ftepp->errors++;
104     }
105
106     va_start(ap, fmt);
107     con_vprintmsg(lvl, ftepp->lex->tok.ctx.file, ftepp->lex->tok.ctx.line, "error", fmt, ap);
108     va_end(ap);
109     return opts_werror;
110 }
111
112 static pptoken *pptoken_make(ftepp_t *ftepp)
113 {
114     pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
115     token->token = ftepp->token;
116 #if 0
117     if (token->token == TOKEN_WHITE)
118         token->value = util_strdup(" ");
119     else
120 #else
121         token->value = util_strdup(ftepp_tokval(ftepp));
122 #endif
123     memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
124     return token;
125 }
126
127 static void pptoken_delete(pptoken *self)
128 {
129     mem_d(self->value);
130     mem_d(self);
131 }
132
133 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
134 {
135     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
136     memset(macro, 0, sizeof(*macro));
137     macro->name = util_strdup(name);
138     return macro;
139 }
140
141 static void ppmacro_delete(ppmacro *self)
142 {
143     size_t i;
144     for (i = 0; i < vec_size(self->params); ++i)
145         mem_d(self->params[i]);
146     vec_free(self->params);
147     for (i = 0; i < vec_size(self->output); ++i)
148         pptoken_delete(self->output[i]);
149     vec_free(self->output);
150     mem_d(self->name);
151     mem_d(self);
152 }
153
154 static ftepp_t* ftepp_new()
155 {
156     ftepp_t *ftepp;
157
158     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
159     memset(ftepp, 0, sizeof(*ftepp));
160
161     ftepp->output_on = true;
162
163     return ftepp;
164 }
165
166 static void ftepp_delete(ftepp_t *self)
167 {
168     size_t i;
169     for (i = 0; i < vec_size(self->macros); ++i)
170         ppmacro_delete(self->macros[i]);
171     vec_free(self->macros);
172     vec_free(self->conditions);
173     if (self->lex)
174         lex_close(self->lex);
175     mem_d(self);
176 }
177
178 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
179 {
180     if (ignore_cond || ftepp->output_on)
181     {
182         size_t len;
183         char  *data;
184         len = strlen(str);
185         data = vec_add(ftepp->output_string, len);
186         memcpy(data, str, len);
187     }
188 }
189
190 static void ftepp_update_output_condition(ftepp_t *ftepp)
191 {
192     size_t i;
193     ftepp->output_on = true;
194     for (i = 0; i < vec_size(ftepp->conditions); ++i)
195         ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
196 }
197
198 static ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
199 {
200     size_t i;
201     for (i = 0; i < vec_size(ftepp->macros); ++i) {
202         if (!strcmp(name, ftepp->macros[i]->name))
203             return ftepp->macros[i];
204     }
205     return NULL;
206 }
207
208 static void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
209 {
210     size_t i;
211     for (i = 0; i < vec_size(ftepp->macros); ++i) {
212         if (!strcmp(name, ftepp->macros[i]->name)) {
213             vec_remove(ftepp->macros, i, 1);
214             return;
215         }
216     }
217 }
218
219 static inline int ftepp_next(ftepp_t *ftepp)
220 {
221     return (ftepp->token = lex_do(ftepp->lex));
222 }
223
224 /* Important: this does not skip newlines! */
225 static bool ftepp_skipspace(ftepp_t *ftepp)
226 {
227     if (ftepp->token != TOKEN_WHITE)
228         return true;
229     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
230     if (ftepp->token >= TOKEN_EOF) {
231         ftepp_error(ftepp, "unexpected end of preprocessor directive");
232         return false;
233     }
234     return true;
235 }
236
237 /* this one skips EOLs as well */
238 static bool ftepp_skipallwhite(ftepp_t *ftepp)
239 {
240     if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
241         return true;
242     do {
243         ftepp_next(ftepp);
244     } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
245     if (ftepp->token >= TOKEN_EOF) {
246         ftepp_error(ftepp, "unexpected end of preprocessor directive");
247         return false;
248     }
249     return true;
250 }
251
252 /**
253  * The huge macro parsing code...
254  */
255 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
256 {
257     do {
258         ftepp_next(ftepp);
259         if (!ftepp_skipspace(ftepp))
260             return false;
261         if (ftepp->token == ')')
262             break;
263         switch (ftepp->token) {
264             case TOKEN_IDENT:
265             case TOKEN_TYPENAME:
266             case TOKEN_KEYWORD:
267                 break;
268             default:
269                 ftepp_error(ftepp, "unexpected token in parameter list");
270                 return false;
271         }
272         vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
273         ftepp_next(ftepp);
274         if (!ftepp_skipspace(ftepp))
275             return false;
276     } while (ftepp->token == ',');
277     if (ftepp->token != ')') {
278         ftepp_error(ftepp, "expected closing paren after macro parameter list");
279         return false;
280     }
281     ftepp_next(ftepp);
282     /* skipspace happens in ftepp_define */
283     return true;
284 }
285
286 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
287 {
288     pptoken *ptok;
289     while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
290         ptok = pptoken_make(ftepp);
291         vec_push(macro->output, ptok);
292         ftepp_next(ftepp);
293     }
294     /* recursive expansion can cause EOFs here */
295     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
296         ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
297         return false;
298     }
299     return true;
300 }
301
302 static bool ftepp_define(ftepp_t *ftepp)
303 {
304     ppmacro *macro;
305     (void)ftepp_next(ftepp);
306     if (!ftepp_skipspace(ftepp))
307         return false;
308
309     switch (ftepp->token) {
310         case TOKEN_IDENT:
311         case TOKEN_TYPENAME:
312         case TOKEN_KEYWORD:
313             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
314             if (macro && ftepp->output_on) {
315                 if (ftepp_warn(ftepp, WARN_PREPROCESSOR, "redefining `%s`", ftepp_tokval(ftepp)))
316                     return false;
317                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
318             }
319             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
320             break;
321         default:
322             ftepp_error(ftepp, "expected macro name");
323             return false;
324     }
325
326     (void)ftepp_next(ftepp);
327
328     if (ftepp->token == '(') {
329         macro->has_params = true;
330         if (!ftepp_define_params(ftepp, macro))
331             return false;
332     }
333
334     if (!ftepp_skipspace(ftepp))
335         return false;
336
337     if (!ftepp_define_body(ftepp, macro))
338         return false;
339
340     if (ftepp->output_on)
341         vec_push(ftepp->macros, macro);
342     else {
343         ppmacro_delete(macro);
344     }
345     return true;
346 }
347
348 /**
349  * When a macro is used we have to handle parameters as well
350  * as special-concatenation via ## or stringification via #
351  *
352  * Note: parenthesis can nest, so FOO((a),b) is valid, but only
353  * this kind of parens. Curly braces or [] don't count towards the
354  * paren-level.
355  */
356 typedef struct {
357     pptoken **tokens;
358 } macroparam;
359
360 static void macroparam_clean(macroparam *self)
361 {
362     size_t i;
363     for (i = 0; i < vec_size(self->tokens); ++i)
364         pptoken_delete(self->tokens[i]);
365     vec_free(self->tokens);
366 }
367
368 /* need to leave the last token up */
369 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
370 {
371     macroparam *params = NULL;
372     pptoken    *ptok;
373     macroparam  mp;
374     size_t      parens = 0;
375     size_t      i;
376
377     if (!ftepp_skipallwhite(ftepp))
378         return false;
379     while (ftepp->token != ')') {
380         mp.tokens = NULL;
381         if (!ftepp_skipallwhite(ftepp))
382             return false;
383         while (parens || ftepp->token != ',') {
384             if (ftepp->token == '(')
385                 ++parens;
386             else if (ftepp->token == ')') {
387                 if (!parens)
388                     break;
389                 --parens;
390             }
391             ptok = pptoken_make(ftepp);
392             vec_push(mp.tokens, ptok);
393             if (ftepp_next(ftepp) >= TOKEN_EOF) {
394                 ftepp_error(ftepp, "unexpected EOF in macro call");
395                 goto on_error;
396             }
397         }
398         vec_push(params, mp);
399         mp.tokens = NULL;
400         if (ftepp->token == ')')
401             break;
402         if (ftepp->token != ',') {
403             ftepp_error(ftepp, "expected closing paren or comma in macro call");
404             goto on_error;
405         }
406         if (ftepp_next(ftepp) >= TOKEN_EOF) {
407             ftepp_error(ftepp, "unexpected EOF in macro call");
408             goto on_error;
409         }
410     }
411     /* need to leave that up
412     if (ftepp_next(ftepp) >= TOKEN_EOF) {
413         ftepp_error(ftepp, "unexpected EOF in macro call");
414         goto on_error;
415     }
416     */
417     *out_params = params;
418     return true;
419
420 on_error:
421     if (mp.tokens)
422         macroparam_clean(&mp);
423     for (i = 0; i < vec_size(params); ++i)
424         macroparam_clean(&params[i]);
425     vec_free(params);
426     return false;
427 }
428
429 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
430 {
431     size_t i;
432     for (i = 0; i < vec_size(macro->params); ++i) {
433         if (!strcmp(macro->params[i], name)) {
434             *idx = i;
435             return true;
436         }
437     }
438     return false;
439 }
440
441 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
442 {
443     char        chs[2];
444     const char *ch;
445     chs[1] = 0;
446     switch (token->token) {
447         case TOKEN_STRINGCONST:
448             ch = token->value;
449             while (*ch) {
450                 /* in preprocessor mode strings already are string,
451                  * so we don't get actual newline bytes here.
452                  * Still need to escape backslashes and quotes.
453                  */
454                 switch (*ch) {
455                     case '\\': ftepp_out(ftepp, "\\\\", false); break;
456                     case '"':  ftepp_out(ftepp, "\\\"", false); break;
457                     default:
458                         chs[0] = *ch;
459                         ftepp_out(ftepp, chs, false);
460                         break;
461                 }
462                 ++ch;
463             }
464             break;
465         case TOKEN_WHITE:
466             ftepp_out(ftepp, " ", false);
467             break;
468         case TOKEN_EOL:
469             ftepp_out(ftepp, "\\n", false);
470             break;
471         default:
472             ftepp_out(ftepp, token->value, false);
473             break;
474     }
475 }
476
477 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
478 {
479     size_t i;
480     ftepp_out(ftepp, "\"", false);
481     for (i = 0; i < vec_size(param->tokens); ++i)
482         ftepp_stringify_token(ftepp, param->tokens[i]);
483     ftepp_out(ftepp, "\"", false);
484 }
485
486 static void ftepp_recursion_header(ftepp_t *ftepp)
487 {
488     ftepp_out(ftepp, "\n#pragma push(line)\n", false);
489 }
490
491 static void ftepp_recursion_footer(ftepp_t *ftepp)
492 {
493     ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
494 }
495
496 static bool ftepp_preprocess(ftepp_t *ftepp);
497 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params)
498 {
499     char     *old_string = ftepp->output_string;
500     lex_file *old_lexer = ftepp->lex;
501     bool retval = true;
502
503     size_t    o, pi, pv;
504     lex_file *inlex;
505
506     int nextok;
507
508     /* really ... */
509     if (!vec_size(macro->output))
510         return true;
511
512     ftepp->output_string = NULL;
513     for (o = 0; o < vec_size(macro->output); ++o) {
514         pptoken *out = macro->output[o];
515         switch (out->token) {
516             case TOKEN_IDENT:
517             case TOKEN_TYPENAME:
518             case TOKEN_KEYWORD:
519                 if (!macro_params_find(macro, out->value, &pi)) {
520                     ftepp_out(ftepp, out->value, false);
521                     break;
522                 } else {
523                     for (pv = 0; pv < vec_size(params[pi].tokens); ++pv) {
524                         out = params[pi].tokens[pv];
525                         if (out->token == TOKEN_EOL)
526                             ftepp_out(ftepp, "\n", false);
527                         else
528                             ftepp_out(ftepp, out->value, false);
529                     }
530                 }
531                 break;
532             case '#':
533                 if (o + 1 < vec_size(macro->output)) {
534                     nextok = macro->output[o+1]->token;
535                     if (nextok == '#') {
536                         /* raw concatenation */
537                         ++o;
538                         break;
539                     }
540                     if ( (nextok == TOKEN_IDENT    ||
541                           nextok == TOKEN_KEYWORD  ||
542                           nextok == TOKEN_TYPENAME) &&
543                         macro_params_find(macro, macro->output[o+1]->value, &pi))
544                     {
545                         ++o;
546                         ftepp_stringify(ftepp, &params[pi]);
547                         break;
548                     }
549                 }
550                 ftepp_out(ftepp, "#", false);
551                 break;
552             case TOKEN_EOL:
553                 ftepp_out(ftepp, "\n", false);
554                 break;
555             default:
556                 ftepp_out(ftepp, out->value, false);
557                 break;
558         }
559     }
560     vec_push(ftepp->output_string, 0);
561     /* Now run the preprocessor recursively on this string buffer */
562     /*
563     printf("__________\n%s\n=========\n", ftepp->output_string);
564     */
565     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
566     if (!inlex) {
567         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
568         retval = false;
569         goto cleanup;
570     }
571     ftepp->output_string = old_string;
572     ftepp->lex = inlex;
573     ftepp_recursion_header(ftepp);
574     if (!ftepp_preprocess(ftepp)) {
575         lex_close(ftepp->lex);
576         retval = false;
577         goto cleanup;
578     }
579     ftepp_recursion_footer(ftepp);
580     old_string = ftepp->output_string;
581
582 cleanup:
583     ftepp->lex           = old_lexer;
584     ftepp->output_string = old_string;
585     return retval;
586 }
587
588 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
589 {
590     size_t     o;
591     macroparam *params = NULL;
592     bool        retval = true;
593
594     if (!macro->has_params) {
595         if (!ftepp_macro_expand(ftepp, macro, NULL))
596             return false;
597         ftepp_next(ftepp);
598         return true;
599     }
600     ftepp_next(ftepp);
601
602     if (!ftepp_skipallwhite(ftepp))
603         return false;
604
605     if (ftepp->token != '(') {
606         ftepp_error(ftepp, "expected macro parameters in parenthesis");
607         return false;
608     }
609
610     ftepp_next(ftepp);
611     if (!ftepp_macro_call_params(ftepp, &params))
612         return false;
613
614     if (vec_size(params) != vec_size(macro->params)) {
615         ftepp_error(ftepp, "macro %s expects %u paramteters, %u provided", macro->name,
616                     (unsigned int)vec_size(macro->params),
617                     (unsigned int)vec_size(params));
618         retval = false;
619         goto cleanup;
620     }
621
622     if (!ftepp_macro_expand(ftepp, macro, params))
623         retval = false;
624     ftepp_next(ftepp);
625
626 cleanup:
627     for (o = 0; o < vec_size(params); ++o)
628         macroparam_clean(&params[o]);
629     vec_free(params);
630     return retval;
631 }
632
633 /**
634  * #if - the FTEQCC way:
635  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
636  *    <numbers>    => True if the number is not 0
637  *    !<factor>    => True if the factor yields false
638  *    !!<factor>   => ERROR on 2 or more unary nots
639  *    <macro>      => becomes the macro's FIRST token regardless of parameters
640  *    <e> && <e>   => True if both expressions are true
641  *    <e> || <e>   => True if either expression is true
642  *    <string>     => False
643  *    <ident>      => False (remember for macros the <macro> rule applies instead)
644  * Unary + and - are weird and wrong in fteqcc so we don't allow them
645  * parenthesis in expressions are allowed
646  * parameter lists on macros are errors
647  * No mathematical calculations are executed
648  */
649 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out)
650 {
651     ppmacro *macro;
652     bool     wasnot = false;
653
654     if (!ftepp_skipspace(ftepp))
655         return false;
656
657     while (ftepp->token == '!') {
658         wasnot = true;
659         ftepp_next(ftepp);
660         if (!ftepp_skipspace(ftepp))
661             return false;
662     }
663
664     switch (ftepp->token) {
665         case TOKEN_IDENT:
666         case TOKEN_TYPENAME:
667         case TOKEN_KEYWORD:
668             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
669                 ftepp_next(ftepp);
670                 if (!ftepp_skipspace(ftepp))
671                     return false;
672                 if (ftepp->token != '(') {
673                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
674                     return false;
675                 }
676                 ftepp_next(ftepp);
677                 if (!ftepp_skipspace(ftepp))
678                     return false;
679                 if (ftepp->token != TOKEN_IDENT &&
680                     ftepp->token != TOKEN_TYPENAME &&
681                     ftepp->token != TOKEN_KEYWORD)
682                 {
683                     ftepp_error(ftepp, "defined() used on an unexpected token type");
684                     return false;
685                 }
686                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
687                 *out = !!macro;
688                 ftepp_next(ftepp);
689                 if (!ftepp_skipspace(ftepp))
690                     return false;
691                 if (ftepp->token != ')') {
692                     ftepp_error(ftepp, "expected closing paren");
693                     return false;
694                 }
695                 break;
696             }
697
698             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
699             if (!macro || !vec_size(macro->output)) {
700                 *out = false;
701             } else {
702                 /* This does not expand recursively! */
703                 switch (macro->output[0]->token) {
704                     case TOKEN_INTCONST:
705                         *out = !!(macro->output[0]->constval.f);
706                         break;
707                     case TOKEN_FLOATCONST:
708                         *out = !!(macro->output[0]->constval.f);
709                         break;
710                     default:
711                         *out = false;
712                         break;
713                 }
714             }
715             break;
716         case TOKEN_STRINGCONST:
717             *out = false;
718             break;
719         case TOKEN_INTCONST:
720             *out = !!(ftepp->lex->tok.constval.i);
721             break;
722         case TOKEN_FLOATCONST:
723             *out = !!(ftepp->lex->tok.constval.f);
724             break;
725
726         case '(':
727             ftepp_next(ftepp);
728             if (!ftepp_if_expr(ftepp, out))
729                 return false;
730             if (ftepp->token != ')') {
731                 ftepp_error(ftepp, "expected closing paren in #if expression");
732                 return false;
733             }
734             break;
735
736         default:
737             ftepp_error(ftepp, "junk in #if");
738             return false;
739     }
740     if (wasnot)
741         *out = !*out;
742
743     ftepp->lex->flags.noops = false;
744     ftepp_next(ftepp);
745     if (!ftepp_skipspace(ftepp))
746         return false;
747     ftepp->lex->flags.noops = true;
748
749     if (ftepp->token == ')')
750         return true;
751
752     if (ftepp->token != TOKEN_OPERATOR)
753         return true;
754
755     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
756         !strcmp(ftepp_tokval(ftepp), "||"))
757     {
758         bool next = false;
759         char opc  = ftepp_tokval(ftepp)[0];
760
761         ftepp_next(ftepp);
762         if (!ftepp_if_expr(ftepp, &next))
763             return false;
764
765         if (opc == '&')
766             *out = *out && next;
767         else
768             *out = *out || next;
769         return true;
770     }
771     else {
772         ftepp_error(ftepp, "junk after #if");
773         return false;
774     }
775 }
776
777 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
778 {
779     bool result = false;
780
781     memset(cond, 0, sizeof(*cond));
782     (void)ftepp_next(ftepp);
783
784     if (!ftepp_skipspace(ftepp))
785         return false;
786     if (ftepp->token == TOKEN_EOL) {
787         ftepp_error(ftepp, "expected expression for #if-directive");
788         return false;
789     }
790
791     if (!ftepp_if_expr(ftepp, &result))
792         return false;
793
794     cond->on = result;
795     return true;
796 }
797
798 /**
799  * ifdef is rather simple
800  */
801 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
802 {
803     ppmacro *macro;
804     memset(cond, 0, sizeof(*cond));
805     (void)ftepp_next(ftepp);
806     if (!ftepp_skipspace(ftepp))
807         return false;
808
809     switch (ftepp->token) {
810         case TOKEN_IDENT:
811         case TOKEN_TYPENAME:
812         case TOKEN_KEYWORD:
813             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
814             break;
815         default:
816             ftepp_error(ftepp, "expected macro name");
817             return false;
818     }
819
820     (void)ftepp_next(ftepp);
821     if (!ftepp_skipspace(ftepp))
822         return false;
823     /* relaxing this condition
824     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
825         ftepp_error(ftepp, "stray tokens after #ifdef");
826         return false;
827     }
828     */
829     cond->on = !!macro;
830     return true;
831 }
832
833 /**
834  * undef is also simple
835  */
836 static bool ftepp_undef(ftepp_t *ftepp)
837 {
838     (void)ftepp_next(ftepp);
839     if (!ftepp_skipspace(ftepp))
840         return false;
841
842     if (ftepp->output_on) {
843         switch (ftepp->token) {
844             case TOKEN_IDENT:
845             case TOKEN_TYPENAME:
846             case TOKEN_KEYWORD:
847                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
848                 break;
849             default:
850                 ftepp_error(ftepp, "expected macro name");
851                 return false;
852         }
853     }
854
855     (void)ftepp_next(ftepp);
856     if (!ftepp_skipspace(ftepp))
857         return false;
858     /* relaxing this condition
859     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
860         ftepp_error(ftepp, "stray tokens after #ifdef");
861         return false;
862     }
863     */
864     return true;
865 }
866
867 /* Basic structure handlers */
868 static bool ftepp_else_allowed(ftepp_t *ftepp)
869 {
870     if (!vec_size(ftepp->conditions)) {
871         ftepp_error(ftepp, "#else without #if");
872         return false;
873     }
874     if (vec_last(ftepp->conditions).had_else) {
875         ftepp_error(ftepp, "multiple #else for a single #if");
876         return false;
877     }
878     return true;
879 }
880
881 static bool ftepp_hash(ftepp_t *ftepp)
882 {
883     ppcondition cond;
884     ppcondition *pc;
885
886     lex_ctx ctx = ftepp_ctx(ftepp);
887
888     if (!ftepp_skipspace(ftepp))
889         return false;
890
891     switch (ftepp->token) {
892         case TOKEN_KEYWORD:
893         case TOKEN_IDENT:
894         case TOKEN_TYPENAME:
895             if (!strcmp(ftepp_tokval(ftepp), "define")) {
896                 return ftepp_define(ftepp);
897             }
898             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
899                 return ftepp_undef(ftepp);
900             }
901             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
902                 if (!ftepp_ifdef(ftepp, &cond))
903                     return false;
904                 cond.was_on = cond.on;
905                 vec_push(ftepp->conditions, cond);
906                 ftepp->output_on = ftepp->output_on && cond.on;
907                 break;
908             }
909             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
910                 if (!ftepp_ifdef(ftepp, &cond))
911                     return false;
912                 cond.on = !cond.on;
913                 cond.was_on = cond.on;
914                 vec_push(ftepp->conditions, cond);
915                 ftepp->output_on = ftepp->output_on && cond.on;
916                 break;
917             }
918             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
919                 if (!ftepp_else_allowed(ftepp))
920                     return false;
921                 if (!ftepp_ifdef(ftepp, &cond))
922                     return false;
923                 pc = &vec_last(ftepp->conditions);
924                 pc->on     = !pc->was_on && cond.on;
925                 pc->was_on = pc->was_on || pc->on;
926                 ftepp_update_output_condition(ftepp);
927                 break;
928             }
929             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
930                 if (!ftepp_else_allowed(ftepp))
931                     return false;
932                 if (!ftepp_ifdef(ftepp, &cond))
933                     return false;
934                 cond.on = !cond.on;
935                 pc = &vec_last(ftepp->conditions);
936                 pc->on     = !pc->was_on && cond.on;
937                 pc->was_on = pc->was_on || pc->on;
938                 ftepp_update_output_condition(ftepp);
939                 break;
940             }
941             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
942                 if (!ftepp_else_allowed(ftepp))
943                     return false;
944                 if (!ftepp_if(ftepp, &cond))
945                     return false;
946                 pc = &vec_last(ftepp->conditions);
947                 pc->on     = !pc->was_on && cond.on;
948                 pc->was_on = pc->was_on  || pc->on;
949                 ftepp_update_output_condition(ftepp);
950                 break;
951             }
952             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
953                 if (!ftepp_if(ftepp, &cond))
954                     return false;
955                 cond.was_on = cond.on;
956                 vec_push(ftepp->conditions, cond);
957                 ftepp->output_on = ftepp->output_on && cond.on;
958                 break;
959             }
960             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
961                 if (!ftepp_else_allowed(ftepp))
962                     return false;
963                 pc = &vec_last(ftepp->conditions);
964                 pc->on = !pc->was_on;
965                 pc->had_else = true;
966                 ftepp_next(ftepp);
967                 ftepp_update_output_condition(ftepp);
968                 break;
969             }
970             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
971                 if (!vec_size(ftepp->conditions)) {
972                     ftepp_error(ftepp, "#endif without #if");
973                     return false;
974                 }
975                 vec_pop(ftepp->conditions);
976                 ftepp_next(ftepp);
977                 ftepp_update_output_condition(ftepp);
978                 break;
979             }
980             else {
981                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
982                 return false;
983             }
984             break;
985         default:
986             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
987             return false;
988         case TOKEN_EOL:
989             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
990             return false;
991         case TOKEN_EOF:
992             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
993             return false;
994
995         /* Builtins! Don't forget the builtins! */
996         case TOKEN_INTCONST:
997         case TOKEN_FLOATCONST:
998             ftepp_out(ftepp, "#", false);
999             return true;
1000     }
1001     if (!ftepp_skipspace(ftepp))
1002         return false;
1003     return true;
1004 }
1005
1006 static bool ftepp_preprocess(ftepp_t *ftepp)
1007 {
1008     ppmacro *macro;
1009     bool     newline = true;
1010
1011     ftepp->lex->flags.preprocessing = true;
1012     ftepp->lex->flags.mergelines    = false;
1013     ftepp->lex->flags.noops         = true;
1014
1015     ftepp_next(ftepp);
1016     do
1017     {
1018         if (ftepp->token >= TOKEN_EOF)
1019             break;
1020 #if 0
1021         ftepp->newline = newline;
1022         newline = false;
1023 #else
1024         /* For the sake of FTE compatibility... FU, really */
1025         ftepp->newline = newline = true;
1026 #endif
1027
1028         switch (ftepp->token) {
1029             case TOKEN_KEYWORD:
1030             case TOKEN_IDENT:
1031             case TOKEN_TYPENAME:
1032                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1033                 if (!macro) {
1034                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1035                     ftepp_next(ftepp);
1036                     break;
1037                 }
1038                 if (!ftepp_macro_call(ftepp, macro))
1039                     ftepp->token = TOKEN_ERROR;
1040                 break;
1041             case '#':
1042                 if (!ftepp->newline) {
1043                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1044                     ftepp_next(ftepp);
1045                     break;
1046                 }
1047                 ftepp->lex->flags.mergelines = true;
1048                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1049                     ftepp_error(ftepp, "error in preprocessor directive");
1050                     ftepp->token = TOKEN_ERROR;
1051                     break;
1052                 }
1053                 if (!ftepp_hash(ftepp))
1054                     ftepp->token = TOKEN_ERROR;
1055                 ftepp->lex->flags.mergelines = false;
1056                 break;
1057             case TOKEN_EOL:
1058                 newline = true;
1059                 ftepp_out(ftepp, "\n", true);
1060                 ftepp_next(ftepp);
1061                 break;
1062             default:
1063                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1064                 ftepp_next(ftepp);
1065                 break;
1066         }
1067     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1068
1069     newline = ftepp->token == TOKEN_EOF;
1070     return newline;
1071 }
1072
1073 /* Like in parser.c - files keep the previous state so we have one global
1074  * preprocessor. Except here we will want to warn about dangling #ifs.
1075  */
1076 static ftepp_t *ftepp;
1077
1078 static bool ftepp_preprocess_done()
1079 {
1080     bool retval = true;
1081     lex_close(ftepp->lex);
1082     ftepp->lex = NULL;
1083     if (vec_size(ftepp->conditions)) {
1084         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1085             retval = false;
1086     }
1087     return retval;
1088 }
1089
1090 bool ftepp_preprocess_file(const char *filename)
1091 {
1092     ftepp->lex = lex_open(filename);
1093     if (!ftepp->lex) {
1094         con_out("failed to open file \"%s\"\n", filename);
1095         return false;
1096     }
1097     if (!ftepp_preprocess(ftepp)) {
1098         ftepp_delete(ftepp);
1099         return false;
1100     }
1101     return ftepp_preprocess_done();
1102 }
1103
1104 bool ftepp_preprocess_string(const char *name, const char *str)
1105 {
1106     ftepp_t *ftepp = ftepp_new();
1107     ftepp->lex = lex_open_string(str, strlen(str), name);
1108     if (!ftepp->lex) {
1109         con_out("failed to create lexer for string \"%s\"\n", name);
1110         return false;
1111     }
1112     if (!ftepp_preprocess(ftepp)) {
1113         ftepp_delete(ftepp);
1114         return false;
1115     }
1116     return ftepp_preprocess_done();
1117 }
1118
1119 bool ftepp_init()
1120 {
1121     ftepp = ftepp_new();
1122     return !!ftepp;
1123 }
1124
1125 const char *ftepp_get()
1126 {
1127     return ftepp->output_string;
1128 }
1129
1130 void ftepp_flush()
1131 {
1132     vec_free(ftepp->output_string);
1133 }
1134
1135 void ftepp_finish()
1136 {
1137     if (!ftepp)
1138         return;
1139     ftepp_delete(ftepp);
1140     ftepp = NULL;
1141 }