]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Look for include files in the currently #included file's directory first
[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
67     char        *itemname;
68     char        *includename;
69 } ftepp_t;
70
71 #define ftepp_tokval(f) ((f)->lex->tok.value)
72 #define ftepp_ctx(f)    ((f)->lex->tok.ctx)
73
74 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
75 {
76     va_list ap;
77
78     ftepp->errors++;
79
80     va_start(ap, fmt);
81     con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
82     va_end(ap);
83 }
84
85 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
86 {
87     va_list ap;
88
89     ftepp->errors++;
90
91     va_start(ap, fmt);
92     con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
93     va_end(ap);
94 }
95
96 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
97 {
98     va_list ap;
99     int lvl = LVL_WARNING;
100
101     if (!OPTS_WARN(warntype))
102         return false;
103
104     if (opts_werror) {
105             lvl = LVL_ERROR;
106         ftepp->errors++;
107     }
108
109     va_start(ap, fmt);
110     con_cvprintmsg((void*)&ftepp->lex->tok.ctx, lvl, "error", fmt, ap);
111     va_end(ap);
112     return opts_werror;
113 }
114
115 static pptoken *pptoken_make(ftepp_t *ftepp)
116 {
117     pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
118     token->token = ftepp->token;
119 #if 0
120     if (token->token == TOKEN_WHITE)
121         token->value = util_strdup(" ");
122     else
123 #else
124         token->value = util_strdup(ftepp_tokval(ftepp));
125 #endif
126     memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
127     return token;
128 }
129
130 static void pptoken_delete(pptoken *self)
131 {
132     mem_d(self->value);
133     mem_d(self);
134 }
135
136 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
137 {
138     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
139     
140     (void)ctx;
141     memset(macro, 0, sizeof(*macro));
142     macro->name = util_strdup(name);
143     return macro;
144 }
145
146 static void ppmacro_delete(ppmacro *self)
147 {
148     size_t i;
149     for (i = 0; i < vec_size(self->params); ++i)
150         mem_d(self->params[i]);
151     vec_free(self->params);
152     for (i = 0; i < vec_size(self->output); ++i)
153         pptoken_delete(self->output[i]);
154     vec_free(self->output);
155     mem_d(self->name);
156     mem_d(self);
157 }
158
159 static ftepp_t* ftepp_new()
160 {
161     ftepp_t *ftepp;
162
163     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
164     memset(ftepp, 0, sizeof(*ftepp));
165
166     ftepp->output_on = true;
167
168     return ftepp;
169 }
170
171 static void ftepp_delete(ftepp_t *self)
172 {
173     size_t i;
174     if (self->itemname)
175         mem_d(self->itemname);
176     if (self->includename)
177         vec_free(self->includename);
178     for (i = 0; i < vec_size(self->macros); ++i)
179         ppmacro_delete(self->macros[i]);
180     vec_free(self->macros);
181     vec_free(self->conditions);
182     if (self->lex)
183         lex_close(self->lex);
184     mem_d(self);
185 }
186
187 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
188 {
189     if (ignore_cond || ftepp->output_on)
190     {
191         size_t len;
192         char  *data;
193         len = strlen(str);
194         data = vec_add(ftepp->output_string, len);
195         memcpy(data, str, len);
196     }
197 }
198
199 static void ftepp_update_output_condition(ftepp_t *ftepp)
200 {
201     size_t i;
202     ftepp->output_on = true;
203     for (i = 0; i < vec_size(ftepp->conditions); ++i)
204         ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
205 }
206
207 static ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
208 {
209     size_t i;
210     for (i = 0; i < vec_size(ftepp->macros); ++i) {
211         if (!strcmp(name, ftepp->macros[i]->name))
212             return ftepp->macros[i];
213     }
214     return NULL;
215 }
216
217 static void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
218 {
219     size_t i;
220     for (i = 0; i < vec_size(ftepp->macros); ++i) {
221         if (!strcmp(name, ftepp->macros[i]->name)) {
222             vec_remove(ftepp->macros, i, 1);
223             return;
224         }
225     }
226 }
227
228 static inline int ftepp_next(ftepp_t *ftepp)
229 {
230     return (ftepp->token = lex_do(ftepp->lex));
231 }
232
233 /* Important: this does not skip newlines! */
234 static bool ftepp_skipspace(ftepp_t *ftepp)
235 {
236     if (ftepp->token != TOKEN_WHITE)
237         return true;
238     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
239     if (ftepp->token >= TOKEN_EOF) {
240         ftepp_error(ftepp, "unexpected end of preprocessor directive");
241         return false;
242     }
243     return true;
244 }
245
246 /* this one skips EOLs as well */
247 static bool ftepp_skipallwhite(ftepp_t *ftepp)
248 {
249     if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
250         return true;
251     do {
252         ftepp_next(ftepp);
253     } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
254     if (ftepp->token >= TOKEN_EOF) {
255         ftepp_error(ftepp, "unexpected end of preprocessor directive");
256         return false;
257     }
258     return true;
259 }
260
261 /**
262  * The huge macro parsing code...
263  */
264 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
265 {
266     do {
267         ftepp_next(ftepp);
268         if (!ftepp_skipspace(ftepp))
269             return false;
270         if (ftepp->token == ')')
271             break;
272         switch (ftepp->token) {
273             case TOKEN_IDENT:
274             case TOKEN_TYPENAME:
275             case TOKEN_KEYWORD:
276                 break;
277             default:
278                 ftepp_error(ftepp, "unexpected token in parameter list");
279                 return false;
280         }
281         vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
282         ftepp_next(ftepp);
283         if (!ftepp_skipspace(ftepp))
284             return false;
285     } while (ftepp->token == ',');
286     if (ftepp->token != ')') {
287         ftepp_error(ftepp, "expected closing paren after macro parameter list");
288         return false;
289     }
290     ftepp_next(ftepp);
291     /* skipspace happens in ftepp_define */
292     return true;
293 }
294
295 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
296 {
297     pptoken *ptok;
298     while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
299         ptok = pptoken_make(ftepp);
300         vec_push(macro->output, ptok);
301         ftepp_next(ftepp);
302     }
303     /* recursive expansion can cause EOFs here */
304     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
305         ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
306         return false;
307     }
308     return true;
309 }
310
311 static bool ftepp_define(ftepp_t *ftepp)
312 {
313     ppmacro *macro;
314     (void)ftepp_next(ftepp);
315     if (!ftepp_skipspace(ftepp))
316         return false;
317
318     switch (ftepp->token) {
319         case TOKEN_IDENT:
320         case TOKEN_TYPENAME:
321         case TOKEN_KEYWORD:
322             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
323             if (macro && ftepp->output_on) {
324                 if (ftepp_warn(ftepp, WARN_PREPROCESSOR, "redefining `%s`", ftepp_tokval(ftepp)))
325                     return false;
326                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
327             }
328             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
329             break;
330         default:
331             ftepp_error(ftepp, "expected macro name");
332             return false;
333     }
334
335     (void)ftepp_next(ftepp);
336
337     if (ftepp->token == '(') {
338         macro->has_params = true;
339         if (!ftepp_define_params(ftepp, macro))
340             return false;
341     }
342
343     if (!ftepp_skipspace(ftepp))
344         return false;
345
346     if (!ftepp_define_body(ftepp, macro))
347         return false;
348
349     if (ftepp->output_on)
350         vec_push(ftepp->macros, macro);
351     else {
352         ppmacro_delete(macro);
353     }
354     return true;
355 }
356
357 /**
358  * When a macro is used we have to handle parameters as well
359  * as special-concatenation via ## or stringification via #
360  *
361  * Note: parenthesis can nest, so FOO((a),b) is valid, but only
362  * this kind of parens. Curly braces or [] don't count towards the
363  * paren-level.
364  */
365 typedef struct {
366     pptoken **tokens;
367 } macroparam;
368
369 static void macroparam_clean(macroparam *self)
370 {
371     size_t i;
372     for (i = 0; i < vec_size(self->tokens); ++i)
373         pptoken_delete(self->tokens[i]);
374     vec_free(self->tokens);
375 }
376
377 /* need to leave the last token up */
378 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
379 {
380     macroparam *params = NULL;
381     pptoken    *ptok;
382     macroparam  mp;
383     size_t      parens = 0;
384     size_t      i;
385
386     if (!ftepp_skipallwhite(ftepp))
387         return false;
388     while (ftepp->token != ')') {
389         mp.tokens = NULL;
390         if (!ftepp_skipallwhite(ftepp))
391             return false;
392         while (parens || ftepp->token != ',') {
393             if (ftepp->token == '(')
394                 ++parens;
395             else if (ftepp->token == ')') {
396                 if (!parens)
397                     break;
398                 --parens;
399             }
400             ptok = pptoken_make(ftepp);
401             vec_push(mp.tokens, ptok);
402             if (ftepp_next(ftepp) >= TOKEN_EOF) {
403                 ftepp_error(ftepp, "unexpected EOF in macro call");
404                 goto on_error;
405             }
406         }
407         vec_push(params, mp);
408         mp.tokens = NULL;
409         if (ftepp->token == ')')
410             break;
411         if (ftepp->token != ',') {
412             ftepp_error(ftepp, "expected closing paren or comma in macro call");
413             goto on_error;
414         }
415         if (ftepp_next(ftepp) >= TOKEN_EOF) {
416             ftepp_error(ftepp, "unexpected EOF in macro call");
417             goto on_error;
418         }
419     }
420     /* need to leave that up
421     if (ftepp_next(ftepp) >= TOKEN_EOF) {
422         ftepp_error(ftepp, "unexpected EOF in macro call");
423         goto on_error;
424     }
425     */
426     *out_params = params;
427     return true;
428
429 on_error:
430     if (mp.tokens)
431         macroparam_clean(&mp);
432     for (i = 0; i < vec_size(params); ++i)
433         macroparam_clean(&params[i]);
434     vec_free(params);
435     return false;
436 }
437
438 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
439 {
440     size_t i;
441     for (i = 0; i < vec_size(macro->params); ++i) {
442         if (!strcmp(macro->params[i], name)) {
443             *idx = i;
444             return true;
445         }
446     }
447     return false;
448 }
449
450 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
451 {
452     char        chs[2];
453     const char *ch;
454     chs[1] = 0;
455     switch (token->token) {
456         case TOKEN_STRINGCONST:
457             ch = token->value;
458             while (*ch) {
459                 /* in preprocessor mode strings already are string,
460                  * so we don't get actual newline bytes here.
461                  * Still need to escape backslashes and quotes.
462                  */
463                 switch (*ch) {
464                     case '\\': ftepp_out(ftepp, "\\\\", false); break;
465                     case '"':  ftepp_out(ftepp, "\\\"", false); break;
466                     default:
467                         chs[0] = *ch;
468                         ftepp_out(ftepp, chs, false);
469                         break;
470                 }
471                 ++ch;
472             }
473             break;
474         case TOKEN_WHITE:
475             ftepp_out(ftepp, " ", false);
476             break;
477         case TOKEN_EOL:
478             ftepp_out(ftepp, "\\n", false);
479             break;
480         default:
481             ftepp_out(ftepp, token->value, false);
482             break;
483     }
484 }
485
486 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
487 {
488     size_t i;
489     ftepp_out(ftepp, "\"", false);
490     for (i = 0; i < vec_size(param->tokens); ++i)
491         ftepp_stringify_token(ftepp, param->tokens[i]);
492     ftepp_out(ftepp, "\"", false);
493 }
494
495 static void ftepp_recursion_header(ftepp_t *ftepp)
496 {
497     ftepp_out(ftepp, "\n#pragma push(line)\n", false);
498 }
499
500 static void ftepp_recursion_footer(ftepp_t *ftepp)
501 {
502     ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
503 }
504
505 static bool ftepp_preprocess(ftepp_t *ftepp);
506 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params)
507 {
508     char     *old_string = ftepp->output_string;
509     lex_file *old_lexer = ftepp->lex;
510     bool retval = true;
511
512     size_t    o, pi, pv;
513     lex_file *inlex;
514
515     int nextok;
516
517     /* really ... */
518     if (!vec_size(macro->output))
519         return true;
520
521     ftepp->output_string = NULL;
522     for (o = 0; o < vec_size(macro->output); ++o) {
523         pptoken *out = macro->output[o];
524         switch (out->token) {
525             case TOKEN_IDENT:
526             case TOKEN_TYPENAME:
527             case TOKEN_KEYWORD:
528                 if (!macro_params_find(macro, out->value, &pi)) {
529                     ftepp_out(ftepp, out->value, false);
530                     break;
531                 } else {
532                     for (pv = 0; pv < vec_size(params[pi].tokens); ++pv) {
533                         out = params[pi].tokens[pv];
534                         if (out->token == TOKEN_EOL)
535                             ftepp_out(ftepp, "\n", false);
536                         else
537                             ftepp_out(ftepp, out->value, false);
538                     }
539                 }
540                 break;
541             case '#':
542                 if (o + 1 < vec_size(macro->output)) {
543                     nextok = macro->output[o+1]->token;
544                     if (nextok == '#') {
545                         /* raw concatenation */
546                         ++o;
547                         break;
548                     }
549                     if ( (nextok == TOKEN_IDENT    ||
550                           nextok == TOKEN_KEYWORD  ||
551                           nextok == TOKEN_TYPENAME) &&
552                         macro_params_find(macro, macro->output[o+1]->value, &pi))
553                     {
554                         ++o;
555                         ftepp_stringify(ftepp, &params[pi]);
556                         break;
557                     }
558                 }
559                 ftepp_out(ftepp, "#", false);
560                 break;
561             case TOKEN_EOL:
562                 ftepp_out(ftepp, "\n", false);
563                 break;
564             default:
565                 ftepp_out(ftepp, out->value, false);
566                 break;
567         }
568     }
569     vec_push(ftepp->output_string, 0);
570     /* Now run the preprocessor recursively on this string buffer */
571     /*
572     printf("__________\n%s\n=========\n", ftepp->output_string);
573     */
574     inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
575     if (!inlex) {
576         ftepp_error(ftepp, "internal error: failed to instantiate lexer");
577         retval = false;
578         goto cleanup;
579     }
580     ftepp->output_string = old_string;
581     ftepp->lex = inlex;
582     ftepp_recursion_header(ftepp);
583     if (!ftepp_preprocess(ftepp)) {
584         lex_close(ftepp->lex);
585         retval = false;
586         goto cleanup;
587     }
588     ftepp_recursion_footer(ftepp);
589     old_string = ftepp->output_string;
590
591 cleanup:
592     ftepp->lex           = old_lexer;
593     ftepp->output_string = old_string;
594     return retval;
595 }
596
597 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
598 {
599     size_t     o;
600     macroparam *params = NULL;
601     bool        retval = true;
602
603     if (!macro->has_params) {
604         if (!ftepp_macro_expand(ftepp, macro, NULL))
605             return false;
606         ftepp_next(ftepp);
607         return true;
608     }
609     ftepp_next(ftepp);
610
611     if (!ftepp_skipallwhite(ftepp))
612         return false;
613
614     if (ftepp->token != '(') {
615         ftepp_error(ftepp, "expected macro parameters in parenthesis");
616         return false;
617     }
618
619     ftepp_next(ftepp);
620     if (!ftepp_macro_call_params(ftepp, &params))
621         return false;
622
623     if (vec_size(params) != vec_size(macro->params)) {
624         ftepp_error(ftepp, "macro %s expects %u paramteters, %u provided", macro->name,
625                     (unsigned int)vec_size(macro->params),
626                     (unsigned int)vec_size(params));
627         retval = false;
628         goto cleanup;
629     }
630
631     if (!ftepp_macro_expand(ftepp, macro, params))
632         retval = false;
633     ftepp_next(ftepp);
634
635 cleanup:
636     for (o = 0; o < vec_size(params); ++o)
637         macroparam_clean(&params[o]);
638     vec_free(params);
639     return retval;
640 }
641
642 /**
643  * #if - the FTEQCC way:
644  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
645  *    <numbers>    => True if the number is not 0
646  *    !<factor>    => True if the factor yields false
647  *    !!<factor>   => ERROR on 2 or more unary nots
648  *    <macro>      => becomes the macro's FIRST token regardless of parameters
649  *    <e> && <e>   => True if both expressions are true
650  *    <e> || <e>   => True if either expression is true
651  *    <string>     => False
652  *    <ident>      => False (remember for macros the <macro> rule applies instead)
653  * Unary + and - are weird and wrong in fteqcc so we don't allow them
654  * parenthesis in expressions are allowed
655  * parameter lists on macros are errors
656  * No mathematical calculations are executed
657  */
658 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out)
659 {
660     ppmacro *macro;
661     bool     wasnot = false;
662
663     if (!ftepp_skipspace(ftepp))
664         return false;
665
666     while (ftepp->token == '!') {
667         wasnot = true;
668         ftepp_next(ftepp);
669         if (!ftepp_skipspace(ftepp))
670             return false;
671     }
672
673     switch (ftepp->token) {
674         case TOKEN_IDENT:
675         case TOKEN_TYPENAME:
676         case TOKEN_KEYWORD:
677             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
678                 ftepp_next(ftepp);
679                 if (!ftepp_skipspace(ftepp))
680                     return false;
681                 if (ftepp->token != '(') {
682                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
683                     return false;
684                 }
685                 ftepp_next(ftepp);
686                 if (!ftepp_skipspace(ftepp))
687                     return false;
688                 if (ftepp->token != TOKEN_IDENT &&
689                     ftepp->token != TOKEN_TYPENAME &&
690                     ftepp->token != TOKEN_KEYWORD)
691                 {
692                     ftepp_error(ftepp, "defined() used on an unexpected token type");
693                     return false;
694                 }
695                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
696                 *out = !!macro;
697                 ftepp_next(ftepp);
698                 if (!ftepp_skipspace(ftepp))
699                     return false;
700                 if (ftepp->token != ')') {
701                     ftepp_error(ftepp, "expected closing paren");
702                     return false;
703                 }
704                 break;
705             }
706
707             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
708             if (!macro || !vec_size(macro->output)) {
709                 *out = false;
710             } else {
711                 /* This does not expand recursively! */
712                 switch (macro->output[0]->token) {
713                     case TOKEN_INTCONST:
714                         *out = !!(macro->output[0]->constval.f);
715                         break;
716                     case TOKEN_FLOATCONST:
717                         *out = !!(macro->output[0]->constval.f);
718                         break;
719                     default:
720                         *out = false;
721                         break;
722                 }
723             }
724             break;
725         case TOKEN_STRINGCONST:
726             *out = false;
727             break;
728         case TOKEN_INTCONST:
729             *out = !!(ftepp->lex->tok.constval.i);
730             break;
731         case TOKEN_FLOATCONST:
732             *out = !!(ftepp->lex->tok.constval.f);
733             break;
734
735         case '(':
736             ftepp_next(ftepp);
737             if (!ftepp_if_expr(ftepp, out))
738                 return false;
739             if (ftepp->token != ')') {
740                 ftepp_error(ftepp, "expected closing paren in #if expression");
741                 return false;
742             }
743             break;
744
745         default:
746             ftepp_error(ftepp, "junk in #if");
747             return false;
748     }
749     if (wasnot)
750         *out = !*out;
751
752     ftepp->lex->flags.noops = false;
753     ftepp_next(ftepp);
754     if (!ftepp_skipspace(ftepp))
755         return false;
756     ftepp->lex->flags.noops = true;
757
758     if (ftepp->token == ')')
759         return true;
760
761     if (ftepp->token != TOKEN_OPERATOR)
762         return true;
763
764     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
765         !strcmp(ftepp_tokval(ftepp), "||"))
766     {
767         bool next = false;
768         char opc  = ftepp_tokval(ftepp)[0];
769
770         ftepp_next(ftepp);
771         if (!ftepp_if_expr(ftepp, &next))
772             return false;
773
774         if (opc == '&')
775             *out = *out && next;
776         else
777             *out = *out || next;
778         return true;
779     }
780     else {
781         ftepp_error(ftepp, "junk after #if");
782         return false;
783     }
784 }
785
786 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
787 {
788     bool result = false;
789
790     memset(cond, 0, sizeof(*cond));
791     (void)ftepp_next(ftepp);
792
793     if (!ftepp_skipspace(ftepp))
794         return false;
795     if (ftepp->token == TOKEN_EOL) {
796         ftepp_error(ftepp, "expected expression for #if-directive");
797         return false;
798     }
799
800     if (!ftepp_if_expr(ftepp, &result))
801         return false;
802
803     cond->on = result;
804     return true;
805 }
806
807 /**
808  * ifdef is rather simple
809  */
810 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
811 {
812     ppmacro *macro;
813     memset(cond, 0, sizeof(*cond));
814     (void)ftepp_next(ftepp);
815     if (!ftepp_skipspace(ftepp))
816         return false;
817
818     switch (ftepp->token) {
819         case TOKEN_IDENT:
820         case TOKEN_TYPENAME:
821         case TOKEN_KEYWORD:
822             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
823             break;
824         default:
825             ftepp_error(ftepp, "expected macro name");
826             return false;
827     }
828
829     (void)ftepp_next(ftepp);
830     if (!ftepp_skipspace(ftepp))
831         return false;
832     /* relaxing this condition
833     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
834         ftepp_error(ftepp, "stray tokens after #ifdef");
835         return false;
836     }
837     */
838     cond->on = !!macro;
839     return true;
840 }
841
842 /**
843  * undef is also simple
844  */
845 static bool ftepp_undef(ftepp_t *ftepp)
846 {
847     (void)ftepp_next(ftepp);
848     if (!ftepp_skipspace(ftepp))
849         return false;
850
851     if (ftepp->output_on) {
852         switch (ftepp->token) {
853             case TOKEN_IDENT:
854             case TOKEN_TYPENAME:
855             case TOKEN_KEYWORD:
856                 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
857                 break;
858             default:
859                 ftepp_error(ftepp, "expected macro name");
860                 return false;
861         }
862     }
863
864     (void)ftepp_next(ftepp);
865     if (!ftepp_skipspace(ftepp))
866         return false;
867     /* relaxing this condition
868     if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
869         ftepp_error(ftepp, "stray tokens after #ifdef");
870         return false;
871     }
872     */
873     return true;
874 }
875
876 /* Special unescape-string function which skips a leading quote
877  * and stops at a quote, not just at \0
878  */
879 static void unescape(const char *str, char *out) {
880     ++str;
881     while (*str && *str != '"') {
882         if (*str == '\\') {
883             ++str;
884             switch (*str) {
885                 case '\\': *out++ = *str; break;
886                 case '"':  *out++ = *str; break;
887                 case 'a':  *out++ = '\a'; break;
888                 case 'b':  *out++ = '\b'; break;
889                 case 'r':  *out++ = '\r'; break;
890                 case 'n':  *out++ = '\n'; break;
891                 case 't':  *out++ = '\t'; break;
892                 case 'f':  *out++ = '\f'; break;
893                 case 'v':  *out++ = '\v'; break;
894                 default:
895                     *out++ = '\\';
896                     *out++ = *str;
897                     break;
898             }
899             ++str;
900             continue;
901         }
902
903         *out++ = *str++;
904     }
905     *out = 0;
906 }
907
908 static char *ftepp_include_find_path(const char *file, const char *pathfile)
909 {
910     FILE       *fp;
911     char       *filename = NULL;
912     const char *last_slash;
913     size_t      len;
914
915     if (!pathfile)
916         return NULL;
917
918     last_slash = strrchr(pathfile, '/');
919
920     if (last_slash) {
921         len = last_slash - pathfile;
922         memcpy(vec_add(filename, len), pathfile, len);
923         vec_push(filename, '/');
924     }
925     else {
926         len = strlen(pathfile);
927         memcpy(vec_add(filename, len), pathfile, len);
928         if (vec_last(filename) != '/')
929             vec_push(filename, '/');
930     }
931
932     len = strlen(file);
933     memcpy(vec_add(filename, len+1), file, len);
934     vec_last(filename) = 0;
935
936     fp = util_fopen(filename, "rb");
937     if (fp) {
938         fclose(fp);
939         return filename;
940     }
941     vec_free(filename);
942     return NULL;
943 }
944
945 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
946 {
947     char *filename = NULL;
948
949     filename = ftepp_include_find_path(file, ftepp->includename);
950     if (!filename)
951         filename = ftepp_include_find_path(file, ftepp->itemname);
952     return filename;
953 }
954
955 /**
956  * Include a file.
957  * FIXME: do we need/want a -I option?
958  * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
959  */
960 static bool ftepp_include(ftepp_t *ftepp)
961 {
962     lex_file *old_lexer = ftepp->lex;
963     lex_file *inlex;
964     lex_ctx  ctx;
965     char     lineno[128];
966     char     *filename;
967     char     *old_includename;
968
969     (void)ftepp_next(ftepp);
970     if (!ftepp_skipspace(ftepp))
971         return false;
972
973     if (ftepp->token != TOKEN_STRINGCONST) {
974         ftepp_error(ftepp, "expected filename to include");
975         return false;
976     }
977
978     ctx = ftepp_ctx(ftepp);
979
980     unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
981
982     ftepp_out(ftepp, "\n#pragma file(", false);
983     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
984     ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
985
986     filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
987     if (!filename) {
988         ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
989         return false;
990     }
991     inlex = lex_open(filename);
992     if (!inlex) {
993         ftepp_error(ftepp, "failed to open include file `%s`", filename);
994         vec_free(filename);
995         return false;
996     }
997     ftepp->lex = inlex;
998     old_includename = ftepp->includename;
999     ftepp->includename = filename;
1000     if (!ftepp_preprocess(ftepp)) {
1001         vec_free(ftepp->includename);
1002         ftepp->includename = old_includename;
1003         lex_close(ftepp->lex);
1004         ftepp->lex = old_lexer;
1005         return false;
1006     }
1007     vec_free(ftepp->includename);
1008     ftepp->includename = old_includename;
1009     lex_close(ftepp->lex);
1010     ftepp->lex = old_lexer;
1011
1012     ftepp_out(ftepp, "\n#pragma file(", false);
1013     ftepp_out(ftepp, ctx.file, false);
1014     snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1015     ftepp_out(ftepp, lineno, false);
1016
1017     /* skip the line */
1018     (void)ftepp_next(ftepp);
1019     if (!ftepp_skipspace(ftepp))
1020         return false;
1021     if (ftepp->token != TOKEN_EOL) {
1022         ftepp_error(ftepp, "stray tokens after #include");
1023         return false;
1024     }
1025     (void)ftepp_next(ftepp);
1026
1027     return true;
1028 }
1029
1030 /* Basic structure handlers */
1031 static bool ftepp_else_allowed(ftepp_t *ftepp)
1032 {
1033     if (!vec_size(ftepp->conditions)) {
1034         ftepp_error(ftepp, "#else without #if");
1035         return false;
1036     }
1037     if (vec_last(ftepp->conditions).had_else) {
1038         ftepp_error(ftepp, "multiple #else for a single #if");
1039         return false;
1040     }
1041     return true;
1042 }
1043
1044 static bool ftepp_hash(ftepp_t *ftepp)
1045 {
1046     ppcondition cond;
1047     ppcondition *pc;
1048
1049     lex_ctx ctx = ftepp_ctx(ftepp);
1050
1051     if (!ftepp_skipspace(ftepp))
1052         return false;
1053
1054     switch (ftepp->token) {
1055         case TOKEN_KEYWORD:
1056         case TOKEN_IDENT:
1057         case TOKEN_TYPENAME:
1058             if (!strcmp(ftepp_tokval(ftepp), "define")) {
1059                 return ftepp_define(ftepp);
1060             }
1061             else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1062                 return ftepp_undef(ftepp);
1063             }
1064             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1065                 if (!ftepp_ifdef(ftepp, &cond))
1066                     return false;
1067                 cond.was_on = cond.on;
1068                 vec_push(ftepp->conditions, cond);
1069                 ftepp->output_on = ftepp->output_on && cond.on;
1070                 break;
1071             }
1072             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1073                 if (!ftepp_ifdef(ftepp, &cond))
1074                     return false;
1075                 cond.on = !cond.on;
1076                 cond.was_on = cond.on;
1077                 vec_push(ftepp->conditions, cond);
1078                 ftepp->output_on = ftepp->output_on && cond.on;
1079                 break;
1080             }
1081             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1082                 if (!ftepp_else_allowed(ftepp))
1083                     return false;
1084                 if (!ftepp_ifdef(ftepp, &cond))
1085                     return false;
1086                 pc = &vec_last(ftepp->conditions);
1087                 pc->on     = !pc->was_on && cond.on;
1088                 pc->was_on = pc->was_on || pc->on;
1089                 ftepp_update_output_condition(ftepp);
1090                 break;
1091             }
1092             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1093                 if (!ftepp_else_allowed(ftepp))
1094                     return false;
1095                 if (!ftepp_ifdef(ftepp, &cond))
1096                     return false;
1097                 cond.on = !cond.on;
1098                 pc = &vec_last(ftepp->conditions);
1099                 pc->on     = !pc->was_on && cond.on;
1100                 pc->was_on = pc->was_on || pc->on;
1101                 ftepp_update_output_condition(ftepp);
1102                 break;
1103             }
1104             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1105                 if (!ftepp_else_allowed(ftepp))
1106                     return false;
1107                 if (!ftepp_if(ftepp, &cond))
1108                     return false;
1109                 pc = &vec_last(ftepp->conditions);
1110                 pc->on     = !pc->was_on && cond.on;
1111                 pc->was_on = pc->was_on  || pc->on;
1112                 ftepp_update_output_condition(ftepp);
1113                 break;
1114             }
1115             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1116                 if (!ftepp_if(ftepp, &cond))
1117                     return false;
1118                 cond.was_on = cond.on;
1119                 vec_push(ftepp->conditions, cond);
1120                 ftepp->output_on = ftepp->output_on && cond.on;
1121                 break;
1122             }
1123             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1124                 if (!ftepp_else_allowed(ftepp))
1125                     return false;
1126                 pc = &vec_last(ftepp->conditions);
1127                 pc->on = !pc->was_on;
1128                 pc->had_else = true;
1129                 ftepp_next(ftepp);
1130                 ftepp_update_output_condition(ftepp);
1131                 break;
1132             }
1133             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1134                 if (!vec_size(ftepp->conditions)) {
1135                     ftepp_error(ftepp, "#endif without #if");
1136                     return false;
1137                 }
1138                 vec_pop(ftepp->conditions);
1139                 ftepp_next(ftepp);
1140                 ftepp_update_output_condition(ftepp);
1141                 break;
1142             }
1143             else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1144                 return ftepp_include(ftepp);
1145             }
1146             else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1147                 ftepp_out(ftepp, "#", false);
1148                 break;
1149             }
1150             else {
1151                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1152                 return false;
1153             }
1154             /* break; never reached */
1155         default:
1156             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1157             return false;
1158         case TOKEN_EOL:
1159             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1160             return false;
1161         case TOKEN_EOF:
1162             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1163             return false;
1164
1165         /* Builtins! Don't forget the builtins! */
1166         case TOKEN_INTCONST:
1167         case TOKEN_FLOATCONST:
1168             ftepp_out(ftepp, "#", false);
1169             return true;
1170     }
1171     if (!ftepp_skipspace(ftepp))
1172         return false;
1173     return true;
1174 }
1175
1176 static bool ftepp_preprocess(ftepp_t *ftepp)
1177 {
1178     ppmacro *macro;
1179     bool     newline = true;
1180
1181     ftepp->lex->flags.preprocessing = true;
1182     ftepp->lex->flags.mergelines    = false;
1183     ftepp->lex->flags.noops         = true;
1184
1185     ftepp_next(ftepp);
1186     do
1187     {
1188         if (ftepp->token >= TOKEN_EOF)
1189             break;
1190 #if 0
1191         ftepp->newline = newline;
1192         newline = false;
1193 #else
1194         /* For the sake of FTE compatibility... FU, really */
1195         ftepp->newline = newline = true;
1196 #endif
1197
1198         switch (ftepp->token) {
1199             case TOKEN_KEYWORD:
1200             case TOKEN_IDENT:
1201             case TOKEN_TYPENAME:
1202                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1203                 if (!macro) {
1204                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1205                     ftepp_next(ftepp);
1206                     break;
1207                 }
1208                 if (!ftepp_macro_call(ftepp, macro))
1209                     ftepp->token = TOKEN_ERROR;
1210                 break;
1211             case '#':
1212                 if (!ftepp->newline) {
1213                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1214                     ftepp_next(ftepp);
1215                     break;
1216                 }
1217                 ftepp->lex->flags.mergelines = true;
1218                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1219                     ftepp_error(ftepp, "error in preprocessor directive");
1220                     ftepp->token = TOKEN_ERROR;
1221                     break;
1222                 }
1223                 if (!ftepp_hash(ftepp))
1224                     ftepp->token = TOKEN_ERROR;
1225                 ftepp->lex->flags.mergelines = false;
1226                 break;
1227             case TOKEN_EOL:
1228                 newline = true;
1229                 ftepp_out(ftepp, "\n", true);
1230                 ftepp_next(ftepp);
1231                 break;
1232             default:
1233                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1234                 ftepp_next(ftepp);
1235                 break;
1236         }
1237     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1238
1239     newline = ftepp->token == TOKEN_EOF;
1240     return newline;
1241 }
1242
1243 /* Like in parser.c - files keep the previous state so we have one global
1244  * preprocessor. Except here we will want to warn about dangling #ifs.
1245  */
1246 static ftepp_t *ftepp;
1247
1248 static bool ftepp_preprocess_done()
1249 {
1250     bool retval = true;
1251     lex_close(ftepp->lex);
1252     ftepp->lex = NULL;
1253     if (vec_size(ftepp->conditions)) {
1254         if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1255             retval = false;
1256     }
1257     if (ftepp->itemname) {
1258         mem_d(ftepp->itemname);
1259         ftepp->itemname = NULL;
1260     }
1261     return retval;
1262 }
1263
1264 bool ftepp_preprocess_file(const char *filename)
1265 {
1266     ftepp->lex = lex_open(filename);
1267     ftepp->itemname = util_strdup(filename);
1268     if (!ftepp->lex) {
1269         con_out("failed to open file \"%s\"\n", filename);
1270         return false;
1271     }
1272     if (!ftepp_preprocess(ftepp))
1273         return false;
1274     return ftepp_preprocess_done();
1275 }
1276
1277 bool ftepp_preprocess_string(const char *name, const char *str)
1278 {
1279     ftepp->lex = lex_open_string(str, strlen(str), name);
1280     ftepp->itemname = util_strdup(name);
1281     if (!ftepp->lex) {
1282         con_out("failed to create lexer for string \"%s\"\n", name);
1283         return false;
1284     }
1285     if (!ftepp_preprocess(ftepp))
1286         return false;
1287     return ftepp_preprocess_done();
1288 }
1289
1290 bool ftepp_init()
1291 {
1292     ftepp = ftepp_new();
1293     if (!ftepp)
1294         return false;
1295     ftepp_add_define(NULL, "GMQCC");
1296     return true;
1297 }
1298
1299 void ftepp_add_define(const char *source, const char *name)
1300 {
1301     ppmacro *macro;
1302     lex_ctx ctx = { "__builtin__", 0 };
1303     ctx.file = source;
1304     macro = ppmacro_new(ctx, name);
1305     vec_push(ftepp->macros, macro);
1306 }
1307
1308 const char *ftepp_get()
1309 {
1310     return ftepp->output_string;
1311 }
1312
1313 void ftepp_flush()
1314 {
1315     vec_free(ftepp->output_string);
1316 }
1317
1318 void ftepp_finish()
1319 {
1320     if (!ftepp)
1321         return;
1322     ftepp_delete(ftepp);
1323     ftepp = NULL;
1324 }