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