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