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