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