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