1deb7bf6a78b8e1e71cd686f360909b13ea534ca
[cparser] / ast.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include "ast_t.h"
23 #include "symbol_t.h"
24 #include "type_t.h"
25 #include "parser.h"
26 #include "lang_features.h"
27 #include "entity_t.h"
28
29 #include <assert.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33
34 #if defined(__INTEL_COMPILER)
35 #include <mathimf.h>
36 #elif defined(__CYGWIN__)
37 #include "win32/cygwin_math_ext.h"
38 #else
39 #include <math.h>
40 #endif
41
42 #include "adt/error.h"
43 #include "adt/util.h"
44
45 struct obstack ast_obstack;
46
47 static FILE *out;
48 static int   indent;
49
50 /** If set, implicit casts are printed. */
51 bool print_implicit_casts = false;
52
53 /** If set parenthesis are printed to indicate operator precedence. */
54 bool print_parenthesis = false;
55
56 static void print_statement(const statement_t *statement);
57 static void print_expression_prec(const expression_t *expression, unsigned prec);
58
59 void change_indent(int delta)
60 {
61         indent += delta;
62         assert(indent >= 0);
63 }
64
65 void print_indent(void)
66 {
67         for (int i = 0; i < indent; ++i)
68                 fputc('\t', out);
69 }
70
71 /**
72  * Returns 1 if a given precedence level has right-to-left
73  * associativity, else 0.
74  *
75  * @param precedence   the operator precedence
76  */
77 static int right_to_left(unsigned precedence)
78 {
79         switch (precedence) {
80                 case PREC_ASSIGNMENT:
81                 case PREC_CONDITIONAL:
82                 case PREC_UNARY:
83                         return 1;
84
85                 default:
86                         return 0;
87         }
88 }
89
90 /**
91  * Return the precedence of an expression given by its kind.
92  *
93  * @param kind   the expression kind
94  */
95 static unsigned get_expression_precedence(expression_kind_t kind)
96 {
97         static const unsigned prec[] = {
98                 [EXPR_UNKNOWN]                    = PREC_PRIMARY,
99                 [EXPR_INVALID]                    = PREC_PRIMARY,
100                 [EXPR_REFERENCE]                  = PREC_PRIMARY,
101                 [EXPR_REFERENCE_ENUM_VALUE]       = PREC_PRIMARY,
102                 [EXPR_CHARACTER_CONSTANT]         = PREC_PRIMARY,
103                 [EXPR_WIDE_CHARACTER_CONSTANT]    = PREC_PRIMARY,
104                 [EXPR_CONST]                      = PREC_PRIMARY,
105                 [EXPR_STRING_LITERAL]             = PREC_PRIMARY,
106                 [EXPR_WIDE_STRING_LITERAL]        = PREC_PRIMARY,
107                 [EXPR_COMPOUND_LITERAL]           = PREC_UNARY,
108                 [EXPR_CALL]                       = PREC_POSTFIX,
109                 [EXPR_CONDITIONAL]                = PREC_CONDITIONAL,
110                 [EXPR_SELECT]                     = PREC_POSTFIX,
111                 [EXPR_ARRAY_ACCESS]               = PREC_POSTFIX,
112                 [EXPR_SIZEOF]                     = PREC_UNARY,
113                 [EXPR_CLASSIFY_TYPE]              = PREC_UNARY,
114                 [EXPR_ALIGNOF]                    = PREC_UNARY,
115
116                 [EXPR_FUNCNAME]                   = PREC_PRIMARY,
117                 [EXPR_BUILTIN_SYMBOL]             = PREC_PRIMARY,
118                 [EXPR_BUILTIN_CONSTANT_P]         = PREC_PRIMARY,
119                 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = PREC_PRIMARY,
120                 [EXPR_OFFSETOF]                   = PREC_PRIMARY,
121                 [EXPR_VA_START]                   = PREC_PRIMARY,
122                 [EXPR_VA_ARG]                     = PREC_PRIMARY,
123                 [EXPR_STATEMENT]                  = PREC_PRIMARY,
124                 [EXPR_LABEL_ADDRESS]              = PREC_PRIMARY,
125
126                 [EXPR_UNARY_NEGATE]               = PREC_UNARY,
127                 [EXPR_UNARY_PLUS]                 = PREC_UNARY,
128                 [EXPR_UNARY_BITWISE_NEGATE]       = PREC_UNARY,
129                 [EXPR_UNARY_NOT]                  = PREC_UNARY,
130                 [EXPR_UNARY_DEREFERENCE]          = PREC_UNARY,
131                 [EXPR_UNARY_TAKE_ADDRESS]         = PREC_UNARY,
132                 [EXPR_UNARY_POSTFIX_INCREMENT]    = PREC_POSTFIX,
133                 [EXPR_UNARY_POSTFIX_DECREMENT]    = PREC_POSTFIX,
134                 [EXPR_UNARY_PREFIX_INCREMENT]     = PREC_UNARY,
135                 [EXPR_UNARY_PREFIX_DECREMENT]     = PREC_UNARY,
136                 [EXPR_UNARY_CAST]                 = PREC_UNARY,
137                 [EXPR_UNARY_CAST_IMPLICIT]        = PREC_UNARY,
138                 [EXPR_UNARY_ASSUME]               = PREC_PRIMARY,
139                 [EXPR_UNARY_DELETE]               = PREC_UNARY,
140                 [EXPR_UNARY_DELETE_ARRAY]         = PREC_UNARY,
141                 [EXPR_UNARY_THROW]                = PREC_ASSIGNMENT,
142
143                 [EXPR_BINARY_ADD]                 = PREC_ADDITIVE,
144                 [EXPR_BINARY_SUB]                 = PREC_ADDITIVE,
145                 [EXPR_BINARY_MUL]                 = PREC_MULTIPLICATIVE,
146                 [EXPR_BINARY_DIV]                 = PREC_MULTIPLICATIVE,
147                 [EXPR_BINARY_MOD]                 = PREC_MULTIPLICATIVE,
148                 [EXPR_BINARY_EQUAL]               = PREC_EQUALITY,
149                 [EXPR_BINARY_NOTEQUAL]            = PREC_EQUALITY,
150                 [EXPR_BINARY_LESS]                = PREC_RELATIONAL,
151                 [EXPR_BINARY_LESSEQUAL]           = PREC_RELATIONAL,
152                 [EXPR_BINARY_GREATER]             = PREC_RELATIONAL,
153                 [EXPR_BINARY_GREATEREQUAL]        = PREC_RELATIONAL,
154                 [EXPR_BINARY_BITWISE_AND]         = PREC_AND,
155                 [EXPR_BINARY_BITWISE_OR]          = PREC_OR,
156                 [EXPR_BINARY_BITWISE_XOR]         = PREC_XOR,
157                 [EXPR_BINARY_LOGICAL_AND]         = PREC_LOGICAL_AND,
158                 [EXPR_BINARY_LOGICAL_OR]          = PREC_LOGICAL_OR,
159                 [EXPR_BINARY_SHIFTLEFT]           = PREC_SHIFT,
160                 [EXPR_BINARY_SHIFTRIGHT]          = PREC_SHIFT,
161                 [EXPR_BINARY_ASSIGN]              = PREC_ASSIGNMENT,
162                 [EXPR_BINARY_MUL_ASSIGN]          = PREC_ASSIGNMENT,
163                 [EXPR_BINARY_DIV_ASSIGN]          = PREC_ASSIGNMENT,
164                 [EXPR_BINARY_MOD_ASSIGN]          = PREC_ASSIGNMENT,
165                 [EXPR_BINARY_ADD_ASSIGN]          = PREC_ASSIGNMENT,
166                 [EXPR_BINARY_SUB_ASSIGN]          = PREC_ASSIGNMENT,
167                 [EXPR_BINARY_SHIFTLEFT_ASSIGN]    = PREC_ASSIGNMENT,
168                 [EXPR_BINARY_SHIFTRIGHT_ASSIGN]   = PREC_ASSIGNMENT,
169                 [EXPR_BINARY_BITWISE_AND_ASSIGN]  = PREC_ASSIGNMENT,
170                 [EXPR_BINARY_BITWISE_XOR_ASSIGN]  = PREC_ASSIGNMENT,
171                 [EXPR_BINARY_BITWISE_OR_ASSIGN]   = PREC_ASSIGNMENT,
172                 [EXPR_BINARY_COMMA]               = PREC_EXPRESSION,
173
174                 [EXPR_BINARY_ISGREATER]           = PREC_PRIMARY,
175                 [EXPR_BINARY_ISGREATEREQUAL]      = PREC_PRIMARY,
176                 [EXPR_BINARY_ISLESS]              = PREC_PRIMARY,
177                 [EXPR_BINARY_ISLESSEQUAL]         = PREC_PRIMARY,
178                 [EXPR_BINARY_ISLESSGREATER]       = PREC_PRIMARY,
179                 [EXPR_BINARY_ISUNORDERED]         = PREC_PRIMARY
180         };
181         assert((size_t)kind < lengthof(prec));
182         unsigned res = prec[kind];
183
184         assert(res != PREC_BOTTOM);
185         return res;
186 }
187
188 /**
189  * Print a constant expression.
190  *
191  * @param cnst  the constant expression
192  */
193 static void print_const(const const_expression_t *cnst)
194 {
195         if (cnst->base.type == NULL)
196                 return;
197
198         const type_t *const type = skip_typeref(cnst->base.type);
199
200         if (is_type_atomic(type, ATOMIC_TYPE_BOOL)) {
201                 fputs(cnst->v.int_value ? "true" : "false", out);
202         } else if (is_type_integer(type)) {
203                 fprintf(out, "%lld", cnst->v.int_value);
204         } else if (is_type_float(type)) {
205                 long double const val = cnst->v.float_value;
206 #ifdef _WIN32
207                 /* ARG, no way to print long double */
208                 fprintf(out, "%.20g", (double)val);
209 #else
210                 fprintf(out, "%.20Lg", val);
211 #endif
212                 if (isfinite(val) && truncl(val) == val)
213                         fputs(".0", out);
214         } else {
215                 panic("unknown constant");
216         }
217
218         char const* suffix;
219         switch (type->atomic.akind) {
220                 case ATOMIC_TYPE_UINT:        suffix = "U";   break;
221                 case ATOMIC_TYPE_LONG:        suffix = "L";   break;
222                 case ATOMIC_TYPE_ULONG:       suffix = "UL";  break;
223                 case ATOMIC_TYPE_LONGLONG:    suffix = "LL";  break;
224                 case ATOMIC_TYPE_ULONGLONG:   suffix = "ULL"; break;
225                 case ATOMIC_TYPE_FLOAT:       suffix = "F";   break;
226                 case ATOMIC_TYPE_LONG_DOUBLE: suffix = "L";   break;
227
228                 default: return;
229         }
230         fputs(suffix, out);
231 }
232
233 /**
234  * Print a quoted string constant.
235  *
236  * @param string  the string constant
237  * @param border  the border char
238  * @param skip    number of chars to skip at the end
239  */
240 static void print_quoted_string(const string_t *const string, char border, int skip)
241 {
242         fputc(border, out);
243         const char *end = string->begin + string->size - skip;
244         for (const char *c = string->begin; c != end; ++c) {
245                 unsigned char const tc = *c;
246                 if (tc == border) {
247                         fputc('\\', out);
248                 }
249                 switch (tc) {
250                 case '\\':  fputs("\\\\", out); break;
251                 case '\a':  fputs("\\a", out); break;
252                 case '\b':  fputs("\\b", out); break;
253                 case '\f':  fputs("\\f", out); break;
254                 case '\n':  fputs("\\n", out); break;
255                 case '\r':  fputs("\\r", out); break;
256                 case '\t':  fputs("\\t", out); break;
257                 case '\v':  fputs("\\v", out); break;
258                 case '\?':  fputs("\\?", out); break;
259                 case 27:
260                         if (c_mode & _GNUC) {
261                                 fputs("\\e", out); break;
262                         }
263                         /* FALLTHROUGH */
264                 default:
265                         if (tc < 0x80 && !isprint(tc)) {
266                                 fprintf(out, "\\%03o", (unsigned)tc);
267                         } else {
268                                 fputc(tc, out);
269                         }
270                         break;
271                 }
272         }
273         fputc(border, out);
274 }
275
276 /**
277  * Prints a wide string literal expression.
278  *
279  * @param wstr    the wide string literal expression
280  * @param border  the border char
281  * @param skip    number of chars to skip at the end
282  */
283 static void print_quoted_wide_string(const wide_string_t *const wstr,
284                                      char border, int skip)
285 {
286         fputc('L', out);
287         fputc(border, out);
288         const wchar_rep_t *end = wstr->begin + wstr->size - skip;
289         for (const wchar_rep_t *c = wstr->begin; c != end; ++c) {
290                 switch (*c) {
291                         case L'\"':  fputs("\\\"", out); break;
292                         case L'\\':  fputs("\\\\", out); break;
293                         case L'\a':  fputs("\\a",  out); break;
294                         case L'\b':  fputs("\\b",  out); break;
295                         case L'\f':  fputs("\\f",  out); break;
296                         case L'\n':  fputs("\\n",  out); break;
297                         case L'\r':  fputs("\\r",  out); break;
298                         case L'\t':  fputs("\\t",  out); break;
299                         case L'\v':  fputs("\\v",  out); break;
300                         case L'\?':  fputs("\\?",  out); break;
301                         case 27:
302                                 if (c_mode & _GNUC) {
303                                         fputs("\\e", out); break;
304                                 }
305                                 /* FALLTHROUGH */
306                         default: {
307                                 const unsigned tc = *c;
308                                 if (tc < 0x80U) {
309                                         if (isprint(*c)) {
310                                                 fputc(*c, out);
311                                         } else {
312                                                 fprintf(out, "\\%03o", tc);
313                                         }
314                                 } else if (tc < 0x800) {
315                                         fputc(0xC0 | (tc >> 6),   out);
316                                         fputc(0x80 | (tc & 0x3F), out);
317                                 } else if (tc < 0x10000) {
318                                         fputc(0xE0 | ( tc >> 12),         out);
319                                         fputc(0x80 | ((tc >>  6) & 0x3F), out);
320                                         fputc(0x80 | ( tc        & 0x3F), out);
321                                 } else {
322                                         fputc(0xF0 | ( tc >> 18),         out);
323                                         fputc(0x80 | ((tc >> 12) & 0x3F), out);
324                                         fputc(0x80 | ((tc >>  6) & 0x3F), out);
325                                         fputc(0x80 | ( tc        & 0x3F), out);
326                                 }
327                         }
328                 }
329         }
330         fputc(border, out);
331 }
332
333 /**
334  * Print a constant character expression.
335  *
336  * @param cnst  the constant character expression
337  */
338 static void print_character_constant(const const_expression_t *cnst)
339 {
340         print_quoted_string(&cnst->v.character, '\'', 0);
341 }
342
343 static void print_wide_character_constant(const const_expression_t *cnst)
344 {
345         print_quoted_wide_string(&cnst->v.wide_character, '\'', 0);
346 }
347
348 /**
349  * Prints a string literal expression.
350  *
351  * @param string_literal  the string literal expression
352  */
353 static void print_string_literal(
354                 const string_literal_expression_t *string_literal)
355 {
356         print_quoted_string(&string_literal->value, '"', 1);
357 }
358
359 /**
360  * Prints a predefined symbol.
361  */
362 static void print_funcname(const funcname_expression_t *funcname)
363 {
364         const char *s = "";
365         switch (funcname->kind) {
366         case FUNCNAME_FUNCTION:        s = (c_mode & _C99) ? "__func__" : "__FUNCTION__"; break;
367         case FUNCNAME_PRETTY_FUNCTION: s = "__PRETTY_FUNCTION__"; break;
368         case FUNCNAME_FUNCSIG:         s = "__FUNCSIG__"; break;
369         case FUNCNAME_FUNCDNAME:       s = "__FUNCDNAME__"; break;
370         }
371         fputs(s, out);
372 }
373
374 static void print_wide_string_literal(
375         const wide_string_literal_expression_t *const wstr)
376 {
377         print_quoted_wide_string(&wstr->value, '"', 1);
378 }
379
380 static void print_compound_literal(
381                 const compound_literal_expression_t *expression)
382 {
383         fputc('(', out);
384         print_type(expression->type);
385         fputc(')', out);
386         print_initializer(expression->initializer);
387 }
388
389 static void print_assignment_expression(const expression_t *const expr)
390 {
391         print_expression_prec(expr, PREC_ASSIGNMENT);
392 }
393
394 /**
395  * Prints a call expression.
396  *
397  * @param call  the call expression
398  */
399 static void print_call_expression(const call_expression_t *call)
400 {
401         unsigned prec = get_expression_precedence(call->base.kind);
402         print_expression_prec(call->function, prec);
403         fputc('(', out);
404         call_argument_t *argument = call->arguments;
405         int              first    = 1;
406         while (argument != NULL) {
407                 if (!first) {
408                         fputs(", ", out);
409                 } else {
410                         first = 0;
411                 }
412                 print_assignment_expression(argument->expression);
413
414                 argument = argument->next;
415         }
416         fputc(')', out);
417 }
418
419 /**
420  * Prints a binary expression.
421  *
422  * @param binexpr   the binary expression
423  */
424 static void print_binary_expression(const binary_expression_t *binexpr)
425 {
426         unsigned prec = get_expression_precedence(binexpr->base.kind);
427         int      r2l  = right_to_left(prec);
428
429         print_expression_prec(binexpr->left, prec + r2l);
430         char const* op;
431         switch (binexpr->base.kind) {
432         case EXPR_BINARY_COMMA:              op = ", ";    break;
433         case EXPR_BINARY_ASSIGN:             op = " = ";   break;
434         case EXPR_BINARY_ADD:                op = " + ";   break;
435         case EXPR_BINARY_SUB:                op = " - ";   break;
436         case EXPR_BINARY_MUL:                op = " * ";   break;
437         case EXPR_BINARY_MOD:                op = " % ";   break;
438         case EXPR_BINARY_DIV:                op = " / ";   break;
439         case EXPR_BINARY_BITWISE_OR:         op = " | ";   break;
440         case EXPR_BINARY_BITWISE_AND:        op = " & ";   break;
441         case EXPR_BINARY_BITWISE_XOR:        op = " ^ ";   break;
442         case EXPR_BINARY_LOGICAL_OR:         op = " || ";  break;
443         case EXPR_BINARY_LOGICAL_AND:        op = " && ";  break;
444         case EXPR_BINARY_NOTEQUAL:           op = " != ";  break;
445         case EXPR_BINARY_EQUAL:              op = " == ";  break;
446         case EXPR_BINARY_LESS:               op = " < ";   break;
447         case EXPR_BINARY_LESSEQUAL:          op = " <= ";  break;
448         case EXPR_BINARY_GREATER:            op = " > ";   break;
449         case EXPR_BINARY_GREATEREQUAL:       op = " >= ";  break;
450         case EXPR_BINARY_SHIFTLEFT:          op = " << ";  break;
451         case EXPR_BINARY_SHIFTRIGHT:         op = " >> ";  break;
452
453         case EXPR_BINARY_ADD_ASSIGN:         op = " += ";  break;
454         case EXPR_BINARY_SUB_ASSIGN:         op = " -= ";  break;
455         case EXPR_BINARY_MUL_ASSIGN:         op = " *= ";  break;
456         case EXPR_BINARY_MOD_ASSIGN:         op = " %= ";  break;
457         case EXPR_BINARY_DIV_ASSIGN:         op = " /= ";  break;
458         case EXPR_BINARY_BITWISE_OR_ASSIGN:  op = " |= ";  break;
459         case EXPR_BINARY_BITWISE_AND_ASSIGN: op = " &= ";  break;
460         case EXPR_BINARY_BITWISE_XOR_ASSIGN: op = " ^= ";  break;
461         case EXPR_BINARY_SHIFTLEFT_ASSIGN:   op = " <<= "; break;
462         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  op = " >>= "; break;
463         default: panic("invalid binexpression found");
464         }
465         fputs(op, out);
466         print_expression_prec(binexpr->right, prec + 1 - r2l);
467 }
468
469 /**
470  * Prints an unary expression.
471  *
472  * @param unexpr   the unary expression
473  */
474 static void print_unary_expression(const unary_expression_t *unexpr)
475 {
476         unsigned prec = get_expression_precedence(unexpr->base.kind);
477         switch (unexpr->base.kind) {
478         case EXPR_UNARY_NEGATE:           fputc('-',          out); break;
479         case EXPR_UNARY_PLUS:             fputc('+',          out); break;
480         case EXPR_UNARY_NOT:              fputc('!',          out); break;
481         case EXPR_UNARY_BITWISE_NEGATE:   fputc('~',          out); break;
482         case EXPR_UNARY_PREFIX_INCREMENT: fputs("++",         out); break;
483         case EXPR_UNARY_PREFIX_DECREMENT: fputs("--",         out); break;
484         case EXPR_UNARY_DEREFERENCE:      fputc('*',          out); break;
485         case EXPR_UNARY_TAKE_ADDRESS:     fputc('&',          out); break;
486         case EXPR_UNARY_DELETE:           fputs("delete ",    out); break;
487         case EXPR_UNARY_DELETE_ARRAY:     fputs("delete [] ", out); break;
488
489         case EXPR_UNARY_POSTFIX_INCREMENT:
490                 print_expression_prec(unexpr->value, prec);
491                 fputs("++", out);
492                 return;
493         case EXPR_UNARY_POSTFIX_DECREMENT:
494                 print_expression_prec(unexpr->value, prec);
495                 fputs("--", out);
496                 return;
497         case EXPR_UNARY_CAST_IMPLICIT:
498         case EXPR_UNARY_CAST:
499                 fputc('(', out);
500                 print_type(unexpr->base.type);
501                 fputc(')', out);
502                 break;
503         case EXPR_UNARY_ASSUME:
504                 fputs("__assume(", out);
505                 print_assignment_expression(unexpr->value);
506                 fputc(')', out);
507                 return;
508
509         case EXPR_UNARY_THROW:
510                 if (unexpr->value == NULL) {
511                         fputs("throw", out);
512                         return;
513                 }
514                 fputs("throw ", out);
515                 break;
516
517         default:
518                 panic("invalid unary expression found");
519         }
520         print_expression_prec(unexpr->value, prec);
521 }
522
523 /**
524  * Prints a reference expression.
525  *
526  * @param ref   the reference expression
527  */
528 static void print_reference_expression(const reference_expression_t *ref)
529 {
530         fputs(ref->entity->base.symbol->string, out);
531 }
532
533 /**
534  * Prints a label address expression.
535  *
536  * @param ref   the reference expression
537  */
538 static void print_label_address_expression(const label_address_expression_t *le)
539 {
540         fprintf(out, "&&%s", le->label->base.symbol->string);
541 }
542
543 /**
544  * Prints an array expression.
545  *
546  * @param expression   the array expression
547  */
548 static void print_array_expression(const array_access_expression_t *expression)
549 {
550         unsigned prec = get_expression_precedence(expression->base.kind);
551         if (!expression->flipped) {
552                 print_expression_prec(expression->array_ref, prec);
553                 fputc('[', out);
554                 print_expression(expression->index);
555                 fputc(']', out);
556         } else {
557                 print_expression_prec(expression->index, prec);
558                 fputc('[', out);
559                 print_expression(expression->array_ref);
560                 fputc(']', out);
561         }
562 }
563
564 /**
565  * Prints a typeproperty expression (sizeof or __alignof__).
566  *
567  * @param expression   the type property expression
568  */
569 static void print_typeprop_expression(const typeprop_expression_t *expression)
570 {
571         if (expression->base.kind == EXPR_SIZEOF) {
572                 fputs("sizeof", out);
573         } else {
574                 assert(expression->base.kind == EXPR_ALIGNOF);
575                 fputs("__alignof__", out);
576         }
577         if (expression->tp_expression != NULL) {
578                 /* PREC_TOP: always print the '()' here, sizeof x is right but unusual */
579                 print_expression_prec(expression->tp_expression, PREC_TOP);
580         } else {
581                 fputc('(', out);
582                 print_type(expression->type);
583                 fputc(')', out);
584         }
585 }
586
587 /**
588  * Prints an builtin symbol.
589  *
590  * @param expression   the builtin symbol expression
591  */
592 static void print_builtin_symbol(const builtin_symbol_expression_t *expression)
593 {
594         fputs(expression->symbol->string, out);
595 }
596
597 /**
598  * Prints a builtin constant expression.
599  *
600  * @param expression   the builtin constant expression
601  */
602 static void print_builtin_constant(const builtin_constant_expression_t *expression)
603 {
604         fputs("__builtin_constant_p(", out);
605         print_assignment_expression(expression->value);
606         fputc(')', out);
607 }
608
609 /**
610  * Prints a builtin types compatible expression.
611  *
612  * @param expression   the builtin types compatible expression
613  */
614 static void print_builtin_types_compatible(
615                 const builtin_types_compatible_expression_t *expression)
616 {
617         fputs("__builtin_types_compatible_p(", out);
618         print_type(expression->left);
619         fputs(", ", out);
620         print_type(expression->right);
621         fputc(')', out);
622 }
623
624 /**
625  * Prints a conditional expression.
626  *
627  * @param expression   the conditional expression
628  */
629 static void print_conditional(const conditional_expression_t *expression)
630 {
631         print_expression_prec(expression->condition, PREC_LOGICAL_OR);
632         fputs(" ? ", out);
633         if (expression->true_expression != NULL) {
634                 print_expression_prec(expression->true_expression, PREC_EXPRESSION);
635                 fputs(" : ", out);
636         } else {
637                 fputs(": ", out);
638         }
639         precedence_t prec = c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL;
640         print_expression_prec(expression->false_expression, prec);
641 }
642
643 /**
644  * Prints a va_start expression.
645  *
646  * @param expression   the va_start expression
647  */
648 static void print_va_start(const va_start_expression_t *const expression)
649 {
650         fputs("__builtin_va_start(", out);
651         print_assignment_expression(expression->ap);
652         fputs(", ", out);
653         fputs(expression->parameter->base.base.symbol->string, out);
654         fputc(')', out);
655 }
656
657 /**
658  * Prints a va_arg expression.
659  *
660  * @param expression   the va_arg expression
661  */
662 static void print_va_arg(const va_arg_expression_t *expression)
663 {
664         fputs("__builtin_va_arg(", out);
665         print_assignment_expression(expression->ap);
666         fputs(", ", out);
667         print_type(expression->base.type);
668         fputc(')', out);
669 }
670
671 /**
672  * Prints a select expression (. or ->).
673  *
674  * @param expression   the select expression
675  */
676 static void print_select(const select_expression_t *expression)
677 {
678         unsigned prec = get_expression_precedence(expression->base.kind);
679         print_expression_prec(expression->compound, prec);
680         if (is_type_pointer(skip_typeref(expression->compound->base.type))) {
681                 fputs("->", out);
682         } else {
683                 fputc('.', out);
684         }
685         fputs(expression->compound_entry->base.symbol->string, out);
686 }
687
688 /**
689  * Prints a type classify expression.
690  *
691  * @param expr   the type classify expression
692  */
693 static void print_classify_type_expression(
694         const classify_type_expression_t *const expr)
695 {
696         fputs("__builtin_classify_type(", out);
697         print_assignment_expression(expr->type_expression);
698         fputc(')', out);
699 }
700
701 /**
702  * Prints a designator.
703  *
704  * @param designator  the designator
705  */
706 static void print_designator(const designator_t *designator)
707 {
708         for ( ; designator != NULL; designator = designator->next) {
709                 if (designator->symbol == NULL) {
710                         fputc('[', out);
711                         print_expression(designator->array_index);
712                         fputc(']', out);
713                 } else {
714                         fputc('.', out);
715                         fputs(designator->symbol->string, out);
716                 }
717         }
718 }
719
720 /**
721  * Prints an offsetof expression.
722  *
723  * @param expression   the offset expression
724  */
725 static void print_offsetof_expression(const offsetof_expression_t *expression)
726 {
727         fputs("__builtin_offsetof", out);
728         fputc('(', out);
729         print_type(expression->type);
730         fputc(',', out);
731         print_designator(expression->designator);
732         fputc(')', out);
733 }
734
735 /**
736  * Prints a statement expression.
737  *
738  * @param expression   the statement expression
739  */
740 static void print_statement_expression(const statement_expression_t *expression)
741 {
742         fputc('(', out);
743         print_statement(expression->statement);
744         fputc(')', out);
745 }
746
747 /**
748  * Prints an expression with parenthesis if needed.
749  *
750  * @param expression  the expression to print
751  * @param top_prec    the precedence of the user of this expression.
752  */
753 static void print_expression_prec(const expression_t *expression, unsigned top_prec)
754 {
755         if (expression->kind == EXPR_UNARY_CAST_IMPLICIT && !print_implicit_casts) {
756                 expression = expression->unary.value;
757         }
758
759         bool parenthesized =
760                 expression->base.parenthesized                 ||
761                 (print_parenthesis && top_prec != PREC_BOTTOM) ||
762                 top_prec > get_expression_precedence(expression->base.kind);
763
764         if (parenthesized)
765                 fputc('(', out);
766         switch (expression->kind) {
767         case EXPR_UNKNOWN:
768         case EXPR_INVALID:
769                 fputs("$invalid expression$", out);
770                 break;
771         case EXPR_CHARACTER_CONSTANT:
772                 print_character_constant(&expression->conste);
773                 break;
774         case EXPR_WIDE_CHARACTER_CONSTANT:
775                 print_wide_character_constant(&expression->conste);
776                 break;
777         case EXPR_CONST:
778                 print_const(&expression->conste);
779                 break;
780         case EXPR_FUNCNAME:
781                 print_funcname(&expression->funcname);
782                 break;
783         case EXPR_STRING_LITERAL:
784                 print_string_literal(&expression->string);
785                 break;
786         case EXPR_WIDE_STRING_LITERAL:
787                 print_wide_string_literal(&expression->wide_string);
788                 break;
789         case EXPR_COMPOUND_LITERAL:
790                 print_compound_literal(&expression->compound_literal);
791                 break;
792         case EXPR_CALL:
793                 print_call_expression(&expression->call);
794                 break;
795         EXPR_BINARY_CASES
796                 print_binary_expression(&expression->binary);
797                 break;
798         case EXPR_REFERENCE:
799         case EXPR_REFERENCE_ENUM_VALUE:
800                 print_reference_expression(&expression->reference);
801                 break;
802         case EXPR_ARRAY_ACCESS:
803                 print_array_expression(&expression->array_access);
804                 break;
805         case EXPR_LABEL_ADDRESS:
806                 print_label_address_expression(&expression->label_address);
807                 break;
808         EXPR_UNARY_CASES
809                 print_unary_expression(&expression->unary);
810                 break;
811         case EXPR_SIZEOF:
812         case EXPR_ALIGNOF:
813                 print_typeprop_expression(&expression->typeprop);
814                 break;
815         case EXPR_BUILTIN_SYMBOL:
816                 print_builtin_symbol(&expression->builtin_symbol);
817                 break;
818         case EXPR_BUILTIN_CONSTANT_P:
819                 print_builtin_constant(&expression->builtin_constant);
820                 break;
821         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
822                 print_builtin_types_compatible(&expression->builtin_types_compatible);
823                 break;
824         case EXPR_CONDITIONAL:
825                 print_conditional(&expression->conditional);
826                 break;
827         case EXPR_VA_START:
828                 print_va_start(&expression->va_starte);
829                 break;
830         case EXPR_VA_ARG:
831                 print_va_arg(&expression->va_arge);
832                 break;
833         case EXPR_SELECT:
834                 print_select(&expression->select);
835                 break;
836         case EXPR_CLASSIFY_TYPE:
837                 print_classify_type_expression(&expression->classify_type);
838                 break;
839         case EXPR_OFFSETOF:
840                 print_offsetof_expression(&expression->offsetofe);
841                 break;
842         case EXPR_STATEMENT:
843                 print_statement_expression(&expression->statement);
844                 break;
845
846         default:
847                 /* TODO */
848                 fprintf(out, "some expression of type %d", (int)expression->kind);
849                 break;
850         }
851         if (parenthesized)
852                 fputc(')', out);
853 }
854
855 /**
856  * Print an compound statement.
857  *
858  * @param block  the compound statement
859  */
860 static void print_compound_statement(const compound_statement_t *block)
861 {
862         fputs("{\n", out);
863         ++indent;
864
865         statement_t *statement = block->statements;
866         while (statement != NULL) {
867                 if (statement->base.kind == STATEMENT_CASE_LABEL)
868                         --indent;
869                 if (statement->kind != STATEMENT_LABEL)
870                         print_indent();
871                 print_statement(statement);
872
873                 statement = statement->base.next;
874         }
875         --indent;
876         print_indent();
877         fputs(block->stmt_expr ? "}" : "}\n", out);
878 }
879
880 /**
881  * Print a return statement.
882  *
883  * @param statement  the return statement
884  */
885 static void print_return_statement(const return_statement_t *statement)
886 {
887         expression_t const *const val = statement->value;
888         if (val != NULL) {
889                 fputs("return ", out);
890                 print_expression(val);
891                 fputs(";\n", out);
892         } else {
893                 fputs("return;\n", out);
894         }
895 }
896
897 /**
898  * Print an expression statement.
899  *
900  * @param statement  the expression statement
901  */
902 static void print_expression_statement(const expression_statement_t *statement)
903 {
904         print_expression(statement->expression);
905         fputs(";\n", out);
906 }
907
908 /**
909  * Print a goto statement.
910  *
911  * @param statement  the goto statement
912  */
913 static void print_goto_statement(const goto_statement_t *statement)
914 {
915         fputs("goto ", out);
916         if (statement->expression != NULL) {
917                 fputc('*', out);
918                 print_expression(statement->expression);
919         } else {
920                 fputs(statement->label->base.symbol->string, out);
921         }
922         fputs(";\n", out);
923 }
924
925 /**
926  * Print a label statement.
927  *
928  * @param statement  the label statement
929  */
930 static void print_label_statement(const label_statement_t *statement)
931 {
932         fprintf(out, "%s:\n", statement->label->base.symbol->string);
933         print_indent();
934         print_statement(statement->statement);
935 }
936
937 /**
938  * Print an if statement.
939  *
940  * @param statement  the if statement
941  */
942 static void print_if_statement(const if_statement_t *statement)
943 {
944         fputs("if (", out);
945         print_expression(statement->condition);
946         fputs(") ", out);
947         print_statement(statement->true_statement);
948
949         if (statement->false_statement != NULL) {
950                 print_indent();
951                 fputs("else ", out);
952                 print_statement(statement->false_statement);
953         }
954 }
955
956 /**
957  * Print a switch statement.
958  *
959  * @param statement  the switch statement
960  */
961 static void print_switch_statement(const switch_statement_t *statement)
962 {
963         fputs("switch (", out);
964         print_expression(statement->expression);
965         fputs(") ", out);
966         print_statement(statement->body);
967 }
968
969 /**
970  * Print a case label (including the default label).
971  *
972  * @param statement  the case label statement
973  */
974 static void print_case_label(const case_label_statement_t *statement)
975 {
976         if (statement->expression == NULL) {
977                 fputs("default:\n", out);
978         } else {
979                 fputs("case ", out);
980                 print_expression(statement->expression);
981                 if (statement->end_range != NULL) {
982                         fputs(" ... ", out);
983                         print_expression(statement->end_range);
984                 }
985                 fputs(":\n", out);
986         }
987         ++indent;
988         if (statement->statement != NULL) {
989                 if (statement->statement->base.kind == STATEMENT_CASE_LABEL) {
990                         --indent;
991                 }
992                 print_indent();
993                 print_statement(statement->statement);
994         }
995 }
996
997 static void print_typedef(const entity_t *entity)
998 {
999         fputs("typedef ", out);
1000         print_type_ext(entity->typedefe.type, entity->base.symbol, NULL);
1001         fputc(';', out);
1002 }
1003
1004 /**
1005  * returns true if the entity is a compiler generated one and has no real
1006  * correspondenc in the source file
1007  */
1008 static bool is_generated_entity(const entity_t *entity)
1009 {
1010         if (entity->kind == ENTITY_TYPEDEF)
1011                 return entity->typedefe.builtin;
1012
1013         if (is_declaration(entity))
1014                 return entity->declaration.implicit;
1015
1016         return false;
1017 }
1018
1019 /**
1020  * Print a declaration statement.
1021  *
1022  * @param statement   the statement
1023  */
1024 static void print_declaration_statement(
1025                 const declaration_statement_t *statement)
1026 {
1027         bool first = true;
1028         entity_t *entity = statement->declarations_begin;
1029         if (entity == NULL) {
1030                 fputs("/* empty declaration statement */\n", out);
1031                 return;
1032         }
1033
1034         entity_t *const end = statement->declarations_end->base.next;
1035         for (; entity != end; entity = entity->base.next) {
1036                 if (entity->kind == ENTITY_ENUM_VALUE)
1037                         continue;
1038                 if (is_generated_entity(entity))
1039                         continue;
1040
1041                 if (!first) {
1042                         print_indent();
1043                 } else {
1044                         first = false;
1045                 }
1046
1047                 print_entity(entity);
1048                 fputc('\n', out);
1049         }
1050 }
1051
1052 /**
1053  * Print a while statement.
1054  *
1055  * @param statement   the statement
1056  */
1057 static void print_while_statement(const while_statement_t *statement)
1058 {
1059         fputs("while (", out);
1060         print_expression(statement->condition);
1061         fputs(") ", out);
1062         print_statement(statement->body);
1063 }
1064
1065 /**
1066  * Print a do-while statement.
1067  *
1068  * @param statement   the statement
1069  */
1070 static void print_do_while_statement(const do_while_statement_t *statement)
1071 {
1072         fputs("do ", out);
1073         print_statement(statement->body);
1074         print_indent();
1075         fputs("while (", out);
1076         print_expression(statement->condition);
1077         fputs(");\n", out);
1078 }
1079
1080 /**
1081  * Print a for statement.
1082  *
1083  * @param statement   the statement
1084  */
1085 static void print_for_statement(const for_statement_t *statement)
1086 {
1087         fputs("for (", out);
1088         entity_t *entity = statement->scope.entities;
1089         while (entity != NULL && is_generated_entity(entity))
1090                 entity = entity->base.next;
1091
1092         if (entity != NULL) {
1093                 assert(statement->initialisation == NULL);
1094                 assert(is_declaration(entity));
1095                 print_declaration(entity);
1096                 if (entity->base.next != NULL) {
1097                         panic("multiple declarations in for statement not supported yet");
1098                 }
1099         } else {
1100                 if (statement->initialisation) {
1101                         print_expression(statement->initialisation);
1102                 }
1103                 fputc(';', out);
1104         }
1105         if (statement->condition != NULL) {
1106                 fputc(' ', out);
1107                 print_expression(statement->condition);
1108         }
1109         fputc(';', out);
1110         if (statement->step != NULL) {
1111                 fputc(' ', out);
1112                 print_expression(statement->step);
1113         }
1114         fputs(") ", out);
1115         print_statement(statement->body);
1116 }
1117
1118 /**
1119  * Print assembler arguments.
1120  *
1121  * @param arguments   the arguments
1122  */
1123 static void print_asm_arguments(asm_argument_t *arguments)
1124 {
1125         asm_argument_t *argument = arguments;
1126         for (; argument != NULL; argument = argument->next) {
1127                 if (argument != arguments)
1128                         fputs(", ", out);
1129
1130                 if (argument->symbol) {
1131                         fprintf(out, "[%s] ", argument->symbol->string);
1132                 }
1133                 print_quoted_string(&argument->constraints, '"', 1);
1134                 fputs(" (", out);
1135                 print_expression(argument->expression);
1136                 fputc(')', out);
1137         }
1138 }
1139
1140 /**
1141  * Print assembler clobbers.
1142  *
1143  * @param clobbers   the clobbers
1144  */
1145 static void print_asm_clobbers(asm_clobber_t *clobbers)
1146 {
1147         asm_clobber_t *clobber = clobbers;
1148         for (; clobber != NULL; clobber = clobber->next) {
1149                 if (clobber != clobbers)
1150                         fputs(", ", out);
1151
1152                 print_quoted_string(&clobber->clobber, '"', 1);
1153         }
1154 }
1155
1156 /**
1157  * Print an assembler statement.
1158  *
1159  * @param statement   the statement
1160  */
1161 static void print_asm_statement(const asm_statement_t *statement)
1162 {
1163         fputs("asm ", out);
1164         if (statement->is_volatile) {
1165                 fputs("volatile ", out);
1166         }
1167         fputc('(', out);
1168         print_quoted_string(&statement->asm_text, '"', 1);
1169         if (statement->outputs  == NULL &&
1170             statement->inputs   == NULL &&
1171             statement->clobbers == NULL)
1172                 goto end_of_print_asm_statement;
1173
1174         fputs(" : ", out);
1175         print_asm_arguments(statement->outputs);
1176         if (statement->inputs == NULL && statement->clobbers == NULL)
1177                 goto end_of_print_asm_statement;
1178
1179         fputs(" : ", out);
1180         print_asm_arguments(statement->inputs);
1181         if (statement->clobbers == NULL)
1182                 goto end_of_print_asm_statement;
1183
1184         fputs(" : ", out);
1185         print_asm_clobbers(statement->clobbers);
1186
1187 end_of_print_asm_statement:
1188         fputs(");\n", out);
1189 }
1190
1191 /**
1192  * Print a microsoft __try statement.
1193  *
1194  * @param statement   the statement
1195  */
1196 static void print_ms_try_statement(const ms_try_statement_t *statement)
1197 {
1198         fputs("__try ", out);
1199         print_statement(statement->try_statement);
1200         print_indent();
1201         if (statement->except_expression != NULL) {
1202                 fputs("__except(", out);
1203                 print_expression(statement->except_expression);
1204                 fputs(") ", out);
1205         } else {
1206                 fputs("__finally ", out);
1207         }
1208         print_statement(statement->final_statement);
1209 }
1210
1211 /**
1212  * Print a microsoft __leave statement.
1213  *
1214  * @param statement   the statement
1215  */
1216 static void print_leave_statement(const leave_statement_t *statement)
1217 {
1218         (void)statement;
1219         fputs("__leave;\n", out);
1220 }
1221
1222 /**
1223  * Print a statement.
1224  *
1225  * @param statement   the statement
1226  */
1227 void print_statement(const statement_t *statement)
1228 {
1229         switch (statement->kind) {
1230         case STATEMENT_EMPTY:
1231                 fputs(";\n", out);
1232                 break;
1233         case STATEMENT_COMPOUND:
1234                 print_compound_statement(&statement->compound);
1235                 break;
1236         case STATEMENT_RETURN:
1237                 print_return_statement(&statement->returns);
1238                 break;
1239         case STATEMENT_EXPRESSION:
1240                 print_expression_statement(&statement->expression);
1241                 break;
1242         case STATEMENT_LABEL:
1243                 print_label_statement(&statement->label);
1244                 break;
1245         case STATEMENT_GOTO:
1246                 print_goto_statement(&statement->gotos);
1247                 break;
1248         case STATEMENT_CONTINUE:
1249                 fputs("continue;\n", out);
1250                 break;
1251         case STATEMENT_BREAK:
1252                 fputs("break;\n", out);
1253                 break;
1254         case STATEMENT_IF:
1255                 print_if_statement(&statement->ifs);
1256                 break;
1257         case STATEMENT_SWITCH:
1258                 print_switch_statement(&statement->switchs);
1259                 break;
1260         case STATEMENT_CASE_LABEL:
1261                 print_case_label(&statement->case_label);
1262                 break;
1263         case STATEMENT_DECLARATION:
1264                 print_declaration_statement(&statement->declaration);
1265                 break;
1266         case STATEMENT_WHILE:
1267                 print_while_statement(&statement->whiles);
1268                 break;
1269         case STATEMENT_DO_WHILE:
1270                 print_do_while_statement(&statement->do_while);
1271                 break;
1272         case STATEMENT_FOR:
1273                 print_for_statement(&statement->fors);
1274                 break;
1275         case STATEMENT_ASM:
1276                 print_asm_statement(&statement->asms);
1277                 break;
1278         case STATEMENT_MS_TRY:
1279                 print_ms_try_statement(&statement->ms_try);
1280                 break;
1281         case STATEMENT_LEAVE:
1282                 print_leave_statement(&statement->leave);
1283                 break;
1284         case STATEMENT_INVALID:
1285                 fputs("$invalid statement$\n", out);
1286                 break;
1287         }
1288 }
1289
1290 /**
1291  * Print a storage class.
1292  *
1293  * @param storage_class   the storage class
1294  */
1295 static void print_storage_class(storage_class_tag_t storage_class)
1296 {
1297         switch (storage_class) {
1298         case STORAGE_CLASS_NONE:     return;
1299         case STORAGE_CLASS_TYPEDEF:  fputs("typedef ",  out); return;
1300         case STORAGE_CLASS_EXTERN:   fputs("extern ",   out); return;
1301         case STORAGE_CLASS_STATIC:   fputs("static ",   out); return;
1302         case STORAGE_CLASS_AUTO:     fputs("auto ",     out); return;
1303         case STORAGE_CLASS_REGISTER: fputs("register ", out); return;
1304         }
1305         panic("invalid storage class");
1306 }
1307
1308 /**
1309  * Print an initializer.
1310  *
1311  * @param initializer  the initializer
1312  */
1313 void print_initializer(const initializer_t *initializer)
1314 {
1315         if (initializer == NULL) {
1316                 fputs("{}", out);
1317                 return;
1318         }
1319
1320         switch (initializer->kind) {
1321         case INITIALIZER_VALUE: {
1322                 const initializer_value_t *value = &initializer->value;
1323                 print_assignment_expression(value->value);
1324                 return;
1325         }
1326         case INITIALIZER_LIST: {
1327                 assert(initializer->kind == INITIALIZER_LIST);
1328                 fputs("{ ", out);
1329                 const initializer_list_t *list = &initializer->list;
1330
1331                 for (size_t i = 0 ; i < list->len; ++i) {
1332                         const initializer_t *sub_init = list->initializers[i];
1333                         print_initializer(list->initializers[i]);
1334                         if (i < list->len-1) {
1335                                 if (sub_init == NULL || sub_init->kind != INITIALIZER_DESIGNATOR)
1336                                         fputs(", ", out);
1337                         }
1338                 }
1339                 fputs(" }", out);
1340                 return;
1341         }
1342         case INITIALIZER_STRING:
1343                 print_quoted_string(&initializer->string.string, '"', 1);
1344                 return;
1345         case INITIALIZER_WIDE_STRING:
1346                 print_quoted_wide_string(&initializer->wide_string.string, '"', 1);
1347                 return;
1348         case INITIALIZER_DESIGNATOR:
1349                 print_designator(initializer->designator.designator);
1350                 fputs(" = ", out);
1351                 return;
1352         }
1353
1354         panic("invalid initializer kind found");
1355 }
1356
1357 /**
1358  * Print microsoft extended declaration modifiers.
1359  */
1360 static void print_ms_modifiers(const declaration_t *declaration)
1361 {
1362         if ((c_mode & _MS) == 0)
1363                 return;
1364
1365         decl_modifiers_t modifiers = declaration->modifiers;
1366
1367         bool        ds_shown = false;
1368         const char *next     = "(";
1369
1370         if (declaration->base.kind == ENTITY_VARIABLE) {
1371                 variable_t *variable = (variable_t*)declaration;
1372                 if (variable->alignment != 0
1373                                 || variable->get_property_sym != NULL
1374                                 || variable->put_property_sym != NULL) {
1375                         if (!ds_shown) {
1376                                 fputs("__declspec", out);
1377                                 ds_shown = true;
1378                         }
1379
1380                         if (variable->alignment != 0) {
1381                                 fputs(next, out); next = ", "; fprintf(out, "align(%u)", variable->alignment);
1382                         }
1383                         if (variable->get_property_sym != NULL
1384                                         || variable->put_property_sym != NULL) {
1385                                 char *comma = "";
1386                                 fputs(next, out); next = ", "; fputs("property(", out);
1387                                 if (variable->get_property_sym != NULL) {
1388                                         fprintf(out, "get=%s", variable->get_property_sym->string);
1389                                         comma = ", ";
1390                                 }
1391                                 if (variable->put_property_sym != NULL)
1392                                         fprintf(out, "%sput=%s", comma, variable->put_property_sym->string);
1393                                 fputc(')', out);
1394                         }
1395                 }
1396         }
1397
1398         /* DM_FORCEINLINE handled outside. */
1399         if ((modifiers & ~DM_FORCEINLINE) != 0) {
1400                 if (!ds_shown) {
1401                         fputs("__declspec", out);
1402                         ds_shown = true;
1403                 }
1404                 if (modifiers & DM_DLLIMPORT) {
1405                         fputs(next, out); next = ", "; fputs("dllimport", out);
1406                 }
1407                 if (modifiers & DM_DLLEXPORT) {
1408                         fputs(next, out); next = ", "; fputs("dllexport", out);
1409                 }
1410                 if (modifiers & DM_THREAD) {
1411                         fputs(next, out); next = ", "; fputs("thread", out);
1412                 }
1413                 if (modifiers & DM_NAKED) {
1414                         fputs(next, out); next = ", "; fputs("naked", out);
1415                 }
1416                 if (modifiers & DM_THREAD) {
1417                         fputs(next, out); next = ", "; fputs("thread", out);
1418                 }
1419                 if (modifiers & DM_SELECTANY) {
1420                         fputs(next, out); next = ", "; fputs("selectany", out);
1421                 }
1422                 if (modifiers & DM_NOTHROW) {
1423                         fputs(next, out); next = ", "; fputs("nothrow", out);
1424                 }
1425                 if (modifiers & DM_NORETURN) {
1426                         fputs(next, out); next = ", "; fputs("noreturn", out);
1427                 }
1428                 if (modifiers & DM_NOINLINE) {
1429                         fputs(next, out); next = ", "; fputs("noinline", out);
1430                 }
1431                 if (modifiers & DM_DEPRECATED) {
1432                         fputs(next, out); next = ", "; fputs("deprecated", out);
1433                         if (declaration->deprecated_string != NULL)
1434                                 fprintf(out, "(\"%s\")",
1435                                         declaration->deprecated_string);
1436                 }
1437                 if (modifiers & DM_RESTRICT) {
1438                         fputs(next, out); next = ", "; fputs("restrict", out);
1439                 }
1440                 if (modifiers & DM_NOALIAS) {
1441                         fputs(next, out); next = ", "; fputs("noalias", out);
1442                 }
1443         }
1444
1445         if (ds_shown)
1446                 fputs(") ", out);
1447 }
1448
1449 static void print_scope(const scope_t *scope)
1450 {
1451         const entity_t *entity = scope->entities;
1452         for ( ; entity != NULL; entity = entity->base.next) {
1453                 print_indent();
1454                 print_entity(entity);
1455                 fputs("\n", out);
1456         }
1457 }
1458
1459 static void print_namespace(const namespace_t *namespace)
1460 {
1461         fputs("namespace ", out);
1462         if (namespace->base.symbol != NULL) {
1463                 fputs(namespace->base.symbol->string, out);
1464                 fputc(' ', out);
1465         }
1466
1467         fputs("{\n", out);
1468         ++indent;
1469
1470         print_scope(&namespace->members);
1471
1472         --indent;
1473         print_indent();
1474         fputs("}\n", out);
1475 }
1476
1477 /**
1478  * Print a variable or function declaration
1479  */
1480 void print_declaration(const entity_t *entity)
1481 {
1482         assert(is_declaration(entity));
1483         const declaration_t *declaration = &entity->declaration;
1484
1485         print_storage_class((storage_class_tag_t)declaration->declared_storage_class);
1486         if (entity->kind == ENTITY_FUNCTION) {
1487                 function_t *function = (function_t*)declaration;
1488                 if (function->is_inline) {
1489                         if (declaration->modifiers & DM_FORCEINLINE) {
1490                                 fputs("__forceinline ", out);
1491                         } else if (declaration->modifiers & DM_MICROSOFT_INLINE) {
1492                                 fputs("__inline ", out);
1493                         } else {
1494                                 fputs("inline ", out);
1495                         }
1496                 }
1497         }
1498         print_ms_modifiers(declaration);
1499         switch (entity->kind) {
1500                 case ENTITY_FUNCTION:
1501                         print_type_ext(entity->declaration.type, entity->base.symbol,
1502                                         &entity->function.parameters);
1503
1504                         if (entity->function.statement != NULL) {
1505                                 fputc('\n', out);
1506                                 print_indent();
1507                                 print_statement(entity->function.statement);
1508                                 return;
1509                         }
1510                         break;
1511
1512                 case ENTITY_VARIABLE:
1513                         if (entity->variable.thread_local)
1514                                 fputs("__thread ", out);
1515                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1516                         if (entity->variable.initializer != NULL) {
1517                                 fputs(" = ", out);
1518                                 print_initializer(entity->variable.initializer);
1519                         }
1520                         break;
1521
1522                 default:
1523                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1524                         break;
1525         }
1526         fputc(';', out);
1527 }
1528
1529 /**
1530  * Prints an expression.
1531  *
1532  * @param expression  the expression
1533  */
1534 void print_expression(const expression_t *expression)
1535 {
1536         print_expression_prec(expression, PREC_BOTTOM);
1537 }
1538
1539 /**
1540  * Print a declaration.
1541  *
1542  * @param declaration  the declaration
1543  */
1544 void print_entity(const entity_t *entity)
1545 {
1546         if (entity->base.namespc != NAMESPACE_NORMAL && entity->base.symbol == NULL)
1547                 return;
1548
1549         switch ((entity_kind_tag_t)entity->kind) {
1550         case ENTITY_VARIABLE:
1551         case ENTITY_PARAMETER:
1552         case ENTITY_COMPOUND_MEMBER:
1553         case ENTITY_FUNCTION:
1554                 print_declaration(entity);
1555                 return;
1556         case ENTITY_TYPEDEF:
1557                 print_typedef(entity);
1558                 return;
1559         case ENTITY_STRUCT:
1560                 fputs("struct ", out);
1561                 fputs(entity->base.symbol->string, out);
1562                 if (entity->structe.complete) {
1563                         fputc(' ', out);
1564                         print_compound_definition(&entity->structe);
1565                 }
1566                 fputc(';', out);
1567                 return;
1568         case ENTITY_UNION:
1569                 fputs("union ", out);
1570                 fputs(entity->base.symbol->string, out);
1571                 if (entity->unione.complete) {
1572                         fputc(' ', out);
1573                         print_compound_definition(&entity->unione);
1574                 }
1575                 fputc(';', out);
1576                 return;
1577         case ENTITY_ENUM:
1578                 fputs("enum ", out);
1579                 fputs(entity->base.symbol->string, out);
1580                 fputc(' ', out);
1581                 print_enum_definition(&entity->enume);
1582                 fputc(';', out);
1583                 return;
1584         case ENTITY_NAMESPACE:
1585                 print_namespace(&entity->namespacee);
1586                 return;
1587         case ENTITY_LOCAL_LABEL:
1588                 fprintf(out, "__label__ %s;", entity->base.symbol->string);
1589                 return;
1590         case ENTITY_LABEL:
1591         case ENTITY_ENUM_VALUE:
1592                 panic("print_entity used on unexpected entity type");
1593         case ENTITY_INVALID:
1594                 break;
1595         }
1596         panic("Invalid entity type encountered");
1597 }
1598
1599 /**
1600  * Print the AST of a translation unit.
1601  *
1602  * @param unit   the translation unit
1603  */
1604 void print_ast(const translation_unit_t *unit)
1605 {
1606         inc_type_visited();
1607
1608         entity_t *entity = unit->scope.entities;
1609         for ( ; entity != NULL; entity = entity->base.next) {
1610                 if (entity->kind == ENTITY_ENUM_VALUE)
1611                         continue;
1612                 if (entity->base.namespc != NAMESPACE_NORMAL
1613                                 && entity->base.symbol == NULL)
1614                         continue;
1615                 if (is_generated_entity(entity))
1616                         continue;
1617
1618                 print_indent();
1619                 print_entity(entity);
1620                 fputc('\n', out);
1621         }
1622 }
1623
1624 bool is_constant_initializer(const initializer_t *initializer)
1625 {
1626         switch (initializer->kind) {
1627         case INITIALIZER_STRING:
1628         case INITIALIZER_WIDE_STRING:
1629         case INITIALIZER_DESIGNATOR:
1630                 return true;
1631
1632         case INITIALIZER_VALUE:
1633                 return is_constant_expression(initializer->value.value);
1634
1635         case INITIALIZER_LIST:
1636                 for (size_t i = 0; i < initializer->list.len; ++i) {
1637                         initializer_t *sub_initializer = initializer->list.initializers[i];
1638                         if (!is_constant_initializer(sub_initializer))
1639                                 return false;
1640                 }
1641                 return true;
1642         }
1643         panic("invalid initializer kind found");
1644 }
1645
1646 static bool is_object_with_linker_constant_address(const expression_t *expression)
1647 {
1648         switch (expression->kind) {
1649         case EXPR_UNARY_DEREFERENCE:
1650                 return is_address_constant(expression->unary.value);
1651
1652         case EXPR_SELECT: {
1653                 type_t *base_type = skip_typeref(expression->select.compound->base.type);
1654                 if (is_type_pointer(base_type)) {
1655                         /* it's a -> */
1656                         return is_address_constant(expression->select.compound);
1657                 } else {
1658                         return is_object_with_linker_constant_address(expression->select.compound);
1659                 }
1660         }
1661
1662         case EXPR_ARRAY_ACCESS:
1663                 return is_constant_expression(expression->array_access.index)
1664                         && is_address_constant(expression->array_access.array_ref);
1665
1666         case EXPR_REFERENCE: {
1667                 entity_t *entity = expression->reference.entity;
1668                 if (is_declaration(entity)) {
1669                         switch ((storage_class_tag_t)entity->declaration.storage_class) {
1670                         case STORAGE_CLASS_NONE:
1671                         case STORAGE_CLASS_EXTERN:
1672                         case STORAGE_CLASS_STATIC:
1673                                 return
1674                                         entity->kind != ENTITY_VARIABLE ||
1675                                         !entity->variable.thread_local;
1676
1677                         case STORAGE_CLASS_REGISTER:
1678                         case STORAGE_CLASS_TYPEDEF:
1679                         case STORAGE_CLASS_AUTO:
1680                                 break;
1681                         }
1682                 }
1683                 return false;
1684         }
1685
1686         default:
1687                 return false;
1688         }
1689 }
1690
1691 bool is_address_constant(const expression_t *expression)
1692 {
1693         switch (expression->kind) {
1694         case EXPR_UNARY_TAKE_ADDRESS:
1695                 return is_object_with_linker_constant_address(expression->unary.value);
1696
1697         case EXPR_UNARY_DEREFERENCE: {
1698                 type_t *real_type
1699                         = revert_automatic_type_conversion(expression->unary.value);
1700                 /* dereferencing a function is a NOP */
1701                 if (is_type_function(real_type)) {
1702                         return is_address_constant(expression->unary.value);
1703                 }
1704                 /* FALLTHROUGH */
1705         }
1706
1707         case EXPR_UNARY_CAST: {
1708                 type_t *dest = skip_typeref(expression->base.type);
1709                 if (!is_type_pointer(dest) && (
1710                         dest->kind != TYPE_ATOMIC                                               ||
1711                         !(get_atomic_type_flags(dest->atomic.akind) & ATOMIC_TYPE_FLAG_INTEGER) ||
1712                         get_atomic_type_size(dest->atomic.akind) < get_atomic_type_size(get_intptr_kind())
1713                     ))
1714                         return false;
1715
1716                 return (is_constant_expression(expression->unary.value)
1717                         || is_address_constant(expression->unary.value));
1718         }
1719
1720         case EXPR_BINARY_ADD:
1721         case EXPR_BINARY_SUB: {
1722                 expression_t *left  = expression->binary.left;
1723                 expression_t *right = expression->binary.right;
1724
1725                 if (is_type_pointer(skip_typeref(left->base.type))) {
1726                         return is_address_constant(left) && is_constant_expression(right);
1727                 } else if (is_type_pointer(skip_typeref(right->base.type))) {
1728                         return is_constant_expression(left)     && is_address_constant(right);
1729                 }
1730
1731                 return false;
1732         }
1733
1734         case EXPR_REFERENCE: {
1735                 entity_t *entity = expression->reference.entity;
1736                 if (!is_declaration(entity))
1737                         return false;
1738
1739                 type_t *type = skip_typeref(entity->declaration.type);
1740                 if (is_type_function(type))
1741                         return true;
1742                 if (is_type_array(type)) {
1743                         return is_object_with_linker_constant_address(expression);
1744                 }
1745                 /* Prevent stray errors */
1746                 if (!is_type_valid(type))
1747                         return true;
1748                 return false;
1749         }
1750
1751         case EXPR_ARRAY_ACCESS: {
1752                 type_t *const type =
1753                         skip_typeref(revert_automatic_type_conversion(expression));
1754                 return
1755                         is_type_array(type)                                    &&
1756                         is_constant_expression(expression->array_access.index) &&
1757                         is_address_constant(expression->array_access.array_ref);
1758         }
1759
1760         default:
1761                 return false;
1762         }
1763 }
1764
1765 static bool is_builtin_const_call(const expression_t *expression)
1766 {
1767         expression_t *function = expression->call.function;
1768         if (function->kind != EXPR_BUILTIN_SYMBOL) {
1769                 return false;
1770         }
1771
1772         symbol_t *symbol = function->builtin_symbol.symbol;
1773
1774         switch (symbol->ID) {
1775         case T___builtin_huge_val:
1776         case T___builtin_inf:
1777         case T___builtin_inff:
1778         case T___builtin_infl:
1779         case T___builtin_nan:
1780         case T___builtin_nanf:
1781         case T___builtin_nanl:
1782                 return true;
1783         }
1784
1785         return false;
1786 }
1787
1788 static bool is_constant_pointer(const expression_t *expression)
1789 {
1790         if (is_constant_expression(expression))
1791                 return true;
1792
1793         switch (expression->kind) {
1794         case EXPR_UNARY_CAST:
1795                 return is_constant_pointer(expression->unary.value);
1796         default:
1797                 return false;
1798         }
1799 }
1800
1801 static bool is_object_with_constant_address(const expression_t *expression)
1802 {
1803         switch (expression->kind) {
1804         case EXPR_SELECT: {
1805                 expression_t *compound      = expression->select.compound;
1806                 type_t       *compound_type = compound->base.type;
1807                 compound_type = skip_typeref(compound_type);
1808                 if (is_type_pointer(compound_type)) {
1809                         return is_constant_pointer(compound);
1810                 } else {
1811                         return is_object_with_constant_address(compound);
1812                 }
1813         }
1814
1815         case EXPR_ARRAY_ACCESS: {
1816                 array_access_expression_t const* const array_access =
1817                         &expression->array_access;
1818                 return
1819                         is_constant_expression(array_access->index) && (
1820                                 is_object_with_constant_address(array_access->array_ref) ||
1821                                 is_constant_pointer(array_access->array_ref)
1822                         );
1823         }
1824
1825         case EXPR_UNARY_DEREFERENCE:
1826                 return is_constant_pointer(expression->unary.value);
1827         default:
1828                 return false;
1829         }
1830 }
1831
1832 bool is_constant_expression(const expression_t *expression)
1833 {
1834         switch (expression->kind) {
1835
1836         case EXPR_CONST:
1837         case EXPR_CHARACTER_CONSTANT:
1838         case EXPR_WIDE_CHARACTER_CONSTANT:
1839         case EXPR_STRING_LITERAL:
1840         case EXPR_WIDE_STRING_LITERAL:
1841         case EXPR_CLASSIFY_TYPE:
1842         case EXPR_FUNCNAME:
1843         case EXPR_OFFSETOF:
1844         case EXPR_ALIGNOF:
1845         case EXPR_BUILTIN_CONSTANT_P:
1846         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1847         case EXPR_LABEL_ADDRESS:
1848         case EXPR_REFERENCE_ENUM_VALUE:
1849                 return true;
1850
1851         case EXPR_SIZEOF: {
1852                 type_t *type = expression->typeprop.type;
1853                 if (type == NULL)
1854                         type = expression->typeprop.tp_expression->base.type;
1855
1856                 type = skip_typeref(type);
1857                 if (is_type_array(type) && type->array.is_vla)
1858                         return false;
1859                 return true;
1860         }
1861
1862         case EXPR_BUILTIN_SYMBOL:
1863         case EXPR_SELECT:
1864         case EXPR_VA_START:
1865         case EXPR_VA_ARG:
1866         case EXPR_STATEMENT:
1867         case EXPR_REFERENCE:
1868         case EXPR_UNARY_POSTFIX_INCREMENT:
1869         case EXPR_UNARY_POSTFIX_DECREMENT:
1870         case EXPR_UNARY_PREFIX_INCREMENT:
1871         case EXPR_UNARY_PREFIX_DECREMENT:
1872         case EXPR_UNARY_ASSUME: /* has VOID type */
1873         case EXPR_UNARY_DEREFERENCE:
1874         case EXPR_UNARY_DELETE:
1875         case EXPR_UNARY_DELETE_ARRAY:
1876         case EXPR_UNARY_THROW:
1877         case EXPR_BINARY_ASSIGN:
1878         case EXPR_BINARY_MUL_ASSIGN:
1879         case EXPR_BINARY_DIV_ASSIGN:
1880         case EXPR_BINARY_MOD_ASSIGN:
1881         case EXPR_BINARY_ADD_ASSIGN:
1882         case EXPR_BINARY_SUB_ASSIGN:
1883         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1884         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1885         case EXPR_BINARY_BITWISE_AND_ASSIGN:
1886         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1887         case EXPR_BINARY_BITWISE_OR_ASSIGN:
1888         case EXPR_BINARY_COMMA:
1889         case EXPR_ARRAY_ACCESS:
1890                 return false;
1891
1892         case EXPR_UNARY_TAKE_ADDRESS:
1893                 return is_object_with_constant_address(expression->unary.value);
1894
1895         case EXPR_CALL:
1896                 return is_builtin_const_call(expression);
1897
1898         case EXPR_UNARY_NEGATE:
1899         case EXPR_UNARY_PLUS:
1900         case EXPR_UNARY_BITWISE_NEGATE:
1901         case EXPR_UNARY_NOT:
1902                 return is_constant_expression(expression->unary.value);
1903
1904         case EXPR_UNARY_CAST:
1905         case EXPR_UNARY_CAST_IMPLICIT:
1906                 return is_type_arithmetic(skip_typeref(expression->base.type))
1907                         && is_constant_expression(expression->unary.value);
1908
1909         case EXPR_BINARY_ADD:
1910         case EXPR_BINARY_SUB:
1911         case EXPR_BINARY_MUL:
1912         case EXPR_BINARY_DIV:
1913         case EXPR_BINARY_MOD:
1914         case EXPR_BINARY_EQUAL:
1915         case EXPR_BINARY_NOTEQUAL:
1916         case EXPR_BINARY_LESS:
1917         case EXPR_BINARY_LESSEQUAL:
1918         case EXPR_BINARY_GREATER:
1919         case EXPR_BINARY_GREATEREQUAL:
1920         case EXPR_BINARY_BITWISE_AND:
1921         case EXPR_BINARY_BITWISE_OR:
1922         case EXPR_BINARY_BITWISE_XOR:
1923         case EXPR_BINARY_SHIFTLEFT:
1924         case EXPR_BINARY_SHIFTRIGHT:
1925         case EXPR_BINARY_ISGREATER:
1926         case EXPR_BINARY_ISGREATEREQUAL:
1927         case EXPR_BINARY_ISLESS:
1928         case EXPR_BINARY_ISLESSEQUAL:
1929         case EXPR_BINARY_ISLESSGREATER:
1930         case EXPR_BINARY_ISUNORDERED:
1931                 return is_constant_expression(expression->binary.left)
1932                         && is_constant_expression(expression->binary.right);
1933
1934         case EXPR_BINARY_LOGICAL_AND: {
1935                 expression_t const *const left = expression->binary.left;
1936                 if (!is_constant_expression(left))
1937                         return false;
1938                 if (fold_constant(left) == 0)
1939                         return true;
1940                 return is_constant_expression(expression->binary.right);
1941         }
1942
1943         case EXPR_BINARY_LOGICAL_OR: {
1944                 expression_t const *const left = expression->binary.left;
1945                 if (!is_constant_expression(left))
1946                         return false;
1947                 if (fold_constant(left) != 0)
1948                         return true;
1949                 return is_constant_expression(expression->binary.right);
1950         }
1951
1952         case EXPR_COMPOUND_LITERAL:
1953                 return is_constant_initializer(expression->compound_literal.initializer);
1954
1955         case EXPR_CONDITIONAL: {
1956                 expression_t *condition = expression->conditional.condition;
1957                 if (!is_constant_expression(condition))
1958                         return false;
1959
1960                 long val = fold_constant(condition);
1961                 if (val != 0) {
1962                         expression_t const *const t = expression->conditional.true_expression;
1963                         return t == NULL || is_constant_expression(t);
1964                 } else {
1965                         return is_constant_expression(expression->conditional.false_expression);
1966                 }
1967         }
1968
1969         case EXPR_INVALID:
1970                 return true;
1971
1972         case EXPR_UNKNOWN:
1973                 break;
1974         }
1975         panic("invalid expression found (is constant expression)");
1976 }
1977
1978 /**
1979  * Initialize the AST construction.
1980  */
1981 void init_ast(void)
1982 {
1983         obstack_init(&ast_obstack);
1984 }
1985
1986 /**
1987  * Free the AST.
1988  */
1989 void exit_ast(void)
1990 {
1991         obstack_free(&ast_obstack, NULL);
1992 }
1993
1994 /**
1995  * Set the output stream for the AST printer.
1996  *
1997  * @param stream  the output stream
1998  */
1999 void ast_set_output(FILE *stream)
2000 {
2001         out = stream;
2002         type_set_output(stream);
2003 }
2004
2005 /**
2006  * Allocate an AST object of the given size.
2007  *
2008  * @param size  the size of the object to allocate
2009  *
2010  * @return  A new allocated object in the AST memeory space.
2011  */
2012 void *(allocate_ast)(size_t size)
2013 {
2014         return _allocate_ast(size);
2015 }