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