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