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