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