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