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