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