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