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