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