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