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