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