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