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