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