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