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