]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Add quotes to the known control sequences... darn. Add stringification via #
[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                 switch (*ch) {
451                     case '\\': ftepp_out(ftepp, "\\\\", false); break;
452                     case '"':  ftepp_out(ftepp, "\\\"", false); break;
453                     default:
454                         chs[0] = *ch;
455                         ftepp_out(ftepp, chs, false);
456                         break;
457                 }
458                 ++ch;
459             }
460             break;
461         case TOKEN_WHITE:
462             ftepp_out(ftepp, " ", false);
463             break;
464         case TOKEN_EOL:
465             ftepp_out(ftepp, "\\n", false);
466             break;
467         default:
468             ftepp_out(ftepp, token->value, false);
469             break;
470     }
471 }
472
473 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
474 {
475     size_t i;
476     ftepp_out(ftepp, "\"", false);
477     for (i = 0; i < vec_size(param->tokens); ++i)
478         ftepp_stringify_token(ftepp, param->tokens[i]);
479     ftepp_out(ftepp, "\"", false);
480 }
481
482 static bool ftepp_preprocess(ftepp_t *ftepp);
483 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params)
484 {
485     char     *old_string = ftepp->output_string;
486     lex_file *old_lexer = ftepp->lex;
487     bool retval = true;
488
489     size_t    o, pi, pv;
490     lex_file *inlex;
491
492     int nextok;
493
494     /* really ... */
495     if (!vec_size(macro->output))
496         return true;
497
498     ftepp->output_string = NULL;
499     for (o = 0; o < vec_size(macro->output); ++o) {
500         pptoken *out = macro->output[o];
501         switch (out->token) {
502             case TOKEN_IDENT:
503             case TOKEN_TYPENAME:
504             case TOKEN_KEYWORD:
505                 if (!macro_params_find(macro, out->value, &pi)) {
506                     ftepp_out(ftepp, out->value, false);
507                     break;
508                 } else {
509                     for (pv = 0; pv < vec_size(params[pi].tokens); ++pv) {
510                         out = params[pi].tokens[pv];
511                         if (out->token == TOKEN_EOL)
512                             ftepp_out(ftepp, "\n", false);
513                         else
514                             ftepp_out(ftepp, out->value, false);
515                     }
516                 }
517                 break;
518             case '#':
519                 if (o + 1 < vec_size(macro->output)) {
520                     nextok = macro->output[o+1]->token;
521                     if (nextok == '#') {
522                         /* raw concatenation */
523                         ++o;
524                         break;
525                     }
526                     if ( (nextok == TOKEN_IDENT    ||
527                           nextok == TOKEN_KEYWORD  ||
528                           nextok == TOKEN_TYPENAME) &&
529                         macro_params_find(macro, macro->output[o+1]->value, &pi))
530                     {
531                         ++o;
532                         ftepp_stringify(ftepp, &params[pi]);
533                         break;
534                     }
535                 }
536                 ftepp_out(ftepp, "#", false);
537                 break;
538             case TOKEN_EOL:
539                 ftepp_out(ftepp, "\n", false);
540                 break;
541             default:
542                 ftepp_out(ftepp, out->value, false);
543                 break;
544         }
545     }
546     vec_push(ftepp->output_string, 0);
547     /* Now run the preprocessor recursively on this string buffer */
548     /*
549     printf("__________\n%s\n=========\n", ftepp->output_string);
550     */
551     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
552     if (!inlex) {
553         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
554         retval = false;
555         goto cleanup;
556     }
557     ftepp->output_string = old_string;
558     ftepp->lex = inlex;
559     if (!ftepp_preprocess(ftepp)) {
560         lex_close(ftepp->lex);
561         retval = false;
562         goto cleanup;
563     }
564
565 cleanup:
566     ftepp->lex           = old_lexer;
567     ftepp->output_string = old_string;
568     return retval;
569 }
570
571 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
572 {
573     size_t     o;
574     macroparam *params = NULL;
575     bool        retval = true;
576
577     if (!macro->has_params) {
578         if (!ftepp_macro_expand(ftepp, macro, NULL))
579             return false;
580         ftepp_next(ftepp);
581         return true;
582     }
583     ftepp_next(ftepp);
584
585     if (!ftepp_skipallwhite(ftepp))
586         return false;
587
588     if (ftepp->token != '(') {
589         ftepp_error(ftepp, "expected macro parameters in parenthesis");
590         return false;
591     }
592
593     ftepp_next(ftepp);
594     if (!ftepp_macro_call_params(ftepp, &params))
595         return false;
596
597     if (vec_size(params) != vec_size(macro->params)) {
598         ftepp_error(ftepp, "macro %s expects %u paramteters, %u provided", macro->name,
599                     (unsigned int)vec_size(macro->params),
600                     (unsigned int)vec_size(params));
601         retval = false;
602         goto cleanup;
603     }
604
605     if (!ftepp_macro_expand(ftepp, macro, params))
606         retval = false;
607     ftepp_next(ftepp);
608
609 cleanup:
610     for (o = 0; o < vec_size(params); ++o)
611         macroparam_clean(&params[o]);
612     vec_free(params);
613     return retval;
614 }
615
616 /**
617  * #if - the FTEQCC way:
618  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
619  *    <numbers>    => True if the number is not 0
620  *    !<factor>    => True if the factor yields false
621  *    !!<factor>   => ERROR on 2 or more unary nots
622  *    <macro>      => becomes the macro's FIRST token regardless of parameters
623  *    <e> && <e>   => True if both expressions are true
624  *    <e> || <e>   => True if either expression is true
625  *    <string>     => False
626  *    <ident>      => False (remember for macros the <macro> rule applies instead)
627  * Unary + and - are weird and wrong in fteqcc so we don't allow them
628  * parenthesis in expressions are allowed
629  * parameter lists on macros are errors
630  * No mathematical calculations are executed
631  */
632 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out)
633 {
634     ppmacro *macro;
635     bool     wasnot = false;
636
637     if (!ftepp_skipspace(ftepp))
638         return false;
639
640     while (ftepp->token == '!') {
641         wasnot = true;
642         ftepp_next(ftepp);
643         if (!ftepp_skipspace(ftepp))
644             return false;
645     }
646
647     switch (ftepp->token) {
648         case TOKEN_IDENT:
649         case TOKEN_TYPENAME:
650         case TOKEN_KEYWORD:
651             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
652                 ftepp_next(ftepp);
653                 if (!ftepp_skipspace(ftepp))
654                     return false;
655                 if (ftepp->token != '(') {
656                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
657                     return false;
658                 }
659                 ftepp_next(ftepp);
660                 if (!ftepp_skipspace(ftepp))
661                     return false;
662                 if (ftepp->token != TOKEN_IDENT &&
663                     ftepp->token != TOKEN_TYPENAME &&
664                     ftepp->token != TOKEN_KEYWORD)
665                 {
666                     ftepp_error(ftepp, "defined() used on an unexpected token type");
667                     return false;
668                 }
669                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
670                 *out = !!macro;
671                 ftepp_next(ftepp);
672                 if (!ftepp_skipspace(ftepp))
673                     return false;
674                 if (ftepp->token != ')') {
675                     ftepp_error(ftepp, "expected closing paren");
676                     return false;
677                 }
678                 break;
679             }
680
681             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
682             if (!macro || !vec_size(macro->output)) {
683                 *out = false;
684             } else {
685                 /* This does not expand recursively! */
686                 switch (macro->output[0]->token) {
687                     case TOKEN_INTCONST:
688                         *out = !!(macro->output[0]->constval.f);
689                         break;
690                     case TOKEN_FLOATCONST:
691                         *out = !!(macro->output[0]->constval.f);
692                         break;
693                     default:
694                         *out = false;
695                         break;
696                 }
697             }
698             break;
699         case TOKEN_STRINGCONST:
700             *out = false;
701             break;
702         case TOKEN_INTCONST:
703             *out = !!(ftepp->lex->tok.constval.i);
704             break;
705         case TOKEN_FLOATCONST:
706             *out = !!(ftepp->lex->tok.constval.f);
707             break;
708
709         case '(':
710             ftepp_next(ftepp);
711             if (!ftepp_if_expr(ftepp, out))
712                 return false;
713             if (ftepp->token != ')') {
714                 ftepp_error(ftepp, "expected closing paren in #if expression");
715                 return false;
716             }
717             break;
718
719         default:
720             ftepp_error(ftepp, "junk in #if");
721             return false;
722     }
723     if (wasnot)
724         *out = !*out;
725
726     ftepp->lex->flags.noops = false;
727     ftepp_next(ftepp);
728     if (!ftepp_skipspace(ftepp))
729         return false;
730     ftepp->lex->flags.noops = true;
731
732     if (ftepp->token == ')')
733         return true;
734
735     if (ftepp->token != TOKEN_OPERATOR)
736         return true;
737
738     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
739         !strcmp(ftepp_tokval(ftepp), "||"))
740     {
741         bool next = false;
742         char opc  = ftepp_tokval(ftepp)[0];
743
744         ftepp_next(ftepp);
745         if (!ftepp_if_expr(ftepp, &next))
746             return false;
747
748         if (opc == '&')
749             *out = *out && next;
750         else
751             *out = *out || next;
752         return true;
753     }
754     else {
755         ftepp_error(ftepp, "junk after #if");
756         return false;
757     }
758 }
759
760 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
761 {
762     bool result = false;
763
764     memset(cond, 0, sizeof(*cond));
765     (void)ftepp_next(ftepp);
766
767     if (!ftepp_skipspace(ftepp))
768         return false;
769     if (ftepp->token == TOKEN_EOL) {
770         ftepp_error(ftepp, "expected expression for #if-directive");
771         return false;
772     }
773
774     if (!ftepp_if_expr(ftepp, &result))
775         return false;
776
777     cond->on = result;
778     return true;
779 }
780
781 /**
782  * ifdef is rather simple
783  */
784 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
785 {
786     ppmacro *macro;
787     memset(cond, 0, sizeof(*cond));
788     (void)ftepp_next(ftepp);
789     if (!ftepp_skipspace(ftepp))
790         return false;
791
792     switch (ftepp->token) {
793         case TOKEN_IDENT:
794         case TOKEN_TYPENAME:
795         case TOKEN_KEYWORD:
796             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
797             break;
798         default:
799             ftepp_error(ftepp, "expected macro name");
800             return false;
801     }
802
803     (void)ftepp_next(ftepp);
804     if (!ftepp_skipspace(ftepp))
805         return false;
806     /* relaxing this condition
807     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
808         ftepp_error(ftepp, "stray tokens after #ifdef");
809         return false;
810     }
811     */
812     cond->on = !!macro;
813     return true;
814 }
815
816 /**
817  * undef is also simple
818  */
819 static bool ftepp_undef(ftepp_t *ftepp)
820 {
821     (void)ftepp_next(ftepp);
822     if (!ftepp_skipspace(ftepp))
823         return false;
824
825     if (ftepp->output_on) {
826         switch (ftepp->token) {
827             case TOKEN_IDENT:
828             case TOKEN_TYPENAME:
829             case TOKEN_KEYWORD:
830                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
831                 break;
832             default:
833                 ftepp_error(ftepp, "expected macro name");
834                 return false;
835         }
836     }
837
838     (void)ftepp_next(ftepp);
839     if (!ftepp_skipspace(ftepp))
840         return false;
841     /* relaxing this condition
842     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
843         ftepp_error(ftepp, "stray tokens after #ifdef");
844         return false;
845     }
846     */
847     return true;
848 }
849
850 /* Basic structure handlers */
851 static bool ftepp_else_allowed(ftepp_t *ftepp)
852 {
853     if (!vec_size(ftepp->conditions)) {
854         ftepp_error(ftepp, "#else without #if");
855         return false;
856     }
857     if (vec_last(ftepp->conditions).had_else) {
858         ftepp_error(ftepp, "multiple #else for a single #if");
859         return false;
860     }
861     return true;
862 }
863
864 static bool ftepp_hash(ftepp_t *ftepp)
865 {
866     ppcondition cond;
867     ppcondition *pc;
868
869     lex_ctx ctx = ftepp_ctx(ftepp);
870
871     if (!ftepp_skipspace(ftepp))
872         return false;
873
874     switch (ftepp->token) {
875         case TOKEN_KEYWORD:
876         case TOKEN_IDENT:
877         case TOKEN_TYPENAME:
878             if (!strcmp(ftepp_tokval(ftepp), "define")) {
879                 return ftepp_define(ftepp);
880             }
881             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
882                 return ftepp_undef(ftepp);
883             }
884             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
885                 if (!ftepp_ifdef(ftepp, &cond))
886                     return false;
887                 cond.was_on = cond.on;
888                 vec_push(ftepp->conditions, cond);
889                 ftepp->output_on = ftepp->output_on && cond.on;
890                 break;
891             }
892             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
893                 if (!ftepp_ifdef(ftepp, &cond))
894                     return false;
895                 cond.on = !cond.on;
896                 cond.was_on = cond.on;
897                 vec_push(ftepp->conditions, cond);
898                 ftepp->output_on = ftepp->output_on && cond.on;
899                 break;
900             }
901             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
902                 if (!ftepp_else_allowed(ftepp))
903                     return false;
904                 if (!ftepp_ifdef(ftepp, &cond))
905                     return false;
906                 pc = &vec_last(ftepp->conditions);
907                 pc->on     = !pc->was_on && cond.on;
908                 pc->was_on = pc->was_on || pc->on;
909                 ftepp_update_output_condition(ftepp);
910                 break;
911             }
912             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
913                 if (!ftepp_else_allowed(ftepp))
914                     return false;
915                 if (!ftepp_ifdef(ftepp, &cond))
916                     return false;
917                 cond.on = !cond.on;
918                 pc = &vec_last(ftepp->conditions);
919                 pc->on     = !pc->was_on && cond.on;
920                 pc->was_on = pc->was_on || pc->on;
921                 ftepp_update_output_condition(ftepp);
922                 break;
923             }
924             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
925                 if (!ftepp_else_allowed(ftepp))
926                     return false;
927                 if (!ftepp_if(ftepp, &cond))
928                     return false;
929                 pc = &vec_last(ftepp->conditions);
930                 pc->on     = !pc->was_on && cond.on;
931                 pc->was_on = pc->was_on  || pc->on;
932                 ftepp_update_output_condition(ftepp);
933                 break;
934             }
935             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
936                 if (!ftepp_if(ftepp, &cond))
937                     return false;
938                 cond.was_on = cond.on;
939                 vec_push(ftepp->conditions, cond);
940                 ftepp->output_on = ftepp->output_on && cond.on;
941                 break;
942             }
943             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
944                 if (!ftepp_else_allowed(ftepp))
945                     return false;
946                 pc = &vec_last(ftepp->conditions);
947                 pc->on = !pc->was_on;
948                 pc->had_else = true;
949                 ftepp_next(ftepp);
950                 ftepp_update_output_condition(ftepp);
951                 break;
952             }
953             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
954                 if (!vec_size(ftepp->conditions)) {
955                     ftepp_error(ftepp, "#endif without #if");
956                     return false;
957                 }
958                 vec_pop(ftepp->conditions);
959                 ftepp_next(ftepp);
960                 ftepp_update_output_condition(ftepp);
961                 break;
962             }
963             else {
964                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
965                 return false;
966             }
967             break;
968         default:
969             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
970             return false;
971         case TOKEN_EOL:
972             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
973             return false;
974         case TOKEN_EOF:
975             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
976             return false;
977
978         /* Builtins! Don't forget the builtins! */
979         case TOKEN_INTCONST:
980         case TOKEN_FLOATCONST:
981             ftepp_out(ftepp, "#", false);
982             return true;
983     }
984     if (!ftepp_skipspace(ftepp))
985         return false;
986     return true;
987 }
988
989 static bool ftepp_preprocess(ftepp_t *ftepp)
990 {
991     ppmacro *macro;
992     bool     newline = true;
993
994     ftepp->lex->flags.preprocessing = true;
995     ftepp->lex->flags.mergelines    = false;
996     ftepp->lex->flags.noops         = true;
997
998     ftepp_next(ftepp);
999     do
1000     {
1001         if (ftepp->token >= TOKEN_EOF)
1002             break;
1003 #if 0
1004         ftepp->newline = newline;
1005         newline = false;
1006 #else
1007         /* For the sake of FTE compatibility... FU, really */
1008         ftepp->newline = newline = true;
1009 #endif
1010
1011         switch (ftepp->token) {
1012             case TOKEN_KEYWORD:
1013             case TOKEN_IDENT:
1014             case TOKEN_TYPENAME:
1015                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1016                 if (!macro) {
1017                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1018                     ftepp_next(ftepp);
1019                     break;
1020                 }
1021                 if (!ftepp_macro_call(ftepp, macro))
1022                     ftepp->token = TOKEN_ERROR;
1023                 break;
1024             case '#':
1025                 if (!ftepp->newline) {
1026                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1027                     ftepp_next(ftepp);
1028                     break;
1029                 }
1030                 ftepp->lex->flags.mergelines = true;
1031                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1032                     ftepp_error(ftepp, "error in preprocessor directive");
1033                     ftepp->token = TOKEN_ERROR;
1034                     break;
1035                 }
1036                 if (!ftepp_hash(ftepp))
1037                     ftepp->token = TOKEN_ERROR;
1038                 ftepp->lex->flags.mergelines = false;
1039                 break;
1040             case TOKEN_EOL:
1041                 newline = true;
1042                 ftepp_out(ftepp, "\n", true);
1043                 ftepp_next(ftepp);
1044                 break;
1045             default:
1046                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1047                 ftepp_next(ftepp);
1048                 break;
1049         }
1050     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1051
1052     newline = ftepp->token == TOKEN_EOF;
1053     return newline;
1054 }
1055
1056 /* Like in parser.c - files keep the previous state so we have one global
1057  * preprocessor. Except here we will want to warn about dangling #ifs.
1058  */
1059 static ftepp_t *ftepp;
1060
1061 static bool ftepp_preprocess_done()
1062 {
1063     bool retval = true;
1064     lex_close(ftepp->lex);
1065     ftepp->lex = NULL;
1066     if (vec_size(ftepp->conditions)) {
1067         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1068             retval = false;
1069     }
1070     return retval;
1071 }
1072
1073 bool ftepp_preprocess_file(const char *filename)
1074 {
1075     ftepp->lex = lex_open(filename);
1076     if (!ftepp->lex) {
1077         con_out("failed to open file \"%s\"\n", filename);
1078         return false;
1079     }
1080     if (!ftepp_preprocess(ftepp)) {
1081         ftepp_delete(ftepp);
1082         return false;
1083     }
1084     return ftepp_preprocess_done();
1085 }
1086
1087 bool ftepp_preprocess_string(const char *name, const char *str)
1088 {
1089     ftepp_t *ftepp = ftepp_new();
1090     ftepp->lex = lex_open_string(str, strlen(str), name);
1091     if (!ftepp->lex) {
1092         con_out("failed to create lexer for string \"%s\"\n", name);
1093         return false;
1094     }
1095     if (!ftepp_preprocess(ftepp)) {
1096         ftepp_delete(ftepp);
1097         return false;
1098     }
1099     return ftepp_preprocess_done();
1100 }
1101
1102 bool ftepp_init()
1103 {
1104     ftepp = ftepp_new();
1105     return !!ftepp;
1106 }
1107
1108 const char *ftepp_get()
1109 {
1110     return ftepp->output_string;
1111 }
1112
1113 void ftepp_flush()
1114 {
1115     vec_free(ftepp->output_string);
1116 }
1117
1118 void ftepp_finish()
1119 {
1120     if (!ftepp)
1121         return;
1122     ftepp_delete(ftepp);
1123     ftepp = NULL;
1124 }