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