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