- implemented va_copy(), needed for C99
[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_CONSTANT_P]         = PREC_PRIMARY,
118                 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = PREC_PRIMARY,
119                 [EXPR_OFFSETOF]                   = PREC_PRIMARY,
120                 [EXPR_VA_START]                   = PREC_PRIMARY,
121                 [EXPR_VA_ARG]                     = PREC_PRIMARY,
122                 [EXPR_VA_COPY]                    = 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         print_expression_prec(call->function, PREC_POSTFIX);
402         fputc('(', out);
403         call_argument_t *argument = call->arguments;
404         int              first    = 1;
405         while (argument != NULL) {
406                 if (!first) {
407                         fputs(", ", out);
408                 } else {
409                         first = 0;
410                 }
411                 print_assignment_expression(argument->expression);
412
413                 argument = argument->next;
414         }
415         fputc(')', out);
416 }
417
418 /**
419  * Prints a binary expression.
420  *
421  * @param binexpr   the binary expression
422  */
423 static void print_binary_expression(const binary_expression_t *binexpr)
424 {
425         unsigned prec = get_expression_precedence(binexpr->base.kind);
426         int      r2l  = right_to_left(prec);
427
428         print_expression_prec(binexpr->left, prec + r2l);
429         char const* op;
430         switch (binexpr->base.kind) {
431         case EXPR_BINARY_COMMA:              op = ", ";    break;
432         case EXPR_BINARY_ASSIGN:             op = " = ";   break;
433         case EXPR_BINARY_ADD:                op = " + ";   break;
434         case EXPR_BINARY_SUB:                op = " - ";   break;
435         case EXPR_BINARY_MUL:                op = " * ";   break;
436         case EXPR_BINARY_MOD:                op = " % ";   break;
437         case EXPR_BINARY_DIV:                op = " / ";   break;
438         case EXPR_BINARY_BITWISE_OR:         op = " | ";   break;
439         case EXPR_BINARY_BITWISE_AND:        op = " & ";   break;
440         case EXPR_BINARY_BITWISE_XOR:        op = " ^ ";   break;
441         case EXPR_BINARY_LOGICAL_OR:         op = " || ";  break;
442         case EXPR_BINARY_LOGICAL_AND:        op = " && ";  break;
443         case EXPR_BINARY_NOTEQUAL:           op = " != ";  break;
444         case EXPR_BINARY_EQUAL:              op = " == ";  break;
445         case EXPR_BINARY_LESS:               op = " < ";   break;
446         case EXPR_BINARY_LESSEQUAL:          op = " <= ";  break;
447         case EXPR_BINARY_GREATER:            op = " > ";   break;
448         case EXPR_BINARY_GREATEREQUAL:       op = " >= ";  break;
449         case EXPR_BINARY_SHIFTLEFT:          op = " << ";  break;
450         case EXPR_BINARY_SHIFTRIGHT:         op = " >> ";  break;
451
452         case EXPR_BINARY_ADD_ASSIGN:         op = " += ";  break;
453         case EXPR_BINARY_SUB_ASSIGN:         op = " -= ";  break;
454         case EXPR_BINARY_MUL_ASSIGN:         op = " *= ";  break;
455         case EXPR_BINARY_MOD_ASSIGN:         op = " %= ";  break;
456         case EXPR_BINARY_DIV_ASSIGN:         op = " /= ";  break;
457         case EXPR_BINARY_BITWISE_OR_ASSIGN:  op = " |= ";  break;
458         case EXPR_BINARY_BITWISE_AND_ASSIGN: op = " &= ";  break;
459         case EXPR_BINARY_BITWISE_XOR_ASSIGN: op = " ^= ";  break;
460         case EXPR_BINARY_SHIFTLEFT_ASSIGN:   op = " <<= "; break;
461         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  op = " >>= "; break;
462         default: panic("invalid binexpression found");
463         }
464         fputs(op, out);
465         print_expression_prec(binexpr->right, prec + 1 - r2l);
466 }
467
468 /**
469  * Prints an unary expression.
470  *
471  * @param unexpr   the unary expression
472  */
473 static void print_unary_expression(const unary_expression_t *unexpr)
474 {
475         unsigned prec = get_expression_precedence(unexpr->base.kind);
476         switch (unexpr->base.kind) {
477         case EXPR_UNARY_NEGATE:           fputc('-',          out); break;
478         case EXPR_UNARY_PLUS:             fputc('+',          out); break;
479         case EXPR_UNARY_NOT:              fputc('!',          out); break;
480         case EXPR_UNARY_BITWISE_NEGATE:   fputc('~',          out); break;
481         case EXPR_UNARY_PREFIX_INCREMENT: fputs("++",         out); break;
482         case EXPR_UNARY_PREFIX_DECREMENT: fputs("--",         out); break;
483         case EXPR_UNARY_DEREFERENCE:      fputc('*',          out); break;
484         case EXPR_UNARY_TAKE_ADDRESS:     fputc('&',          out); break;
485         case EXPR_UNARY_DELETE:           fputs("delete ",    out); break;
486         case EXPR_UNARY_DELETE_ARRAY:     fputs("delete [] ", out); break;
487
488         case EXPR_UNARY_POSTFIX_INCREMENT:
489                 print_expression_prec(unexpr->value, prec);
490                 fputs("++", out);
491                 return;
492         case EXPR_UNARY_POSTFIX_DECREMENT:
493                 print_expression_prec(unexpr->value, prec);
494                 fputs("--", out);
495                 return;
496         case EXPR_UNARY_CAST_IMPLICIT:
497         case EXPR_UNARY_CAST:
498                 fputc('(', out);
499                 print_type(unexpr->base.type);
500                 fputc(')', out);
501                 break;
502         case EXPR_UNARY_ASSUME:
503                 fputs("__assume(", out);
504                 print_assignment_expression(unexpr->value);
505                 fputc(')', out);
506                 return;
507
508         case EXPR_UNARY_THROW:
509                 if (unexpr->value == NULL) {
510                         fputs("throw", out);
511                         return;
512                 }
513                 fputs("throw ", out);
514                 break;
515
516         default:
517                 panic("invalid unary expression found");
518         }
519         print_expression_prec(unexpr->value, prec);
520 }
521
522 /**
523  * Prints a reference expression.
524  *
525  * @param ref   the reference expression
526  */
527 static void print_reference_expression(const reference_expression_t *ref)
528 {
529         fputs(ref->entity->base.symbol->string, out);
530 }
531
532 /**
533  * Prints a label address expression.
534  *
535  * @param ref   the reference expression
536  */
537 static void print_label_address_expression(const label_address_expression_t *le)
538 {
539         fprintf(out, "&&%s", le->label->base.symbol->string);
540 }
541
542 /**
543  * Prints an array expression.
544  *
545  * @param expression   the array expression
546  */
547 static void print_array_expression(const array_access_expression_t *expression)
548 {
549         if (!expression->flipped) {
550                 print_expression_prec(expression->array_ref, PREC_POSTFIX);
551                 fputc('[', out);
552                 print_expression(expression->index);
553                 fputc(']', out);
554         } else {
555                 print_expression_prec(expression->index, PREC_POSTFIX);
556                 fputc('[', out);
557                 print_expression(expression->array_ref);
558                 fputc(']', out);
559         }
560 }
561
562 /**
563  * Prints a typeproperty expression (sizeof or __alignof__).
564  *
565  * @param expression   the type property expression
566  */
567 static void print_typeprop_expression(const typeprop_expression_t *expression)
568 {
569         if (expression->base.kind == EXPR_SIZEOF) {
570                 fputs("sizeof", out);
571         } else {
572                 assert(expression->base.kind == EXPR_ALIGNOF);
573                 fputs("__alignof__", out);
574         }
575         if (expression->tp_expression != NULL) {
576                 /* PREC_TOP: always print the '()' here, sizeof x is right but unusual */
577                 print_expression_prec(expression->tp_expression, PREC_TOP);
578         } else {
579                 fputc('(', out);
580                 print_type(expression->type);
581                 fputc(')', out);
582         }
583 }
584
585 /**
586  * Prints a builtin constant expression.
587  *
588  * @param expression   the builtin constant expression
589  */
590 static void print_builtin_constant(const builtin_constant_expression_t *expression)
591 {
592         fputs("__builtin_constant_p(", out);
593         print_assignment_expression(expression->value);
594         fputc(')', out);
595 }
596
597 /**
598  * Prints a builtin types compatible expression.
599  *
600  * @param expression   the builtin types compatible expression
601  */
602 static void print_builtin_types_compatible(
603                 const builtin_types_compatible_expression_t *expression)
604 {
605         fputs("__builtin_types_compatible_p(", out);
606         print_type(expression->left);
607         fputs(", ", out);
608         print_type(expression->right);
609         fputc(')', out);
610 }
611
612 /**
613  * Prints a conditional expression.
614  *
615  * @param expression   the conditional expression
616  */
617 static void print_conditional(const conditional_expression_t *expression)
618 {
619         print_expression_prec(expression->condition, PREC_LOGICAL_OR);
620         if (expression->true_expression != NULL) {
621                 fputs(" ? ", out);
622                 print_expression_prec(expression->true_expression, PREC_EXPRESSION);
623                 fputs(" : ", out);
624         } else {
625                 fputs(" ?: ", out);
626         }
627         precedence_t prec = c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL;
628         print_expression_prec(expression->false_expression, prec);
629 }
630
631 /**
632  * Prints a va_start expression.
633  *
634  * @param expression   the va_start expression
635  */
636 static void print_va_start(const va_start_expression_t *const expression)
637 {
638         fputs("__builtin_va_start(", out);
639         print_assignment_expression(expression->ap);
640         fputs(", ", out);
641         fputs(expression->parameter->base.base.symbol->string, out);
642         fputc(')', out);
643 }
644
645 /**
646  * Prints a va_arg expression.
647  *
648  * @param expression   the va_arg expression
649  */
650 static void print_va_arg(const va_arg_expression_t *expression)
651 {
652         fputs("__builtin_va_arg(", out);
653         print_assignment_expression(expression->ap);
654         fputs(", ", out);
655         print_type(expression->base.type);
656         fputc(')', out);
657 }
658
659 /**
660  * Prints a va_copy expression.
661  *
662  * @param expression   the va_copy expression
663  */
664 static void print_va_copy(const va_copy_expression_t *expression)
665 {
666         fputs("__builtin_va_copy(", out);
667         print_assignment_expression(expression->dst);
668         fputs(", ", out);
669         print_assignment_expression(expression->src);
670         fputc(')', out);
671 }
672
673 /**
674  * Prints a select expression (. or ->).
675  *
676  * @param expression   the select expression
677  */
678 static void print_select(const select_expression_t *expression)
679 {
680         print_expression_prec(expression->compound, PREC_POSTFIX);
681         if (is_type_pointer(skip_typeref(expression->compound->base.type))) {
682                 fputs("->", out);
683         } else {
684                 fputc('.', out);
685         }
686         fputs(expression->compound_entry->base.symbol->string, out);
687 }
688
689 /**
690  * Prints a type classify expression.
691  *
692  * @param expr   the type classify expression
693  */
694 static void print_classify_type_expression(
695         const classify_type_expression_t *const expr)
696 {
697         fputs("__builtin_classify_type(", out);
698         print_assignment_expression(expr->type_expression);
699         fputc(')', out);
700 }
701
702 /**
703  * Prints a designator.
704  *
705  * @param designator  the designator
706  */
707 static void print_designator(const designator_t *designator)
708 {
709         for ( ; designator != NULL; designator = designator->next) {
710                 if (designator->symbol == NULL) {
711                         fputc('[', out);
712                         print_expression(designator->array_index);
713                         fputc(']', out);
714                 } else {
715                         fputc('.', out);
716                         fputs(designator->symbol->string, out);
717                 }
718         }
719 }
720
721 /**
722  * Prints an offsetof expression.
723  *
724  * @param expression   the offset expression
725  */
726 static void print_offsetof_expression(const offsetof_expression_t *expression)
727 {
728         fputs("__builtin_offsetof", out);
729         fputc('(', out);
730         print_type(expression->type);
731         fputc(',', out);
732         print_designator(expression->designator);
733         fputc(')', out);
734 }
735
736 /**
737  * Prints a statement expression.
738  *
739  * @param expression   the statement expression
740  */
741 static void print_statement_expression(const statement_expression_t *expression)
742 {
743         fputc('(', out);
744         print_statement(expression->statement);
745         fputc(')', out);
746 }
747
748 /**
749  * Prints an expression with parenthesis if needed.
750  *
751  * @param expression  the expression to print
752  * @param top_prec    the precedence of the user of this expression.
753  */
754 static void print_expression_prec(const expression_t *expression, unsigned top_prec)
755 {
756         if (expression->kind == EXPR_UNARY_CAST_IMPLICIT && !print_implicit_casts) {
757                 expression = expression->unary.value;
758         }
759
760         bool parenthesized =
761                 expression->base.parenthesized                 ||
762                 (print_parenthesis && top_prec != PREC_BOTTOM) ||
763                 top_prec > get_expression_precedence(expression->base.kind);
764
765         if (parenthesized)
766                 fputc('(', out);
767         switch (expression->kind) {
768         case EXPR_UNKNOWN:
769         case EXPR_INVALID:
770                 fputs("$invalid expression$", out);
771                 break;
772         case EXPR_CHARACTER_CONSTANT:
773                 print_character_constant(&expression->conste);
774                 break;
775         case EXPR_WIDE_CHARACTER_CONSTANT:
776                 print_wide_character_constant(&expression->conste);
777                 break;
778         case EXPR_CONST:
779                 print_const(&expression->conste);
780                 break;
781         case EXPR_FUNCNAME:
782                 print_funcname(&expression->funcname);
783                 break;
784         case EXPR_STRING_LITERAL:
785                 print_string_literal(&expression->string);
786                 break;
787         case EXPR_WIDE_STRING_LITERAL:
788                 print_wide_string_literal(&expression->wide_string);
789                 break;
790         case EXPR_COMPOUND_LITERAL:
791                 print_compound_literal(&expression->compound_literal);
792                 break;
793         case EXPR_CALL:
794                 print_call_expression(&expression->call);
795                 break;
796         EXPR_BINARY_CASES
797                 print_binary_expression(&expression->binary);
798                 break;
799         case EXPR_REFERENCE:
800         case EXPR_REFERENCE_ENUM_VALUE:
801                 print_reference_expression(&expression->reference);
802                 break;
803         case EXPR_ARRAY_ACCESS:
804                 print_array_expression(&expression->array_access);
805                 break;
806         case EXPR_LABEL_ADDRESS:
807                 print_label_address_expression(&expression->label_address);
808                 break;
809         EXPR_UNARY_CASES
810                 print_unary_expression(&expression->unary);
811                 break;
812         case EXPR_SIZEOF:
813         case EXPR_ALIGNOF:
814                 print_typeprop_expression(&expression->typeprop);
815                 break;
816         case EXPR_BUILTIN_CONSTANT_P:
817                 print_builtin_constant(&expression->builtin_constant);
818                 break;
819         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
820                 print_builtin_types_compatible(&expression->builtin_types_compatible);
821                 break;
822         case EXPR_CONDITIONAL:
823                 print_conditional(&expression->conditional);
824                 break;
825         case EXPR_VA_START:
826                 print_va_start(&expression->va_starte);
827                 break;
828         case EXPR_VA_ARG:
829                 print_va_arg(&expression->va_arge);
830                 break;
831         case EXPR_VA_COPY:
832                 print_va_copy(&expression->va_copye);
833                 break;
834         case EXPR_SELECT:
835                 print_select(&expression->select);
836                 break;
837         case EXPR_CLASSIFY_TYPE:
838                 print_classify_type_expression(&expression->classify_type);
839                 break;
840         case EXPR_OFFSETOF:
841                 print_offsetof_expression(&expression->offsetofe);
842                 break;
843         case EXPR_STATEMENT:
844                 print_statement_expression(&expression->statement);
845                 break;
846
847         default:
848                 /* TODO */
849                 fprintf(out, "some expression of type %d", (int)expression->kind);
850                 break;
851         }
852         if (parenthesized)
853                 fputc(')', out);
854 }
855
856 /**
857  * Print an compound statement.
858  *
859  * @param block  the compound statement
860  */
861 static void print_compound_statement(const compound_statement_t *block)
862 {
863         fputs("{\n", out);
864         ++indent;
865
866         statement_t *statement = block->statements;
867         while (statement != NULL) {
868                 if (statement->base.kind == STATEMENT_CASE_LABEL)
869                         --indent;
870                 if (statement->kind != STATEMENT_LABEL)
871                         print_indent();
872                 print_statement(statement);
873
874                 statement = statement->base.next;
875         }
876         --indent;
877         print_indent();
878         fputs(block->stmt_expr ? "}" : "}\n", out);
879 }
880
881 /**
882  * Print a return statement.
883  *
884  * @param statement  the return statement
885  */
886 static void print_return_statement(const return_statement_t *statement)
887 {
888         expression_t const *const val = statement->value;
889         if (val != NULL) {
890                 fputs("return ", out);
891                 print_expression(val);
892                 fputs(";\n", out);
893         } else {
894                 fputs("return;\n", out);
895         }
896 }
897
898 /**
899  * Print an expression statement.
900  *
901  * @param statement  the expression statement
902  */
903 static void print_expression_statement(const expression_statement_t *statement)
904 {
905         print_expression(statement->expression);
906         fputs(";\n", out);
907 }
908
909 /**
910  * Print a goto statement.
911  *
912  * @param statement  the goto statement
913  */
914 static void print_goto_statement(const goto_statement_t *statement)
915 {
916         fputs("goto ", out);
917         if (statement->expression != NULL) {
918                 fputc('*', out);
919                 print_expression(statement->expression);
920         } else {
921                 fputs(statement->label->base.symbol->string, out);
922         }
923         fputs(";\n", out);
924 }
925
926 /**
927  * Print a label statement.
928  *
929  * @param statement  the label statement
930  */
931 static void print_label_statement(const label_statement_t *statement)
932 {
933         fprintf(out, "%s:\n", statement->label->base.symbol->string);
934         print_indent();
935         print_statement(statement->statement);
936 }
937
938 /**
939  * Print an if statement.
940  *
941  * @param statement  the if statement
942  */
943 static void print_if_statement(const if_statement_t *statement)
944 {
945         fputs("if (", out);
946         print_expression(statement->condition);
947         fputs(") ", out);
948         print_statement(statement->true_statement);
949
950         if (statement->false_statement != NULL) {
951                 print_indent();
952                 fputs("else ", out);
953                 print_statement(statement->false_statement);
954         }
955 }
956
957 /**
958  * Print a switch statement.
959  *
960  * @param statement  the switch statement
961  */
962 static void print_switch_statement(const switch_statement_t *statement)
963 {
964         fputs("switch (", out);
965         print_expression(statement->expression);
966         fputs(") ", out);
967         print_statement(statement->body);
968 }
969
970 /**
971  * Print a case label (including the default label).
972  *
973  * @param statement  the case label statement
974  */
975 static void print_case_label(const case_label_statement_t *statement)
976 {
977         if (statement->expression == NULL) {
978                 fputs("default:\n", out);
979         } else {
980                 fputs("case ", out);
981                 print_expression(statement->expression);
982                 if (statement->end_range != NULL) {
983                         fputs(" ... ", out);
984                         print_expression(statement->end_range);
985                 }
986                 fputs(":\n", out);
987         }
988         ++indent;
989         if (statement->statement != NULL) {
990                 if (statement->statement->base.kind == STATEMENT_CASE_LABEL) {
991                         --indent;
992                 }
993                 print_indent();
994                 print_statement(statement->statement);
995         }
996 }
997
998 static void print_typedef(const entity_t *entity)
999 {
1000         fputs("typedef ", out);
1001         print_type_ext(entity->typedefe.type, entity->base.symbol, NULL);
1002         fputc(';', out);
1003 }
1004
1005 /**
1006  * returns true if the entity is a compiler generated one and has no real
1007  * correspondenc in the source file
1008  */
1009 static bool is_generated_entity(const entity_t *entity)
1010 {
1011         if (entity->kind == ENTITY_TYPEDEF)
1012                 return entity->typedefe.builtin;
1013
1014         if (is_declaration(entity))
1015                 return entity->declaration.implicit;
1016
1017         return false;
1018 }
1019
1020 /**
1021  * Print a declaration statement.
1022  *
1023  * @param statement   the statement
1024  */
1025 static void print_declaration_statement(
1026                 const declaration_statement_t *statement)
1027 {
1028         bool first = true;
1029         entity_t *entity = statement->declarations_begin;
1030         if (entity == NULL) {
1031                 fputs("/* empty declaration statement */\n", out);
1032                 return;
1033         }
1034
1035         entity_t *const end = statement->declarations_end->base.next;
1036         for (; entity != end; entity = entity->base.next) {
1037                 if (entity->kind == ENTITY_ENUM_VALUE)
1038                         continue;
1039                 if (is_generated_entity(entity))
1040                         continue;
1041
1042                 if (!first) {
1043                         print_indent();
1044                 } else {
1045                         first = false;
1046                 }
1047
1048                 print_entity(entity);
1049                 fputc('\n', out);
1050         }
1051 }
1052
1053 /**
1054  * Print a while statement.
1055  *
1056  * @param statement   the statement
1057  */
1058 static void print_while_statement(const while_statement_t *statement)
1059 {
1060         fputs("while (", out);
1061         print_expression(statement->condition);
1062         fputs(") ", out);
1063         print_statement(statement->body);
1064 }
1065
1066 /**
1067  * Print a do-while statement.
1068  *
1069  * @param statement   the statement
1070  */
1071 static void print_do_while_statement(const do_while_statement_t *statement)
1072 {
1073         fputs("do ", out);
1074         print_statement(statement->body);
1075         print_indent();
1076         fputs("while (", out);
1077         print_expression(statement->condition);
1078         fputs(");\n", out);
1079 }
1080
1081 /**
1082  * Print a for statement.
1083  *
1084  * @param statement   the statement
1085  */
1086 static void print_for_statement(const for_statement_t *statement)
1087 {
1088         fputs("for (", out);
1089         if (statement->initialisation != NULL) {
1090                 print_expression(statement->initialisation);
1091                 fputc(';', out);
1092         } else {
1093                 entity_t const *entity = statement->scope.entities;
1094                 for (; entity != NULL; entity = entity->base.next) {
1095                         if (is_generated_entity(entity))
1096                                 continue;
1097                         /* FIXME display of multiple declarations is wrong */
1098                         print_declaration(entity);
1099                 }
1100         }
1101         if (statement->condition != NULL) {
1102                 fputc(' ', out);
1103                 print_expression(statement->condition);
1104         }
1105         fputc(';', out);
1106         if (statement->step != NULL) {
1107                 fputc(' ', out);
1108                 print_expression(statement->step);
1109         }
1110         fputs(") ", out);
1111         print_statement(statement->body);
1112 }
1113
1114 /**
1115  * Print assembler arguments.
1116  *
1117  * @param arguments   the arguments
1118  */
1119 static void print_asm_arguments(asm_argument_t *arguments)
1120 {
1121         asm_argument_t *argument = arguments;
1122         for (; argument != NULL; argument = argument->next) {
1123                 if (argument != arguments)
1124                         fputs(", ", out);
1125
1126                 if (argument->symbol) {
1127                         fprintf(out, "[%s] ", argument->symbol->string);
1128                 }
1129                 print_quoted_string(&argument->constraints, '"', 1);
1130                 fputs(" (", out);
1131                 print_expression(argument->expression);
1132                 fputc(')', out);
1133         }
1134 }
1135
1136 /**
1137  * Print assembler clobbers.
1138  *
1139  * @param clobbers   the clobbers
1140  */
1141 static void print_asm_clobbers(asm_clobber_t *clobbers)
1142 {
1143         asm_clobber_t *clobber = clobbers;
1144         for (; clobber != NULL; clobber = clobber->next) {
1145                 if (clobber != clobbers)
1146                         fputs(", ", out);
1147
1148                 print_quoted_string(&clobber->clobber, '"', 1);
1149         }
1150 }
1151
1152 /**
1153  * Print an assembler statement.
1154  *
1155  * @param statement   the statement
1156  */
1157 static void print_asm_statement(const asm_statement_t *statement)
1158 {
1159         fputs("asm ", out);
1160         if (statement->is_volatile) {
1161                 fputs("volatile ", out);
1162         }
1163         fputc('(', out);
1164         print_quoted_string(&statement->asm_text, '"', 1);
1165         if (statement->outputs  == NULL &&
1166             statement->inputs   == NULL &&
1167             statement->clobbers == NULL)
1168                 goto end_of_print_asm_statement;
1169
1170         fputs(" : ", out);
1171         print_asm_arguments(statement->outputs);
1172         if (statement->inputs == NULL && statement->clobbers == NULL)
1173                 goto end_of_print_asm_statement;
1174
1175         fputs(" : ", out);
1176         print_asm_arguments(statement->inputs);
1177         if (statement->clobbers == NULL)
1178                 goto end_of_print_asm_statement;
1179
1180         fputs(" : ", out);
1181         print_asm_clobbers(statement->clobbers);
1182
1183 end_of_print_asm_statement:
1184         fputs(");\n", out);
1185 }
1186
1187 /**
1188  * Print a microsoft __try statement.
1189  *
1190  * @param statement   the statement
1191  */
1192 static void print_ms_try_statement(const ms_try_statement_t *statement)
1193 {
1194         fputs("__try ", out);
1195         print_statement(statement->try_statement);
1196         print_indent();
1197         if (statement->except_expression != NULL) {
1198                 fputs("__except(", out);
1199                 print_expression(statement->except_expression);
1200                 fputs(") ", out);
1201         } else {
1202                 fputs("__finally ", out);
1203         }
1204         print_statement(statement->final_statement);
1205 }
1206
1207 /**
1208  * Print a microsoft __leave statement.
1209  *
1210  * @param statement   the statement
1211  */
1212 static void print_leave_statement(const leave_statement_t *statement)
1213 {
1214         (void)statement;
1215         fputs("__leave;\n", out);
1216 }
1217
1218 /**
1219  * Print a statement.
1220  *
1221  * @param statement   the statement
1222  */
1223 void print_statement(const statement_t *statement)
1224 {
1225         switch (statement->kind) {
1226         case STATEMENT_EMPTY:
1227                 fputs(";\n", out);
1228                 break;
1229         case STATEMENT_COMPOUND:
1230                 print_compound_statement(&statement->compound);
1231                 break;
1232         case STATEMENT_RETURN:
1233                 print_return_statement(&statement->returns);
1234                 break;
1235         case STATEMENT_EXPRESSION:
1236                 print_expression_statement(&statement->expression);
1237                 break;
1238         case STATEMENT_LABEL:
1239                 print_label_statement(&statement->label);
1240                 break;
1241         case STATEMENT_GOTO:
1242                 print_goto_statement(&statement->gotos);
1243                 break;
1244         case STATEMENT_CONTINUE:
1245                 fputs("continue;\n", out);
1246                 break;
1247         case STATEMENT_BREAK:
1248                 fputs("break;\n", out);
1249                 break;
1250         case STATEMENT_IF:
1251                 print_if_statement(&statement->ifs);
1252                 break;
1253         case STATEMENT_SWITCH:
1254                 print_switch_statement(&statement->switchs);
1255                 break;
1256         case STATEMENT_CASE_LABEL:
1257                 print_case_label(&statement->case_label);
1258                 break;
1259         case STATEMENT_DECLARATION:
1260                 print_declaration_statement(&statement->declaration);
1261                 break;
1262         case STATEMENT_WHILE:
1263                 print_while_statement(&statement->whiles);
1264                 break;
1265         case STATEMENT_DO_WHILE:
1266                 print_do_while_statement(&statement->do_while);
1267                 break;
1268         case STATEMENT_FOR:
1269                 print_for_statement(&statement->fors);
1270                 break;
1271         case STATEMENT_ASM:
1272                 print_asm_statement(&statement->asms);
1273                 break;
1274         case STATEMENT_MS_TRY:
1275                 print_ms_try_statement(&statement->ms_try);
1276                 break;
1277         case STATEMENT_LEAVE:
1278                 print_leave_statement(&statement->leave);
1279                 break;
1280         case STATEMENT_INVALID:
1281                 fputs("$invalid statement$\n", out);
1282                 break;
1283         }
1284 }
1285
1286 /**
1287  * Print a storage class.
1288  *
1289  * @param storage_class   the storage class
1290  */
1291 static void print_storage_class(storage_class_tag_t storage_class)
1292 {
1293         switch (storage_class) {
1294         case STORAGE_CLASS_NONE:     return;
1295         case STORAGE_CLASS_TYPEDEF:  fputs("typedef ",  out); return;
1296         case STORAGE_CLASS_EXTERN:   fputs("extern ",   out); return;
1297         case STORAGE_CLASS_STATIC:   fputs("static ",   out); return;
1298         case STORAGE_CLASS_AUTO:     fputs("auto ",     out); return;
1299         case STORAGE_CLASS_REGISTER: fputs("register ", out); return;
1300         }
1301         panic("invalid storage class");
1302 }
1303
1304 /**
1305  * Print an initializer.
1306  *
1307  * @param initializer  the initializer
1308  */
1309 void print_initializer(const initializer_t *initializer)
1310 {
1311         if (initializer == NULL) {
1312                 fputs("{}", out);
1313                 return;
1314         }
1315
1316         switch (initializer->kind) {
1317         case INITIALIZER_VALUE: {
1318                 const initializer_value_t *value = &initializer->value;
1319                 print_assignment_expression(value->value);
1320                 return;
1321         }
1322         case INITIALIZER_LIST: {
1323                 assert(initializer->kind == INITIALIZER_LIST);
1324                 fputs("{ ", out);
1325                 const initializer_list_t *list = &initializer->list;
1326
1327                 for (size_t i = 0 ; i < list->len; ++i) {
1328                         const initializer_t *sub_init = list->initializers[i];
1329                         print_initializer(list->initializers[i]);
1330                         if (i < list->len-1) {
1331                                 if (sub_init == NULL || sub_init->kind != INITIALIZER_DESIGNATOR)
1332                                         fputs(", ", out);
1333                         }
1334                 }
1335                 fputs(" }", out);
1336                 return;
1337         }
1338         case INITIALIZER_STRING:
1339                 print_quoted_string(&initializer->string.string, '"', 1);
1340                 return;
1341         case INITIALIZER_WIDE_STRING:
1342                 print_quoted_wide_string(&initializer->wide_string.string, '"', 1);
1343                 return;
1344         case INITIALIZER_DESIGNATOR:
1345                 print_designator(initializer->designator.designator);
1346                 fputs(" = ", out);
1347                 return;
1348         }
1349
1350         panic("invalid initializer kind found");
1351 }
1352
1353 /**
1354  * Print microsoft extended declaration modifiers.
1355  */
1356 static void print_ms_modifiers(const declaration_t *declaration)
1357 {
1358         if ((c_mode & _MS) == 0)
1359                 return;
1360
1361         decl_modifiers_t modifiers = declaration->modifiers;
1362
1363         bool        ds_shown = false;
1364         const char *next     = "(";
1365
1366         if (declaration->base.kind == ENTITY_VARIABLE) {
1367                 variable_t *variable = (variable_t*)declaration;
1368                 if (variable->alignment != 0
1369                                 || variable->get_property_sym != NULL
1370                                 || variable->put_property_sym != NULL) {
1371                         if (!ds_shown) {
1372                                 fputs("__declspec", out);
1373                                 ds_shown = true;
1374                         }
1375
1376                         if (variable->alignment != 0) {
1377                                 fputs(next, out); next = ", "; fprintf(out, "align(%u)", variable->alignment);
1378                         }
1379                         if (variable->get_property_sym != NULL
1380                                         || variable->put_property_sym != NULL) {
1381                                 char *comma = "";
1382                                 fputs(next, out); next = ", "; fputs("property(", out);
1383                                 if (variable->get_property_sym != NULL) {
1384                                         fprintf(out, "get=%s", variable->get_property_sym->string);
1385                                         comma = ", ";
1386                                 }
1387                                 if (variable->put_property_sym != NULL)
1388                                         fprintf(out, "%sput=%s", comma, variable->put_property_sym->string);
1389                                 fputc(')', out);
1390                         }
1391                 }
1392         }
1393
1394         /* DM_FORCEINLINE handled outside. */
1395         if ((modifiers & ~DM_FORCEINLINE) != 0) {
1396                 if (!ds_shown) {
1397                         fputs("__declspec", out);
1398                         ds_shown = true;
1399                 }
1400                 if (modifiers & DM_DLLIMPORT) {
1401                         fputs(next, out); next = ", "; fputs("dllimport", out);
1402                 }
1403                 if (modifiers & DM_DLLEXPORT) {
1404                         fputs(next, out); next = ", "; fputs("dllexport", out);
1405                 }
1406                 if (modifiers & DM_THREAD) {
1407                         fputs(next, out); next = ", "; fputs("thread", out);
1408                 }
1409                 if (modifiers & DM_NAKED) {
1410                         fputs(next, out); next = ", "; fputs("naked", out);
1411                 }
1412                 if (modifiers & DM_THREAD) {
1413                         fputs(next, out); next = ", "; fputs("thread", out);
1414                 }
1415                 if (modifiers & DM_SELECTANY) {
1416                         fputs(next, out); next = ", "; fputs("selectany", out);
1417                 }
1418                 if (modifiers & DM_NOTHROW) {
1419                         fputs(next, out); next = ", "; fputs("nothrow", out);
1420                 }
1421                 if (modifiers & DM_NORETURN) {
1422                         fputs(next, out); next = ", "; fputs("noreturn", out);
1423                 }
1424                 if (modifiers & DM_NOINLINE) {
1425                         fputs(next, out); next = ", "; fputs("noinline", out);
1426                 }
1427                 if (modifiers & DM_DEPRECATED) {
1428                         fputs(next, out); next = ", "; fputs("deprecated", out);
1429                         if (declaration->deprecated_string != NULL)
1430                                 fprintf(out, "(\"%s\")",
1431                                         declaration->deprecated_string);
1432                 }
1433                 if (modifiers & DM_RESTRICT) {
1434                         fputs(next, out); next = ", "; fputs("restrict", out);
1435                 }
1436                 if (modifiers & DM_NOALIAS) {
1437                         fputs(next, out); next = ", "; fputs("noalias", out);
1438                 }
1439         }
1440
1441         if (ds_shown)
1442                 fputs(") ", out);
1443 }
1444
1445 static void print_scope(const scope_t *scope)
1446 {
1447         const entity_t *entity = scope->entities;
1448         for ( ; entity != NULL; entity = entity->base.next) {
1449                 print_indent();
1450                 print_entity(entity);
1451                 fputs("\n", out);
1452         }
1453 }
1454
1455 static void print_namespace(const namespace_t *namespace)
1456 {
1457         fputs("namespace ", out);
1458         if (namespace->base.symbol != NULL) {
1459                 fputs(namespace->base.symbol->string, out);
1460                 fputc(' ', out);
1461         }
1462
1463         fputs("{\n", out);
1464         ++indent;
1465
1466         print_scope(&namespace->members);
1467
1468         --indent;
1469         print_indent();
1470         fputs("}\n", out);
1471 }
1472
1473 /**
1474  * Print a variable or function declaration
1475  */
1476 void print_declaration(const entity_t *entity)
1477 {
1478         assert(is_declaration(entity));
1479         const declaration_t *declaration = &entity->declaration;
1480
1481         print_storage_class((storage_class_tag_t)declaration->declared_storage_class);
1482         if (entity->kind == ENTITY_FUNCTION) {
1483                 function_t *function = (function_t*)declaration;
1484                 if (function->is_inline) {
1485                         if (declaration->modifiers & DM_FORCEINLINE) {
1486                                 fputs("__forceinline ", out);
1487                         } else if (declaration->modifiers & DM_MICROSOFT_INLINE) {
1488                                 fputs("__inline ", out);
1489                         } else {
1490                                 fputs("inline ", out);
1491                         }
1492                 }
1493         }
1494         print_ms_modifiers(declaration);
1495         switch (entity->kind) {
1496                 case ENTITY_FUNCTION:
1497                         print_type_ext(entity->declaration.type, entity->base.symbol,
1498                                         &entity->function.parameters);
1499
1500                         if (entity->function.statement != NULL) {
1501                                 fputc('\n', out);
1502                                 print_indent();
1503                                 print_statement(entity->function.statement);
1504                                 return;
1505                         }
1506                         break;
1507
1508                 case ENTITY_VARIABLE:
1509                         if (entity->variable.thread_local)
1510                                 fputs("__thread ", out);
1511                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1512                         if (entity->variable.initializer != NULL) {
1513                                 fputs(" = ", out);
1514                                 print_initializer(entity->variable.initializer);
1515                         }
1516                         break;
1517
1518                 default:
1519                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1520                         break;
1521         }
1522         fputc(';', out);
1523 }
1524
1525 /**
1526  * Prints an expression.
1527  *
1528  * @param expression  the expression
1529  */
1530 void print_expression(const expression_t *expression)
1531 {
1532         print_expression_prec(expression, PREC_BOTTOM);
1533 }
1534
1535 /**
1536  * Print a declaration.
1537  *
1538  * @param declaration  the declaration
1539  */
1540 void print_entity(const entity_t *entity)
1541 {
1542         if (entity->base.namespc != NAMESPACE_NORMAL && entity->base.symbol == NULL)
1543                 return;
1544
1545         switch ((entity_kind_tag_t)entity->kind) {
1546         case ENTITY_VARIABLE:
1547         case ENTITY_PARAMETER:
1548         case ENTITY_COMPOUND_MEMBER:
1549         case ENTITY_FUNCTION:
1550                 print_declaration(entity);
1551                 return;
1552         case ENTITY_TYPEDEF:
1553                 print_typedef(entity);
1554                 return;
1555         case ENTITY_STRUCT:
1556                 fputs("struct ", out);
1557                 fputs(entity->base.symbol->string, out);
1558                 if (entity->structe.complete) {
1559                         fputc(' ', out);
1560                         print_compound_definition(&entity->structe);
1561                 }
1562                 fputc(';', out);
1563                 return;
1564         case ENTITY_UNION:
1565                 fputs("union ", out);
1566                 fputs(entity->base.symbol->string, out);
1567                 if (entity->unione.complete) {
1568                         fputc(' ', out);
1569                         print_compound_definition(&entity->unione);
1570                 }
1571                 fputc(';', out);
1572                 return;
1573         case ENTITY_ENUM:
1574                 fputs("enum ", out);
1575                 fputs(entity->base.symbol->string, out);
1576                 fputc(' ', out);
1577                 print_enum_definition(&entity->enume);
1578                 fputc(';', out);
1579                 return;
1580         case ENTITY_NAMESPACE:
1581                 print_namespace(&entity->namespacee);
1582                 return;
1583         case ENTITY_LOCAL_LABEL:
1584                 fprintf(out, "__label__ %s;", entity->base.symbol->string);
1585                 return;
1586         case ENTITY_LABEL:
1587         case ENTITY_ENUM_VALUE:
1588                 panic("print_entity used on unexpected entity type");
1589         case ENTITY_INVALID:
1590                 break;
1591         }
1592         panic("Invalid entity type encountered");
1593 }
1594
1595 /**
1596  * Print the AST of a translation unit.
1597  *
1598  * @param unit   the translation unit
1599  */
1600 void print_ast(const translation_unit_t *unit)
1601 {
1602         inc_type_visited();
1603
1604         entity_t *entity = unit->scope.entities;
1605         for ( ; entity != NULL; entity = entity->base.next) {
1606                 if (entity->kind == ENTITY_ENUM_VALUE)
1607                         continue;
1608                 if (entity->base.namespc != NAMESPACE_NORMAL
1609                                 && entity->base.symbol == NULL)
1610                         continue;
1611                 if (is_generated_entity(entity))
1612                         continue;
1613
1614                 print_indent();
1615                 print_entity(entity);
1616                 fputc('\n', out);
1617         }
1618 }
1619
1620 bool is_constant_initializer(const initializer_t *initializer)
1621 {
1622         switch (initializer->kind) {
1623         case INITIALIZER_STRING:
1624         case INITIALIZER_WIDE_STRING:
1625         case INITIALIZER_DESIGNATOR:
1626                 return true;
1627
1628         case INITIALIZER_VALUE:
1629                 return is_constant_expression(initializer->value.value);
1630
1631         case INITIALIZER_LIST:
1632                 for (size_t i = 0; i < initializer->list.len; ++i) {
1633                         initializer_t *sub_initializer = initializer->list.initializers[i];
1634                         if (!is_constant_initializer(sub_initializer))
1635                                 return false;
1636                 }
1637                 return true;
1638         }
1639         panic("invalid initializer kind found");
1640 }
1641
1642 static bool is_object_with_linker_constant_address(const expression_t *expression)
1643 {
1644         switch (expression->kind) {
1645         case EXPR_UNARY_DEREFERENCE:
1646                 return is_address_constant(expression->unary.value);
1647
1648         case EXPR_SELECT: {
1649                 type_t *base_type = skip_typeref(expression->select.compound->base.type);
1650                 if (is_type_pointer(base_type)) {
1651                         /* it's a -> */
1652                         return is_address_constant(expression->select.compound);
1653                 } else {
1654                         return is_object_with_linker_constant_address(expression->select.compound);
1655                 }
1656         }
1657
1658         case EXPR_ARRAY_ACCESS:
1659                 return is_constant_expression(expression->array_access.index)
1660                         && is_address_constant(expression->array_access.array_ref);
1661
1662         case EXPR_REFERENCE: {
1663                 entity_t *entity = expression->reference.entity;
1664                 if (is_declaration(entity)) {
1665                         switch ((storage_class_tag_t)entity->declaration.storage_class) {
1666                         case STORAGE_CLASS_NONE:
1667                         case STORAGE_CLASS_EXTERN:
1668                         case STORAGE_CLASS_STATIC:
1669                                 return
1670                                         entity->kind != ENTITY_VARIABLE ||
1671                                         !entity->variable.thread_local;
1672
1673                         case STORAGE_CLASS_REGISTER:
1674                         case STORAGE_CLASS_TYPEDEF:
1675                         case STORAGE_CLASS_AUTO:
1676                                 break;
1677                         }
1678                 }
1679                 return false;
1680         }
1681
1682         default:
1683                 return false;
1684         }
1685 }
1686
1687 bool is_address_constant(const expression_t *expression)
1688 {
1689         switch (expression->kind) {
1690         case EXPR_UNARY_TAKE_ADDRESS:
1691                 return is_object_with_linker_constant_address(expression->unary.value);
1692
1693         case EXPR_UNARY_DEREFERENCE: {
1694                 type_t *real_type
1695                         = revert_automatic_type_conversion(expression->unary.value);
1696                 /* dereferencing a function is a NOP */
1697                 if (is_type_function(real_type)) {
1698                         return is_address_constant(expression->unary.value);
1699                 }
1700                 /* FALLTHROUGH */
1701         }
1702
1703         case EXPR_UNARY_CAST: {
1704                 type_t *dest = skip_typeref(expression->base.type);
1705                 if (!is_type_pointer(dest) && (
1706                         dest->kind != TYPE_ATOMIC                                               ||
1707                         !(get_atomic_type_flags(dest->atomic.akind) & ATOMIC_TYPE_FLAG_INTEGER) ||
1708                         get_atomic_type_size(dest->atomic.akind) < get_atomic_type_size(get_intptr_kind())
1709                     ))
1710                         return false;
1711
1712                 return (is_constant_expression(expression->unary.value)
1713                         || is_address_constant(expression->unary.value));
1714         }
1715
1716         case EXPR_BINARY_ADD:
1717         case EXPR_BINARY_SUB: {
1718                 expression_t *left  = expression->binary.left;
1719                 expression_t *right = expression->binary.right;
1720
1721                 if (is_type_pointer(skip_typeref(left->base.type))) {
1722                         return is_address_constant(left) && is_constant_expression(right);
1723                 } else if (is_type_pointer(skip_typeref(right->base.type))) {
1724                         return is_constant_expression(left)     && is_address_constant(right);
1725                 }
1726
1727                 return false;
1728         }
1729
1730         case EXPR_REFERENCE: {
1731                 entity_t *entity = expression->reference.entity;
1732                 if (!is_declaration(entity))
1733                         return false;
1734
1735                 type_t *type = skip_typeref(entity->declaration.type);
1736                 if (is_type_function(type))
1737                         return true;
1738                 if (is_type_array(type)) {
1739                         return is_object_with_linker_constant_address(expression);
1740                 }
1741                 /* Prevent stray errors */
1742                 if (!is_type_valid(type))
1743                         return true;
1744                 return false;
1745         }
1746
1747         case EXPR_ARRAY_ACCESS: {
1748                 type_t *const type =
1749                         skip_typeref(revert_automatic_type_conversion(expression));
1750                 return
1751                         is_type_array(type)                                    &&
1752                         is_constant_expression(expression->array_access.index) &&
1753                         is_address_constant(expression->array_access.array_ref);
1754         }
1755
1756         default:
1757                 return false;
1758         }
1759 }
1760
1761 /**
1762  * Check if the given expression is a call to a builtin function
1763  * returning a constant result.
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_REFERENCE)
1769                 return false;
1770         reference_expression_t *ref = &function->reference;
1771         if (ref->entity->kind != ENTITY_FUNCTION)
1772                 return false;
1773
1774         switch (ref->entity->function.btk) {
1775         case bk_gnu_builtin_huge_val:
1776         case bk_gnu_builtin_inf:
1777         case bk_gnu_builtin_inff:
1778         case bk_gnu_builtin_infl:
1779         case bk_gnu_builtin_nan:
1780         case bk_gnu_builtin_nanf:
1781         case bk_gnu_builtin_nanl:
1782                 return true;
1783         default:
1784                 return false;
1785         }
1786
1787 }
1788
1789 static bool is_constant_pointer(const expression_t *expression)
1790 {
1791         if (is_constant_expression(expression))
1792                 return true;
1793
1794         switch (expression->kind) {
1795         case EXPR_UNARY_CAST:
1796                 return is_constant_pointer(expression->unary.value);
1797         default:
1798                 return false;
1799         }
1800 }
1801
1802 static bool is_object_with_constant_address(const expression_t *expression)
1803 {
1804         switch (expression->kind) {
1805         case EXPR_SELECT: {
1806                 expression_t *compound      = expression->select.compound;
1807                 type_t       *compound_type = compound->base.type;
1808                 compound_type = skip_typeref(compound_type);
1809                 if (is_type_pointer(compound_type)) {
1810                         return is_constant_pointer(compound);
1811                 } else {
1812                         return is_object_with_constant_address(compound);
1813                 }
1814         }
1815
1816         case EXPR_ARRAY_ACCESS: {
1817                 array_access_expression_t const* const array_access =
1818                         &expression->array_access;
1819                 return
1820                         is_constant_expression(array_access->index) && (
1821                                 is_object_with_constant_address(array_access->array_ref) ||
1822                                 is_constant_pointer(array_access->array_ref)
1823                         );
1824         }
1825
1826         case EXPR_UNARY_DEREFERENCE:
1827                 return is_constant_pointer(expression->unary.value);
1828         default:
1829                 return false;
1830         }
1831 }
1832
1833 bool is_constant_expression(const expression_t *expression)
1834 {
1835         switch (expression->kind) {
1836
1837         case EXPR_CONST:
1838         case EXPR_CHARACTER_CONSTANT:
1839         case EXPR_WIDE_CHARACTER_CONSTANT:
1840         case EXPR_STRING_LITERAL:
1841         case EXPR_WIDE_STRING_LITERAL:
1842         case EXPR_CLASSIFY_TYPE:
1843         case EXPR_FUNCNAME:
1844         case EXPR_OFFSETOF:
1845         case EXPR_ALIGNOF:
1846         case EXPR_BUILTIN_CONSTANT_P:
1847         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1848         case EXPR_LABEL_ADDRESS:
1849         case EXPR_REFERENCE_ENUM_VALUE:
1850                 return true;
1851
1852         case EXPR_SIZEOF: {
1853                 type_t *type = expression->typeprop.type;
1854                 if (type == NULL)
1855                         type = expression->typeprop.tp_expression->base.type;
1856
1857                 type = skip_typeref(type);
1858                 if (is_type_array(type) && type->array.is_vla)
1859                         return false;
1860                 return true;
1861         }
1862
1863         case EXPR_SELECT:
1864         case EXPR_VA_START:
1865         case EXPR_VA_ARG:
1866         case EXPR_VA_COPY:
1867         case EXPR_STATEMENT:
1868         case EXPR_REFERENCE:
1869         case EXPR_UNARY_POSTFIX_INCREMENT:
1870         case EXPR_UNARY_POSTFIX_DECREMENT:
1871         case EXPR_UNARY_PREFIX_INCREMENT:
1872         case EXPR_UNARY_PREFIX_DECREMENT:
1873         case EXPR_UNARY_ASSUME: /* has VOID type */
1874         case EXPR_UNARY_DEREFERENCE:
1875         case EXPR_UNARY_DELETE:
1876         case EXPR_UNARY_DELETE_ARRAY:
1877         case EXPR_UNARY_THROW:
1878         case EXPR_BINARY_ASSIGN:
1879         case EXPR_BINARY_MUL_ASSIGN:
1880         case EXPR_BINARY_DIV_ASSIGN:
1881         case EXPR_BINARY_MOD_ASSIGN:
1882         case EXPR_BINARY_ADD_ASSIGN:
1883         case EXPR_BINARY_SUB_ASSIGN:
1884         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1885         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1886         case EXPR_BINARY_BITWISE_AND_ASSIGN:
1887         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1888         case EXPR_BINARY_BITWISE_OR_ASSIGN:
1889         case EXPR_BINARY_COMMA:
1890         case EXPR_ARRAY_ACCESS:
1891                 return false;
1892
1893         case EXPR_UNARY_TAKE_ADDRESS:
1894                 return is_object_with_constant_address(expression->unary.value);
1895
1896         case EXPR_CALL:
1897                 return is_builtin_const_call(expression);
1898
1899         case EXPR_UNARY_NEGATE:
1900         case EXPR_UNARY_PLUS:
1901         case EXPR_UNARY_BITWISE_NEGATE:
1902         case EXPR_UNARY_NOT:
1903                 return is_constant_expression(expression->unary.value);
1904
1905         case EXPR_UNARY_CAST:
1906         case EXPR_UNARY_CAST_IMPLICIT:
1907                 return is_type_arithmetic(skip_typeref(expression->base.type))
1908                         && is_constant_expression(expression->unary.value);
1909
1910         case EXPR_BINARY_ADD:
1911         case EXPR_BINARY_SUB:
1912         case EXPR_BINARY_MUL:
1913         case EXPR_BINARY_DIV:
1914         case EXPR_BINARY_MOD:
1915         case EXPR_BINARY_EQUAL:
1916         case EXPR_BINARY_NOTEQUAL:
1917         case EXPR_BINARY_LESS:
1918         case EXPR_BINARY_LESSEQUAL:
1919         case EXPR_BINARY_GREATER:
1920         case EXPR_BINARY_GREATEREQUAL:
1921         case EXPR_BINARY_BITWISE_AND:
1922         case EXPR_BINARY_BITWISE_OR:
1923         case EXPR_BINARY_BITWISE_XOR:
1924         case EXPR_BINARY_SHIFTLEFT:
1925         case EXPR_BINARY_SHIFTRIGHT:
1926         case EXPR_BINARY_ISGREATER:
1927         case EXPR_BINARY_ISGREATEREQUAL:
1928         case EXPR_BINARY_ISLESS:
1929         case EXPR_BINARY_ISLESSEQUAL:
1930         case EXPR_BINARY_ISLESSGREATER:
1931         case EXPR_BINARY_ISUNORDERED:
1932                 return is_constant_expression(expression->binary.left)
1933                         && is_constant_expression(expression->binary.right);
1934
1935         case EXPR_BINARY_LOGICAL_AND: {
1936                 expression_t const *const left = expression->binary.left;
1937                 if (!is_constant_expression(left))
1938                         return false;
1939                 if (fold_constant(left) == 0)
1940                         return true;
1941                 return is_constant_expression(expression->binary.right);
1942         }
1943
1944         case EXPR_BINARY_LOGICAL_OR: {
1945                 expression_t const *const left = expression->binary.left;
1946                 if (!is_constant_expression(left))
1947                         return false;
1948                 if (fold_constant(left) != 0)
1949                         return true;
1950                 return is_constant_expression(expression->binary.right);
1951         }
1952
1953         case EXPR_COMPOUND_LITERAL:
1954                 return is_constant_initializer(expression->compound_literal.initializer);
1955
1956         case EXPR_CONDITIONAL: {
1957                 expression_t *condition = expression->conditional.condition;
1958                 if (!is_constant_expression(condition))
1959                         return false;
1960
1961                 long val = fold_constant(condition);
1962                 if (val != 0) {
1963                         expression_t const *const t = expression->conditional.true_expression;
1964                         return t == NULL || is_constant_expression(t);
1965                 } else {
1966                         return is_constant_expression(expression->conditional.false_expression);
1967                 }
1968         }
1969
1970         case EXPR_INVALID:
1971                 return true;
1972
1973         case EXPR_UNKNOWN:
1974                 break;
1975         }
1976         panic("invalid expression found (is constant expression)");
1977 }
1978
1979 /**
1980  * Initialize the AST construction.
1981  */
1982 void init_ast(void)
1983 {
1984         obstack_init(&ast_obstack);
1985 }
1986
1987 /**
1988  * Free the AST.
1989  */
1990 void exit_ast(void)
1991 {
1992         obstack_free(&ast_obstack, NULL);
1993 }
1994
1995 /**
1996  * Set the output stream for the AST printer.
1997  *
1998  * @param stream  the output stream
1999  */
2000 void ast_set_output(FILE *stream)
2001 {
2002         out = stream;
2003         type_set_output(stream);
2004 }
2005
2006 /**
2007  * Allocate an AST object of the given size.
2008  *
2009  * @param size  the size of the object to allocate
2010  *
2011  * @return  A new allocated object in the AST memeory space.
2012  */
2013 void *(allocate_ast)(size_t size)
2014 {
2015         return _allocate_ast(size);
2016 }