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