- implemented GNU ?: operator (no ast2firm support yet
[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         if (expression->true_expression != NULL) {
592                 print_expression_prec(expression->true_expression, prec);
593                 fputs(" : ", out);
594         } else {
595                 fputs(": ", out);
596         }
597         print_expression_prec(expression->false_expression, prec);
598         fputs(")", out);
599 }
600
601 /**
602  * Prints a va_start expression.
603  *
604  * @param expression   the va_start expression
605  */
606 static void print_va_start(const va_start_expression_t *const expression)
607 {
608         fputs("__builtin_va_start(", out);
609         print_expression_prec(expression->ap, PREC_COMMA + 1);
610         fputs(", ", out);
611         fputs(expression->parameter->symbol->string, out);
612         fputs(")", out);
613 }
614
615 /**
616  * Prints a va_arg expression.
617  *
618  * @param expression   the va_arg expression
619  */
620 static void print_va_arg(const va_arg_expression_t *expression)
621 {
622         fputs("__builtin_va_arg(", out);
623         print_expression_prec(expression->ap, PREC_COMMA + 1);
624         fputs(", ", out);
625         print_type(expression->base.type);
626         fputs(")", out);
627 }
628
629 /**
630  * Prints a select expression (. or ->).
631  *
632  * @param expression   the select expression
633  */
634 static void print_select(const select_expression_t *expression)
635 {
636         unsigned prec = get_expression_precedence(expression->base.kind);
637         print_expression_prec(expression->compound, prec);
638         if(is_type_pointer(skip_typeref(expression->compound->base.type))) {
639                 fputs("->", out);
640         } else {
641                 fputc('.', out);
642         }
643         fputs(expression->symbol->string, out);
644 }
645
646 /**
647  * Prints a type classify expression.
648  *
649  * @param expr   the type classify expression
650  */
651 static void print_classify_type_expression(
652         const classify_type_expression_t *const expr)
653 {
654         fputs("__builtin_classify_type(", out);
655         print_expression_prec(expr->type_expression, PREC_COMMA + 1);
656         fputc(')', out);
657 }
658
659 /**
660  * Prints a designator.
661  *
662  * @param designator  the designator
663  */
664 static void print_designator(const designator_t *designator)
665 {
666         for ( ; designator != NULL; designator = designator->next) {
667                 if (designator->symbol == NULL) {
668                         fputc('[', out);
669                         print_expression_prec(designator->array_index, PREC_BOTTOM);
670                         fputc(']', out);
671                 } else {
672                         fputc('.', out);
673                         fputs(designator->symbol->string, out);
674                 }
675         }
676 }
677
678 /**
679  * Prints an offsetof expression.
680  *
681  * @param expression   the offset expression
682  */
683 static void print_offsetof_expression(const offsetof_expression_t *expression)
684 {
685         fputs("__builtin_offsetof", out);
686         fputc('(', out);
687         print_type(expression->type);
688         fputc(',', out);
689         print_designator(expression->designator);
690         fputc(')', out);
691 }
692
693 /**
694  * Prints a statement expression.
695  *
696  * @param expression   the statement expression
697  */
698 static void print_statement_expression(const statement_expression_t *expression)
699 {
700         fputc('(', out);
701         print_statement(expression->statement);
702         fputc(')', out);
703 }
704
705 /**
706  * Prints an expression with parenthesis if needed.
707  *
708  * @param expression  the expression to print
709  * @param top_prec    the precedence of the user of this expression.
710  */
711 static void print_expression_prec(const expression_t *expression, unsigned top_prec)
712 {
713         if (expression->kind == EXPR_UNARY_CAST_IMPLICIT && !print_implicit_casts) {
714                 expression = expression->unary.value;
715         }
716         unsigned prec = get_expression_precedence(expression->base.kind);
717         if (print_parenthesis && top_prec != PREC_BOTTOM)
718                 top_prec = PREC_TOP;
719         if (top_prec > prec)
720                 fputc('(', out);
721         switch(expression->kind) {
722         case EXPR_UNKNOWN:
723         case EXPR_INVALID:
724                 fprintf(out, "$invalid expression$");
725                 break;
726         case EXPR_CHARACTER_CONSTANT:
727                 print_character_constant(&expression->conste);
728                 break;
729         case EXPR_WIDE_CHARACTER_CONSTANT:
730                 print_wide_character_constant(&expression->conste);
731                 break;
732         case EXPR_CONST:
733                 print_const(&expression->conste);
734                 break;
735         case EXPR_FUNCNAME:
736                 print_funcname(&expression->funcname);
737                 break;
738         case EXPR_STRING_LITERAL:
739                 print_string_literal(&expression->string);
740                 break;
741         case EXPR_WIDE_STRING_LITERAL:
742                 print_wide_string_literal(&expression->wide_string);
743                 break;
744         case EXPR_COMPOUND_LITERAL:
745                 print_compound_literal(&expression->compound_literal);
746                 break;
747         case EXPR_CALL:
748                 print_call_expression(&expression->call);
749                 break;
750         EXPR_BINARY_CASES
751                 print_binary_expression(&expression->binary);
752                 break;
753         case EXPR_REFERENCE:
754                 print_reference_expression(&expression->reference);
755                 break;
756         case EXPR_ARRAY_ACCESS:
757                 print_array_expression(&expression->array_access);
758                 break;
759         EXPR_UNARY_CASES
760                 print_unary_expression(&expression->unary);
761                 break;
762         case EXPR_SIZEOF:
763         case EXPR_ALIGNOF:
764                 print_typeprop_expression(&expression->typeprop);
765                 break;
766         case EXPR_BUILTIN_SYMBOL:
767                 print_builtin_symbol(&expression->builtin_symbol);
768                 break;
769         case EXPR_BUILTIN_CONSTANT_P:
770                 print_builtin_constant(&expression->builtin_constant);
771                 break;
772         case EXPR_BUILTIN_PREFETCH:
773                 print_builtin_prefetch(&expression->builtin_prefetch);
774                 break;
775         case EXPR_CONDITIONAL:
776                 print_conditional(&expression->conditional);
777                 break;
778         case EXPR_VA_START:
779                 print_va_start(&expression->va_starte);
780                 break;
781         case EXPR_VA_ARG:
782                 print_va_arg(&expression->va_arge);
783                 break;
784         case EXPR_SELECT:
785                 print_select(&expression->select);
786                 break;
787         case EXPR_CLASSIFY_TYPE:
788                 print_classify_type_expression(&expression->classify_type);
789                 break;
790         case EXPR_OFFSETOF:
791                 print_offsetof_expression(&expression->offsetofe);
792                 break;
793         case EXPR_STATEMENT:
794                 print_statement_expression(&expression->statement);
795                 break;
796
797         default:
798                 /* TODO */
799                 fprintf(out, "some expression of type %d", (int) expression->kind);
800                 break;
801         }
802         if (top_prec > prec)
803                 fputc(')', out);
804 }
805
806 /**
807  * Print an compound statement.
808  *
809  * @param block  the compound statement
810  */
811 static void print_compound_statement(const compound_statement_t *block)
812 {
813         fputs("{\n", out);
814         ++indent;
815
816         statement_t *statement = block->statements;
817         while(statement != NULL) {
818                 if (statement->base.kind == STATEMENT_CASE_LABEL)
819                         --indent;
820                 print_indent();
821                 print_statement(statement);
822
823                 statement = statement->base.next;
824         }
825         --indent;
826         print_indent();
827         fputs("}\n", out);
828 }
829
830 /**
831  * Print a return statement.
832  *
833  * @param statement  the return statement
834  */
835 static void print_return_statement(const return_statement_t *statement)
836 {
837         fprintf(out, "return ");
838         if(statement->value != NULL)
839                 print_expression(statement->value);
840         fputs(";\n", out);
841 }
842
843 /**
844  * Print an expression statement.
845  *
846  * @param statement  the expression statement
847  */
848 static void print_expression_statement(const expression_statement_t *statement)
849 {
850         print_expression(statement->expression);
851         fputs(";\n", out);
852 }
853
854 /**
855  * Print a goto statement.
856  *
857  * @param statement  the goto statement
858  */
859 static void print_goto_statement(const goto_statement_t *statement)
860 {
861         fprintf(out, "goto ");
862         fputs(statement->label->symbol->string, out);
863         fprintf(stderr, "(%p)", (void*) statement->label);
864         fputs(";\n", out);
865 }
866
867 /**
868  * Print a label statement.
869  *
870  * @param statement  the label statement
871  */
872 static void print_label_statement(const label_statement_t *statement)
873 {
874         fprintf(stderr, "(%p)", (void*) statement->label);
875         fprintf(out, "%s:\n", statement->label->symbol->string);
876         print_statement(statement->statement);
877 }
878
879 /**
880  * Print an if statement.
881  *
882  * @param statement  the if statement
883  */
884 static void print_if_statement(const if_statement_t *statement)
885 {
886         fputs("if (", out);
887         print_expression(statement->condition);
888         fputs(") ", out);
889         print_statement(statement->true_statement);
890
891         if(statement->false_statement != NULL) {
892                 print_indent();
893                 fputs("else ", out);
894                 print_statement(statement->false_statement);
895         }
896 }
897
898 /**
899  * Print a switch statement.
900  *
901  * @param statement  the switch statement
902  */
903 static void print_switch_statement(const switch_statement_t *statement)
904 {
905         fputs("switch (", out);
906         print_expression(statement->expression);
907         fputs(") ", out);
908         print_statement(statement->body);
909 }
910
911 /**
912  * Print a case label (including the default label).
913  *
914  * @param statement  the case label statement
915  */
916 static void print_case_label(const case_label_statement_t *statement)
917 {
918         if(statement->expression == NULL) {
919                 fputs("default:\n", out);
920         } else {
921                 fputs("case ", out);
922                 print_expression(statement->expression);
923                 if (statement->end_range != NULL) {
924                         fputs(" ... ", out);
925                         print_expression(statement->end_range);
926                 }
927                 fputs(":\n", out);
928         }
929         ++indent;
930         if(statement->statement != NULL) {
931                 if (statement->statement->base.kind == STATEMENT_CASE_LABEL) {
932                         --indent;
933                 }
934                 print_indent();
935                 print_statement(statement->statement);
936         }
937 }
938
939 /**
940  * Print a declaration statement.
941  *
942  * @param statement   the statement
943  */
944 static void print_declaration_statement(
945                 const declaration_statement_t *statement)
946 {
947         int first = 1;
948         declaration_t *declaration = statement->declarations_begin;
949         for( ; declaration != statement->declarations_end->next;
950                declaration = declaration->next) {
951             if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY)
952                 continue;
953
954                 if(!first) {
955                         print_indent();
956                 } else {
957                         first = 0;
958                 }
959                 print_declaration(declaration);
960                 fputc('\n', out);
961         }
962 }
963
964 /**
965  * Print a while statement.
966  *
967  * @param statement   the statement
968  */
969 static void print_while_statement(const while_statement_t *statement)
970 {
971         fputs("while (", out);
972         print_expression(statement->condition);
973         fputs(") ", out);
974         print_statement(statement->body);
975 }
976
977 /**
978  * Print a do-while statement.
979  *
980  * @param statement   the statement
981  */
982 static void print_do_while_statement(const do_while_statement_t *statement)
983 {
984         fputs("do ", out);
985         print_statement(statement->body);
986         print_indent();
987         fputs("while (", out);
988         print_expression(statement->condition);
989         fputs(");\n", out);
990 }
991
992 /**
993  * Print a for statement.
994  *
995  * @param statement   the statement
996  */
997 static void print_for_statement(const for_statement_t *statement)
998 {
999         fputs("for (", out);
1000         if(statement->scope.declarations != NULL) {
1001                 assert(statement->initialisation == NULL);
1002                 print_declaration(statement->scope.declarations);
1003                 if(statement->scope.declarations->next != NULL) {
1004                         panic("multiple declarations in for statement not supported yet");
1005                 }
1006                 fputc(' ', out);
1007         } else {
1008                 if(statement->initialisation) {
1009                         print_expression(statement->initialisation);
1010                 }
1011                 fputs("; ", out);
1012         }
1013         if(statement->condition != NULL) {
1014                 print_expression(statement->condition);
1015         }
1016         fputs("; ", out);
1017         if(statement->step != NULL) {
1018                 print_expression(statement->step);
1019         }
1020         fputs(")", out);
1021         print_statement(statement->body);
1022 }
1023
1024 /**
1025  * Print assembler arguments.
1026  *
1027  * @param arguments   the arguments
1028  */
1029 static void print_asm_arguments(asm_argument_t *arguments)
1030 {
1031         asm_argument_t *argument = arguments;
1032         for( ; argument != NULL; argument = argument->next) {
1033                 if(argument != arguments)
1034                         fputs(", ", out);
1035
1036                 if(argument->symbol) {
1037                         fprintf(out, "[%s] ", argument->symbol->string);
1038                 }
1039                 print_quoted_string(&argument->constraints, '"');
1040                 fputs(" (", out);
1041                 print_expression(argument->expression);
1042                 fputs(")", out);
1043         }
1044 }
1045
1046 /**
1047  * Print assembler clobbers.
1048  *
1049  * @param clobbers   the clobbers
1050  */
1051 static void print_asm_clobbers(asm_clobber_t *clobbers)
1052 {
1053         asm_clobber_t *clobber = clobbers;
1054         for( ; clobber != NULL; clobber = clobber->next) {
1055                 if(clobber != clobbers)
1056                         fputs(", ", out);
1057
1058                 print_quoted_string(&clobber->clobber, '"');
1059         }
1060 }
1061
1062 /**
1063  * Print an assembler statement.
1064  *
1065  * @param statement   the statement
1066  */
1067 static void print_asm_statement(const asm_statement_t *statement)
1068 {
1069         fputs("asm ", out);
1070         if(statement->is_volatile) {
1071                 fputs("volatile ", out);
1072         }
1073         fputs("(", out);
1074         print_quoted_string(&statement->asm_text, '"');
1075         if(statement->inputs == NULL && statement->outputs == NULL
1076                         && statement->clobbers == NULL)
1077                 goto end_of_print_asm_statement;
1078
1079         fputs(" : ", out);
1080         print_asm_arguments(statement->inputs);
1081         if(statement->outputs == NULL && statement->clobbers == NULL)
1082                 goto end_of_print_asm_statement;
1083
1084         fputs(" : ", out);
1085         print_asm_arguments(statement->outputs);
1086         if(statement->clobbers == NULL)
1087                 goto end_of_print_asm_statement;
1088
1089         fputs(" : ", out);
1090         print_asm_clobbers(statement->clobbers);
1091
1092 end_of_print_asm_statement:
1093         fputs(");\n", out);
1094 }
1095
1096 /**
1097  * Print a microsoft __try statement.
1098  *
1099  * @param statement   the statement
1100  */
1101 static void print_ms_try_statement(const ms_try_statement_t *statement)
1102 {
1103         fputs("__try ", out);
1104         print_statement(statement->try_statement);
1105         print_indent();
1106         if(statement->except_expression != NULL) {
1107                 fputs("__except(", out);
1108                 print_expression(statement->except_expression);
1109                 fputs(") ", out);
1110         } else {
1111                 fputs("__finally ", out);
1112         }
1113         print_statement(statement->final_statement);
1114 }
1115
1116 /**
1117  * Print a microsoft __leave statement.
1118  *
1119  * @param statement   the statement
1120  */
1121 static void print_leave_statement(const leave_statement_t *statement)
1122 {
1123         (void) statement;
1124         fputs("__leave;\n", out);
1125 }
1126
1127 /**
1128  * Print a statement.
1129  *
1130  * @param statement   the statement
1131  */
1132 void print_statement(const statement_t *statement)
1133 {
1134         switch(statement->kind) {
1135         case STATEMENT_EMPTY:
1136                 fputs(";\n", out);
1137                 break;
1138         case STATEMENT_COMPOUND:
1139                 print_compound_statement(&statement->compound);
1140                 break;
1141         case STATEMENT_RETURN:
1142                 print_return_statement(&statement->returns);
1143                 break;
1144         case STATEMENT_EXPRESSION:
1145                 print_expression_statement(&statement->expression);
1146                 break;
1147         case STATEMENT_LABEL:
1148                 print_label_statement(&statement->label);
1149                 break;
1150         case STATEMENT_GOTO:
1151                 print_goto_statement(&statement->gotos);
1152                 break;
1153         case STATEMENT_CONTINUE:
1154                 fputs("continue;\n", out);
1155                 break;
1156         case STATEMENT_BREAK:
1157                 fputs("break;\n", out);
1158                 break;
1159         case STATEMENT_IF:
1160                 print_if_statement(&statement->ifs);
1161                 break;
1162         case STATEMENT_SWITCH:
1163                 print_switch_statement(&statement->switchs);
1164                 break;
1165         case STATEMENT_CASE_LABEL:
1166                 print_case_label(&statement->case_label);
1167                 break;
1168         case STATEMENT_DECLARATION:
1169                 print_declaration_statement(&statement->declaration);
1170                 break;
1171         case STATEMENT_WHILE:
1172                 print_while_statement(&statement->whiles);
1173                 break;
1174         case STATEMENT_DO_WHILE:
1175                 print_do_while_statement(&statement->do_while);
1176                 break;
1177         case STATEMENT_FOR:
1178                 print_for_statement(&statement->fors);
1179                 break;
1180         case STATEMENT_ASM:
1181                 print_asm_statement(&statement->asms);
1182                 break;
1183         case STATEMENT_MS_TRY:
1184                 print_ms_try_statement(&statement->ms_try);
1185                 break;
1186         case STATEMENT_LEAVE:
1187                 print_leave_statement(&statement->leave);
1188                 break;
1189         case STATEMENT_INVALID:
1190                 fprintf(out, "$invalid statement$");
1191                 break;
1192         }
1193 }
1194
1195 /**
1196  * Print a storage class.
1197  *
1198  * @param storage_class   the storage class
1199  */
1200 static void print_storage_class(storage_class_tag_t storage_class)
1201 {
1202         switch(storage_class) {
1203         case STORAGE_CLASS_ENUM_ENTRY:
1204         case STORAGE_CLASS_NONE:
1205                 break;
1206         case STORAGE_CLASS_TYPEDEF:       fputs("typedef ",        out); break;
1207         case STORAGE_CLASS_EXTERN:        fputs("extern ",         out); break;
1208         case STORAGE_CLASS_STATIC:        fputs("static ",         out); break;
1209         case STORAGE_CLASS_AUTO:          fputs("auto ",           out); break;
1210         case STORAGE_CLASS_REGISTER:      fputs("register ",       out); break;
1211         case STORAGE_CLASS_THREAD:        fputs("__thread",        out); break;
1212         case STORAGE_CLASS_THREAD_EXTERN: fputs("extern __thread", out); break;
1213         case STORAGE_CLASS_THREAD_STATIC: fputs("static __thread", out); break;
1214         }
1215 }
1216
1217 /**
1218  * Print an initializer.
1219  *
1220  * @param initializer  the initializer
1221  */
1222 void print_initializer(const initializer_t *initializer)
1223 {
1224         if(initializer == NULL) {
1225                 fputs("{}", out);
1226                 return;
1227         }
1228
1229         switch(initializer->kind) {
1230         case INITIALIZER_VALUE: {
1231                 const initializer_value_t *value = &initializer->value;
1232                 print_expression(value->value);
1233                 return;
1234         }
1235         case INITIALIZER_LIST: {
1236                 assert(initializer->kind == INITIALIZER_LIST);
1237                 fputs("{ ", out);
1238                 const initializer_list_t *list = &initializer->list;
1239
1240                 for(size_t i = 0 ; i < list->len; ++i) {
1241                         const initializer_t *sub_init = list->initializers[i];
1242                         print_initializer(list->initializers[i]);
1243                         if(i < list->len-1) {
1244                                 if(sub_init == NULL || sub_init->kind != INITIALIZER_DESIGNATOR)
1245                                         fputs(", ", out);
1246                         }
1247                 }
1248                 fputs(" }", out);
1249                 return;
1250         }
1251         case INITIALIZER_STRING:
1252                 print_quoted_string(&initializer->string.string, '"');
1253                 return;
1254         case INITIALIZER_WIDE_STRING:
1255                 print_quoted_wide_string(&initializer->wide_string.string, '"');
1256                 return;
1257         case INITIALIZER_DESIGNATOR:
1258                 print_designator(initializer->designator.designator);
1259                 fputs(" = ", out);
1260                 return;
1261         }
1262
1263         panic("invalid initializer kind found");
1264 }
1265
1266 /**
1267  * Print microsoft extended declaration modifiers.
1268  */
1269 static void print_ms_modifiers(const declaration_t *declaration) {
1270         if((c_mode & _MS) == 0)
1271                 return;
1272
1273         decl_modifiers_t modifiers = declaration->modifiers;
1274
1275         /* DM_FORCEINLINE handled outside. */
1276         if ((modifiers & ~DM_FORCEINLINE) != 0    ||
1277             declaration->alignment        != 0    ||
1278             declaration->get_property_sym != NULL ||
1279             declaration->put_property_sym != NULL) {
1280                 char *next = "(";
1281
1282                 fputs("__declspec", out);
1283                 if(modifiers & DM_DLLIMPORT) {
1284                         fputs(next, out); next = ", "; fputs("dllimport", out);
1285                 }
1286                 if(modifiers & DM_DLLEXPORT) {
1287                         fputs(next, out); next = ", "; fputs("dllexport", out);
1288                 }
1289                 if(modifiers & DM_THREAD) {
1290                         fputs(next, out); next = ", "; fputs("thread", out);
1291                 }
1292                 if(modifiers & DM_NAKED) {
1293                         fputs(next, out); next = ", "; fputs("naked", out);
1294                 }
1295                 if(modifiers & DM_THREAD) {
1296                         fputs(next, out); next = ", "; fputs("thread", out);
1297                 }
1298                 if(modifiers & DM_SELECTANY) {
1299                         fputs(next, out); next = ", "; fputs("selectany", out);
1300                 }
1301                 if(modifiers & DM_NOTHROW) {
1302                         fputs(next, out); next = ", "; fputs("nothrow", out);
1303                 }
1304                 if(modifiers & DM_NORETURN) {
1305                         fputs(next, out); next = ", "; fputs("noreturn", out);
1306                 }
1307                 if(modifiers & DM_NOINLINE) {
1308                         fputs(next, out); next = ", "; fputs("noinline", out);
1309                 }
1310                 if (modifiers & DM_DEPRECATED) {
1311                         fputs(next, out); next = ", "; fputs("deprecated", out);
1312                         if(declaration->deprecated_string != NULL)
1313                                 fprintf(out, "(\"%s\")", declaration->deprecated_string);
1314                 }
1315                 if(declaration->alignment != 0) {
1316                         fputs(next, out); next = ", "; fprintf(out, "align(%u)", declaration->alignment);
1317                 }
1318                 if(modifiers & DM_RESTRICT) {
1319                         fputs(next, out); next = ", "; fputs("restrict", out);
1320                 }
1321                 if(modifiers & DM_NOALIAS) {
1322                         fputs(next, out); next = ", "; fputs("noalias", out);
1323                 }
1324             if(declaration->get_property_sym != NULL || declaration->put_property_sym != NULL) {
1325                 char *comma = "";
1326                         fputs(next, out); next = ", "; fprintf(out, "property(");
1327                 if(declaration->get_property_sym != NULL) {
1328                         fprintf(out, "get=%s", declaration->get_property_sym->string);
1329                         comma = ", ";
1330                         }
1331                 if(declaration->put_property_sym != NULL)
1332                         fprintf(out, "%sput=%s", comma, declaration->put_property_sym->string);
1333                         fputc(')', out);
1334                 }
1335                 fputs(") ", out);
1336         }
1337 }
1338
1339 /**
1340  * Print a declaration in the NORMAL namespace.
1341  *
1342  * @param declaration  the declaration
1343  */
1344 static void print_normal_declaration(const declaration_t *declaration)
1345 {
1346         print_storage_class((storage_class_tag_t) declaration->declared_storage_class);
1347         if (declaration->is_inline) {
1348                 if (declaration->modifiers & DM_FORCEINLINE) {
1349                         fputs("__forceinline ", out);
1350                 } else if (declaration->modifiers & DM_MICROSOFT_INLINE) {
1351                         fputs("__inline ", out);
1352                 } else {
1353                         fputs("inline ", out);
1354                 }
1355         }
1356         print_ms_modifiers(declaration);
1357         print_type_ext(declaration->type, declaration->symbol,
1358                        &declaration->scope);
1359
1360         if(declaration->type->kind == TYPE_FUNCTION) {
1361                 if(declaration->init.statement != NULL) {
1362                         fputs("\n", out);
1363                         print_statement(declaration->init.statement);
1364                         return;
1365                 }
1366         } else if(declaration->init.initializer != NULL) {
1367                 fputs(" = ", out);
1368                 print_initializer(declaration->init.initializer);
1369         }
1370         fputc(';', out);
1371 }
1372
1373 /**
1374  * Prints an expression.
1375  *
1376  * @param expression  the expression
1377  */
1378 void print_expression(const expression_t *expression) {
1379         print_expression_prec(expression, PREC_BOTTOM);
1380 }
1381
1382 /**
1383  * Print a declaration.
1384  *
1385  * @param declaration  the declaration
1386  */
1387 void print_declaration(const declaration_t *declaration)
1388 {
1389         if(declaration->namespc != NAMESPACE_NORMAL &&
1390                         declaration->symbol == NULL)
1391                 return;
1392
1393         switch(declaration->namespc) {
1394         case NAMESPACE_NORMAL:
1395                 print_normal_declaration(declaration);
1396                 break;
1397         case NAMESPACE_STRUCT:
1398                 fputs("struct ", out);
1399                 fputs(declaration->symbol->string, out);
1400                 fputc(' ', out);
1401                 print_compound_definition(declaration);
1402                 fputc(';', out);
1403                 break;
1404         case NAMESPACE_UNION:
1405                 fputs("union ", out);
1406                 fputs(declaration->symbol->string, out);
1407                 fputc(' ', out);
1408                 print_compound_definition(declaration);
1409                 fputc(';', out);
1410                 break;
1411         case NAMESPACE_ENUM:
1412                 fputs("enum ", out);
1413                 fputs(declaration->symbol->string, out);
1414                 fputc(' ', out);
1415                 print_enum_definition(declaration);
1416                 fputc(';', out);
1417                 break;
1418         }
1419 }
1420
1421 /**
1422  * Print the AST of a translation unit.
1423  *
1424  * @param unit   the translation unit
1425  */
1426 void print_ast(const translation_unit_t *unit)
1427 {
1428         inc_type_visited();
1429
1430         declaration_t *declaration = unit->scope.declarations;
1431         for( ; declaration != NULL; declaration = declaration->next) {
1432                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY)
1433                         continue;
1434                 if(declaration->namespc != NAMESPACE_NORMAL &&
1435                                 declaration->symbol == NULL)
1436                         continue;
1437
1438                 print_indent();
1439                 print_declaration(declaration);
1440                 fputc('\n', out);
1441         }
1442 }
1443
1444 bool is_constant_initializer(const initializer_t *initializer)
1445 {
1446         switch(initializer->kind) {
1447         case INITIALIZER_STRING:
1448         case INITIALIZER_WIDE_STRING:
1449         case INITIALIZER_DESIGNATOR:
1450                 return true;
1451
1452         case INITIALIZER_VALUE:
1453                 return is_constant_expression(initializer->value.value);
1454
1455         case INITIALIZER_LIST:
1456                 for(size_t i = 0; i < initializer->list.len; ++i) {
1457                         initializer_t *sub_initializer = initializer->list.initializers[i];
1458                         if(!is_constant_initializer(sub_initializer))
1459                                 return false;
1460                 }
1461                 return true;
1462         }
1463         panic("invalid initializer kind found");
1464 }
1465
1466 static bool is_object_with_linker_constant_address(const expression_t *expression)
1467 {
1468         switch(expression->kind) {
1469         case EXPR_UNARY_DEREFERENCE:
1470                 return is_address_constant(expression->unary.value);
1471
1472         case EXPR_SELECT: {
1473                 type_t *base_type = skip_typeref(expression->select.compound->base.type);
1474                 if(is_type_pointer(base_type)) {
1475                         /* it's a -> */
1476                         return is_address_constant(expression->select.compound);
1477                 } else {
1478                         return is_object_with_linker_constant_address(expression->select.compound);
1479                 }
1480         }
1481
1482         case EXPR_ARRAY_ACCESS:
1483                 return is_constant_expression(expression->array_access.index)
1484                         && is_address_constant(expression->array_access.array_ref);
1485
1486         case EXPR_REFERENCE: {
1487                 declaration_t *declaration = expression->reference.declaration;
1488                 switch((storage_class_tag_t) declaration->storage_class) {
1489                 case STORAGE_CLASS_NONE:
1490                 case STORAGE_CLASS_EXTERN:
1491                 case STORAGE_CLASS_STATIC:
1492                         return true;
1493                 default:
1494                         return false;
1495                 }
1496         }
1497
1498         default:
1499                 return false;
1500         }
1501 }
1502
1503 bool is_address_constant(const expression_t *expression)
1504 {
1505         switch(expression->kind) {
1506         case EXPR_UNARY_TAKE_ADDRESS:
1507                 return is_object_with_linker_constant_address(expression->unary.value);
1508
1509         case EXPR_UNARY_DEREFERENCE: {
1510                 type_t *real_type
1511                         = revert_automatic_type_conversion(expression->unary.value);
1512                 /* dereferencing a function is a NOP */
1513                 if(is_type_function(real_type)) {
1514                         return is_address_constant(expression->unary.value);
1515                 }
1516
1517                 /* fallthrough */
1518         }
1519
1520         case EXPR_UNARY_CAST: {
1521                 type_t *dest = skip_typeref(expression->base.type);
1522                 if (!is_type_pointer(dest) &&
1523                                 ! (dest->kind == TYPE_ATOMIC
1524                                         && (get_atomic_type_flags(dest->atomic.akind) & ATOMIC_TYPE_FLAG_INTEGER)
1525                                         && (get_atomic_type_size(dest->atomic.akind) >= get_atomic_type_size(get_intptr_kind()))))
1526                         return false;
1527
1528                 return (is_constant_expression(expression->unary.value)
1529                         || is_address_constant(expression->unary.value));
1530         }
1531
1532         case EXPR_BINARY_ADD:
1533         case EXPR_BINARY_SUB: {
1534                 expression_t *left  = expression->binary.left;
1535                 expression_t *right = expression->binary.right;
1536
1537                 if(is_type_pointer(skip_typeref(left->base.type))) {
1538                         return is_address_constant(left) && is_constant_expression(right);
1539                 } else if(is_type_pointer(skip_typeref(right->base.type))) {
1540                         return is_constant_expression(left)     && is_address_constant(right);
1541                 }
1542
1543                 return false;
1544         }
1545
1546         case EXPR_REFERENCE: {
1547                 declaration_t *declaration = expression->reference.declaration;
1548                 type_t *type = skip_typeref(declaration->type);
1549                 if(is_type_function(type))
1550                         return true;
1551                 if(is_type_array(type)) {
1552                         return is_object_with_linker_constant_address(expression);
1553                 }
1554                 return false;
1555         }
1556
1557         default:
1558                 return false;
1559         }
1560 }
1561
1562 static bool is_builtin_const_call(const expression_t *expression)
1563 {
1564         expression_t *function = expression->call.function;
1565         if (function->kind != EXPR_BUILTIN_SYMBOL) {
1566                 return false;
1567         }
1568
1569         symbol_t *symbol = function->builtin_symbol.symbol;
1570
1571         switch (symbol->ID) {
1572         case T___builtin_huge_val:
1573         case T___builtin_nan:
1574         case T___builtin_nanf:
1575         case T___builtin_nand:
1576                 return true;
1577         }
1578
1579         return false;
1580 }
1581
1582 static bool is_constant_pointer(const expression_t *expression)
1583 {
1584         if (is_constant_expression(expression))
1585                 return true;
1586
1587         switch (expression->kind) {
1588         case EXPR_SELECT:
1589                 return is_constant_pointer(expression->select.compound);
1590         case EXPR_UNARY_CAST:
1591                 return is_constant_pointer(expression->unary.value);
1592         default:
1593                 return false;
1594         }
1595 }
1596
1597 static bool is_object_with_constant_address(const expression_t *expression)
1598 {
1599         switch(expression->kind) {
1600         case EXPR_SELECT: {
1601                 expression_t *compound      = expression->select.compound;
1602                 type_t       *compound_type = compound->base.type;
1603                 compound_type = skip_typeref(compound_type);
1604                 if(is_type_pointer(compound_type)) {
1605                         return is_constant_pointer(compound);
1606                 } else {
1607                         return is_object_with_constant_address(compound);
1608                 }
1609         }
1610         case EXPR_ARRAY_ACCESS:
1611                 return is_constant_pointer(expression->array_access.array_ref)
1612                         && is_constant_expression(expression->array_access.index);
1613         case EXPR_UNARY_DEREFERENCE:
1614                 return is_constant_pointer(expression->unary.value);
1615         default:
1616                 return false;
1617         }
1618 }
1619
1620 bool is_constant_expression(const expression_t *expression)
1621 {
1622         switch(expression->kind) {
1623
1624         case EXPR_CONST:
1625         case EXPR_CHARACTER_CONSTANT:
1626         case EXPR_WIDE_CHARACTER_CONSTANT:
1627         case EXPR_STRING_LITERAL:
1628         case EXPR_WIDE_STRING_LITERAL:
1629         case EXPR_SIZEOF:
1630         case EXPR_CLASSIFY_TYPE:
1631         case EXPR_FUNCNAME:
1632         case EXPR_OFFSETOF:
1633         case EXPR_ALIGNOF:
1634         case EXPR_BUILTIN_CONSTANT_P:
1635                 return true;
1636
1637         case EXPR_BUILTIN_SYMBOL:
1638         case EXPR_BUILTIN_PREFETCH:
1639         case EXPR_SELECT:
1640         case EXPR_VA_START:
1641         case EXPR_VA_ARG:
1642         case EXPR_STATEMENT:
1643         case EXPR_UNARY_POSTFIX_INCREMENT:
1644         case EXPR_UNARY_POSTFIX_DECREMENT:
1645         case EXPR_UNARY_PREFIX_INCREMENT:
1646         case EXPR_UNARY_PREFIX_DECREMENT:
1647         case EXPR_UNARY_ASSUME: /* has VOID type */
1648         case EXPR_UNARY_DEREFERENCE:
1649         case EXPR_BINARY_ASSIGN:
1650         case EXPR_BINARY_MUL_ASSIGN:
1651         case EXPR_BINARY_DIV_ASSIGN:
1652         case EXPR_BINARY_MOD_ASSIGN:
1653         case EXPR_BINARY_ADD_ASSIGN:
1654         case EXPR_BINARY_SUB_ASSIGN:
1655         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1656         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1657         case EXPR_BINARY_BITWISE_AND_ASSIGN:
1658         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1659         case EXPR_BINARY_BITWISE_OR_ASSIGN:
1660         case EXPR_BINARY_COMMA:
1661                 return false;
1662
1663         case EXPR_UNARY_TAKE_ADDRESS:
1664                 return is_object_with_constant_address(expression->unary.value);
1665
1666         case EXPR_CALL:
1667                 return is_builtin_const_call(expression);
1668
1669         case EXPR_UNARY_NEGATE:
1670         case EXPR_UNARY_PLUS:
1671         case EXPR_UNARY_BITWISE_NEGATE:
1672         case EXPR_UNARY_NOT:
1673                 return is_constant_expression(expression->unary.value);
1674
1675         case EXPR_UNARY_CAST:
1676         case EXPR_UNARY_CAST_IMPLICIT:
1677                 return is_type_arithmetic(skip_typeref(expression->base.type))
1678                         && is_constant_expression(expression->unary.value);
1679
1680         case EXPR_BINARY_ADD:
1681         case EXPR_BINARY_SUB:
1682         case EXPR_BINARY_MUL:
1683         case EXPR_BINARY_DIV:
1684         case EXPR_BINARY_MOD:
1685         case EXPR_BINARY_EQUAL:
1686         case EXPR_BINARY_NOTEQUAL:
1687         case EXPR_BINARY_LESS:
1688         case EXPR_BINARY_LESSEQUAL:
1689         case EXPR_BINARY_GREATER:
1690         case EXPR_BINARY_GREATEREQUAL:
1691         case EXPR_BINARY_BITWISE_AND:
1692         case EXPR_BINARY_BITWISE_OR:
1693         case EXPR_BINARY_BITWISE_XOR:
1694         case EXPR_BINARY_LOGICAL_AND:
1695         case EXPR_BINARY_LOGICAL_OR:
1696         case EXPR_BINARY_SHIFTLEFT:
1697         case EXPR_BINARY_SHIFTRIGHT:
1698         case EXPR_BINARY_BUILTIN_EXPECT:
1699         case EXPR_BINARY_ISGREATER:
1700         case EXPR_BINARY_ISGREATEREQUAL:
1701         case EXPR_BINARY_ISLESS:
1702         case EXPR_BINARY_ISLESSEQUAL:
1703         case EXPR_BINARY_ISLESSGREATER:
1704         case EXPR_BINARY_ISUNORDERED:
1705                 return is_constant_expression(expression->binary.left)
1706                         && is_constant_expression(expression->binary.right);
1707
1708         case EXPR_COMPOUND_LITERAL:
1709                 return is_constant_initializer(expression->compound_literal.initializer);
1710
1711         case EXPR_CONDITIONAL: {
1712                 expression_t *condition = expression->conditional.condition;
1713                 if(!is_constant_expression(condition))
1714                         return false;
1715
1716                 long val = fold_constant(condition);
1717                 if(val != 0)
1718                         return is_constant_expression(expression->conditional.true_expression);
1719                 else
1720                         return is_constant_expression(expression->conditional.false_expression);
1721         }
1722
1723         case EXPR_ARRAY_ACCESS:
1724                 return is_constant_expression(expression->array_access.array_ref)
1725                         && is_constant_expression(expression->array_access.index);
1726
1727         case EXPR_REFERENCE: {
1728                 declaration_t *declaration = expression->reference.declaration;
1729                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY)
1730                         return true;
1731
1732                 return false;
1733         }
1734
1735         case EXPR_INVALID:
1736                 return true;
1737
1738         case EXPR_UNKNOWN:
1739                 break;
1740         }
1741         panic("invalid expression found (is constant expression)");
1742 }
1743
1744 /**
1745  * Initialize the AST construction.
1746  */
1747 void init_ast(void)
1748 {
1749         obstack_init(&ast_obstack);
1750 }
1751
1752 /**
1753  * Free the AST.
1754  */
1755 void exit_ast(void)
1756 {
1757         obstack_free(&ast_obstack, NULL);
1758 }
1759
1760 /**
1761  * Set the output stream for the AST printer.
1762  *
1763  * @param stream  the output stream
1764  */
1765 void ast_set_output(FILE *stream)
1766 {
1767         out = stream;
1768         type_set_output(stream);
1769 }
1770
1771 /**
1772  * Allocate an AST object of the given size.
1773  *
1774  * @param size  the size of the object to allocate
1775  *
1776  * @return  A new allocated object in the AST memeory space.
1777  */
1778 void *(allocate_ast)(size_t size)
1779 {
1780         return _allocate_ast(size);
1781 }