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