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