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