]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ftepp.c
handling the noops flag better now
[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_next(ftepp);
211                 if (!ftepp_skipspace(ftepp))
212                     return false;
213                 if (ftepp->token != '(') {
214                     ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
215                     return false;
216                 }
217                 ftepp_next(ftepp);
218                 if (!ftepp_skipspace(ftepp))
219                     return false;
220                 if (ftepp->token != TOKEN_IDENT &&
221                     ftepp->token != TOKEN_TYPENAME &&
222                     ftepp->token != TOKEN_KEYWORD)
223                 {
224                     ftepp_error(ftepp, "defined() used on an unexpected token type");
225                     return false;
226                 }
227                 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
228                 *out = !!macro;
229                 ftepp_next(ftepp);
230                 if (!ftepp_skipspace(ftepp))
231                     return false;
232                 if (ftepp->token != ')') {
233                     ftepp_error(ftepp, "expected closing paren");
234                     return false;
235                 }
236                 break;
237             }
238
239             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
240             if (!macro || !vec_size(macro->output)) {
241                 *out = false;
242             } else {
243                 /* This does not expand recursively! */
244                 switch (macro->output[0]->token) {
245                     case TOKEN_INTCONST:
246                         *out = !!(macro->output[0]->constval.f);
247                         break;
248                     case TOKEN_FLOATCONST:
249                         *out = !!(macro->output[0]->constval.f);
250                         break;
251                     default:
252                         *out = false;
253                         break;
254                 }
255             }
256             break;
257         case TOKEN_STRINGCONST:
258             *out = false;
259             break;
260         case TOKEN_INTCONST:
261             *out = !!(ftepp->lex->tok.constval.i);
262             break;
263         case TOKEN_FLOATCONST:
264             *out = !!(ftepp->lex->tok.constval.f);
265             break;
266
267         case '(':
268             ftepp_next(ftepp);
269             if (!ftepp_if_expr(ftepp, out))
270                 return false;
271             if (ftepp->token != ')') {
272                 ftepp_error(ftepp, "expected closing paren in #if expression");
273                 return false;
274             }
275             break;
276
277         default:
278             ftepp_error(ftepp, "junk in #if");
279             return false;
280     }
281
282     ftepp->lex->flags.noops = false;
283     ftepp_next(ftepp);
284     if (!ftepp_skipspace(ftepp))
285         return false;
286     ftepp->lex->flags.noops = true;
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     memset(cond, 0, sizeof(*cond));
321     (void)ftepp_next(ftepp);
322
323     if (!ftepp_skipspace(ftepp))
324         return false;
325     if (ftepp->token == TOKEN_EOL) {
326         ftepp_error(ftepp, "expected expression for #if-directive");
327         return false;
328     }
329
330     if (!ftepp_if_expr(ftepp, &result))
331         return false;
332
333     cond->on = result;
334     return true;
335 }
336
337 /**
338  * ifdef is rather simple
339  */
340 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
341 {
342     ppmacro *macro;
343     memset(cond, 0, sizeof(*cond));
344     (void)ftepp_next(ftepp);
345     if (!ftepp_skipspace(ftepp))
346         return false;
347
348     switch (ftepp->token) {
349         case TOKEN_IDENT:
350         case TOKEN_TYPENAME:
351         case TOKEN_KEYWORD:
352             macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
353             break;
354         default:
355             ftepp_error(ftepp, "expected macro name");
356             return false;
357     }
358
359     (void)ftepp_next(ftepp);
360     if (!ftepp_skipspace(ftepp))
361         return false;
362     if (ftepp->token != TOKEN_EOL) {
363         ftepp_error(ftepp, "stray tokens after #ifdef");
364         return false;
365     }
366     cond->on = !!macro;
367     return true;
368 }
369
370 /* Basic structure handlers */
371 static bool ftepp_else_allowed(ftepp_t *ftepp)
372 {
373     if (!vec_size(ftepp->conditions)) {
374         ftepp_error(ftepp, "#else without #if");
375         return false;
376     }
377     if (vec_last(ftepp->conditions).had_else) {
378         ftepp_error(ftepp, "multiple #else for a single #if");
379         return false;
380     }
381     return true;
382 }
383
384 static bool ftepp_hash(ftepp_t *ftepp)
385 {
386     ppcondition cond;
387     ppcondition *pc;
388
389     lex_ctx ctx = ftepp_ctx(ftepp);
390
391     if (!ftepp_skipspace(ftepp))
392         return false;
393
394     switch (ftepp->token) {
395         case TOKEN_KEYWORD:
396         case TOKEN_IDENT:
397         case TOKEN_TYPENAME:
398             if (!strcmp(ftepp_tokval(ftepp), "define")) {
399                 return ftepp_define(ftepp);
400             }
401             else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
402                 if (!ftepp_ifdef(ftepp, &cond))
403                     return false;
404                 cond.was_on = cond.on;
405                 vec_push(ftepp->conditions, cond);
406                 break;
407             }
408             else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
409                 if (!ftepp_ifdef(ftepp, &cond))
410                     return false;
411                 cond.on = !cond.on;
412                 cond.was_on = cond.on;
413                 vec_push(ftepp->conditions, cond);
414                 break;
415             }
416             else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
417                 if (!ftepp_else_allowed(ftepp))
418                     return false;
419                 if (!ftepp_ifdef(ftepp, &cond))
420                     return false;
421                 pc = &vec_last(ftepp->conditions);
422                 pc->on     = !pc->was_on && cond.on;
423                 pc->was_on = pc->was_on || pc->on;
424                 break;
425             }
426             else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
427                 if (!ftepp_else_allowed(ftepp))
428                     return false;
429                 if (!ftepp_ifdef(ftepp, &cond))
430                     return false;
431                 cond.on = !cond.on;
432                 pc = &vec_last(ftepp->conditions);
433                 pc->on     = !pc->was_on && cond.on;
434                 pc->was_on = pc->was_on || pc->on;
435                 break;
436             }
437             else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
438                 if (!ftepp_else_allowed(ftepp))
439                     return false;
440                 if (!ftepp_if(ftepp, &cond))
441                     return false;
442                 pc = &vec_last(ftepp->conditions);
443                 pc->on     = !pc->was_on && cond.on;
444                 pc->was_on = pc->was_on  || pc->on;
445                 break;
446             }
447             else if (!strcmp(ftepp_tokval(ftepp), "if")) {
448                 if (!ftepp_if(ftepp, &cond))
449                     return false;
450                 cond.was_on = cond.on;
451                 vec_push(ftepp->conditions, cond);
452                 break;
453             }
454             else if (!strcmp(ftepp_tokval(ftepp), "else")) {
455                 if (!ftepp_else_allowed(ftepp))
456                     return false;
457                 pc = &vec_last(ftepp->conditions);
458                 pc->on = !pc->was_on;
459                 pc->had_else = true;
460                 ftepp_next(ftepp);
461                 break;
462             }
463             else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
464                 if (!vec_size(ftepp->conditions)) {
465                     ftepp_error(ftepp, "#endif without #if");
466                     return false;
467                 }
468                 vec_pop(ftepp->conditions);
469                 ftepp_next(ftepp);
470                 break;
471             }
472             else {
473                 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
474                 return false;
475             }
476             break;
477         default:
478             ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
479             return false;
480         case TOKEN_EOL:
481             ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
482             return false;
483         case TOKEN_EOF:
484             ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
485             return false;
486     }
487     if (!ftepp_skipspace(ftepp))
488         return false;
489     return true;
490 }
491
492 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
493 {
494     if (ignore_cond ||
495         !vec_size(ftepp->conditions) ||
496         vec_last(ftepp->conditions).on)
497     {
498         printf("%s", str);
499     }
500 }
501
502 static bool ftepp_preprocess(ftepp_t *ftepp)
503 {
504     bool newline = true;
505
506     ftepp->lex->flags.preprocessing = true;
507     ftepp->lex->flags.noops = true;
508
509     ftepp_next(ftepp);
510     do
511     {
512         if (ftepp->token >= TOKEN_EOF)
513             break;
514
515         ftepp->newline = newline;
516         newline = false;
517
518         switch (ftepp->token) {
519             case '#':
520                 if (!ftepp->newline) {
521                     ftepp_out(ftepp, ftepp_tokval(ftepp), false);
522                     ftepp_next(ftepp);
523                     break;
524                 }
525                 if (ftepp_next(ftepp) >= TOKEN_EOF) {
526                     ftepp_error(ftepp, "error in preprocessor directive");
527                     ftepp->token = TOKEN_ERROR;
528                     break;
529                 }
530                 if (!ftepp_hash(ftepp))
531                     ftepp->token = TOKEN_ERROR;
532                 break;
533             case TOKEN_EOL:
534                 newline = true;
535                 ftepp_out(ftepp, "\n", true);
536                 ftepp_next(ftepp);
537                 break;
538             default:
539                 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
540                 ftepp_next(ftepp);
541                 break;
542         }
543     } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
544
545     ftepp_delete(ftepp);
546     return (ftepp->token == TOKEN_EOF);
547 }
548
549 bool ftepp_preprocess_file(const char *filename)
550 {
551     ftepp_t *ftepp = ftepp_init();
552     ftepp->lex = lex_open(filename);
553     if (!ftepp->lex) {
554         con_out("failed to open file \"%s\"\n", filename);
555         return false;
556     }
557     return ftepp_preprocess(ftepp);
558 }
559
560 bool ftepp_preprocess_string(const char *name, const char *str)
561 {
562     ftepp_t *ftepp = ftepp_init();
563     ftepp->lex = lex_open_string(str, strlen(str), name);
564     if (!ftepp->lex) {
565         con_out("failed to create lexer for string \"%s\"\n", name);
566         return false;
567     }
568     return ftepp_preprocess(ftepp);
569 }