Split computed gotos (STATEMENT_COMPUTED_GOTO) from normal goto statements.
[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(expression_t const *expr, unsigned const top_prec)
667 {
668         if (expr->kind == EXPR_UNARY_CAST && expr->base.implicit && !print_implicit_casts) {
669                 expr = expr->unary.value;
670         }
671
672         bool parenthesized =
673                 expr->base.parenthesized                       ||
674                 (print_parenthesis && top_prec != PREC_BOTTOM) ||
675                 top_prec > get_expression_precedence(expr->base.kind);
676
677         if (parenthesized)
678                 print_char('(');
679         switch (expr->kind) {
680         case EXPR_ALIGNOF:
681         case EXPR_SIZEOF:                     print_typeprop_expression(     &expr->typeprop);                 break;
682         case EXPR_ARRAY_ACCESS:               print_array_expression(        &expr->array_access);             break;
683         case EXPR_BINARY_CASES:               print_binary_expression(       &expr->binary);                   break;
684         case EXPR_BUILTIN_CONSTANT_P:         print_builtin_constant(        &expr->builtin_constant);         break;
685         case EXPR_BUILTIN_TYPES_COMPATIBLE_P: print_builtin_types_compatible(&expr->builtin_types_compatible); break;
686         case EXPR_CALL:                       print_call_expression(         &expr->call);                     break;
687         case EXPR_CLASSIFY_TYPE:              print_classify_type_expression(&expr->classify_type);            break;
688         case EXPR_COMPOUND_LITERAL:           print_compound_literal(        &expr->compound_literal);         break;
689         case EXPR_CONDITIONAL:                print_conditional(             &expr->conditional);              break;
690         case EXPR_ERROR:                      print_string("$error$");                                         break;
691         case EXPR_FUNCNAME:                   print_funcname(                &expr->funcname);                 break;
692         case EXPR_LABEL_ADDRESS:              print_label_address_expression(&expr->label_address);            break;
693         case EXPR_LITERAL_CASES:              print_literal(                 &expr->literal);                  break;
694         case EXPR_OFFSETOF:                   print_offsetof_expression(     &expr->offsetofe);                break;
695         case EXPR_REFERENCE:
696         case EXPR_REFERENCE_ENUM_VALUE:       print_reference_expression(    &expr->reference);                break;
697         case EXPR_SELECT:                     print_select(                  &expr->select);                   break;
698         case EXPR_STATEMENT:                  print_statement_expression(    &expr->statement);                break;
699         case EXPR_STRING_LITERAL:
700         case EXPR_WIDE_STRING_LITERAL:        print_string_literal(          &expr->string_literal);           break;
701         case EXPR_UNARY_CASES:                print_unary_expression(        &expr->unary);                    break;
702         case EXPR_VA_ARG:                     print_va_arg(                  &expr->va_arge);                  break;
703         case EXPR_VA_COPY:                    print_va_copy(                 &expr->va_copye);                 break;
704         case EXPR_VA_START:                   print_va_start(                &expr->va_starte);                break;
705         }
706         if (parenthesized)
707                 print_char(')');
708 }
709
710 static void print_indented_statement(statement_t const *const stmt)
711 {
712         switch (stmt->kind) {
713         case STATEMENT_LABEL:
714                 break;
715
716         case STATEMENT_CASE_LABEL:
717                 for (int i = 0; i != case_indent; ++i)
718                         print_char('\t');
719                 break;
720
721         default:
722                 print_indent();
723                 break;
724         }
725         print_statement(stmt);
726 }
727
728 /**
729  * Print an compound statement.
730  *
731  * @param block  the compound statement
732  */
733 static void print_compound_statement(const compound_statement_t *block)
734 {
735         print_string("{\n");
736         ++indent;
737
738         for (statement_t const *stmt = block->statements; stmt; stmt = stmt->base.next) {
739                 print_indented_statement(stmt);
740                 print_char('\n');
741         }
742
743         --indent;
744         print_indent();
745         print_char('}');
746 }
747
748 /**
749  * Print a return statement.
750  *
751  * @param statement  the return statement
752  */
753 static void print_return_statement(const return_statement_t *statement)
754 {
755         expression_t const *const val = statement->value;
756         if (val != NULL) {
757                 print_string("return ");
758                 print_expression(val);
759                 print_char(';');
760         } else {
761                 print_string("return;");
762         }
763 }
764
765 /**
766  * Print an expression statement.
767  *
768  * @param statement  the expression statement
769  */
770 static void print_expression_statement(const expression_statement_t *statement)
771 {
772         print_expression(statement->expression);
773         print_char(';');
774 }
775
776 /**
777  * Print a computed goto statement.
778  *
779  * @param statement  the computed goto statement
780  */
781 static void print_computed_goto_statement(computed_goto_statement_t const *const stmt)
782 {
783         print_string("goto *");
784         print_expression(stmt->expression);
785         print_char(';');
786 }
787
788 /**
789  * Print a goto statement.
790  *
791  * @param statement  the goto statement
792  */
793 static void print_goto_statement(const goto_statement_t *statement)
794 {
795         print_string("goto ");
796         print_string(statement->label->base.symbol->string);
797         print_char(';');
798 }
799
800 /**
801  * Print a label statement.
802  *
803  * @param statement  the label statement
804  */
805 static void print_label_statement(const label_statement_t *statement)
806 {
807         print_format("%s:\n", statement->label->base.symbol->string);
808         print_indented_statement(statement->statement);
809 }
810
811 static void print_inner_statement(statement_t const *const stmt)
812 {
813         if (stmt->kind == STATEMENT_COMPOUND) {
814                 print_char(' ');
815                 print_compound_statement(&stmt->compound);
816         } else {
817                 print_char('\n');
818                 ++indent;
819                 print_indented_statement(stmt);
820                 --indent;
821         }
822 }
823
824 static void print_after_inner_statement(statement_t const *const stmt)
825 {
826         if (stmt->kind == STATEMENT_COMPOUND) {
827                 print_char(' ');
828         } else {
829                 print_char('\n');
830                 print_indent();
831         }
832 }
833
834 /**
835  * Print an if statement.
836  *
837  * @param statement  the if statement
838  */
839 static void print_if_statement(const if_statement_t *statement)
840 {
841         print_string("if (");
842         print_expression(statement->condition);
843         print_char(')');
844         print_inner_statement(statement->true_statement);
845
846         statement_t const *const f = statement->false_statement;
847         if (f) {
848                 print_after_inner_statement(statement->true_statement);
849                 print_string("else");
850                 if (f->kind == STATEMENT_IF) {
851                         print_char(' ');
852                         print_if_statement(&f->ifs);
853                 } else {
854                         print_inner_statement(f);
855                 }
856         }
857 }
858
859 /**
860  * Print a switch statement.
861  *
862  * @param statement  the switch statement
863  */
864 static void print_switch_statement(const switch_statement_t *statement)
865 {
866         int const old_case_indent = case_indent;
867         case_indent = indent;
868
869         print_string("switch (");
870         print_expression(statement->expression);
871         print_char(')');
872         print_inner_statement(statement->body);
873
874         case_indent = old_case_indent;
875 }
876
877 /**
878  * Print a case label (including the default label).
879  *
880  * @param statement  the case label statement
881  */
882 static void print_case_label(const case_label_statement_t *statement)
883 {
884         if (statement->expression == NULL) {
885                 print_string("default:\n");
886         } else {
887                 print_string("case ");
888                 print_expression(statement->expression);
889                 if (statement->end_range != NULL) {
890                         print_string(" ... ");
891                         print_expression(statement->end_range);
892                 }
893                 print_string(":\n");
894         }
895         print_indented_statement(statement->statement);
896 }
897
898 static void print_typedef(const entity_t *entity)
899 {
900         print_string("typedef ");
901         print_type_ext(entity->typedefe.type, entity->base.symbol, NULL);
902         print_char(';');
903 }
904
905 /**
906  * returns true if the entity is a compiler generated one and has no real
907  * correspondenc in the source file
908  */
909 static bool is_generated_entity(const entity_t *entity)
910 {
911         if (entity->kind == ENTITY_TYPEDEF)
912                 return entity->typedefe.builtin;
913
914         if (is_declaration(entity))
915                 return entity->declaration.implicit;
916
917         return false;
918 }
919
920 /**
921  * Print a declaration statement.
922  *
923  * @param statement   the statement
924  */
925 static void print_declaration_statement(
926                 const declaration_statement_t *statement)
927 {
928         bool first = true;
929         entity_t *entity = statement->declarations_begin;
930         if (entity == NULL) {
931                 print_string("/* empty declaration statement */");
932                 return;
933         }
934
935         entity_t *const end = statement->declarations_end->base.next;
936         for (; entity != end; entity = entity->base.next) {
937                 if (entity->kind == ENTITY_ENUM_VALUE)
938                         continue;
939                 if (is_generated_entity(entity))
940                         continue;
941
942                 if (!first) {
943                         print_char('\n');
944                         print_indent();
945                 } else {
946                         first = false;
947                 }
948
949                 print_entity(entity);
950         }
951 }
952
953 /**
954  * Print a while statement.
955  *
956  * @param statement   the statement
957  */
958 static void print_while_statement(const while_statement_t *statement)
959 {
960         print_string("while (");
961         print_expression(statement->condition);
962         print_char(')');
963         print_inner_statement(statement->body);
964 }
965
966 /**
967  * Print a do-while statement.
968  *
969  * @param statement   the statement
970  */
971 static void print_do_while_statement(const do_while_statement_t *statement)
972 {
973         print_string("do");
974         print_inner_statement(statement->body);
975         print_after_inner_statement(statement->body);
976         print_string("while (");
977         print_expression(statement->condition);
978         print_string(");");
979 }
980
981 /**
982  * Print a for statement.
983  *
984  * @param statement   the statement
985  */
986 static void print_for_statement(const for_statement_t *statement)
987 {
988         print_string("for (");
989         if (statement->initialisation != NULL) {
990                 print_expression(statement->initialisation);
991                 print_char(';');
992         } else {
993                 entity_t const *entity = statement->scope.entities;
994                 for (; entity != NULL; entity = entity->base.next) {
995                         if (is_generated_entity(entity))
996                                 continue;
997                         /* FIXME display of multiple declarations is wrong */
998                         print_declaration(entity);
999                 }
1000         }
1001         if (statement->condition != NULL) {
1002                 print_char(' ');
1003                 print_expression(statement->condition);
1004         }
1005         print_char(';');
1006         if (statement->step != NULL) {
1007                 print_char(' ');
1008                 print_expression(statement->step);
1009         }
1010         print_char(')');
1011         print_inner_statement(statement->body);
1012 }
1013
1014 /**
1015  * Print assembler arguments.
1016  *
1017  * @param arguments   the arguments
1018  */
1019 static void print_asm_arguments(asm_argument_t *arguments)
1020 {
1021         asm_argument_t *argument = arguments;
1022         for (; argument != NULL; argument = argument->next) {
1023                 if (argument != arguments)
1024                         print_string(", ");
1025
1026                 if (argument->symbol) {
1027                         print_format("[%s] ", argument->symbol->string);
1028                 }
1029                 print_quoted_string(&argument->constraints, '"', 1);
1030                 print_string(" (");
1031                 print_expression(argument->expression);
1032                 print_char(')');
1033         }
1034 }
1035
1036 /**
1037  * Print assembler clobbers.
1038  *
1039  * @param clobbers   the clobbers
1040  */
1041 static void print_asm_clobbers(asm_clobber_t *clobbers)
1042 {
1043         asm_clobber_t *clobber = clobbers;
1044         for (; clobber != NULL; clobber = clobber->next) {
1045                 if (clobber != clobbers)
1046                         print_string(", ");
1047
1048                 print_quoted_string(&clobber->clobber, '"', 1);
1049         }
1050 }
1051
1052 /**
1053  * Print an assembler statement.
1054  *
1055  * @param statement   the statement
1056  */
1057 static void print_asm_statement(const asm_statement_t *statement)
1058 {
1059         print_string("asm ");
1060         if (statement->is_volatile) {
1061                 print_string("volatile ");
1062         }
1063         print_char('(');
1064         print_quoted_string(&statement->asm_text, '"', 1);
1065         if (statement->outputs  == NULL &&
1066             statement->inputs   == NULL &&
1067             statement->clobbers == NULL)
1068                 goto end_of_print_asm_statement;
1069
1070         print_string(" : ");
1071         print_asm_arguments(statement->outputs);
1072         if (statement->inputs == NULL && statement->clobbers == NULL)
1073                 goto end_of_print_asm_statement;
1074
1075         print_string(" : ");
1076         print_asm_arguments(statement->inputs);
1077         if (statement->clobbers == NULL)
1078                 goto end_of_print_asm_statement;
1079
1080         print_string(" : ");
1081         print_asm_clobbers(statement->clobbers);
1082
1083 end_of_print_asm_statement:
1084         print_string(");");
1085 }
1086
1087 /**
1088  * Print a microsoft __try statement.
1089  *
1090  * @param statement   the statement
1091  */
1092 static void print_ms_try_statement(const ms_try_statement_t *statement)
1093 {
1094         print_string("__try");
1095         print_inner_statement(statement->try_statement);
1096         print_after_inner_statement(statement->try_statement);
1097         if (statement->except_expression != NULL) {
1098                 print_string("__except(");
1099                 print_expression(statement->except_expression);
1100                 print_char(')');
1101         } else {
1102                 print_string("__finally");
1103         }
1104         print_inner_statement(statement->final_statement);
1105 }
1106
1107 /**
1108  * Print a microsoft __leave statement.
1109  *
1110  * @param statement   the statement
1111  */
1112 static void print_leave_statement(const leave_statement_t *statement)
1113 {
1114         (void)statement;
1115         print_string("__leave;");
1116 }
1117
1118 /**
1119  * Print a statement.
1120  *
1121  * @param statement   the statement
1122  */
1123 void print_statement(statement_t const *const stmt)
1124 {
1125         switch (stmt->kind) {
1126         case STATEMENT_ASM:           print_asm_statement(          &stmt->asms);          break;
1127         case STATEMENT_BREAK:         print_string("break;");                              break;
1128         case STATEMENT_CASE_LABEL:    print_case_label(             &stmt->case_label);    break;
1129         case STATEMENT_COMPOUND:      print_compound_statement(     &stmt->compound);      break;
1130         case STATEMENT_COMPUTED_GOTO: print_computed_goto_statement(&stmt->computed_goto); break;
1131         case STATEMENT_CONTINUE:      print_string("continue;");                           break;
1132         case STATEMENT_DECLARATION:   print_declaration_statement(  &stmt->declaration);   break;
1133         case STATEMENT_DO_WHILE:      print_do_while_statement(     &stmt->do_while);      break;
1134         case STATEMENT_EMPTY:         print_char(';');                                     break;
1135         case STATEMENT_ERROR:         print_string("$error statement$");                   break;
1136         case STATEMENT_EXPRESSION:    print_expression_statement(   &stmt->expression);    break;
1137         case STATEMENT_FOR:           print_for_statement(          &stmt->fors);          break;
1138         case STATEMENT_GOTO:          print_goto_statement(         &stmt->gotos);         break;
1139         case STATEMENT_IF:            print_if_statement(           &stmt->ifs);           break;
1140         case STATEMENT_LABEL:         print_label_statement(        &stmt->label);         break;
1141         case STATEMENT_LEAVE:         print_leave_statement(        &stmt->leave);         break;
1142         case STATEMENT_MS_TRY:        print_ms_try_statement(       &stmt->ms_try);        break;
1143         case STATEMENT_RETURN:        print_return_statement(       &stmt->returns);       break;
1144         case STATEMENT_SWITCH:        print_switch_statement(       &stmt->switchs);       break;
1145         case STATEMENT_WHILE:         print_while_statement(        &stmt->whiles);        break;
1146         }
1147 }
1148
1149 /**
1150  * Print a storage class.
1151  *
1152  * @param storage_class   the storage class
1153  */
1154 static void print_storage_class(storage_class_tag_t storage_class)
1155 {
1156         switch (storage_class) {
1157         case STORAGE_CLASS_NONE:     return;
1158         case STORAGE_CLASS_TYPEDEF:  print_string("typedef ");  return;
1159         case STORAGE_CLASS_EXTERN:   print_string("extern ");   return;
1160         case STORAGE_CLASS_STATIC:   print_string("static ");   return;
1161         case STORAGE_CLASS_AUTO:     print_string("auto ");     return;
1162         case STORAGE_CLASS_REGISTER: print_string("register "); return;
1163         }
1164         panic("invalid storage class");
1165 }
1166
1167 /**
1168  * Print an initializer.
1169  *
1170  * @param initializer  the initializer
1171  */
1172 void print_initializer(const initializer_t *initializer)
1173 {
1174         if (initializer == NULL) {
1175                 print_string("{}");
1176                 return;
1177         }
1178
1179         switch (initializer->kind) {
1180         case INITIALIZER_VALUE: {
1181                 const initializer_value_t *value = &initializer->value;
1182                 print_assignment_expression(value->value);
1183                 return;
1184         }
1185         case INITIALIZER_LIST: {
1186                 assert(initializer->kind == INITIALIZER_LIST);
1187                 print_string("{ ");
1188                 const initializer_list_t *list = &initializer->list;
1189
1190                 for (size_t i = 0 ; i < list->len; ++i) {
1191                         const initializer_t *sub_init = list->initializers[i];
1192                         print_initializer(list->initializers[i]);
1193                         if (i < list->len-1) {
1194                                 if (sub_init == NULL || sub_init->kind != INITIALIZER_DESIGNATOR)
1195                                         print_string(", ");
1196                         }
1197                 }
1198                 print_string(" }");
1199                 return;
1200         }
1201         case INITIALIZER_STRING:
1202                 print_quoted_string(&initializer->string.string, '"', 1);
1203                 return;
1204         case INITIALIZER_WIDE_STRING:
1205                 print_quoted_string(&initializer->string.string, '"', 1);
1206                 return;
1207         case INITIALIZER_DESIGNATOR:
1208                 print_designator(initializer->designator.designator);
1209                 print_string(" = ");
1210                 return;
1211         }
1212
1213         panic("invalid initializer kind found");
1214 }
1215
1216 #if 0
1217 /**
1218  * Print microsoft extended declaration modifiers.
1219  */
1220 static void print_ms_modifiers(const declaration_t *declaration)
1221 {
1222         if ((c_mode & _MS) == 0)
1223                 return;
1224
1225         decl_modifiers_t modifiers = declaration->modifiers;
1226
1227         bool        ds_shown = false;
1228         const char *next     = "(";
1229
1230         if (declaration->base.kind == ENTITY_VARIABLE) {
1231                 variable_t *variable = (variable_t*)declaration;
1232                 if (variable->alignment != 0
1233                                 || variable->get_property_sym != NULL
1234                                 || variable->put_property_sym != NULL) {
1235                         if (!ds_shown) {
1236                                 print_string("__declspec");
1237                                 ds_shown = true;
1238                         }
1239
1240                         if (variable->alignment != 0) {
1241                                 print_string(next); next = ", "; print_format("align(%u)", variable->alignment);
1242                         }
1243                         if (variable->get_property_sym != NULL
1244                                         || variable->put_property_sym != NULL) {
1245                                 char *comma = "";
1246                                 print_string(next); next = ", "; print_string("property(");
1247                                 if (variable->get_property_sym != NULL) {
1248                                         print_format("get=%s", variable->get_property_sym->string);
1249                                         comma = ", ";
1250                                 }
1251                                 if (variable->put_property_sym != NULL)
1252                                         print_format("%sput=%s", comma, variable->put_property_sym->string);
1253                                 print_char(')');
1254                         }
1255                 }
1256         }
1257
1258         /* DM_FORCEINLINE handled outside. */
1259         if ((modifiers & ~DM_FORCEINLINE) != 0) {
1260                 if (!ds_shown) {
1261                         print_string("__declspec");
1262                         ds_shown = true;
1263                 }
1264                 if (modifiers & DM_DLLIMPORT) {
1265                         print_string(next); next = ", "; print_string("dllimport");
1266                 }
1267                 if (modifiers & DM_DLLEXPORT) {
1268                         print_string(next); next = ", "; print_string("dllexport");
1269                 }
1270                 if (modifiers & DM_THREAD) {
1271                         print_string(next); next = ", "; print_string("thread");
1272                 }
1273                 if (modifiers & DM_NAKED) {
1274                         print_string(next); next = ", "; print_string("naked");
1275                 }
1276                 if (modifiers & DM_THREAD) {
1277                         print_string(next); next = ", "; print_string("thread");
1278                 }
1279                 if (modifiers & DM_SELECTANY) {
1280                         print_string(next); next = ", "; print_string("selectany");
1281                 }
1282                 if (modifiers & DM_NOTHROW) {
1283                         print_string(next); next = ", "; print_string("nothrow");
1284                 }
1285                 if (modifiers & DM_NORETURN) {
1286                         print_string(next); next = ", "; print_string("noreturn");
1287                 }
1288                 if (modifiers & DM_NOINLINE) {
1289                         print_string(next); next = ", "; print_string("noinline");
1290                 }
1291                 if (modifiers & DM_DEPRECATED) {
1292                         print_string(next); next = ", "; print_string("deprecated");
1293                         if (declaration->deprecated_string != NULL)
1294                                 print_format("(\"%s\")",
1295                                         declaration->deprecated_string);
1296                 }
1297                 if (modifiers & DM_RESTRICT) {
1298                         print_string(next); next = ", "; print_string("restrict");
1299                 }
1300                 if (modifiers & DM_NOALIAS) {
1301                         print_string(next); next = ", "; print_string("noalias");
1302                 }
1303         }
1304
1305         if (ds_shown)
1306                 print_string(") ");
1307 }
1308 #endif
1309
1310 static void print_scope(const scope_t *scope)
1311 {
1312         const entity_t *entity = scope->entities;
1313         for ( ; entity != NULL; entity = entity->base.next) {
1314                 print_indent();
1315                 print_entity(entity);
1316                 print_char('\n');
1317         }
1318 }
1319
1320 static void print_namespace(const namespace_t *namespace)
1321 {
1322         print_string("namespace ");
1323         if (namespace->base.symbol != NULL) {
1324                 print_string(namespace->base.symbol->string);
1325                 print_char(' ');
1326         }
1327
1328         print_string("{\n");
1329         ++indent;
1330
1331         print_scope(&namespace->members);
1332
1333         --indent;
1334         print_indent();
1335         print_string("}\n");
1336 }
1337
1338 /**
1339  * Print a variable or function declaration
1340  */
1341 void print_declaration(const entity_t *entity)
1342 {
1343         assert(is_declaration(entity));
1344         const declaration_t *declaration = &entity->declaration;
1345
1346         print_storage_class((storage_class_tag_t)declaration->declared_storage_class);
1347         if (entity->kind == ENTITY_FUNCTION) {
1348                 function_t *function = (function_t*)declaration;
1349                 if (function->is_inline) {
1350                         if (declaration->modifiers & DM_FORCEINLINE) {
1351                                 print_string("__forceinline ");
1352                         } else if (declaration->modifiers & DM_MICROSOFT_INLINE) {
1353                                 print_string("__inline ");
1354                         } else {
1355                                 print_string("inline ");
1356                         }
1357                 }
1358         }
1359         //print_ms_modifiers(declaration);
1360         switch (entity->kind) {
1361                 case ENTITY_FUNCTION:
1362                         print_type_ext(entity->declaration.type, entity->base.symbol,
1363                                         &entity->function.parameters);
1364
1365                         if (entity->function.statement != NULL) {
1366                                 print_char('\n');
1367                                 print_indented_statement(entity->function.statement);
1368                                 print_char('\n');
1369                                 return;
1370                         }
1371                         break;
1372
1373                 case ENTITY_VARIABLE:
1374                         if (entity->variable.thread_local)
1375                                 print_string("__thread ");
1376                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1377                         if (entity->variable.initializer != NULL) {
1378                                 print_string(" = ");
1379                                 print_initializer(entity->variable.initializer);
1380                         }
1381                         break;
1382
1383                 case ENTITY_COMPOUND_MEMBER:
1384                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1385                         if (entity->compound_member.bitfield) {
1386                                 print_format(" : %u", entity->compound_member.bit_size);
1387                         }
1388                         break;
1389
1390                 default:
1391                         print_type_ext(declaration->type, declaration->base.symbol, NULL);
1392                         break;
1393         }
1394         print_char(';');
1395 }
1396
1397 /**
1398  * Prints an expression.
1399  *
1400  * @param expression  the expression
1401  */
1402 void print_expression(const expression_t *expression)
1403 {
1404         print_expression_prec(expression, PREC_BOTTOM);
1405 }
1406
1407 /**
1408  * Print a declaration.
1409  *
1410  * @param declaration  the declaration
1411  */
1412 void print_entity(const entity_t *entity)
1413 {
1414         if (entity->base.namespc != NAMESPACE_NORMAL && entity->base.symbol == NULL)
1415                 return;
1416
1417         switch ((entity_kind_tag_t)entity->kind) {
1418         case ENTITY_VARIABLE:
1419         case ENTITY_PARAMETER:
1420         case ENTITY_COMPOUND_MEMBER:
1421         case ENTITY_FUNCTION:
1422                 print_declaration(entity);
1423                 return;
1424         case ENTITY_TYPEDEF:
1425                 print_typedef(entity);
1426                 return;
1427         case ENTITY_CLASS:
1428                 /* TODO */
1429                 print_string("class ");
1430                 print_string(entity->base.symbol->string);
1431                 print_string("; /* TODO */\n");
1432                 return;
1433         case ENTITY_STRUCT:
1434                 print_string("struct ");
1435                 goto print_compound;
1436         case ENTITY_UNION:
1437                 print_string("union ");
1438 print_compound:
1439                 print_string(entity->base.symbol->string);
1440                 if (entity->compound.complete) {
1441                         print_char(' ');
1442                         print_compound_definition(&entity->compound);
1443                 }
1444                 print_char(';');
1445                 return;
1446         case ENTITY_ENUM:
1447                 print_string("enum ");
1448                 print_string(entity->base.symbol->string);
1449                 print_char(' ');
1450                 print_enum_definition(&entity->enume);
1451                 print_char(';');
1452                 return;
1453         case ENTITY_NAMESPACE:
1454                 print_namespace(&entity->namespacee);
1455                 return;
1456         case ENTITY_LOCAL_LABEL:
1457                 print_string("__label__ ");
1458                 print_string(entity->base.symbol->string);
1459                 print_char(';');
1460                 return;
1461         case ENTITY_LABEL:
1462         case ENTITY_ENUM_VALUE:
1463                 panic("print_entity used on unexpected entity type");
1464         }
1465         panic("Invalid entity type encountered");
1466 }
1467
1468 /**
1469  * Print the AST of a translation unit.
1470  *
1471  * @param unit   the translation unit
1472  */
1473 void print_ast(const translation_unit_t *unit)
1474 {
1475         entity_t *entity = unit->scope.entities;
1476         for ( ; entity != NULL; entity = entity->base.next) {
1477                 if (entity->kind == ENTITY_ENUM_VALUE)
1478                         continue;
1479                 if (entity->base.namespc != NAMESPACE_NORMAL
1480                                 && entity->base.symbol == NULL)
1481                         continue;
1482                 if (is_generated_entity(entity))
1483                         continue;
1484
1485                 print_indent();
1486                 print_entity(entity);
1487                 print_char('\n');
1488         }
1489 }
1490
1491 expression_classification_t is_constant_initializer(const initializer_t *initializer)
1492 {
1493         switch (initializer->kind) {
1494         case INITIALIZER_STRING:
1495         case INITIALIZER_WIDE_STRING:
1496         case INITIALIZER_DESIGNATOR:
1497                 return EXPR_CLASS_CONSTANT;
1498
1499         case INITIALIZER_VALUE:
1500                 return is_linker_constant(initializer->value.value);
1501
1502         case INITIALIZER_LIST: {
1503                 expression_classification_t all = EXPR_CLASS_CONSTANT;
1504                 for (size_t i = 0; i < initializer->list.len; ++i) {
1505                         initializer_t *sub_initializer = initializer->list.initializers[i];
1506                         expression_classification_t const cur = is_constant_initializer(sub_initializer);
1507                         if (all > cur) {
1508                                 all = cur;
1509                         }
1510                 }
1511                 return all;
1512         }
1513         }
1514         panic("invalid initializer kind found");
1515 }
1516
1517 /**
1518  * Checks if an expression references an object with a constant/known location
1519  * to the linker. Example:
1520  *  - "x", "*&x" with x being a global variable. The value of x need not be
1521  *         constant but the address of x is.
1522  *  - "a.b.c" when a has a constant/known location to the linker
1523  */
1524 static expression_classification_t is_object_with_linker_constant_address(
1525         const expression_t *expression)
1526 {
1527         switch (expression->kind) {
1528         case EXPR_UNARY_DEREFERENCE:
1529                 return is_linker_constant(expression->unary.value);
1530
1531         case EXPR_SELECT: {
1532                 type_t *base_type = skip_typeref(expression->select.compound->base.type);
1533                 if (is_type_pointer(base_type)) {
1534                         /* it's a -> */
1535                         return is_linker_constant(expression->select.compound);
1536                 } else {
1537                         return is_object_with_linker_constant_address(expression->select.compound);
1538                 }
1539         }
1540
1541         case EXPR_ARRAY_ACCESS: {
1542                 expression_classification_t const ref = is_linker_constant(expression->array_access.array_ref);
1543                 expression_classification_t const idx = is_constant_expression(expression->array_access.index);
1544                 return ref < idx ? ref : idx;
1545         }
1546
1547         case EXPR_REFERENCE: {
1548                 entity_t *entity = expression->reference.entity;
1549                 if (!is_declaration(entity))
1550                         return EXPR_CLASS_VARIABLE;
1551
1552                 switch ((storage_class_tag_t)entity->declaration.storage_class) {
1553                 case STORAGE_CLASS_NONE:
1554                 case STORAGE_CLASS_EXTERN:
1555                 case STORAGE_CLASS_STATIC:
1556                         return
1557                                 entity->kind != ENTITY_VARIABLE ||
1558                                 !entity->variable.thread_local ? EXPR_CLASS_CONSTANT :
1559                                 EXPR_CLASS_VARIABLE;
1560
1561                 case STORAGE_CLASS_REGISTER:
1562                 case STORAGE_CLASS_TYPEDEF:
1563                 case STORAGE_CLASS_AUTO:
1564                         break;
1565                 }
1566                 return EXPR_CLASS_VARIABLE;
1567         }
1568
1569         case EXPR_ERROR:
1570                 return EXPR_CLASS_ERROR;
1571
1572         default:
1573                 return EXPR_CLASS_VARIABLE;
1574         }
1575 }
1576
1577 expression_classification_t is_linker_constant(const expression_t *expression)
1578 {
1579         switch (expression->kind) {
1580         case EXPR_STRING_LITERAL:
1581         case EXPR_WIDE_STRING_LITERAL:
1582         case EXPR_FUNCNAME:
1583         case EXPR_LABEL_ADDRESS:
1584                 return EXPR_CLASS_CONSTANT;
1585
1586         case EXPR_COMPOUND_LITERAL:
1587                 return is_constant_initializer(expression->compound_literal.initializer);
1588
1589         case EXPR_UNARY_TAKE_ADDRESS:
1590                 return is_object_with_linker_constant_address(expression->unary.value);
1591
1592         case EXPR_UNARY_DEREFERENCE: {
1593                 type_t *real_type
1594                         = revert_automatic_type_conversion(expression->unary.value);
1595                 /* dereferencing a function is a NOP */
1596                 if (is_type_function(real_type)) {
1597                         return is_linker_constant(expression->unary.value);
1598                 }
1599                 /* FALLTHROUGH */
1600         }
1601
1602         case EXPR_UNARY_CAST: {
1603                 type_t *dest = skip_typeref(expression->base.type);
1604                 if (!is_type_pointer(dest) && (
1605                                 dest->kind != TYPE_ATOMIC                                               ||
1606                                 !(get_atomic_type_flags(dest->atomic.akind) & ATOMIC_TYPE_FLAG_INTEGER) ||
1607                                 get_atomic_type_size(dest->atomic.akind) < get_type_size(type_void_ptr)
1608                     ))
1609                         return is_constant_expression(expression);
1610
1611                 return is_linker_constant(expression->unary.value);
1612         }
1613
1614         case EXPR_BINARY_ADD:
1615         case EXPR_BINARY_SUB: {
1616                 expression_t *const left  = expression->binary.left;
1617                 expression_t *const right = expression->binary.right;
1618                 type_t       *const ltype = skip_typeref(left->base.type);
1619                 type_t       *const rtype = skip_typeref(right->base.type);
1620
1621                 if (is_type_pointer(ltype)) {
1622                         expression_classification_t const l = is_linker_constant(left);
1623                         expression_classification_t const r = is_constant_expression(right);
1624                         return l < r ? l : r;
1625                 } else if (is_type_pointer(rtype)) {
1626                         expression_classification_t const l = is_constant_expression(left);
1627                         expression_classification_t const r = is_linker_constant(right);
1628                         return l < r ? l : r;
1629                 } else if (!is_type_valid(ltype) || !is_type_valid(rtype)) {
1630                         return EXPR_CLASS_ERROR;
1631                 } else {
1632                         return is_constant_expression(expression);
1633                 }
1634         }
1635
1636         case EXPR_REFERENCE: {
1637                 entity_t *entity = expression->reference.entity;
1638                 if (!is_declaration(entity))
1639                         return EXPR_CLASS_VARIABLE;
1640
1641                 type_t *type = skip_typeref(entity->declaration.type);
1642                 if (is_type_function(type))
1643                         return EXPR_CLASS_CONSTANT;
1644                 if (is_type_array(type)) {
1645                         return is_object_with_linker_constant_address(expression);
1646                 }
1647                 /* Prevent stray errors */
1648                 if (!is_type_valid(type))
1649                         return EXPR_CLASS_ERROR;
1650                 return EXPR_CLASS_VARIABLE;
1651         }
1652
1653         case EXPR_ARRAY_ACCESS: {
1654                 type_t *const type =
1655                         skip_typeref(revert_automatic_type_conversion(expression));
1656                 if (!is_type_array(type))
1657                         return EXPR_CLASS_VARIABLE;
1658                 return is_linker_constant(expression->array_access.array_ref);
1659         }
1660
1661         case EXPR_CONDITIONAL: {
1662                 expression_t *const c = expression->conditional.condition;
1663                 expression_classification_t const cclass = is_constant_expression(c);
1664                 if (cclass != EXPR_CLASS_CONSTANT)
1665                         return cclass;
1666
1667                 if (fold_constant_to_bool(c)) {
1668                         expression_t const *const t = expression->conditional.true_expression;
1669                         return is_linker_constant(t != NULL ? t : c);
1670                 } else {
1671                         return is_linker_constant(expression->conditional.false_expression);
1672                 }
1673         }
1674
1675         case EXPR_SELECT: {
1676                 entity_t *entity = expression->select.compound_entry;
1677                 if (!is_declaration(entity))
1678                         return EXPR_CLASS_VARIABLE;
1679                 type_t *type = skip_typeref(entity->declaration.type);
1680                 if (is_type_array(type)) {
1681                         /* arrays automatically convert to their address */
1682                         expression_t *compound  = expression->select.compound;
1683                         type_t       *base_type = skip_typeref(compound->base.type);
1684                         if (is_type_pointer(base_type)) {
1685                                 /* it's a -> */
1686                                 return is_linker_constant(compound);
1687                         } else {
1688                                 return is_object_with_linker_constant_address(compound);
1689                         }
1690                 }
1691                 return EXPR_CLASS_VARIABLE;
1692         }
1693
1694         default:
1695                 return is_constant_expression(expression);
1696         }
1697 }
1698
1699 /**
1700  * Check if the given expression is a call to a builtin function
1701  * returning a constant result.
1702  */
1703 static expression_classification_t is_builtin_const_call(const expression_t *expression)
1704 {
1705         expression_t *function = expression->call.function;
1706         if (function->kind != EXPR_REFERENCE)
1707                 return EXPR_CLASS_VARIABLE;
1708         reference_expression_t *ref = &function->reference;
1709         if (ref->entity->kind != ENTITY_FUNCTION)
1710                 return EXPR_CLASS_VARIABLE;
1711
1712         switch (ref->entity->function.btk) {
1713         case BUILTIN_INF:
1714         case BUILTIN_NAN:
1715                 return EXPR_CLASS_CONSTANT;
1716         default:
1717                 return EXPR_CLASS_VARIABLE;
1718         }
1719
1720 }
1721
1722 static expression_classification_t is_constant_pointer(const expression_t *expression)
1723 {
1724         expression_classification_t const expr_class = is_constant_expression(expression);
1725         if (expr_class != EXPR_CLASS_VARIABLE)
1726                 return expr_class;
1727
1728         switch (expression->kind) {
1729         case EXPR_UNARY_CAST:
1730                 return is_constant_pointer(expression->unary.value);
1731         default:
1732                 return EXPR_CLASS_VARIABLE;
1733         }
1734 }
1735
1736 static expression_classification_t is_object_with_constant_address(const expression_t *expression)
1737 {
1738         switch (expression->kind) {
1739         case EXPR_SELECT: {
1740                 expression_t *compound      = expression->select.compound;
1741                 type_t       *compound_type = compound->base.type;
1742                 compound_type = skip_typeref(compound_type);
1743                 if (is_type_pointer(compound_type)) {
1744                         return is_constant_pointer(compound);
1745                 } else {
1746                         return is_object_with_constant_address(compound);
1747                 }
1748         }
1749
1750         case EXPR_ARRAY_ACCESS: {
1751                 array_access_expression_t const* const array_access =
1752                         &expression->array_access;
1753                 expression_classification_t const idx_class = is_constant_expression(array_access->index);
1754                 if (idx_class != EXPR_CLASS_CONSTANT)
1755                         return idx_class;
1756                 expression_classification_t const ref_addr = is_object_with_constant_address(array_access->array_ref);
1757                 expression_classification_t const ref_ptr  = is_constant_pointer(array_access->array_ref);
1758                 return ref_addr > ref_ptr ? ref_addr : ref_ptr;
1759         }
1760
1761         case EXPR_UNARY_DEREFERENCE:
1762                 return is_constant_pointer(expression->unary.value);
1763
1764         case EXPR_ERROR:
1765                 return EXPR_CLASS_ERROR;
1766
1767         default:
1768                 return EXPR_CLASS_VARIABLE;
1769         }
1770 }
1771
1772 expression_classification_t is_constant_expression(const expression_t *expression)
1773 {
1774         switch (expression->kind) {
1775         case EXPR_LITERAL_CASES:
1776         case EXPR_CLASSIFY_TYPE:
1777         case EXPR_OFFSETOF:
1778         case EXPR_ALIGNOF:
1779         case EXPR_BUILTIN_CONSTANT_P:
1780         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1781         case EXPR_REFERENCE_ENUM_VALUE:
1782                 return EXPR_CLASS_CONSTANT;
1783
1784         case EXPR_SIZEOF: {
1785                 type_t *const type = skip_typeref(expression->typeprop.type);
1786                 return
1787                         !is_type_array(type) || !type->array.is_vla ? EXPR_CLASS_CONSTANT :
1788                         EXPR_CLASS_VARIABLE;
1789         }
1790
1791         case EXPR_STRING_LITERAL:
1792         case EXPR_WIDE_STRING_LITERAL:
1793         case EXPR_FUNCNAME:
1794         case EXPR_LABEL_ADDRESS:
1795         case EXPR_SELECT:
1796         case EXPR_VA_START:
1797         case EXPR_VA_ARG:
1798         case EXPR_VA_COPY:
1799         case EXPR_STATEMENT:
1800         case EXPR_UNARY_POSTFIX_INCREMENT:
1801         case EXPR_UNARY_POSTFIX_DECREMENT:
1802         case EXPR_UNARY_PREFIX_INCREMENT:
1803         case EXPR_UNARY_PREFIX_DECREMENT:
1804         case EXPR_UNARY_ASSUME: /* has VOID type */
1805         case EXPR_UNARY_DEREFERENCE:
1806         case EXPR_UNARY_DELETE:
1807         case EXPR_UNARY_DELETE_ARRAY:
1808         case EXPR_UNARY_THROW:
1809         case EXPR_BINARY_ASSIGN:
1810         case EXPR_BINARY_MUL_ASSIGN:
1811         case EXPR_BINARY_DIV_ASSIGN:
1812         case EXPR_BINARY_MOD_ASSIGN:
1813         case EXPR_BINARY_ADD_ASSIGN:
1814         case EXPR_BINARY_SUB_ASSIGN:
1815         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1816         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1817         case EXPR_BINARY_BITWISE_AND_ASSIGN:
1818         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1819         case EXPR_BINARY_BITWISE_OR_ASSIGN:
1820         case EXPR_BINARY_COMMA:
1821         case EXPR_ARRAY_ACCESS:
1822                 return EXPR_CLASS_VARIABLE;
1823
1824         case EXPR_REFERENCE: {
1825                 type_t *const type = skip_typeref(expression->base.type);
1826                 return is_type_valid(type) ? EXPR_CLASS_VARIABLE : EXPR_CLASS_ERROR;
1827         }
1828
1829         case EXPR_UNARY_TAKE_ADDRESS:
1830                 return is_object_with_constant_address(expression->unary.value);
1831
1832         case EXPR_CALL:
1833                 return is_builtin_const_call(expression);
1834
1835         case EXPR_UNARY_NEGATE:
1836         case EXPR_UNARY_PLUS:
1837         case EXPR_UNARY_BITWISE_NEGATE:
1838         case EXPR_UNARY_NOT:
1839                 return is_constant_expression(expression->unary.value);
1840
1841         case EXPR_UNARY_CAST: {
1842                 type_t *const type = skip_typeref(expression->base.type);
1843                 if (is_type_scalar(type))
1844                         return is_constant_expression(expression->unary.value);
1845                 if (!is_type_valid(type))
1846                         return EXPR_CLASS_ERROR;
1847                 return EXPR_CLASS_VARIABLE;
1848         }
1849
1850         case EXPR_BINARY_ADD:
1851         case EXPR_BINARY_SUB:
1852         case EXPR_BINARY_MUL:
1853         case EXPR_BINARY_DIV:
1854         case EXPR_BINARY_MOD:
1855         case EXPR_BINARY_EQUAL:
1856         case EXPR_BINARY_NOTEQUAL:
1857         case EXPR_BINARY_LESS:
1858         case EXPR_BINARY_LESSEQUAL:
1859         case EXPR_BINARY_GREATER:
1860         case EXPR_BINARY_GREATEREQUAL:
1861         case EXPR_BINARY_BITWISE_AND:
1862         case EXPR_BINARY_BITWISE_OR:
1863         case EXPR_BINARY_BITWISE_XOR:
1864         case EXPR_BINARY_SHIFTLEFT:
1865         case EXPR_BINARY_SHIFTRIGHT:
1866         case EXPR_BINARY_ISGREATER:
1867         case EXPR_BINARY_ISGREATEREQUAL:
1868         case EXPR_BINARY_ISLESS:
1869         case EXPR_BINARY_ISLESSEQUAL:
1870         case EXPR_BINARY_ISLESSGREATER:
1871         case EXPR_BINARY_ISUNORDERED: {
1872                 expression_classification_t const l = is_constant_expression(expression->binary.left);
1873                 expression_classification_t const r = is_constant_expression(expression->binary.right);
1874                 return l < r ? l : r;
1875         }
1876
1877         case EXPR_BINARY_LOGICAL_AND: {
1878                 expression_t const         *const left   = expression->binary.left;
1879                 expression_classification_t const lclass = is_constant_expression(left);
1880                 if (lclass != EXPR_CLASS_CONSTANT)
1881                         return lclass;
1882                 if (!fold_constant_to_bool(left))
1883                         return EXPR_CLASS_CONSTANT;
1884                 return is_constant_expression(expression->binary.right);
1885         }
1886
1887         case EXPR_BINARY_LOGICAL_OR: {
1888                 expression_t const         *const left   = expression->binary.left;
1889                 expression_classification_t const lclass = is_constant_expression(left);
1890                 if (lclass != EXPR_CLASS_CONSTANT)
1891                         return lclass;
1892                 if (fold_constant_to_bool(left))
1893                         return EXPR_CLASS_CONSTANT;
1894                 return is_constant_expression(expression->binary.right);
1895         }
1896
1897         case EXPR_COMPOUND_LITERAL:
1898                 return is_constant_initializer(expression->compound_literal.initializer);
1899
1900         case EXPR_CONDITIONAL: {
1901                 expression_t               *const condition = expression->conditional.condition;
1902                 expression_classification_t const cclass    = is_constant_expression(condition);
1903                 if (cclass != EXPR_CLASS_CONSTANT)
1904                         return cclass;
1905
1906                 if (fold_constant_to_bool(condition)) {
1907                         expression_t const *const t = expression->conditional.true_expression;
1908                         return t == NULL ? EXPR_CLASS_CONSTANT : is_constant_expression(t);
1909                 } else {
1910                         return is_constant_expression(expression->conditional.false_expression);
1911                 }
1912         }
1913
1914         case EXPR_ERROR:
1915                 return EXPR_CLASS_ERROR;
1916         }
1917         panic("invalid expression found (is constant expression)");
1918 }
1919
1920 void init_ast(void)
1921 {
1922         obstack_init(&ast_obstack);
1923 }
1924
1925 void exit_ast(void)
1926 {
1927         obstack_free(&ast_obstack, NULL);
1928 }