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