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