]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
macro_body parse function shouldn't skip whitespace inside
[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     ppcondition *conditions;
62     ppmacro    **macros;
63 } ftepp_t;
64
65 #define ftepp_tokval(f) ((f)->lex->tok.value)
66 #define ftepp_ctx(f)    ((f)->lex->tok.ctx)
67
68 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
69 {
70     va_list ap;
71
72     ftepp->errors++;
73
74     va_start(ap, fmt);
75     con_vprintmsg(LVL_ERROR, ctx.file, ctx.line, "error", fmt, ap);
76     va_end(ap);
77 }
78
79 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
80 {
81     va_list ap;
82
83     ftepp->errors++;
84
85     va_start(ap, fmt);
86     con_vprintmsg(LVL_ERROR, ftepp->lex->tok.ctx.file, ftepp->lex->tok.ctx.line, "error", fmt, ap);
87     va_end(ap);
88 }
89
90 pptoken *pptoken_make(ftepp_t *ftepp)
91 {
92     pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
93     token->token = ftepp->token;
94     if (token->token == TOKEN_WHITE)
95         token->value = util_strdup(" ");
96     else
97         token->value = util_strdup(ftepp_tokval(ftepp));
98     memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
99     return token;
100 }
101
102 void pptoken_delete(pptoken *self)
103 {
104     mem_d(self->value);
105     mem_d(self);
106 }
107
108 ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
109 {
110     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
111     memset(macro, 0, sizeof(*macro));
112     macro->name = util_strdup(name);
113     return macro;
114 }
115
116 void ppmacro_delete(ppmacro *self)
117 {
118     size_t i;
119     for (i = 0; i < vec_size(self->params); ++i)
120         mem_d(self->params[i]);
121     vec_free(self->params);
122     for (i = 0; i < vec_size(self->output); ++i)
123         pptoken_delete(self->output[i]);
124     vec_free(self->output);
125     mem_d(self->name);
126     mem_d(self);
127 }
128
129 ftepp_t* ftepp_init()
130 {
131     ftepp_t *ftepp;
132
133     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
134     memset(ftepp, 0, sizeof(*ftepp));
135
136     return ftepp;
137 }
138
139 void ftepp_delete(ftepp_t *self)
140 {
141     size_t i;
142     for (i = 0; i < vec_size(self->macros); ++i)
143         ppmacro_delete(self->macros[i]);
144     vec_free(self->macros);
145     vec_free(self->conditions);
146     lex_close(self->lex);
147     mem_d(self);
148 }
149
150 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
151 {
152     if (ignore_cond ||
153         !vec_size(ftepp->conditions) ||
154         vec_last(ftepp->conditions).on)
155     {
156         printf("%s", str);
157     }
158 }
159
160 ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
161 {
162     size_t i;
163     for (i = 0; i < vec_size(ftepp->macros); ++i) {
164         if (!strcmp(name, ftepp->macros[i]->name))
165             return ftepp->macros[i];
166     }
167     return NULL;
168 }
169
170 static inline int ftepp_next(ftepp_t *ftepp)
171 {
172     return (ftepp->token = lex_do(ftepp->lex));
173 }
174
175 /* Important: this does not skip newlines! */
176 static bool ftepp_skipspace(ftepp_t *ftepp)
177 {
178     if (ftepp->token != TOKEN_WHITE)
179         return true;
180     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
181     if (ftepp->token >= TOKEN_EOF) {
182         ftepp_error(ftepp, "unexpected end of preprocessor directive");
183         return false;
184     }
185     return true;
186 }
187
188 /* this one skips EOLs as well */
189 static bool ftepp_skipallwhite(ftepp_t *ftepp)
190 {
191     if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
192         return true;
193     do {
194         ftepp_next(ftepp);
195     } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
196     if (ftepp->token >= TOKEN_EOF) {
197         ftepp_error(ftepp, "unexpected end of preprocessor directive");
198         return false;
199     }
200     return true;
201 }
202
203 /**
204  * The huge macro parsing code...
205  */
206 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
207 {
208     do {
209         ftepp_next(ftepp);
210         if (!ftepp_skipspace(ftepp))
211             return false;
212         if (ftepp->token == ')')
213             break;
214         switch (ftepp->token) {
215             case TOKEN_IDENT:
216             case TOKEN_TYPENAME:
217             case TOKEN_KEYWORD:
218                 break;
219             default:
220                 ftepp_error(ftepp, "unexpected token in parameter list");
221                 return false;
222         }
223         vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
224         ftepp_next(ftepp);
225         if (!ftepp_skipspace(ftepp))
226             return false;
227     } while (ftepp->token == ',');
228     if (ftepp->token != ')') {
229         ftepp_error(ftepp, "expected closing paren after macro parameter list");
230         return false;
231     }
232     ftepp_next(ftepp);
233     /* skipspace happens in ftepp_define */
234     return true;
235 }
236
237 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
238 {
239     pptoken *ptok;
240     while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
241         ptok = pptoken_make(ftepp);
242         vec_push(macro->output, ptok);
243         ftepp_next(ftepp);
244     }
245     if (ftepp->token != TOKEN_EOL) {
246         ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
247         return false;
248     }
249     return true;
250 }
251
252 static bool ftepp_define(ftepp_t *ftepp)
253 {
254     ppmacro *macro;
255     (void)ftepp_next(ftepp);
256     if (!ftepp_skipspace(ftepp))
257         return false;
258
259     switch (ftepp->token) {
260         case TOKEN_IDENT:
261         case TOKEN_TYPENAME:
262         case TOKEN_KEYWORD:
263             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
264             break;
265         default:
266             ftepp_error(ftepp, "expected macro name");
267             return false;
268     }
269
270     (void)ftepp_next(ftepp);
271
272     if (ftepp->token == '(') {
273         macro->has_params = true;
274         if (!ftepp_define_params(ftepp, macro))
275             return false;
276     }
277
278     if (!ftepp_skipspace(ftepp))
279         return false;
280
281     if (!ftepp_define_body(ftepp, macro))
282         return false;
283
284     vec_push(ftepp->macros, macro);
285     return true;
286 }
287
288 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
289 {
290     size_t o;
291     ftepp_next(ftepp);
292
293     if (!macro->has_params) {
294         for (o = 0; o < vec_size(macro->output); ++o) {
295             ftepp_out(ftepp, macro->output[o]->value, false);
296         }
297         return true;
298     }
299
300     if (!ftepp_skipallwhite(ftepp))
301         return false;
302     return true;
303 }
304
305 /**
306  * When a macro is used we have to handle parameters as well
307  * as special-concatenation via ## or stringification via #
308  */
309
310 /**
311  * #if - the FTEQCC way:
312  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
313  *    <numbers>    => True if the number is not 0
314  *    !<factor>    => True if the factor yields false
315  *    !!<factor>   => ERROR on 2 or more unary nots
316  *    <macro>      => becomes the macro's FIRST token regardless of parameters
317  *    <e> && <e>   => True if both expressions are true
318  *    <e> || <e>   => True if either expression is true
319  *    <string>     => False
320  *    <ident>      => False (remember for macros the <macro> rule applies instead)
321  * Unary + and - are weird and wrong in fteqcc so we don't allow them
322  * parenthesis in expressions are allowed
323  * parameter lists on macros are errors
324  * No mathematical calculations are executed
325  */
326 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out)
327 {
328     ppmacro *macro;
329     bool     wasnot = false;
330
331     if (!ftepp_skipspace(ftepp))
332         return false;
333
334     while (ftepp->token == '!') {
335         wasnot = true;
336         ftepp_next(ftepp);
337         if (!ftepp_skipspace(ftepp))
338             return false;
339     }
340
341     switch (ftepp->token) {
342         case TOKEN_IDENT:
343         case TOKEN_TYPENAME:
344         case TOKEN_KEYWORD:
345             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
346                 ftepp_next(ftepp);
347                 if (!ftepp_skipspace(ftepp))
348                     return false;
349                 if (ftepp->token != '(') {
350                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
351                     return false;
352                 }
353                 ftepp_next(ftepp);
354                 if (!ftepp_skipspace(ftepp))
355                     return false;
356                 if (ftepp->token != TOKEN_IDENT &&
357                     ftepp->token != TOKEN_TYPENAME &&
358                     ftepp->token != TOKEN_KEYWORD)
359                 {
360                     ftepp_error(ftepp, "defined() used on an unexpected token type");
361                     return false;
362                 }
363                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
364                 *out = !!macro;
365                 ftepp_next(ftepp);
366                 if (!ftepp_skipspace(ftepp))
367                     return false;
368                 if (ftepp->token != ')') {
369                     ftepp_error(ftepp, "expected closing paren");
370                     return false;
371                 }
372                 break;
373             }
374
375             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
376             if (!macro || !vec_size(macro->output)) {
377                 *out = false;
378             } else {
379                 /* This does not expand recursively! */
380                 switch (macro->output[0]->token) {
381                     case TOKEN_INTCONST:
382                         *out = !!(macro->output[0]->constval.f);
383                         break;
384                     case TOKEN_FLOATCONST:
385                         *out = !!(macro->output[0]->constval.f);
386                         break;
387                     default:
388                         *out = false;
389                         break;
390                 }
391             }
392             break;
393         case TOKEN_STRINGCONST:
394             *out = false;
395             break;
396         case TOKEN_INTCONST:
397             *out = !!(ftepp->lex->tok.constval.i);
398             break;
399         case TOKEN_FLOATCONST:
400             *out = !!(ftepp->lex->tok.constval.f);
401             break;
402
403         case '(':
404             ftepp_next(ftepp);
405             if (!ftepp_if_expr(ftepp, out))
406                 return false;
407             if (ftepp->token != ')') {
408                 ftepp_error(ftepp, "expected closing paren in #if expression");
409                 return false;
410             }
411             break;
412
413         default:
414             ftepp_error(ftepp, "junk in #if");
415             return false;
416     }
417     if (wasnot)
418         *out = !*out;
419
420     ftepp->lex->flags.noops = false;
421     ftepp_next(ftepp);
422     if (!ftepp_skipspace(ftepp))
423         return false;
424     ftepp->lex->flags.noops = true;
425
426     if (ftepp->token == ')')
427         return true;
428
429     if (ftepp->token != TOKEN_OPERATOR)
430         return true;
431
432     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
433         !strcmp(ftepp_tokval(ftepp), "||"))
434     {
435         bool next = false;
436         char opc  = ftepp_tokval(ftepp)[0];
437
438         ftepp_next(ftepp);
439         if (!ftepp_if_expr(ftepp, &next))
440             return false;
441
442         if (opc == '&')
443             *out = *out && next;
444         else
445             *out = *out || next;
446         return true;
447     }
448     else {
449         ftepp_error(ftepp, "junk after #if");
450         return false;
451     }
452 }
453
454 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
455 {
456     bool result = false;
457
458     memset(cond, 0, sizeof(*cond));
459     (void)ftepp_next(ftepp);
460
461     if (!ftepp_skipspace(ftepp))
462         return false;
463     if (ftepp->token == TOKEN_EOL) {
464         ftepp_error(ftepp, "expected expression for #if-directive");
465         return false;
466     }
467
468     if (!ftepp_if_expr(ftepp, &result))
469         return false;
470
471     cond->on = result;
472     return true;
473 }
474
475 /**
476  * ifdef is rather simple
477  */
478 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
479 {
480     ppmacro *macro;
481     memset(cond, 0, sizeof(*cond));
482     (void)ftepp_next(ftepp);
483     if (!ftepp_skipspace(ftepp))
484         return false;
485
486     switch (ftepp->token) {
487         case TOKEN_IDENT:
488         case TOKEN_TYPENAME:
489         case TOKEN_KEYWORD:
490             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
491             break;
492         default:
493             ftepp_error(ftepp, "expected macro name");
494             return false;
495     }
496
497     (void)ftepp_next(ftepp);
498     if (!ftepp_skipspace(ftepp))
499         return false;
500     if (ftepp->token != TOKEN_EOL) {
501         ftepp_error(ftepp, "stray tokens after #ifdef");
502         return false;
503     }
504     cond->on = !!macro;
505     return true;
506 }
507
508 /* Basic structure handlers */
509 static bool ftepp_else_allowed(ftepp_t *ftepp)
510 {
511     if (!vec_size(ftepp->conditions)) {
512         ftepp_error(ftepp, "#else without #if");
513         return false;
514     }
515     if (vec_last(ftepp->conditions).had_else) {
516         ftepp_error(ftepp, "multiple #else for a single #if");
517         return false;
518     }
519     return true;
520 }
521
522 static bool ftepp_hash(ftepp_t *ftepp)
523 {
524     ppcondition cond;
525     ppcondition *pc;
526
527     lex_ctx ctx = ftepp_ctx(ftepp);
528
529     if (!ftepp_skipspace(ftepp))
530         return false;
531
532     switch (ftepp->token) {
533         case TOKEN_KEYWORD:
534         case TOKEN_IDENT:
535         case TOKEN_TYPENAME:
536             if (!strcmp(ftepp_tokval(ftepp), "define")) {
537                 return ftepp_define(ftepp);
538             }
539             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
540                 if (!ftepp_ifdef(ftepp, &cond))
541                     return false;
542                 cond.was_on = cond.on;
543                 vec_push(ftepp->conditions, cond);
544                 break;
545             }
546             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
547                 if (!ftepp_ifdef(ftepp, &cond))
548                     return false;
549                 cond.on = !cond.on;
550                 cond.was_on = cond.on;
551                 vec_push(ftepp->conditions, cond);
552                 break;
553             }
554             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
555                 if (!ftepp_else_allowed(ftepp))
556                     return false;
557                 if (!ftepp_ifdef(ftepp, &cond))
558                     return false;
559                 pc = &vec_last(ftepp->conditions);
560                 pc->on     = !pc->was_on && cond.on;
561                 pc->was_on = pc->was_on || pc->on;
562                 break;
563             }
564             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
565                 if (!ftepp_else_allowed(ftepp))
566                     return false;
567                 if (!ftepp_ifdef(ftepp, &cond))
568                     return false;
569                 cond.on = !cond.on;
570                 pc = &vec_last(ftepp->conditions);
571                 pc->on     = !pc->was_on && cond.on;
572                 pc->was_on = pc->was_on || pc->on;
573                 break;
574             }
575             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
576                 if (!ftepp_else_allowed(ftepp))
577                     return false;
578                 if (!ftepp_if(ftepp, &cond))
579                     return false;
580                 pc = &vec_last(ftepp->conditions);
581                 pc->on     = !pc->was_on && cond.on;
582                 pc->was_on = pc->was_on  || pc->on;
583                 break;
584             }
585             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
586                 if (!ftepp_if(ftepp, &cond))
587                     return false;
588                 cond.was_on = cond.on;
589                 vec_push(ftepp->conditions, cond);
590                 break;
591             }
592             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
593                 if (!ftepp_else_allowed(ftepp))
594                     return false;
595                 pc = &vec_last(ftepp->conditions);
596                 pc->on = !pc->was_on;
597                 pc->had_else = true;
598                 ftepp_next(ftepp);
599                 break;
600             }
601             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
602                 if (!vec_size(ftepp->conditions)) {
603                     ftepp_error(ftepp, "#endif without #if");
604                     return false;
605                 }
606                 vec_pop(ftepp->conditions);
607                 ftepp_next(ftepp);
608                 break;
609             }
610             else {
611                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
612                 return false;
613             }
614             break;
615         default:
616             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
617             return false;
618         case TOKEN_EOL:
619             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
620             return false;
621         case TOKEN_EOF:
622             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
623             return false;
624     }
625     if (!ftepp_skipspace(ftepp))
626         return false;
627     return true;
628 }
629
630 static bool ftepp_preprocess(ftepp_t *ftepp)
631 {
632     ppmacro *macro;
633     bool     newline = true;
634
635     ftepp->lex->flags.preprocessing = true;
636     ftepp->lex->flags.mergelines    = false;
637     ftepp->lex->flags.noops         = true;
638
639     ftepp_next(ftepp);
640     do
641     {
642         if (ftepp->token >= TOKEN_EOF)
643             break;
644
645         ftepp->newline = newline;
646         newline = false;
647
648         switch (ftepp->token) {
649             case TOKEN_KEYWORD:
650             case TOKEN_IDENT:
651             case TOKEN_TYPENAME:
652                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
653                 if (!macro) {
654                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
655                     ftepp_next(ftepp);
656                     break;
657                 }
658                 if (!ftepp_macro_call(ftepp, macro))
659                     ftepp->token = TOKEN_ERROR;
660                 break;
661             case '#':
662                 if (!ftepp->newline) {
663                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
664                     ftepp_next(ftepp);
665                     break;
666                 }
667                 ftepp->lex->flags.mergelines = true;
668                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
669                     ftepp_error(ftepp, "error in preprocessor directive");
670                     ftepp->token = TOKEN_ERROR;
671                     break;
672                 }
673                 if (!ftepp_hash(ftepp))
674                     ftepp->token = TOKEN_ERROR;
675                 ftepp->lex->flags.mergelines = false;
676                 break;
677             case TOKEN_EOL:
678                 newline = true;
679                 ftepp_out(ftepp, "\n", true);
680                 ftepp_next(ftepp);
681                 break;
682             default:
683                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
684                 ftepp_next(ftepp);
685                 break;
686         }
687     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
688
689     newline = ftepp->token == TOKEN_EOF;
690     ftepp_delete(ftepp);
691     return newline;
692 }
693
694 bool ftepp_preprocess_file(const char *filename)
695 {
696     ftepp_t *ftepp = ftepp_init();
697     ftepp->lex = lex_open(filename);
698     if (!ftepp->lex) {
699         con_out("failed to open file \"%s\"\n", filename);
700         return false;
701     }
702     return ftepp_preprocess(ftepp);
703 }
704
705 bool ftepp_preprocess_string(const char *name, const char *str)
706 {
707     ftepp_t *ftepp = ftepp_init();
708     ftepp->lex = lex_open_string(str, strlen(str), name);
709     if (!ftepp->lex) {
710         con_out("failed to create lexer for string \"%s\"\n", name);
711         return false;
712     }
713     return ftepp_preprocess(ftepp);
714 }