]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
Parsing some basic #ifs with defined()
[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 ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
91 {
92     ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
93     memset(macro, 0, sizeof(*macro));
94     macro->name = util_strdup(name);
95     return macro;
96 }
97
98 void ppmacro_delete(ppmacro *self)
99 {
100     vec_free(self->params);
101     vec_free(self->output);
102     mem_d(self->name);
103     mem_d(self);
104 }
105
106 ftepp_t* ftepp_init()
107 {
108     ftepp_t *ftepp;
109
110     ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
111     memset(ftepp, 0, sizeof(*ftepp));
112
113     return ftepp;
114 }
115
116 void ftepp_delete(ftepp_t *self)
117 {
118     vec_free(self->macros);
119     vec_free(self->conditions);
120     mem_d(self);
121 }
122
123 ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
124 {
125     size_t i;
126     for (i = 0; i < vec_size(ftepp->macros); ++i) {
127         if (!strcmp(name, ftepp->macros[i]->name))
128             return ftepp->macros[i];
129     }
130     return NULL;
131 }
132
133 static inline int ftepp_next(ftepp_t *ftepp)
134 {
135     return (ftepp->token = lex_do(ftepp->lex));
136 }
137
138 /* Important: this does not skip newlines! */
139 static bool ftepp_skipspace(ftepp_t *ftepp)
140 {
141     if (ftepp->token != TOKEN_WHITE)
142         return true;
143     while (ftepp_next(ftepp) == TOKEN_WHITE) {}
144     if (ftepp->token >= TOKEN_EOF) {
145         ftepp_error(ftepp, "unexpected end of preprocessor directive");
146         return false;
147     }
148     return true;
149 }
150
151 /**
152  * The huge macro parsing code...
153  */
154 static bool ftepp_define(ftepp_t *ftepp)
155 {
156     ppmacro *macro;
157     (void)ftepp_next(ftepp);
158     if (!ftepp_skipspace(ftepp))
159         return false;
160
161     switch (ftepp->token) {
162         case TOKEN_IDENT:
163         case TOKEN_TYPENAME:
164         case TOKEN_KEYWORD:
165             macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
166             break;
167         default:
168             ftepp_error(ftepp, "expected macro name");
169             return false;
170     }
171
172     (void)ftepp_next(ftepp);
173     if (!ftepp_skipspace(ftepp))
174         return false;
175     if (ftepp->token != TOKEN_EOL) {
176         ftepp_error(ftepp, "stray tokens after macro");
177         return false;
178     }
179     vec_push(ftepp->macros, macro);
180     return true;
181 }
182
183 /**
184  * #if - the FTEQCC way:
185  *    defined(FOO) => true if FOO was #defined regardless of parameters or contents
186  *    <numbers>    => True if the number is not 0
187  *    !<factor>    => True if the factor yields false
188  *    <macro>      => becomes the macro's FIRST token regardless of parameters
189  *    <e> && <e>   => True if both expressions are true
190  *    <e> || <e>   => True if either expression is true
191  *    <string>     => False
192  *    <ident>      => False (remember for macros the <macro> rule applies instead)
193  * Unary + and - are skipped
194  * parenthesis in expressions are allowed
195  * parameter lists on macros are errors
196  * No mathematical calculations are executed
197  */
198 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out)
199 {
200     ppmacro *macro;
201
202     if (!ftepp_skipspace(ftepp))
203         return false;
204
205     switch (ftepp->token) {
206         case TOKEN_IDENT:
207         case TOKEN_TYPENAME:
208         case TOKEN_KEYWORD:
209             if (!strcmp(ftepp_tokval(ftepp), "defined")) {
210                 ftepp->lex->flags.noops = true;
211                 ftepp_next(ftepp);
212                 if (!ftepp_skipspace(ftepp))
213                     return false;
214                 if (ftepp->token != '(') {
215                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
216                     return false;
217                 }
218                 ftepp->lex->flags.noops = false;
219                 ftepp_next(ftepp);
220                 if (!ftepp_skipspace(ftepp))
221                     return false;
222                 if (ftepp->token != TOKEN_IDENT &&
223                     ftepp->token != TOKEN_TYPENAME &&
224                     ftepp->token != TOKEN_KEYWORD)
225                 {
226                     ftepp_error(ftepp, "defined() used on an unexpected token type");
227                     return false;
228                 }
229                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
230                 *out = !!macro;
231                 ftepp_next(ftepp);
232                 if (!ftepp_skipspace(ftepp))
233                     return false;
234                 if (ftepp->token != ')') {
235                     ftepp_error(ftepp, "expected closing paren");
236                     return false;
237                 }
238                 break;
239             }
240
241             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
242             if (!macro || !vec_size(macro->output)) {
243                 *out = false;
244             } else {
245                 /* This does not expand recursively! */
246                 switch (macro->output[0]->token) {
247                     case TOKEN_INTCONST:
248                         *out = !!(macro->output[0]->constval.f);
249                         break;
250                     case TOKEN_FLOATCONST:
251                         *out = !!(macro->output[0]->constval.f);
252                         break;
253                     default:
254                         *out = false;
255                         break;
256                 }
257             }
258             break;
259         case TOKEN_STRINGCONST:
260             *out = false;
261             break;
262         case TOKEN_INTCONST:
263             *out = !!(ftepp->lex->tok.constval.i);
264             break;
265         case TOKEN_FLOATCONST:
266             *out = !!(ftepp->lex->tok.constval.f);
267             break;
268
269         case '(':
270             ftepp_next(ftepp);
271             if (!ftepp_if_expr(ftepp, out))
272                 return false;
273             if (ftepp->token != ')') {
274                 ftepp_error(ftepp, "expected closing paren in #if expression");
275                 return false;
276             }
277             break;
278
279         default:
280             ftepp_error(ftepp, "junk in #if");
281             return false;
282     }
283
284     ftepp_next(ftepp);
285     if (!ftepp_skipspace(ftepp))
286         return false;
287
288     if (ftepp->token == ')')
289         return true;
290
291     if (ftepp->token != TOKEN_OPERATOR)
292         return true;
293
294     if (!strcmp(ftepp_tokval(ftepp), "&&") ||
295         !strcmp(ftepp_tokval(ftepp), "||"))
296     {
297         bool next = false;
298         char opc  = ftepp_tokval(ftepp)[0];
299
300         ftepp_next(ftepp);
301         if (!ftepp_if_expr(ftepp, &next))
302             return false;
303
304         if (opc == '&')
305             *out = *out && next;
306         else
307             *out = *out || next;
308         return true;
309     }
310     else {
311         ftepp_error(ftepp, "junk after #if");
312         return false;
313     }
314 }
315
316 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
317 {
318     bool result = false;
319
320     ftepp->lex->flags.noops = false;
321
322     memset(cond, 0, sizeof(*cond));
323     (void)ftepp_next(ftepp);
324
325     if (!ftepp_skipspace(ftepp))
326         return false;
327     if (ftepp->token == TOKEN_EOL) {
328         ftepp_error(ftepp, "expected expression for #if-directive");
329         return false;
330     }
331
332     if (!ftepp_if_expr(ftepp, &result))
333         return false;
334     ftepp->lex->flags.noops = true;
335
336     cond->on = result;
337     return true;
338 }
339
340 /**
341  * ifdef is rather simple
342  */
343 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
344 {
345     ppmacro *macro;
346     memset(cond, 0, sizeof(*cond));
347     (void)ftepp_next(ftepp);
348     if (!ftepp_skipspace(ftepp))
349         return false;
350
351     switch (ftepp->token) {
352         case TOKEN_IDENT:
353         case TOKEN_TYPENAME:
354         case TOKEN_KEYWORD:
355             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
356             break;
357         default:
358             ftepp_error(ftepp, "expected macro name");
359             return false;
360     }
361
362     (void)ftepp_next(ftepp);
363     if (!ftepp_skipspace(ftepp))
364         return false;
365     if (ftepp->token != TOKEN_EOL) {
366         ftepp_error(ftepp, "stray tokens after #ifdef");
367         return false;
368     }
369     cond->on = !!macro;
370     return true;
371 }
372
373 /* Basic structure handlers */
374 static bool ftepp_else_allowed(ftepp_t *ftepp)
375 {
376     if (!vec_size(ftepp->conditions)) {
377         ftepp_error(ftepp, "#else without #if");
378         return false;
379     }
380     if (vec_last(ftepp->conditions).had_else) {
381         ftepp_error(ftepp, "multiple #else for a single #if");
382         return false;
383     }
384     return true;
385 }
386
387 static bool ftepp_hash(ftepp_t *ftepp)
388 {
389     ppcondition cond;
390     ppcondition *pc;
391
392     lex_ctx ctx = ftepp_ctx(ftepp);
393
394     if (!ftepp_skipspace(ftepp))
395         return false;
396
397     switch (ftepp->token) {
398         case TOKEN_KEYWORD:
399         case TOKEN_IDENT:
400         case TOKEN_TYPENAME:
401             if (!strcmp(ftepp_tokval(ftepp), "define")) {
402                 return ftepp_define(ftepp);
403             }
404             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
405                 if (!ftepp_ifdef(ftepp, &cond))
406                     return false;
407                 cond.was_on = cond.on;
408                 vec_push(ftepp->conditions, cond);
409                 break;
410             }
411             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
412                 if (!ftepp_ifdef(ftepp, &cond))
413                     return false;
414                 cond.on = !cond.on;
415                 cond.was_on = cond.on;
416                 vec_push(ftepp->conditions, cond);
417                 break;
418             }
419             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
420                 if (!ftepp_else_allowed(ftepp))
421                     return false;
422                 if (!ftepp_ifdef(ftepp, &cond))
423                     return false;
424                 pc = &vec_last(ftepp->conditions);
425                 pc->on     = !pc->was_on && cond.on;
426                 pc->was_on = pc->was_on || pc->on;
427                 break;
428             }
429             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
430                 if (!ftepp_else_allowed(ftepp))
431                     return false;
432                 if (!ftepp_ifdef(ftepp, &cond))
433                     return false;
434                 cond.on = !cond.on;
435                 pc = &vec_last(ftepp->conditions);
436                 pc->on     = !pc->was_on && cond.on;
437                 pc->was_on = pc->was_on || pc->on;
438                 break;
439             }
440             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
441                 if (!ftepp_else_allowed(ftepp))
442                     return false;
443                 if (!ftepp_if(ftepp, &cond))
444                     return false;
445                 pc = &vec_last(ftepp->conditions);
446                 pc->on     = !pc->was_on && cond.on;
447                 pc->was_on = pc->was_on  || pc->on;
448                 break;
449             }
450             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
451                 if (!ftepp_if(ftepp, &cond))
452                     return false;
453                 cond.was_on = cond.on;
454                 vec_push(ftepp->conditions, cond);
455                 break;
456             }
457             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
458                 if (!ftepp_else_allowed(ftepp))
459                     return false;
460                 pc = &vec_last(ftepp->conditions);
461                 pc->on = !pc->was_on;
462                 pc->had_else = true;
463                 ftepp_next(ftepp);
464                 break;
465             }
466             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
467                 if (!vec_size(ftepp->conditions)) {
468                     ftepp_error(ftepp, "#endif without #if");
469                     return false;
470                 }
471                 vec_pop(ftepp->conditions);
472                 ftepp_next(ftepp);
473                 break;
474             }
475             else {
476                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
477                 return false;
478             }
479             break;
480         default:
481             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
482             return false;
483         case TOKEN_EOL:
484             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
485             return false;
486         case TOKEN_EOF:
487             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
488             return false;
489     }
490     if (!ftepp_skipspace(ftepp))
491         return false;
492     return true;
493 }
494
495 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
496 {
497     if (ignore_cond ||
498         !vec_size(ftepp->conditions) ||
499         vec_last(ftepp->conditions).on)
500     {
501         printf("%s", str);
502     }
503 }
504
505 static bool ftepp_preprocess(ftepp_t *ftepp)
506 {
507     bool newline = true;
508
509     ftepp->lex->flags.preprocessing = true;
510
511     ftepp_next(ftepp);
512     do
513     {
514         if (ftepp->token >= TOKEN_EOF)
515             break;
516
517         ftepp->newline = newline;
518         newline = false;
519
520         switch (ftepp->token) {
521             case '#':
522                 if (!ftepp->newline) {
523                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
524                     ftepp_next(ftepp);
525                     break;
526                 }
527                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
528                     ftepp_error(ftepp, "error in preprocessor directive");
529                     ftepp->token = TOKEN_ERROR;
530                     break;
531                 }
532                 if (!ftepp_hash(ftepp))
533                     ftepp->token = TOKEN_ERROR;
534                 break;
535             case TOKEN_EOL:
536                 newline = true;
537                 ftepp_out(ftepp, "\n", true);
538                 ftepp_next(ftepp);
539                 break;
540             default:
541                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
542                 ftepp_next(ftepp);
543                 break;
544         }
545     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
546
547     ftepp_delete(ftepp);
548     return (ftepp->token == TOKEN_EOF);
549 }
550
551 bool ftepp_preprocess_file(const char *filename)
552 {
553     ftepp_t *ftepp = ftepp_init();
554     ftepp->lex = lex_open(filename);
555     if (!ftepp->lex) {
556         con_out("failed to open file \"%s\"\n", filename);
557         return false;
558     }
559     return ftepp_preprocess(ftepp);
560 }
561
562 bool ftepp_preprocess_string(const char *name, const char *str)
563 {
564     ftepp_t *ftepp = ftepp_init();
565     ftepp->lex = lex_open_string(str, strlen(str), name);
566     if (!ftepp->lex) {
567         con_out("failed to create lexer for string \"%s\"\n", name);
568         return false;
569     }
570     return ftepp_preprocess(ftepp);
571 }