more parsetests
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "diagnostic.h"
8 #include "format_check.h"
9 #include "parser.h"
10 #include "lexer.h"
11 #include "token_t.h"
12 #include "types.h"
13 #include "type_t.h"
14 #include "type_hash.h"
15 #include "ast_t.h"
16 #include "lang_features.h"
17 #include "warning.h"
18 #include "adt/bitfiddle.h"
19 #include "adt/error.h"
20 #include "adt/array.h"
21
22 //#define PRINT_TOKENS
23 #define MAX_LOOKAHEAD 2
24
25 typedef struct {
26         declaration_t *old_declaration;
27         symbol_t      *symbol;
28         unsigned short namespc;
29 } stack_entry_t;
30
31 typedef struct declaration_specifiers_t  declaration_specifiers_t;
32 struct declaration_specifiers_t {
33         source_position_t  source_position;
34         unsigned char      storage_class;
35         bool               is_inline;
36         decl_modifiers_t   decl_modifiers;
37         type_t            *type;
38 };
39
40 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
41
42 static token_t             token;
43 static token_t             lookahead_buffer[MAX_LOOKAHEAD];
44 static int                 lookahead_bufpos;
45 static stack_entry_t      *environment_stack = NULL;
46 static stack_entry_t      *label_stack       = NULL;
47 static scope_t            *global_scope      = NULL;
48 static scope_t            *scope             = NULL;
49 static declaration_t      *last_declaration  = NULL;
50 static declaration_t      *current_function  = NULL;
51 static switch_statement_t *current_switch    = NULL;
52 static statement_t        *current_loop      = NULL;
53 static goto_statement_t   *goto_first        = NULL;
54 static goto_statement_t   *goto_last         = NULL;
55 static label_statement_t  *label_first       = NULL;
56 static label_statement_t  *label_last        = NULL;
57 static struct obstack      temp_obst;
58
59 /** The current source position. */
60 #define HERE token.source_position
61
62 static type_t *type_valist;
63
64 static statement_t *parse_compound_statement(void);
65 static statement_t *parse_statement(void);
66
67 static expression_t *parse_sub_expression(unsigned precedence);
68 static expression_t *parse_expression(void);
69 static type_t       *parse_typename(void);
70
71 static void parse_compound_type_entries(declaration_t *compound_declaration);
72 static declaration_t *parse_declarator(
73                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
74 static declaration_t *record_declaration(declaration_t *declaration);
75
76 static void semantic_comparison(binary_expression_t *expression);
77
78 #define STORAGE_CLASSES     \
79         case T_typedef:         \
80         case T_extern:          \
81         case T_static:          \
82         case T_auto:            \
83         case T_register:
84
85 #define TYPE_QUALIFIERS     \
86         case T_const:           \
87         case T_restrict:        \
88         case T_volatile:        \
89         case T_inline:          \
90         case T_forceinline:
91
92 #ifdef PROVIDE_COMPLEX
93 #define COMPLEX_SPECIFIERS  \
94         case T__Complex:
95 #define IMAGINARY_SPECIFIERS \
96         case T__Imaginary:
97 #else
98 #define COMPLEX_SPECIFIERS
99 #define IMAGINARY_SPECIFIERS
100 #endif
101
102 #define TYPE_SPECIFIERS       \
103         case T_void:              \
104         case T_char:              \
105         case T_short:             \
106         case T_int:               \
107         case T_long:              \
108         case T_float:             \
109         case T_double:            \
110         case T_signed:            \
111         case T_unsigned:          \
112         case T__Bool:             \
113         case T_struct:            \
114         case T_union:             \
115         case T_enum:              \
116         case T___typeof__:        \
117         case T___builtin_va_list: \
118         COMPLEX_SPECIFIERS        \
119         IMAGINARY_SPECIFIERS
120
121 #define DECLARATION_START   \
122         STORAGE_CLASSES         \
123         TYPE_QUALIFIERS         \
124         TYPE_SPECIFIERS
125
126 #define TYPENAME_START      \
127         TYPE_QUALIFIERS         \
128         TYPE_SPECIFIERS
129
130 /**
131  * Allocate an AST node with given size and
132  * initialize all fields with zero.
133  */
134 static void *allocate_ast_zero(size_t size)
135 {
136         void *res = allocate_ast(size);
137         memset(res, 0, size);
138         return res;
139 }
140
141 static declaration_t *allocate_declaration_zero(void)
142 {
143         declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
144         declaration->type = type_error_type;
145         return declaration;
146 }
147
148 /**
149  * Returns the size of a statement node.
150  *
151  * @param kind  the statement kind
152  */
153 static size_t get_statement_struct_size(statement_kind_t kind)
154 {
155         static const size_t sizes[] = {
156                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
157                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
158                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
159                 [STATEMENT_IF]          = sizeof(if_statement_t),
160                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
161                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
162                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
163                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
164                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
165                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
166                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
167                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
168                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
169                 [STATEMENT_FOR]         = sizeof(for_statement_t),
170                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
171         };
172         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
173         assert(sizes[kind] != 0);
174         return sizes[kind];
175 }
176
177 /**
178  * Allocate a statement node of given kind and initialize all
179  * fields with zero.
180  */
181 static statement_t *allocate_statement_zero(statement_kind_t kind)
182 {
183         size_t       size = get_statement_struct_size(kind);
184         statement_t *res  = allocate_ast_zero(size);
185
186         res->base.kind = kind;
187         return res;
188 }
189
190 /**
191  * Returns the size of an expression node.
192  *
193  * @param kind  the expression kind
194  */
195 static size_t get_expression_struct_size(expression_kind_t kind)
196 {
197         static const size_t sizes[] = {
198                 [EXPR_INVALID]             = sizeof(expression_base_t),
199                 [EXPR_REFERENCE]           = sizeof(reference_expression_t),
200                 [EXPR_CONST]               = sizeof(const_expression_t),
201                 [EXPR_CHAR_CONST]          = sizeof(const_expression_t),
202                 [EXPR_STRING_LITERAL]      = sizeof(string_literal_expression_t),
203                 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
204                 [EXPR_COMPOUND_LITERAL]    = sizeof(compound_literal_expression_t),
205                 [EXPR_CALL]                = sizeof(call_expression_t),
206                 [EXPR_UNARY_FIRST]         = sizeof(unary_expression_t),
207                 [EXPR_BINARY_FIRST]        = sizeof(binary_expression_t),
208                 [EXPR_CONDITIONAL]         = sizeof(conditional_expression_t),
209                 [EXPR_SELECT]              = sizeof(select_expression_t),
210                 [EXPR_ARRAY_ACCESS]        = sizeof(array_access_expression_t),
211                 [EXPR_SIZEOF]              = sizeof(typeprop_expression_t),
212                 [EXPR_ALIGNOF]             = sizeof(typeprop_expression_t),
213                 [EXPR_CLASSIFY_TYPE]       = sizeof(classify_type_expression_t),
214                 [EXPR_FUNCTION]            = sizeof(string_literal_expression_t),
215                 [EXPR_PRETTY_FUNCTION]     = sizeof(string_literal_expression_t),
216                 [EXPR_BUILTIN_SYMBOL]      = sizeof(builtin_symbol_expression_t),
217                 [EXPR_BUILTIN_CONSTANT_P]  = sizeof(builtin_constant_expression_t),
218                 [EXPR_BUILTIN_PREFETCH]    = sizeof(builtin_prefetch_expression_t),
219                 [EXPR_OFFSETOF]            = sizeof(offsetof_expression_t),
220                 [EXPR_VA_START]            = sizeof(va_start_expression_t),
221                 [EXPR_VA_ARG]              = sizeof(va_arg_expression_t),
222                 [EXPR_STATEMENT]           = sizeof(statement_expression_t),
223         };
224         if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
225                 return sizes[EXPR_UNARY_FIRST];
226         }
227         if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
228                 return sizes[EXPR_BINARY_FIRST];
229         }
230         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
231         assert(sizes[kind] != 0);
232         return sizes[kind];
233 }
234
235 /**
236  * Allocate an expression node of given kind and initialize all
237  * fields with zero.
238  */
239 static expression_t *allocate_expression_zero(expression_kind_t kind)
240 {
241         size_t        size = get_expression_struct_size(kind);
242         expression_t *res  = allocate_ast_zero(size);
243
244         res->base.kind = kind;
245         res->base.type = type_error_type;
246         return res;
247 }
248
249 /**
250  * Returns the size of a type node.
251  *
252  * @param kind  the type kind
253  */
254 static size_t get_type_struct_size(type_kind_t kind)
255 {
256         static const size_t sizes[] = {
257                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
258                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
259                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
260                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
261                 [TYPE_ENUM]            = sizeof(enum_type_t),
262                 [TYPE_FUNCTION]        = sizeof(function_type_t),
263                 [TYPE_POINTER]         = sizeof(pointer_type_t),
264                 [TYPE_ARRAY]           = sizeof(array_type_t),
265                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
266                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
267                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
268         };
269         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
270         assert(kind <= TYPE_TYPEOF);
271         assert(sizes[kind] != 0);
272         return sizes[kind];
273 }
274
275 /**
276  * Allocate a type node of given kind and initialize all
277  * fields with zero.
278  */
279 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
280 {
281         size_t  size = get_type_struct_size(kind);
282         type_t *res  = obstack_alloc(type_obst, size);
283         memset(res, 0, size);
284
285         res->base.kind            = kind;
286         res->base.source_position = source_position;
287         return res;
288 }
289
290 /**
291  * Returns the size of an initializer node.
292  *
293  * @param kind  the initializer kind
294  */
295 static size_t get_initializer_size(initializer_kind_t kind)
296 {
297         static const size_t sizes[] = {
298                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
299                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
300                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
301                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
302                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
303         };
304         assert(kind < sizeof(sizes) / sizeof(*sizes));
305         assert(sizes[kind] != 0);
306         return sizes[kind];
307 }
308
309 /**
310  * Allocate an initializer node of given kind and initialize all
311  * fields with zero.
312  */
313 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
314 {
315         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
316         result->kind          = kind;
317
318         return result;
319 }
320
321 /**
322  * Free a type from the type obstack.
323  */
324 static void free_type(void *type)
325 {
326         obstack_free(type_obst, type);
327 }
328
329 /**
330  * Returns the index of the top element of the environment stack.
331  */
332 static size_t environment_top(void)
333 {
334         return ARR_LEN(environment_stack);
335 }
336
337 /**
338  * Returns the index of the top element of the label stack.
339  */
340 static size_t label_top(void)
341 {
342         return ARR_LEN(label_stack);
343 }
344
345
346 /**
347  * Return the next token.
348  */
349 static inline void next_token(void)
350 {
351         token                              = lookahead_buffer[lookahead_bufpos];
352         lookahead_buffer[lookahead_bufpos] = lexer_token;
353         lexer_next_token();
354
355         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
356
357 #ifdef PRINT_TOKENS
358         print_token(stderr, &token);
359         fprintf(stderr, "\n");
360 #endif
361 }
362
363 /**
364  * Return the next token with a given lookahead.
365  */
366 static inline const token_t *look_ahead(int num)
367 {
368         assert(num > 0 && num <= MAX_LOOKAHEAD);
369         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
370         return &lookahead_buffer[pos];
371 }
372
373 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
374
375 /**
376  * Report a parse error because an expected token was not found.
377  */
378 static void parse_error_expected(const char *message, ...)
379 {
380         if(message != NULL) {
381                 errorf(HERE, "%s", message);
382         }
383         va_list ap;
384         va_start(ap, message);
385         errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
386         va_end(ap);
387 }
388
389 /**
390  * Report a type error.
391  */
392 static void type_error(const char *msg, const source_position_t source_position,
393                        type_t *type)
394 {
395         errorf(source_position, "%s, but found type '%T'", msg, type);
396 }
397
398 /**
399  * Report an incompatible type.
400  */
401 static void type_error_incompatible(const char *msg,
402                 const source_position_t source_position, type_t *type1, type_t *type2)
403 {
404         errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
405 }
406
407 /**
408  * Eat an complete block, ie. '{ ... }'.
409  */
410 static void eat_block(void)
411 {
412         if(token.type == '{')
413                 next_token();
414
415         while(token.type != '}') {
416                 if(token.type == T_EOF)
417                         return;
418                 if(token.type == '{') {
419                         eat_block();
420                         continue;
421                 }
422                 next_token();
423         }
424         eat('}');
425 }
426
427 /**
428  * Eat a statement until an ';' token.
429  */
430 static void eat_statement(void)
431 {
432         while(token.type != ';') {
433                 if(token.type == T_EOF)
434                         return;
435                 if(token.type == '}')
436                         return;
437                 if(token.type == '{') {
438                         eat_block();
439                         continue;
440                 }
441                 next_token();
442         }
443         eat(';');
444 }
445
446 /**
447  * Eat a parenthesed term, ie. '( ... )'.
448  */
449 static void eat_paren(void)
450 {
451         if(token.type == '(')
452                 next_token();
453
454         while(token.type != ')') {
455                 if(token.type == T_EOF)
456                         return;
457                 if(token.type == ')' || token.type == ';' || token.type == '}') {
458                         return;
459                 }
460                 if(token.type == '(') {
461                         eat_paren();
462                         continue;
463                 }
464                 if(token.type == '{') {
465                         eat_block();
466                         continue;
467                 }
468                 next_token();
469         }
470         eat(')');
471 }
472
473 #define expect(expected)                           \
474         do {                                           \
475     if(UNLIKELY(token.type != (expected))) {       \
476         parse_error_expected(NULL, (expected), 0); \
477         eat_statement();                           \
478         return NULL;                               \
479     }                                              \
480     next_token();                                  \
481         } while(0)
482
483 #define expect_block(expected)                     \
484         do {                                           \
485     if(UNLIKELY(token.type != (expected))) {       \
486         parse_error_expected(NULL, (expected), 0); \
487         eat_block();                               \
488         return NULL;                               \
489     }                                              \
490     next_token();                                  \
491         } while(0)
492
493 #define expect_void(expected)                      \
494         do {                                           \
495     if(UNLIKELY(token.type != (expected))) {       \
496         parse_error_expected(NULL, (expected), 0); \
497         eat_statement();                           \
498         return;                                    \
499     }                                              \
500     next_token();                                  \
501     } while(0)
502
503 static void set_scope(scope_t *new_scope)
504 {
505         if(scope != NULL) {
506                 scope->last_declaration = last_declaration;
507         }
508         scope = new_scope;
509
510         last_declaration = new_scope->last_declaration;
511 }
512
513 /**
514  * Search a symbol in a given namespace and returns its declaration or
515  * NULL if this symbol was not found.
516  */
517 static declaration_t *get_declaration(const symbol_t *const symbol, const namespace_t namespc)
518 {
519         declaration_t *declaration = symbol->declaration;
520         for( ; declaration != NULL; declaration = declaration->symbol_next) {
521                 if(declaration->namespc == namespc)
522                         return declaration;
523         }
524
525         return NULL;
526 }
527
528 /**
529  * pushs an environment_entry on the environment stack and links the
530  * corresponding symbol to the new entry
531  */
532 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
533 {
534         symbol_t    *symbol  = declaration->symbol;
535         namespace_t  namespc = (namespace_t) declaration->namespc;
536
537         /* replace/add declaration into declaration list of the symbol */
538         declaration_t *iter = symbol->declaration;
539         if (iter == NULL) {
540                 symbol->declaration = declaration;
541         } else {
542                 declaration_t *iter_last = NULL;
543                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
544                         /* replace an entry? */
545                         if(iter->namespc == namespc) {
546                                 if(iter_last == NULL) {
547                                         symbol->declaration = declaration;
548                                 } else {
549                                         iter_last->symbol_next = declaration;
550                                 }
551                                 declaration->symbol_next = iter->symbol_next;
552                                 break;
553                         }
554                 }
555                 if(iter == NULL) {
556                         assert(iter_last->symbol_next == NULL);
557                         iter_last->symbol_next = declaration;
558                 }
559         }
560
561         /* remember old declaration */
562         stack_entry_t entry;
563         entry.symbol          = symbol;
564         entry.old_declaration = iter;
565         entry.namespc         = (unsigned short) namespc;
566         ARR_APP1(stack_entry_t, *stack_ptr, entry);
567 }
568
569 static void environment_push(declaration_t *declaration)
570 {
571         assert(declaration->source_position.input_name != NULL);
572         assert(declaration->parent_scope != NULL);
573         stack_push(&environment_stack, declaration);
574 }
575
576 static void label_push(declaration_t *declaration)
577 {
578         declaration->parent_scope = &current_function->scope;
579         stack_push(&label_stack, declaration);
580 }
581
582 /**
583  * pops symbols from the environment stack until @p new_top is the top element
584  */
585 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
586 {
587         stack_entry_t *stack = *stack_ptr;
588         size_t         top   = ARR_LEN(stack);
589         size_t         i;
590
591         assert(new_top <= top);
592         if(new_top == top)
593                 return;
594
595         for(i = top; i > new_top; --i) {
596                 stack_entry_t *entry = &stack[i - 1];
597
598                 declaration_t *old_declaration = entry->old_declaration;
599                 symbol_t      *symbol          = entry->symbol;
600                 namespace_t    namespc         = (namespace_t)entry->namespc;
601
602                 /* replace/remove declaration */
603                 declaration_t *declaration = symbol->declaration;
604                 assert(declaration != NULL);
605                 if(declaration->namespc == namespc) {
606                         if(old_declaration == NULL) {
607                                 symbol->declaration = declaration->symbol_next;
608                         } else {
609                                 symbol->declaration = old_declaration;
610                         }
611                 } else {
612                         declaration_t *iter_last = declaration;
613                         declaration_t *iter      = declaration->symbol_next;
614                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
615                                 /* replace an entry? */
616                                 if(iter->namespc == namespc) {
617                                         assert(iter_last != NULL);
618                                         iter_last->symbol_next = old_declaration;
619                                         if(old_declaration != NULL) {
620                                                 old_declaration->symbol_next = iter->symbol_next;
621                                         }
622                                         break;
623                                 }
624                         }
625                         assert(iter != NULL);
626                 }
627         }
628
629         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
630 }
631
632 static void environment_pop_to(size_t new_top)
633 {
634         stack_pop_to(&environment_stack, new_top);
635 }
636
637 static void label_pop_to(size_t new_top)
638 {
639         stack_pop_to(&label_stack, new_top);
640 }
641
642
643 static int get_rank(const type_t *type)
644 {
645         assert(!is_typeref(type));
646         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
647          * and esp. footnote 108). However we can't fold constants (yet), so we
648          * can't decide whether unsigned int is possible, while int always works.
649          * (unsigned int would be preferable when possible... for stuff like
650          *  struct { enum { ... } bla : 4; } ) */
651         if(type->kind == TYPE_ENUM)
652                 return ATOMIC_TYPE_INT;
653
654         assert(type->kind == TYPE_ATOMIC);
655         return type->atomic.akind;
656 }
657
658 static type_t *promote_integer(type_t *type)
659 {
660         if(type->kind == TYPE_BITFIELD)
661                 type = type->bitfield.base;
662
663         if(get_rank(type) < ATOMIC_TYPE_INT)
664                 type = type_int;
665
666         return type;
667 }
668
669 /**
670  * Create a cast expression.
671  *
672  * @param expression  the expression to cast
673  * @param dest_type   the destination type
674  */
675 static expression_t *create_cast_expression(expression_t *expression,
676                                             type_t *dest_type)
677 {
678         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
679
680         cast->unary.value = expression;
681         cast->base.type   = dest_type;
682
683         return cast;
684 }
685
686 /**
687  * Check if a given expression represents the 0 pointer constant.
688  */
689 static bool is_null_pointer_constant(const expression_t *expression)
690 {
691         /* skip void* cast */
692         if(expression->kind == EXPR_UNARY_CAST
693                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
694                 expression = expression->unary.value;
695         }
696
697         /* TODO: not correct yet, should be any constant integer expression
698          * which evaluates to 0 */
699         if (expression->kind != EXPR_CONST)
700                 return false;
701
702         type_t *const type = skip_typeref(expression->base.type);
703         if (!is_type_integer(type))
704                 return false;
705
706         return expression->conste.v.int_value == 0;
707 }
708
709 /**
710  * Create an implicit cast expression.
711  *
712  * @param expression  the expression to cast
713  * @param dest_type   the destination type
714  */
715 static expression_t *create_implicit_cast(expression_t *expression,
716                                           type_t *dest_type)
717 {
718         type_t *const source_type = expression->base.type;
719
720         if (source_type == dest_type)
721                 return expression;
722
723         return create_cast_expression(expression, dest_type);
724 }
725
726 /** Implements the rules from Â§ 6.5.16.1 */
727 static type_t *semantic_assign(type_t *orig_type_left,
728                             const expression_t *const right,
729                             const char *context)
730 {
731         type_t *const orig_type_right = right->base.type;
732         type_t *const type_left       = skip_typeref(orig_type_left);
733         type_t *const type_right      = skip_typeref(orig_type_right);
734
735         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
736             (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
737             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
738                 && is_type_pointer(type_right))) {
739                 return orig_type_left;
740         }
741
742         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
743                 type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
744                 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
745
746                 /* the left type has all qualifiers from the right type */
747                 unsigned missing_qualifiers
748                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
749                 if(missing_qualifiers != 0) {
750                         errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
751                         return orig_type_left;
752                 }
753
754                 points_to_left  = get_unqualified_type(points_to_left);
755                 points_to_right = get_unqualified_type(points_to_right);
756
757                 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
758                                 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
759                         return orig_type_left;
760                 }
761
762                 if (!types_compatible(points_to_left, points_to_right)) {
763                         warningf(right->base.source_position,
764                                 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
765                                 orig_type_left, context, right, orig_type_right);
766                 }
767
768                 return orig_type_left;
769         }
770
771         if ((is_type_compound(type_left)  && is_type_compound(type_right))
772                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
773                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
774                 type_t *const unqual_type_right = get_unqualified_type(type_right);
775                 if (types_compatible(unqual_type_left, unqual_type_right)) {
776                         return orig_type_left;
777                 }
778         }
779
780         if (!is_type_valid(type_left))
781                 return type_left;
782
783         if (!is_type_valid(type_right))
784                 return orig_type_right;
785
786         return NULL;
787 }
788
789 static expression_t *parse_constant_expression(void)
790 {
791         /* start parsing at precedence 7 (conditional expression) */
792         expression_t *result = parse_sub_expression(7);
793
794         if(!is_constant_expression(result)) {
795                 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
796         }
797
798         return result;
799 }
800
801 static expression_t *parse_assignment_expression(void)
802 {
803         /* start parsing at precedence 2 (assignment expression) */
804         return parse_sub_expression(2);
805 }
806
807 static type_t *make_global_typedef(const char *name, type_t *type)
808 {
809         symbol_t *const symbol       = symbol_table_insert(name);
810
811         declaration_t *const declaration = allocate_declaration_zero();
812         declaration->namespc         = NAMESPACE_NORMAL;
813         declaration->storage_class   = STORAGE_CLASS_TYPEDEF;
814         declaration->type            = type;
815         declaration->symbol          = symbol;
816         declaration->source_position = builtin_source_position;
817
818         record_declaration(declaration);
819
820         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
821         typedef_type->typedeft.declaration = declaration;
822
823         return typedef_type;
824 }
825
826 static string_t parse_string_literals(void)
827 {
828         assert(token.type == T_STRING_LITERAL);
829         string_t result = token.v.string;
830
831         next_token();
832
833         while (token.type == T_STRING_LITERAL) {
834                 result = concat_strings(&result, &token.v.string);
835                 next_token();
836         }
837
838         return result;
839 }
840
841 static void parse_attributes(void)
842 {
843         while(true) {
844                 switch(token.type) {
845                 case T___attribute__: {
846                         next_token();
847
848                         expect_void('(');
849                         int depth = 1;
850                         while(depth > 0) {
851                                 switch(token.type) {
852                                 case T_EOF:
853                                         errorf(HERE, "EOF while parsing attribute");
854                                         break;
855                                 case '(':
856                                         next_token();
857                                         depth++;
858                                         break;
859                                 case ')':
860                                         next_token();
861                                         depth--;
862                                         break;
863                                 default:
864                                         next_token();
865                                 }
866                         }
867                         break;
868                 }
869                 case T_asm:
870                         next_token();
871                         expect_void('(');
872                         if(token.type != T_STRING_LITERAL) {
873                                 parse_error_expected("while parsing assembler attribute",
874                                                      T_STRING_LITERAL);
875                                 eat_paren();
876                                 break;
877                         } else {
878                                 parse_string_literals();
879                         }
880                         expect_void(')');
881                         break;
882                 default:
883                         goto attributes_finished;
884                 }
885         }
886
887 attributes_finished:
888         ;
889 }
890
891 static designator_t *parse_designation(void)
892 {
893         designator_t *result = NULL;
894         designator_t *last   = NULL;
895
896         while(true) {
897                 designator_t *designator;
898                 switch(token.type) {
899                 case '[':
900                         designator = allocate_ast_zero(sizeof(designator[0]));
901                         designator->source_position = token.source_position;
902                         next_token();
903                         designator->array_index = parse_constant_expression();
904                         expect(']');
905                         break;
906                 case '.':
907                         designator = allocate_ast_zero(sizeof(designator[0]));
908                         designator->source_position = token.source_position;
909                         next_token();
910                         if(token.type != T_IDENTIFIER) {
911                                 parse_error_expected("while parsing designator",
912                                                      T_IDENTIFIER, 0);
913                                 return NULL;
914                         }
915                         designator->symbol = token.v.symbol;
916                         next_token();
917                         break;
918                 default:
919                         expect('=');
920                         return result;
921                 }
922
923                 assert(designator != NULL);
924                 if(last != NULL) {
925                         last->next = designator;
926                 } else {
927                         result = designator;
928                 }
929                 last = designator;
930         }
931 }
932
933 static initializer_t *initializer_from_string(array_type_t *type,
934                                               const string_t *const string)
935 {
936         /* TODO: check len vs. size of array type */
937         (void) type;
938
939         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
940         initializer->string.string = *string;
941
942         return initializer;
943 }
944
945 static initializer_t *initializer_from_wide_string(array_type_t *const type,
946                                                    wide_string_t *const string)
947 {
948         /* TODO: check len vs. size of array type */
949         (void) type;
950
951         initializer_t *const initializer =
952                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
953         initializer->wide_string.string = *string;
954
955         return initializer;
956 }
957
958 static initializer_t *initializer_from_expression(type_t *orig_type,
959                                                   expression_t *expression)
960 {
961         /* TODO check that expression is a constant expression */
962
963         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
964         type_t *type           = skip_typeref(orig_type);
965         type_t *expr_type_orig = expression->base.type;
966         type_t *expr_type      = skip_typeref(expr_type_orig);
967         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
968                 array_type_t *const array_type   = &type->array;
969                 type_t       *const element_type = skip_typeref(array_type->element_type);
970
971                 if (element_type->kind == TYPE_ATOMIC) {
972                         atomic_type_kind_t akind = element_type->atomic.akind;
973                         switch (expression->kind) {
974                                 case EXPR_STRING_LITERAL:
975                                         if (akind == ATOMIC_TYPE_CHAR
976                                                         || akind == ATOMIC_TYPE_SCHAR
977                                                         || akind == ATOMIC_TYPE_UCHAR) {
978                                                 return initializer_from_string(array_type,
979                                                         &expression->string.value);
980                                         }
981
982                                 case EXPR_WIDE_STRING_LITERAL: {
983                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
984                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
985                                                 return initializer_from_wide_string(array_type,
986                                                         &expression->wide_string.value);
987                                         }
988                                 }
989
990                                 default:
991                                         break;
992                         }
993                 }
994         }
995
996         type_t *const res_type = semantic_assign(type, expression, "initializer");
997         if (res_type == NULL)
998                 return NULL;
999
1000         initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1001         result->value.value = create_implicit_cast(expression, res_type);
1002
1003         return result;
1004 }
1005
1006 static initializer_t *parse_scalar_initializer(type_t *type)
1007 {
1008         /* there might be extra {} hierarchies */
1009         int braces = 0;
1010         while(token.type == '{') {
1011                 next_token();
1012                 if(braces == 0) {
1013                         warningf(HERE, "extra curly braces around scalar initializer");
1014                 }
1015                 braces++;
1016         }
1017
1018         expression_t  *expression  = parse_assignment_expression();
1019         initializer_t *initializer = initializer_from_expression(type, expression);
1020
1021         if(initializer == NULL) {
1022                 errorf(expression->base.source_position,
1023                        "expression '%E' doesn't match expected type '%T'",
1024                        expression, type);
1025                 /* TODO */
1026                 return NULL;
1027         }
1028
1029         bool additional_warning_displayed = false;
1030         while(braces > 0) {
1031                 if(token.type == ',') {
1032                         next_token();
1033                 }
1034                 if(token.type != '}') {
1035                         if(!additional_warning_displayed) {
1036                                 warningf(HERE, "additional elements in scalar initializer");
1037                                 additional_warning_displayed = true;
1038                         }
1039                 }
1040                 eat_block();
1041                 braces--;
1042         }
1043
1044         return initializer;
1045 }
1046
1047 typedef struct type_path_entry_t type_path_entry_t;
1048 struct type_path_entry_t {
1049         type_t *type;
1050         union {
1051                 size_t         index;
1052                 declaration_t *compound_entry;
1053         } v;
1054 };
1055
1056 typedef struct type_path_t type_path_t;
1057 struct type_path_t {
1058         type_path_entry_t *path;
1059         type_t            *top_type;
1060         bool               invalid;
1061 };
1062
1063 static __attribute__((unused)) void debug_print_type_path(const type_path_t *path)
1064 {
1065         size_t len = ARR_LEN(path->path);
1066
1067         if(path->invalid) {
1068                 fprintf(stderr, "invalid path");
1069                 return;
1070         }
1071
1072         for(size_t i = 0; i < len; ++i) {
1073                 const type_path_entry_t *entry = & path->path[i];
1074
1075                 type_t *type = skip_typeref(entry->type);
1076                 if(is_type_compound(type)) {
1077                         fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1078                 } else if(is_type_array(type)) {
1079                         fprintf(stderr, "[%u]", entry->v.index);
1080                 } else {
1081                         fprintf(stderr, "-INVALID-");
1082                 }
1083         }
1084         fprintf(stderr, "  (");
1085         print_type(path->top_type);
1086         fprintf(stderr, ")");
1087 }
1088
1089 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1090 {
1091         size_t len = ARR_LEN(path->path);
1092         assert(len > 0);
1093         return & path->path[len-1];
1094 }
1095
1096 static type_path_entry_t *append_to_type_path(type_path_t *path)
1097 {
1098         size_t len = ARR_LEN(path->path);
1099         ARR_RESIZE(type_path_entry_t, path->path, len+1);
1100
1101         type_path_entry_t *result = & path->path[len];
1102         memset(result, 0, sizeof(result[0]));
1103         return result;
1104 }
1105
1106 static void descend_into_subtype(type_path_t *path)
1107 {
1108         type_t *orig_top_type = path->top_type;
1109         type_t *top_type      = skip_typeref(orig_top_type);
1110
1111         assert(is_type_compound(top_type) || is_type_array(top_type));
1112
1113         type_path_entry_t *top = append_to_type_path(path);
1114         top->type              = top_type;
1115
1116         if(is_type_compound(top_type)) {
1117                 declaration_t *declaration = top_type->compound.declaration;
1118                 declaration_t *entry       = declaration->scope.declarations;
1119
1120                 top->v.compound_entry = entry;
1121                 path->top_type        = entry->type;
1122         } else {
1123                 assert(is_type_array(top_type));
1124
1125                 top->v.index   = 0;
1126                 path->top_type = top_type->array.element_type;
1127         }
1128 }
1129
1130 static void ascend_from_subtype(type_path_t *path)
1131 {
1132         type_path_entry_t *top = get_type_path_top(path);
1133
1134         path->top_type = top->type;
1135
1136         size_t len = ARR_LEN(path->path);
1137         ARR_RESIZE(type_path_entry_t, path->path, len-1);
1138 }
1139
1140 static void ascend_to(type_path_t *path, size_t top_path_level)
1141 {
1142         size_t len = ARR_LEN(path->path);
1143         assert(len >= top_path_level);
1144
1145         while(len > top_path_level) {
1146                 ascend_from_subtype(path);
1147                 len = ARR_LEN(path->path);
1148         }
1149 }
1150
1151 static bool walk_designator(type_path_t *path, const designator_t *designator,
1152                             bool used_in_offsetof)
1153 {
1154         for( ; designator != NULL; designator = designator->next) {
1155                 type_path_entry_t *top       = get_type_path_top(path);
1156                 type_t            *orig_type = top->type;
1157
1158                 type_t *type = skip_typeref(orig_type);
1159
1160                 if(designator->symbol != NULL) {
1161                         symbol_t *symbol = designator->symbol;
1162                         if(!is_type_compound(type)) {
1163                                 if(is_type_valid(type)) {
1164                                         errorf(designator->source_position,
1165                                                "'.%Y' designator used for non-compound type '%T'",
1166                                                symbol, orig_type);
1167                                 }
1168                                 goto failed;
1169                         }
1170
1171                         declaration_t *declaration = type->compound.declaration;
1172                         declaration_t *iter        = declaration->scope.declarations;
1173                         for( ; iter != NULL; iter = iter->next) {
1174                                 if(iter->symbol == symbol) {
1175                                         break;
1176                                 }
1177                         }
1178                         if(iter == NULL) {
1179                                 errorf(designator->source_position,
1180                                        "'%T' has no member named '%Y'", orig_type, symbol);
1181                                 goto failed;
1182                         }
1183                         if(used_in_offsetof) {
1184                                 type_t *real_type = skip_typeref(iter->type);
1185                                 if(real_type->kind == TYPE_BITFIELD) {
1186                                         errorf(designator->source_position,
1187                                                "offsetof designator '%Y' may not specify bitfield",
1188                                                symbol);
1189                                         goto failed;
1190                                 }
1191                         }
1192
1193                         top->type             = orig_type;
1194                         top->v.compound_entry = iter;
1195                         orig_type             = iter->type;
1196                 } else {
1197                         expression_t *array_index = designator->array_index;
1198                         assert(designator->array_index != NULL);
1199
1200                         if(!is_type_array(type)) {
1201                                 if(is_type_valid(type)) {
1202                                         errorf(designator->source_position,
1203                                                "[%E] designator used for non-array type '%T'",
1204                                                array_index, orig_type);
1205                                 }
1206                                 goto failed;
1207                         }
1208                         if(!is_type_valid(array_index->base.type)) {
1209                                 goto failed;
1210                         }
1211
1212                         long index = fold_constant(array_index);
1213                         if(!used_in_offsetof) {
1214                                 if(index < 0) {
1215                                         errorf(designator->source_position,
1216                                                "array index [%E] must be positive", array_index);
1217                                         goto failed;
1218                                 }
1219                                 if(type->array.size_constant == true) {
1220                                         long array_size = type->array.size;
1221                                         if(index >= array_size) {
1222                                                 errorf(designator->source_position,
1223                                                                 "designator [%E] (%d) exceeds array size %d",
1224                                                                 array_index, index, array_size);
1225                                                 goto failed;
1226                                         }
1227                                 }
1228                         }
1229
1230                         top->type    = orig_type;
1231                         top->v.index = (size_t) index;
1232                         orig_type    = type->array.element_type;
1233                 }
1234                 path->top_type = orig_type;
1235
1236                 if(designator->next != NULL) {
1237                         descend_into_subtype(path);
1238                 }
1239         }
1240
1241         path->invalid  = false;
1242         return true;
1243
1244 failed:
1245         return false;
1246 }
1247
1248 static void advance_current_object(type_path_t *path, size_t top_path_level)
1249 {
1250         if(path->invalid)
1251                 return;
1252
1253         type_path_entry_t *top = get_type_path_top(path);
1254
1255         type_t *type = skip_typeref(top->type);
1256         if(is_type_union(type)) {
1257                 /* in unions only the first element is initialized */
1258                 top->v.compound_entry = NULL;
1259         } else if(is_type_struct(type)) {
1260                 declaration_t *entry = top->v.compound_entry;
1261
1262                 entry                 = entry->next;
1263                 top->v.compound_entry = entry;
1264                 if(entry != NULL) {
1265                         path->top_type = entry->type;
1266                         return;
1267                 }
1268         } else {
1269                 assert(is_type_array(type));
1270
1271                 top->v.index++;
1272
1273                 if(!type->array.size_constant || top->v.index < type->array.size) {
1274                         return;
1275                 }
1276         }
1277
1278         /* we're past the last member of the current sub-aggregate, try if we
1279          * can ascend in the type hierarchy and continue with another subobject */
1280         size_t len = ARR_LEN(path->path);
1281
1282         if(len > top_path_level) {
1283                 ascend_from_subtype(path);
1284                 advance_current_object(path, top_path_level);
1285         } else {
1286                 path->invalid = true;
1287         }
1288 }
1289
1290 static void skip_initializers(void)
1291 {
1292         if(token.type == '{')
1293                 next_token();
1294
1295         while(token.type != '}') {
1296                 if(token.type == T_EOF)
1297                         return;
1298                 if(token.type == '{') {
1299                         eat_block();
1300                         continue;
1301                 }
1302                 next_token();
1303         }
1304 }
1305
1306 static initializer_t *parse_sub_initializer(type_path_t *path,
1307                 type_t *outer_type, size_t top_path_level)
1308 {
1309         type_t *orig_type = path->top_type;
1310         type_t *type      = skip_typeref(orig_type);
1311
1312         /* we can't do usefull stuff if we didn't even parse the type. Skip the
1313          * initializers in this case. */
1314         if(!is_type_valid(type)) {
1315                 skip_initializers();
1316                 return NULL;
1317         }
1318
1319         initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1320
1321         while(true) {
1322                 designator_t *designator = NULL;
1323                 if(token.type == '.' || token.type == '[') {
1324                         designator = parse_designation();
1325
1326                         /* reset path to toplevel, evaluate designator from there */
1327                         ascend_to(path, top_path_level);
1328                         if(!walk_designator(path, designator, false)) {
1329                                 /* can't continue after designation error */
1330                                 goto end_error;
1331                         }
1332
1333                         initializer_t *designator_initializer
1334                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1335                         designator_initializer->designator.designator = designator;
1336                         ARR_APP1(initializer_t*, initializers, designator_initializer);
1337                 }
1338
1339                 initializer_t *sub;
1340
1341                 if(token.type == '{') {
1342                         if(is_type_scalar(type)) {
1343                                 sub = parse_scalar_initializer(type);
1344                         } else {
1345                                 eat('{');
1346                                 descend_into_subtype(path);
1347
1348                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1);
1349
1350                                 ascend_from_subtype(path);
1351
1352                                 expect_block('}');
1353                         }
1354                 } else {
1355                         /* must be an expression */
1356                         expression_t *expression = parse_assignment_expression();
1357
1358                         /* handle { "string" } special case */
1359                         if((expression->kind == EXPR_STRING_LITERAL
1360                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
1361                                         && outer_type != NULL) {
1362                                 sub = initializer_from_expression(outer_type, expression);
1363                                 if(sub != NULL) {
1364                                         if(token.type == ',') {
1365                                                 next_token();
1366                                         }
1367                                         if(token.type != '}') {
1368                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
1369                                                                  orig_type);
1370                                         }
1371                                         /* TODO: eat , ... */
1372                                         return sub;
1373                                 }
1374                         }
1375
1376                         /* descend into subtypes until expression matches type */
1377                         while(true) {
1378                                 orig_type = path->top_type;
1379                                 type      = skip_typeref(orig_type);
1380
1381                                 sub = initializer_from_expression(orig_type, expression);
1382                                 if(sub != NULL) {
1383                                         break;
1384                                 }
1385                                 if(!is_type_valid(type)) {
1386                                         goto end_error;
1387                                 }
1388                                 if(is_type_scalar(type)) {
1389                                         errorf(expression->base.source_position,
1390                                                         "expression '%E' doesn't match expected type '%T'",
1391                                                         expression, orig_type);
1392                                         goto end_error;
1393                                 }
1394
1395                                 descend_into_subtype(path);
1396                         }
1397                 }
1398                 ARR_APP1(initializer_t*, initializers, sub);
1399
1400                 if(token.type == '}') {
1401                         break;
1402                 }
1403                 expect(',');
1404                 if(token.type == '}') {
1405                         break;
1406                 }
1407
1408                 advance_current_object(path, top_path_level);
1409                 orig_type = path->top_type;
1410                 type      = skip_typeref(orig_type);
1411         }
1412
1413         size_t len  = ARR_LEN(initializers);
1414         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1415         initializer_t *result = allocate_ast_zero(size);
1416         result->kind          = INITIALIZER_LIST;
1417         result->list.len      = len;
1418         memcpy(&result->list.initializers, initializers,
1419                len * sizeof(initializers[0]));
1420
1421         ascend_to(path, top_path_level);
1422
1423         /* TODO: if(is_global && !is_constant(...)) { error } */
1424
1425         return result;
1426
1427 end_error:
1428         skip_initializers();
1429         DEL_ARR_F(initializers);
1430         ascend_to(path, top_path_level);
1431         return NULL;
1432 }
1433
1434 static initializer_t *parse_initializer(type_t *const orig_type)
1435 {
1436         initializer_t *result;
1437
1438         type_t *const type = skip_typeref(orig_type);
1439
1440         if(token.type != '{') {
1441                 expression_t  *expression  = parse_assignment_expression();
1442                 initializer_t *initializer = initializer_from_expression(type, expression);
1443                 if(initializer == NULL) {
1444                         errorf(HERE,
1445                                 "initializer expression '%E' of type '%T' is incompatible with type '%T'",
1446                                 expression, expression->base.type, orig_type);
1447                 }
1448                 return initializer;
1449         }
1450
1451         if(is_type_scalar(type)) {
1452                 /* TODO: Â§ 6.7.8.11; eat {} without warning */
1453
1454                 result = parse_scalar_initializer(type);
1455
1456                 if(token.type == ',')
1457                         next_token();
1458
1459                 return result;
1460         } else if(token.type == '{') {
1461                 next_token();
1462
1463                 type_path_t path;
1464                 memset(&path, 0, sizeof(path));
1465                 path.top_type = orig_type;
1466                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
1467
1468                 descend_into_subtype(&path);
1469
1470                 result = parse_sub_initializer(&path, orig_type, 1);
1471
1472                 DEL_ARR_F(path.path);
1473
1474                 expect('}');
1475         } else {
1476                 panic("TODO");
1477         }
1478
1479         return result;
1480 }
1481
1482 static declaration_t *append_declaration(declaration_t *declaration);
1483
1484 static declaration_t *parse_compound_type_specifier(bool is_struct)
1485 {
1486         if(is_struct) {
1487                 eat(T_struct);
1488         } else {
1489                 eat(T_union);
1490         }
1491
1492         symbol_t      *symbol      = NULL;
1493         declaration_t *declaration = NULL;
1494
1495         if (token.type == T___attribute__) {
1496                 /* TODO */
1497                 parse_attributes();
1498         }
1499
1500         if(token.type == T_IDENTIFIER) {
1501                 symbol = token.v.symbol;
1502                 next_token();
1503
1504                 if(is_struct) {
1505                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1506                 } else {
1507                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1508                 }
1509         } else if(token.type != '{') {
1510                 if(is_struct) {
1511                         parse_error_expected("while parsing struct type specifier",
1512                                              T_IDENTIFIER, '{', 0);
1513                 } else {
1514                         parse_error_expected("while parsing union type specifier",
1515                                              T_IDENTIFIER, '{', 0);
1516                 }
1517
1518                 return NULL;
1519         }
1520
1521         if(declaration == NULL) {
1522                 declaration = allocate_declaration_zero();
1523                 declaration->namespc         =
1524                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1525                 declaration->source_position = token.source_position;
1526                 declaration->symbol          = symbol;
1527                 declaration->parent_scope  = scope;
1528                 if (symbol != NULL) {
1529                         environment_push(declaration);
1530                 }
1531                 append_declaration(declaration);
1532         }
1533
1534         if(token.type == '{') {
1535                 if(declaration->init.is_defined) {
1536                         assert(symbol != NULL);
1537                         errorf(HERE, "multiple definitions of '%s %Y'",
1538                                is_struct ? "struct" : "union", symbol);
1539                         declaration->scope.declarations = NULL;
1540                 }
1541                 declaration->init.is_defined = true;
1542
1543                 parse_compound_type_entries(declaration);
1544                 parse_attributes();
1545         }
1546
1547         return declaration;
1548 }
1549
1550 static void parse_enum_entries(type_t *const enum_type)
1551 {
1552         eat('{');
1553
1554         if(token.type == '}') {
1555                 next_token();
1556                 errorf(HERE, "empty enum not allowed");
1557                 return;
1558         }
1559
1560         do {
1561                 if(token.type != T_IDENTIFIER) {
1562                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1563                         eat_block();
1564                         return;
1565                 }
1566
1567                 declaration_t *const entry = allocate_declaration_zero();
1568                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1569                 entry->type            = enum_type;
1570                 entry->symbol          = token.v.symbol;
1571                 entry->source_position = token.source_position;
1572                 next_token();
1573
1574                 if(token.type == '=') {
1575                         next_token();
1576                         expression_t *value = parse_constant_expression();
1577
1578                         value = create_implicit_cast(value, enum_type);
1579                         entry->init.enum_value = value;
1580
1581                         /* TODO semantic */
1582                 }
1583
1584                 record_declaration(entry);
1585
1586                 if(token.type != ',')
1587                         break;
1588                 next_token();
1589         } while(token.type != '}');
1590
1591         expect_void('}');
1592 }
1593
1594 static type_t *parse_enum_specifier(void)
1595 {
1596         eat(T_enum);
1597
1598         declaration_t *declaration;
1599         symbol_t      *symbol;
1600
1601         if(token.type == T_IDENTIFIER) {
1602                 symbol = token.v.symbol;
1603                 next_token();
1604
1605                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1606         } else if(token.type != '{') {
1607                 parse_error_expected("while parsing enum type specifier",
1608                                      T_IDENTIFIER, '{', 0);
1609                 return NULL;
1610         } else {
1611                 declaration = NULL;
1612                 symbol      = NULL;
1613         }
1614
1615         if(declaration == NULL) {
1616                 declaration = allocate_declaration_zero();
1617                 declaration->namespc         = NAMESPACE_ENUM;
1618                 declaration->source_position = token.source_position;
1619                 declaration->symbol          = symbol;
1620                 declaration->parent_scope  = scope;
1621         }
1622
1623         type_t *const type      = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1624         type->enumt.declaration = declaration;
1625
1626         if(token.type == '{') {
1627                 if(declaration->init.is_defined) {
1628                         errorf(HERE, "multiple definitions of enum %Y", symbol);
1629                 }
1630                 if (symbol != NULL) {
1631                         environment_push(declaration);
1632                 }
1633                 append_declaration(declaration);
1634                 declaration->init.is_defined = 1;
1635
1636                 parse_enum_entries(type);
1637                 parse_attributes();
1638         }
1639
1640         return type;
1641 }
1642
1643 /**
1644  * if a symbol is a typedef to another type, return true
1645  */
1646 static bool is_typedef_symbol(symbol_t *symbol)
1647 {
1648         const declaration_t *const declaration =
1649                 get_declaration(symbol, NAMESPACE_NORMAL);
1650         return
1651                 declaration != NULL &&
1652                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1653 }
1654
1655 static type_t *parse_typeof(void)
1656 {
1657         eat(T___typeof__);
1658
1659         type_t *type;
1660
1661         expect('(');
1662
1663         expression_t *expression  = NULL;
1664
1665 restart:
1666         switch(token.type) {
1667         case T___extension__:
1668                 /* this can be a prefix to a typename or an expression */
1669                 /* we simply eat it now. */
1670                 do {
1671                         next_token();
1672                 } while(token.type == T___extension__);
1673                 goto restart;
1674
1675         case T_IDENTIFIER:
1676                 if(is_typedef_symbol(token.v.symbol)) {
1677                         type = parse_typename();
1678                 } else {
1679                         expression = parse_expression();
1680                         type       = expression->base.type;
1681                 }
1682                 break;
1683
1684         TYPENAME_START
1685                 type = parse_typename();
1686                 break;
1687
1688         default:
1689                 expression = parse_expression();
1690                 type       = expression->base.type;
1691                 break;
1692         }
1693
1694         expect(')');
1695
1696         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1697         typeof_type->typeoft.expression  = expression;
1698         typeof_type->typeoft.typeof_type = type;
1699
1700         return typeof_type;
1701 }
1702
1703 typedef enum {
1704         SPECIFIER_SIGNED    = 1 << 0,
1705         SPECIFIER_UNSIGNED  = 1 << 1,
1706         SPECIFIER_LONG      = 1 << 2,
1707         SPECIFIER_INT       = 1 << 3,
1708         SPECIFIER_DOUBLE    = 1 << 4,
1709         SPECIFIER_CHAR      = 1 << 5,
1710         SPECIFIER_SHORT     = 1 << 6,
1711         SPECIFIER_LONG_LONG = 1 << 7,
1712         SPECIFIER_FLOAT     = 1 << 8,
1713         SPECIFIER_BOOL      = 1 << 9,
1714         SPECIFIER_VOID      = 1 << 10,
1715 #ifdef PROVIDE_COMPLEX
1716         SPECIFIER_COMPLEX   = 1 << 11,
1717         SPECIFIER_IMAGINARY = 1 << 12,
1718 #endif
1719 } specifiers_t;
1720
1721 static type_t *create_builtin_type(symbol_t *const symbol,
1722                                    type_t *const real_type)
1723 {
1724         type_t *type            = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1725         type->builtin.symbol    = symbol;
1726         type->builtin.real_type = real_type;
1727
1728         type_t *result = typehash_insert(type);
1729         if (type != result) {
1730                 free_type(type);
1731         }
1732
1733         return result;
1734 }
1735
1736 static type_t *get_typedef_type(symbol_t *symbol)
1737 {
1738         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1739         if(declaration == NULL
1740                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1741                 return NULL;
1742
1743         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1744         type->typedeft.declaration = declaration;
1745
1746         return type;
1747 }
1748
1749 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1750 {
1751         type_t   *type            = NULL;
1752         unsigned  type_qualifiers = 0;
1753         unsigned  type_specifiers = 0;
1754         int       newtype         = 0;
1755
1756         specifiers->source_position = token.source_position;
1757
1758         while(true) {
1759                 switch(token.type) {
1760
1761                 /* storage class */
1762 #define MATCH_STORAGE_CLASS(token, class)                                \
1763                 case token:                                                      \
1764                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1765                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1766                         }                                                            \
1767                         specifiers->storage_class = class;                           \
1768                         next_token();                                                \
1769                         break;
1770
1771                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1772                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1773                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1774                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1775                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1776
1777                 case T___thread:
1778                         switch (specifiers->storage_class) {
1779                                 case STORAGE_CLASS_NONE:
1780                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1781                                         break;
1782
1783                                 case STORAGE_CLASS_EXTERN:
1784                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1785                                         break;
1786
1787                                 case STORAGE_CLASS_STATIC:
1788                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1789                                         break;
1790
1791                                 default:
1792                                         errorf(HERE, "multiple storage classes in declaration specifiers");
1793                                         break;
1794                         }
1795                         next_token();
1796                         break;
1797
1798                 /* type qualifiers */
1799 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1800                 case token:                                                     \
1801                         type_qualifiers |= qualifier;                               \
1802                         next_token();                                               \
1803                         break;
1804
1805                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1806                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1807                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1808
1809                 case T___extension__:
1810                         /* TODO */
1811                         next_token();
1812                         break;
1813
1814                 /* type specifiers */
1815 #define MATCH_SPECIFIER(token, specifier, name)                         \
1816                 case token:                                                     \
1817                         next_token();                                               \
1818                         if(type_specifiers & specifier) {                           \
1819                                 errorf(HERE, "multiple " name " type specifiers given"); \
1820                         } else {                                                    \
1821                                 type_specifiers |= specifier;                           \
1822                         }                                                           \
1823                         break;
1824
1825                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1826                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1827                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1828                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1829                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1830                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1831                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1832                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1833                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1834 #ifdef PROVIDE_COMPLEX
1835                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1836                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1837 #endif
1838                 case T_forceinline:
1839                         /* only in microsoft mode */
1840                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1841
1842                 case T_inline:
1843                         next_token();
1844                         specifiers->is_inline = true;
1845                         break;
1846
1847                 case T_long:
1848                         next_token();
1849                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1850                                 errorf(HERE, "multiple type specifiers given");
1851                         } else if(type_specifiers & SPECIFIER_LONG) {
1852                                 type_specifiers |= SPECIFIER_LONG_LONG;
1853                         } else {
1854                                 type_specifiers |= SPECIFIER_LONG;
1855                         }
1856                         break;
1857
1858                 case T_struct: {
1859                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
1860
1861                         type->compound.declaration = parse_compound_type_specifier(true);
1862                         break;
1863                 }
1864                 case T_union: {
1865                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
1866
1867                         type->compound.declaration = parse_compound_type_specifier(false);
1868                         break;
1869                 }
1870                 case T_enum:
1871                         type = parse_enum_specifier();
1872                         break;
1873                 case T___typeof__:
1874                         type = parse_typeof();
1875                         break;
1876                 case T___builtin_va_list:
1877                         type = duplicate_type(type_valist);
1878                         next_token();
1879                         break;
1880
1881                 case T___attribute__:
1882                         parse_attributes();
1883                         break;
1884
1885                 case T_IDENTIFIER: {
1886                         /* only parse identifier if we haven't found a type yet */
1887                         if(type != NULL || type_specifiers != 0)
1888                                 goto finish_specifiers;
1889
1890                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1891
1892                         if(typedef_type == NULL)
1893                                 goto finish_specifiers;
1894
1895                         next_token();
1896                         type = typedef_type;
1897                         break;
1898                 }
1899
1900                 /* function specifier */
1901                 default:
1902                         goto finish_specifiers;
1903                 }
1904         }
1905
1906 finish_specifiers:
1907
1908         if(type == NULL) {
1909                 atomic_type_kind_t atomic_type;
1910
1911                 /* match valid basic types */
1912                 switch(type_specifiers) {
1913                 case SPECIFIER_VOID:
1914                         atomic_type = ATOMIC_TYPE_VOID;
1915                         break;
1916                 case SPECIFIER_CHAR:
1917                         atomic_type = ATOMIC_TYPE_CHAR;
1918                         break;
1919                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1920                         atomic_type = ATOMIC_TYPE_SCHAR;
1921                         break;
1922                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1923                         atomic_type = ATOMIC_TYPE_UCHAR;
1924                         break;
1925                 case SPECIFIER_SHORT:
1926                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1927                 case SPECIFIER_SHORT | SPECIFIER_INT:
1928                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1929                         atomic_type = ATOMIC_TYPE_SHORT;
1930                         break;
1931                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1932                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1933                         atomic_type = ATOMIC_TYPE_USHORT;
1934                         break;
1935                 case SPECIFIER_INT:
1936                 case SPECIFIER_SIGNED:
1937                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1938                         atomic_type = ATOMIC_TYPE_INT;
1939                         break;
1940                 case SPECIFIER_UNSIGNED:
1941                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1942                         atomic_type = ATOMIC_TYPE_UINT;
1943                         break;
1944                 case SPECIFIER_LONG:
1945                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1946                 case SPECIFIER_LONG | SPECIFIER_INT:
1947                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1948                         atomic_type = ATOMIC_TYPE_LONG;
1949                         break;
1950                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1951                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1952                         atomic_type = ATOMIC_TYPE_ULONG;
1953                         break;
1954                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1955                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1956                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1957                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1958                         | SPECIFIER_INT:
1959                         atomic_type = ATOMIC_TYPE_LONGLONG;
1960                         break;
1961                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1962                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1963                         | SPECIFIER_INT:
1964                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1965                         break;
1966                 case SPECIFIER_FLOAT:
1967                         atomic_type = ATOMIC_TYPE_FLOAT;
1968                         break;
1969                 case SPECIFIER_DOUBLE:
1970                         atomic_type = ATOMIC_TYPE_DOUBLE;
1971                         break;
1972                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1973                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1974                         break;
1975                 case SPECIFIER_BOOL:
1976                         atomic_type = ATOMIC_TYPE_BOOL;
1977                         break;
1978 #ifdef PROVIDE_COMPLEX
1979                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1980                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1981                         break;
1982                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1983                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1984                         break;
1985                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1986                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1987                         break;
1988                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1989                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1990                         break;
1991                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1992                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1993                         break;
1994                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1995                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1996                         break;
1997 #endif
1998                 default:
1999                         /* invalid specifier combination, give an error message */
2000                         if(type_specifiers == 0) {
2001                                 if (! strict_mode) {
2002                                         if (warning.implicit_int) {
2003                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
2004                                         }
2005                                         atomic_type = ATOMIC_TYPE_INT;
2006                                         break;
2007                                 } else {
2008                                         errorf(HERE, "no type specifiers given in declaration");
2009                                 }
2010                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
2011                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
2012                                 errorf(HERE, "signed and unsigned specifiers gives");
2013                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2014                                 errorf(HERE, "only integer types can be signed or unsigned");
2015                         } else {
2016                                 errorf(HERE, "multiple datatypes in declaration");
2017                         }
2018                         atomic_type = ATOMIC_TYPE_INVALID;
2019                 }
2020
2021                 type               = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2022                 type->atomic.akind = atomic_type;
2023                 newtype            = 1;
2024         } else {
2025                 if(type_specifiers != 0) {
2026                         errorf(HERE, "multiple datatypes in declaration");
2027                 }
2028         }
2029
2030         type->base.qualifiers = type_qualifiers;
2031
2032         type_t *result = typehash_insert(type);
2033         if(newtype && result != type) {
2034                 free_type(type);
2035         }
2036
2037         specifiers->type = result;
2038 }
2039
2040 static type_qualifiers_t parse_type_qualifiers(void)
2041 {
2042         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2043
2044         while(true) {
2045                 switch(token.type) {
2046                 /* type qualifiers */
2047                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2048                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2049                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2050
2051                 default:
2052                         return type_qualifiers;
2053                 }
2054         }
2055 }
2056
2057 static declaration_t *parse_identifier_list(void)
2058 {
2059         declaration_t *declarations     = NULL;
2060         declaration_t *last_declaration = NULL;
2061         do {
2062                 declaration_t *const declaration = allocate_declaration_zero();
2063                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
2064                 declaration->source_position = token.source_position;
2065                 declaration->symbol          = token.v.symbol;
2066                 next_token();
2067
2068                 if(last_declaration != NULL) {
2069                         last_declaration->next = declaration;
2070                 } else {
2071                         declarations = declaration;
2072                 }
2073                 last_declaration = declaration;
2074
2075                 if(token.type != ',')
2076                         break;
2077                 next_token();
2078         } while(token.type == T_IDENTIFIER);
2079
2080         return declarations;
2081 }
2082
2083 static void semantic_parameter(declaration_t *declaration)
2084 {
2085         /* TODO: improve error messages */
2086
2087         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
2088                 errorf(HERE, "typedef not allowed in parameter list");
2089         } else if(declaration->storage_class != STORAGE_CLASS_NONE
2090                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
2091                 errorf(HERE, "parameter may only have none or register storage class");
2092         }
2093
2094         type_t *const orig_type = declaration->type;
2095         type_t *      type      = skip_typeref(orig_type);
2096
2097         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
2098          * into a pointer. Â§ 6.7.5.3 (7) */
2099         if (is_type_array(type)) {
2100                 type_t *const element_type = type->array.element_type;
2101
2102                 type = make_pointer_type(element_type, type->base.qualifiers);
2103
2104                 declaration->type = type;
2105         }
2106
2107         if(is_type_incomplete(type)) {
2108                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2109                        orig_type, declaration->symbol);
2110         }
2111 }
2112
2113 static declaration_t *parse_parameter(void)
2114 {
2115         declaration_specifiers_t specifiers;
2116         memset(&specifiers, 0, sizeof(specifiers));
2117
2118         parse_declaration_specifiers(&specifiers);
2119
2120         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2121
2122         semantic_parameter(declaration);
2123
2124         return declaration;
2125 }
2126
2127 static declaration_t *parse_parameters(function_type_t *type)
2128 {
2129         if(token.type == T_IDENTIFIER) {
2130                 symbol_t *symbol = token.v.symbol;
2131                 if(!is_typedef_symbol(symbol)) {
2132                         type->kr_style_parameters = true;
2133                         return parse_identifier_list();
2134                 }
2135         }
2136
2137         if(token.type == ')') {
2138                 type->unspecified_parameters = 1;
2139                 return NULL;
2140         }
2141         if(token.type == T_void && look_ahead(1)->type == ')') {
2142                 next_token();
2143                 return NULL;
2144         }
2145
2146         declaration_t        *declarations = NULL;
2147         declaration_t        *declaration;
2148         declaration_t        *last_declaration = NULL;
2149         function_parameter_t *parameter;
2150         function_parameter_t *last_parameter = NULL;
2151
2152         while(true) {
2153                 switch(token.type) {
2154                 case T_DOTDOTDOT:
2155                         next_token();
2156                         type->variadic = 1;
2157                         return declarations;
2158
2159                 case T_IDENTIFIER:
2160                 case T___extension__:
2161                 DECLARATION_START
2162                         declaration = parse_parameter();
2163
2164                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
2165                         memset(parameter, 0, sizeof(parameter[0]));
2166                         parameter->type = declaration->type;
2167
2168                         if(last_parameter != NULL) {
2169                                 last_declaration->next = declaration;
2170                                 last_parameter->next   = parameter;
2171                         } else {
2172                                 type->parameters = parameter;
2173                                 declarations     = declaration;
2174                         }
2175                         last_parameter   = parameter;
2176                         last_declaration = declaration;
2177                         break;
2178
2179                 default:
2180                         return declarations;
2181                 }
2182                 if(token.type != ',')
2183                         return declarations;
2184                 next_token();
2185         }
2186 }
2187
2188 typedef enum {
2189         CONSTRUCT_INVALID,
2190         CONSTRUCT_POINTER,
2191         CONSTRUCT_FUNCTION,
2192         CONSTRUCT_ARRAY
2193 } construct_type_kind_t;
2194
2195 typedef struct construct_type_t construct_type_t;
2196 struct construct_type_t {
2197         construct_type_kind_t  kind;
2198         construct_type_t      *next;
2199 };
2200
2201 typedef struct parsed_pointer_t parsed_pointer_t;
2202 struct parsed_pointer_t {
2203         construct_type_t  construct_type;
2204         type_qualifiers_t type_qualifiers;
2205 };
2206
2207 typedef struct construct_function_type_t construct_function_type_t;
2208 struct construct_function_type_t {
2209         construct_type_t  construct_type;
2210         type_t           *function_type;
2211 };
2212
2213 typedef struct parsed_array_t parsed_array_t;
2214 struct parsed_array_t {
2215         construct_type_t  construct_type;
2216         type_qualifiers_t type_qualifiers;
2217         bool              is_static;
2218         bool              is_variable;
2219         expression_t     *size;
2220 };
2221
2222 typedef struct construct_base_type_t construct_base_type_t;
2223 struct construct_base_type_t {
2224         construct_type_t  construct_type;
2225         type_t           *type;
2226 };
2227
2228 static construct_type_t *parse_pointer_declarator(void)
2229 {
2230         eat('*');
2231
2232         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2233         memset(pointer, 0, sizeof(pointer[0]));
2234         pointer->construct_type.kind = CONSTRUCT_POINTER;
2235         pointer->type_qualifiers     = parse_type_qualifiers();
2236
2237         return (construct_type_t*) pointer;
2238 }
2239
2240 static construct_type_t *parse_array_declarator(void)
2241 {
2242         eat('[');
2243
2244         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2245         memset(array, 0, sizeof(array[0]));
2246         array->construct_type.kind = CONSTRUCT_ARRAY;
2247
2248         if(token.type == T_static) {
2249                 array->is_static = true;
2250                 next_token();
2251         }
2252
2253         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2254         if(type_qualifiers != 0) {
2255                 if(token.type == T_static) {
2256                         array->is_static = true;
2257                         next_token();
2258                 }
2259         }
2260         array->type_qualifiers = type_qualifiers;
2261
2262         if(token.type == '*' && look_ahead(1)->type == ']') {
2263                 array->is_variable = true;
2264                 next_token();
2265         } else if(token.type != ']') {
2266                 array->size = parse_assignment_expression();
2267         }
2268
2269         expect(']');
2270
2271         return (construct_type_t*) array;
2272 }
2273
2274 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2275 {
2276         eat('(');
2277
2278         type_t *type;
2279         if(declaration != NULL) {
2280                 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2281         } else {
2282                 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2283         }
2284
2285         declaration_t *parameters = parse_parameters(&type->function);
2286         if(declaration != NULL) {
2287                 declaration->scope.declarations = parameters;
2288         }
2289
2290         construct_function_type_t *construct_function_type =
2291                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2292         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2293         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2294         construct_function_type->function_type       = type;
2295
2296         expect(')');
2297
2298         return (construct_type_t*) construct_function_type;
2299 }
2300
2301 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2302                 bool may_be_abstract)
2303 {
2304         /* construct a single linked list of construct_type_t's which describe
2305          * how to construct the final declarator type */
2306         construct_type_t *first = NULL;
2307         construct_type_t *last  = NULL;
2308
2309         /* pointers */
2310         while(token.type == '*') {
2311                 construct_type_t *type = parse_pointer_declarator();
2312
2313                 if(last == NULL) {
2314                         first = type;
2315                         last  = type;
2316                 } else {
2317                         last->next = type;
2318                         last       = type;
2319                 }
2320         }
2321
2322         /* TODO: find out if this is correct */
2323         parse_attributes();
2324
2325         construct_type_t *inner_types = NULL;
2326
2327         switch(token.type) {
2328         case T_IDENTIFIER:
2329                 if(declaration == NULL) {
2330                         errorf(HERE, "no identifier expected in typename");
2331                 } else {
2332                         declaration->symbol          = token.v.symbol;
2333                         declaration->source_position = token.source_position;
2334                 }
2335                 next_token();
2336                 break;
2337         case '(':
2338                 next_token();
2339                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2340                 expect(')');
2341                 break;
2342         default:
2343                 if(may_be_abstract)
2344                         break;
2345                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2346                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2347                  * eat '}' */
2348                 if(token.type == '}' && current_function == NULL) {
2349                         next_token();
2350                 } else {
2351                         eat_statement();
2352                 }
2353                 return NULL;
2354         }
2355
2356         construct_type_t *p = last;
2357
2358         while(true) {
2359                 construct_type_t *type;
2360                 switch(token.type) {
2361                 case '(':
2362                         type = parse_function_declarator(declaration);
2363                         break;
2364                 case '[':
2365                         type = parse_array_declarator();
2366                         break;
2367                 default:
2368                         goto declarator_finished;
2369                 }
2370
2371                 /* insert in the middle of the list (behind p) */
2372                 if(p != NULL) {
2373                         type->next = p->next;
2374                         p->next    = type;
2375                 } else {
2376                         type->next = first;
2377                         first      = type;
2378                 }
2379                 if(last == p) {
2380                         last = type;
2381                 }
2382         }
2383
2384 declarator_finished:
2385         parse_attributes();
2386
2387         /* append inner_types at the end of the list, we don't to set last anymore
2388          * as it's not needed anymore */
2389         if(last == NULL) {
2390                 assert(first == NULL);
2391                 first = inner_types;
2392         } else {
2393                 last->next = inner_types;
2394         }
2395
2396         return first;
2397 }
2398
2399 static type_t *construct_declarator_type(construct_type_t *construct_list,
2400                                          type_t *type)
2401 {
2402         construct_type_t *iter = construct_list;
2403         for( ; iter != NULL; iter = iter->next) {
2404                 switch(iter->kind) {
2405                 case CONSTRUCT_INVALID:
2406                         panic("invalid type construction found");
2407                 case CONSTRUCT_FUNCTION: {
2408                         construct_function_type_t *construct_function_type
2409                                 = (construct_function_type_t*) iter;
2410
2411                         type_t *function_type = construct_function_type->function_type;
2412
2413                         function_type->function.return_type = type;
2414
2415                         type_t *skipped_return_type = skip_typeref(type);
2416                         if (is_type_function(skipped_return_type)) {
2417                                 errorf(HERE, "function returning function is not allowed");
2418                                 type = type_error_type;
2419                         } else if (is_type_array(skipped_return_type)) {
2420                                 errorf(HERE, "function returning array is not allowed");
2421                                 type = type_error_type;
2422                         } else {
2423                                 type = function_type;
2424                         }
2425                         break;
2426                 }
2427
2428                 case CONSTRUCT_POINTER: {
2429                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2430                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2431                         pointer_type->pointer.points_to  = type;
2432                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2433
2434                         type = pointer_type;
2435                         break;
2436                 }
2437
2438                 case CONSTRUCT_ARRAY: {
2439                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2440                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2441
2442                         expression_t *size_expression = parsed_array->size;
2443
2444                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
2445                         array_type->array.element_type    = type;
2446                         array_type->array.is_static       = parsed_array->is_static;
2447                         array_type->array.is_variable     = parsed_array->is_variable;
2448                         array_type->array.size_expression = size_expression;
2449
2450                         if(size_expression != NULL &&
2451                                         is_constant_expression(size_expression)) {
2452                                 array_type->array.size_constant = true;
2453                                 array_type->array.size
2454                                         = fold_constant(size_expression);
2455                         }
2456
2457                         type_t *skipped_type = skip_typeref(type);
2458                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2459                                 errorf(HERE, "array of void is not allowed");
2460                                 type = type_error_type;
2461                         } else {
2462                                 type = array_type;
2463                         }
2464                         break;
2465                 }
2466                 }
2467
2468                 type_t *hashed_type = typehash_insert(type);
2469                 if(hashed_type != type) {
2470                         /* the function type was constructed earlier freeing it here will
2471                          * destroy other types... */
2472                         if(iter->kind != CONSTRUCT_FUNCTION) {
2473                                 free_type(type);
2474                         }
2475                         type = hashed_type;
2476                 }
2477         }
2478
2479         return type;
2480 }
2481
2482 static declaration_t *parse_declarator(
2483                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2484 {
2485         declaration_t *const declaration = allocate_declaration_zero();
2486         declaration->storage_class  = specifiers->storage_class;
2487         declaration->modifiers      = specifiers->decl_modifiers;
2488         declaration->is_inline      = specifiers->is_inline;
2489
2490         construct_type_t *construct_type
2491                 = parse_inner_declarator(declaration, may_be_abstract);
2492         type_t *const type = specifiers->type;
2493         declaration->type = construct_declarator_type(construct_type, type);
2494
2495         if(construct_type != NULL) {
2496                 obstack_free(&temp_obst, construct_type);
2497         }
2498
2499         return declaration;
2500 }
2501
2502 static type_t *parse_abstract_declarator(type_t *base_type)
2503 {
2504         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2505
2506         type_t *result = construct_declarator_type(construct_type, base_type);
2507         if(construct_type != NULL) {
2508                 obstack_free(&temp_obst, construct_type);
2509         }
2510
2511         return result;
2512 }
2513
2514 static declaration_t *append_declaration(declaration_t* const declaration)
2515 {
2516         if (last_declaration != NULL) {
2517                 last_declaration->next = declaration;
2518         } else {
2519                 scope->declarations = declaration;
2520         }
2521         last_declaration = declaration;
2522         return declaration;
2523 }
2524
2525 /**
2526  * Check if the declaration of main is suspicious.  main should be a
2527  * function with external linkage, returning int, taking either zero
2528  * arguments, two, or three arguments of appropriate types, ie.
2529  *
2530  * int main([ int argc, char **argv [, char **env ] ]).
2531  *
2532  * @param decl    the declaration to check
2533  * @param type    the function type of the declaration
2534  */
2535 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2536 {
2537         if (decl->storage_class == STORAGE_CLASS_STATIC) {
2538                 warningf(decl->source_position, "'main' is normally a non-static function");
2539         }
2540         if (skip_typeref(func_type->return_type) != type_int) {
2541                 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2542         }
2543         const function_parameter_t *parm = func_type->parameters;
2544         if (parm != NULL) {
2545                 type_t *const first_type = parm->type;
2546                 if (!types_compatible(skip_typeref(first_type), type_int)) {
2547                         warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2548                 }
2549                 parm = parm->next;
2550                 if (parm != NULL) {
2551                         type_t *const second_type = parm->type;
2552                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2553                                 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2554                         }
2555                         parm = parm->next;
2556                         if (parm != NULL) {
2557                                 type_t *const third_type = parm->type;
2558                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2559                                         warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2560                                 }
2561                                 parm = parm->next;
2562                                 if (parm != NULL) {
2563                                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2564                                 }
2565                         }
2566                 } else {
2567                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2568                 }
2569         }
2570 }
2571
2572 /**
2573  * Check if a symbol is the equal to "main".
2574  */
2575 static bool is_sym_main(const symbol_t *const sym)
2576 {
2577         return strcmp(sym->string, "main") == 0;
2578 }
2579
2580 static declaration_t *internal_record_declaration(
2581         declaration_t *const declaration,
2582         const bool is_function_definition)
2583 {
2584         const symbol_t *const symbol  = declaration->symbol;
2585         const namespace_t     namespc = (namespace_t)declaration->namespc;
2586
2587         type_t *const orig_type = declaration->type;
2588         type_t *const type      = skip_typeref(orig_type);
2589         if (is_type_function(type) &&
2590                         type->function.unspecified_parameters &&
2591                         warning.strict_prototypes) {
2592                 warningf(declaration->source_position,
2593                          "function declaration '%#T' is not a prototype",
2594                          orig_type, declaration->symbol);
2595         }
2596
2597         if (is_function_definition && warning.main && is_sym_main(symbol)) {
2598                 check_type_of_main(declaration, &type->function);
2599         }
2600
2601         assert(declaration->symbol != NULL);
2602         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2603
2604         assert(declaration != previous_declaration);
2605         if (previous_declaration != NULL) {
2606                 if (previous_declaration->parent_scope == scope) {
2607                         /* can happen for K&R style declarations */
2608                         if(previous_declaration->type == NULL) {
2609                                 previous_declaration->type = declaration->type;
2610                         }
2611
2612                         const type_t *prev_type = skip_typeref(previous_declaration->type);
2613                         if (!types_compatible(type, prev_type)) {
2614                                 errorf(declaration->source_position,
2615                                        "declaration '%#T' is incompatible with "
2616                                        "previous declaration '%#T'",
2617                                        orig_type, symbol, previous_declaration->type, symbol);
2618                                 errorf(previous_declaration->source_position,
2619                                        "previous declaration of '%Y' was here", symbol);
2620                         } else {
2621                                 unsigned old_storage_class
2622                                         = previous_declaration->storage_class;
2623                                 unsigned new_storage_class = declaration->storage_class;
2624
2625                                 if(is_type_incomplete(prev_type)) {
2626                                         previous_declaration->type = type;
2627                                         prev_type                  = type;
2628                                 }
2629
2630                                 /* pretend no storage class means extern for function
2631                                  * declarations (except if the previous declaration is neither
2632                                  * none nor extern) */
2633                                 if (is_type_function(type)) {
2634                                         switch (old_storage_class) {
2635                                                 case STORAGE_CLASS_NONE:
2636                                                         old_storage_class = STORAGE_CLASS_EXTERN;
2637
2638                                                 case STORAGE_CLASS_EXTERN:
2639                                                         if (is_function_definition) {
2640                                                                 if (warning.missing_prototypes &&
2641                                                                     prev_type->function.unspecified_parameters &&
2642                                                                     !is_sym_main(symbol)) {
2643                                                                         warningf(declaration->source_position,
2644                                                                                  "no previous prototype for '%#T'",
2645                                                                                  orig_type, symbol);
2646                                                                 }
2647                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
2648                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
2649                                                         }
2650                                                         break;
2651
2652                                                 default: break;
2653                                         }
2654                                 }
2655
2656                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2657                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
2658 warn_redundant_declaration:
2659                                         if (warning.redundant_decls) {
2660                                                 warningf(declaration->source_position,
2661                                                          "redundant declaration for '%Y'", symbol);
2662                                                 warningf(previous_declaration->source_position,
2663                                                          "previous declaration of '%Y' was here",
2664                                                          symbol);
2665                                         }
2666                                 } else if (current_function == NULL) {
2667                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
2668                                                         new_storage_class == STORAGE_CLASS_STATIC) {
2669                                                 errorf(declaration->source_position,
2670                                                        "static declaration of '%Y' follows non-static declaration",
2671                                                        symbol);
2672                                                 errorf(previous_declaration->source_position,
2673                                                        "previous declaration of '%Y' was here", symbol);
2674                                         } else {
2675                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2676                                                         goto warn_redundant_declaration;
2677                                                 }
2678                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
2679                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
2680                                                 }
2681                                         }
2682                                 } else {
2683                                         if (old_storage_class == new_storage_class) {
2684                                                 errorf(declaration->source_position,
2685                                                        "redeclaration of '%Y'", symbol);
2686                                         } else {
2687                                                 errorf(declaration->source_position,
2688                                                        "redeclaration of '%Y' with different linkage",
2689                                                        symbol);
2690                                         }
2691                                         errorf(previous_declaration->source_position,
2692                                                "previous declaration of '%Y' was here", symbol);
2693                                 }
2694                         }
2695                         return previous_declaration;
2696                 }
2697         } else if (is_function_definition) {
2698                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
2699                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
2700                                 warningf(declaration->source_position,
2701                                          "no previous prototype for '%#T'", orig_type, symbol);
2702                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
2703                                 warningf(declaration->source_position,
2704                                          "no previous declaration for '%#T'", orig_type,
2705                                          symbol);
2706                         }
2707                 }
2708         } else if (warning.missing_declarations &&
2709             scope == global_scope &&
2710             !is_type_function(type) && (
2711               declaration->storage_class == STORAGE_CLASS_NONE ||
2712               declaration->storage_class == STORAGE_CLASS_THREAD
2713             )) {
2714                 warningf(declaration->source_position,
2715                          "no previous declaration for '%#T'", orig_type, symbol);
2716         }
2717
2718         assert(declaration->parent_scope == NULL);
2719         assert(scope != NULL);
2720
2721         declaration->parent_scope = scope;
2722
2723         environment_push(declaration);
2724         return append_declaration(declaration);
2725 }
2726
2727 static declaration_t *record_declaration(declaration_t *declaration)
2728 {
2729         return internal_record_declaration(declaration, false);
2730 }
2731
2732 static declaration_t *record_function_definition(declaration_t *declaration)
2733 {
2734         return internal_record_declaration(declaration, true);
2735 }
2736
2737 static void parser_error_multiple_definition(declaration_t *declaration,
2738                 const source_position_t source_position)
2739 {
2740         errorf(source_position, "multiple definition of symbol '%Y'",
2741                declaration->symbol);
2742         errorf(declaration->source_position,
2743                "this is the location of the previous definition.");
2744 }
2745
2746 static bool is_declaration_specifier(const token_t *token,
2747                                      bool only_type_specifiers)
2748 {
2749         switch(token->type) {
2750                 TYPE_SPECIFIERS
2751                         return true;
2752                 case T_IDENTIFIER:
2753                         return is_typedef_symbol(token->v.symbol);
2754
2755                 case T___extension__:
2756                 STORAGE_CLASSES
2757                 TYPE_QUALIFIERS
2758                         return !only_type_specifiers;
2759
2760                 default:
2761                         return false;
2762         }
2763 }
2764
2765 static void parse_init_declarator_rest(declaration_t *declaration)
2766 {
2767         eat('=');
2768
2769         type_t *orig_type = declaration->type;
2770         type_t *type      = type = skip_typeref(orig_type);
2771
2772         if(declaration->init.initializer != NULL) {
2773                 parser_error_multiple_definition(declaration, token.source_position);
2774         }
2775
2776         initializer_t *initializer = parse_initializer(type);
2777
2778         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2779          * the array type size */
2780         if(is_type_array(type) && initializer != NULL) {
2781                 array_type_t *array_type = &type->array;
2782
2783                 if(array_type->size_expression == NULL) {
2784                         size_t size;
2785                         switch (initializer->kind) {
2786                                 case INITIALIZER_LIST: {
2787                                         /* TODO */
2788                                         size = initializer->list.len;
2789                                         break;
2790                                 }
2791
2792                                 case INITIALIZER_STRING: {
2793                                         size = initializer->string.string.size;
2794                                         break;
2795                                 }
2796
2797                                 case INITIALIZER_WIDE_STRING: {
2798                                         size = initializer->wide_string.string.size;
2799                                         break;
2800                                 }
2801
2802                                 default: {
2803                                         panic("invalid initializer type");
2804                                         break;
2805                                 }
2806                         }
2807
2808                         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2809                         cnst->base.type          = type_size_t;
2810                         cnst->conste.v.int_value = size;
2811
2812                         array_type->size_expression = cnst;
2813                         array_type->size_constant   = true;
2814                         array_type->size            = size;
2815                 }
2816         }
2817
2818         if(is_type_function(type)) {
2819                 errorf(declaration->source_position,
2820                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2821                        declaration->symbol, orig_type);
2822         } else {
2823                 declaration->init.initializer = initializer;
2824         }
2825 }
2826
2827 /* parse rest of a declaration without any declarator */
2828 static void parse_anonymous_declaration_rest(
2829                 const declaration_specifiers_t *specifiers,
2830                 parsed_declaration_func finished_declaration)
2831 {
2832         eat(';');
2833
2834         declaration_t *const declaration = allocate_declaration_zero();
2835         declaration->type            = specifiers->type;
2836         declaration->storage_class   = specifiers->storage_class;
2837         declaration->source_position = specifiers->source_position;
2838
2839         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2840                 warningf(declaration->source_position, "useless storage class in empty declaration");
2841         }
2842
2843         type_t *type = declaration->type;
2844         switch (type->kind) {
2845                 case TYPE_COMPOUND_STRUCT:
2846                 case TYPE_COMPOUND_UNION: {
2847                         if (type->compound.declaration->symbol == NULL) {
2848                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2849                         }
2850                         break;
2851                 }
2852
2853                 case TYPE_ENUM:
2854                         break;
2855
2856                 default:
2857                         warningf(declaration->source_position, "empty declaration");
2858                         break;
2859         }
2860
2861         finished_declaration(declaration);
2862 }
2863
2864 static void parse_declaration_rest(declaration_t *ndeclaration,
2865                 const declaration_specifiers_t *specifiers,
2866                 parsed_declaration_func finished_declaration)
2867 {
2868         while(true) {
2869                 declaration_t *declaration = finished_declaration(ndeclaration);
2870
2871                 type_t *orig_type = declaration->type;
2872                 type_t *type      = skip_typeref(orig_type);
2873
2874                 if (type->kind != TYPE_FUNCTION &&
2875                     declaration->is_inline &&
2876                     is_type_valid(type)) {
2877                         warningf(declaration->source_position,
2878                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2879                 }
2880
2881                 if(token.type == '=') {
2882                         parse_init_declarator_rest(declaration);
2883                 }
2884
2885                 if(token.type != ',')
2886                         break;
2887                 eat(',');
2888
2889                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2890         }
2891         expect_void(';');
2892 }
2893
2894 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2895 {
2896         symbol_t *symbol  = declaration->symbol;
2897         if(symbol == NULL) {
2898                 errorf(HERE, "anonymous declaration not valid as function parameter");
2899                 return declaration;
2900         }
2901         namespace_t namespc = (namespace_t) declaration->namespc;
2902         if(namespc != NAMESPACE_NORMAL) {
2903                 return record_declaration(declaration);
2904         }
2905
2906         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2907         if(previous_declaration == NULL ||
2908                         previous_declaration->parent_scope != scope) {
2909                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2910                        symbol);
2911                 return declaration;
2912         }
2913
2914         if(previous_declaration->type == NULL) {
2915                 previous_declaration->type          = declaration->type;
2916                 previous_declaration->storage_class = declaration->storage_class;
2917                 previous_declaration->parent_scope  = scope;
2918                 return previous_declaration;
2919         } else {
2920                 return record_declaration(declaration);
2921         }
2922 }
2923
2924 static void parse_declaration(parsed_declaration_func finished_declaration)
2925 {
2926         declaration_specifiers_t specifiers;
2927         memset(&specifiers, 0, sizeof(specifiers));
2928         parse_declaration_specifiers(&specifiers);
2929
2930         if(token.type == ';') {
2931                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2932         } else {
2933                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2934                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2935         }
2936 }
2937
2938 static void parse_kr_declaration_list(declaration_t *declaration)
2939 {
2940         type_t *type = skip_typeref(declaration->type);
2941         if(!is_type_function(type))
2942                 return;
2943
2944         if(!type->function.kr_style_parameters)
2945                 return;
2946
2947         /* push function parameters */
2948         int       top        = environment_top();
2949         scope_t  *last_scope = scope;
2950         set_scope(&declaration->scope);
2951
2952         declaration_t *parameter = declaration->scope.declarations;
2953         for( ; parameter != NULL; parameter = parameter->next) {
2954                 assert(parameter->parent_scope == NULL);
2955                 parameter->parent_scope = scope;
2956                 environment_push(parameter);
2957         }
2958
2959         /* parse declaration list */
2960         while(is_declaration_specifier(&token, false)) {
2961                 parse_declaration(finished_kr_declaration);
2962         }
2963
2964         /* pop function parameters */
2965         assert(scope == &declaration->scope);
2966         set_scope(last_scope);
2967         environment_pop_to(top);
2968
2969         /* update function type */
2970         type_t *new_type = duplicate_type(type);
2971         new_type->function.kr_style_parameters = false;
2972
2973         function_parameter_t *parameters     = NULL;
2974         function_parameter_t *last_parameter = NULL;
2975
2976         declaration_t *parameter_declaration = declaration->scope.declarations;
2977         for( ; parameter_declaration != NULL;
2978                         parameter_declaration = parameter_declaration->next) {
2979                 type_t *parameter_type = parameter_declaration->type;
2980                 if(parameter_type == NULL) {
2981                         if (strict_mode) {
2982                                 errorf(HERE, "no type specified for function parameter '%Y'",
2983                                        parameter_declaration->symbol);
2984                         } else {
2985                                 if (warning.implicit_int) {
2986                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
2987                                                 parameter_declaration->symbol);
2988                                 }
2989                                 parameter_type              = type_int;
2990                                 parameter_declaration->type = parameter_type;
2991                         }
2992                 }
2993
2994                 semantic_parameter(parameter_declaration);
2995                 parameter_type = parameter_declaration->type;
2996
2997                 function_parameter_t *function_parameter
2998                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2999                 memset(function_parameter, 0, sizeof(function_parameter[0]));
3000
3001                 function_parameter->type = parameter_type;
3002                 if(last_parameter != NULL) {
3003                         last_parameter->next = function_parameter;
3004                 } else {
3005                         parameters = function_parameter;
3006                 }
3007                 last_parameter = function_parameter;
3008         }
3009         new_type->function.parameters = parameters;
3010
3011         type = typehash_insert(new_type);
3012         if(type != new_type) {
3013                 obstack_free(type_obst, new_type);
3014         }
3015
3016         declaration->type = type;
3017 }
3018
3019 static bool first_err = true;
3020
3021 /**
3022  * When called with first_err set, prints the name of the current function,
3023  * else does noting.
3024  */
3025 static void print_in_function(void) {
3026         if (first_err) {
3027                 first_err = false;
3028                 diagnosticf("%s: In function '%Y':\n",
3029                         current_function->source_position.input_name,
3030                         current_function->symbol);
3031         }
3032 }
3033
3034 /**
3035  * Check if all labels are defined in the current function.
3036  * Check if all labels are used in the current function.
3037  */
3038 static void check_labels(void)
3039 {
3040         for (const goto_statement_t *goto_statement = goto_first;
3041             goto_statement != NULL;
3042             goto_statement = goto_statement->next) {
3043                 declaration_t *label = goto_statement->label;
3044
3045                 label->used = true;
3046                 if (label->source_position.input_name == NULL) {
3047                         print_in_function();
3048                         errorf(goto_statement->base.source_position,
3049                                "label '%Y' used but not defined", label->symbol);
3050                  }
3051         }
3052         goto_first = goto_last = NULL;
3053
3054         if (warning.unused_label) {
3055                 for (const label_statement_t *label_statement = label_first;
3056                          label_statement != NULL;
3057                          label_statement = label_statement->next) {
3058                         const declaration_t *label = label_statement->label;
3059
3060                         if (! label->used) {
3061                                 print_in_function();
3062                                 warningf(label_statement->base.source_position,
3063                                         "label '%Y' defined but not used", label->symbol);
3064                         }
3065                 }
3066         }
3067         label_first = label_last = NULL;
3068 }
3069
3070 /**
3071  * Check declarations of current_function for unused entities.
3072  */
3073 static void check_declarations(void)
3074 {
3075         if (warning.unused_parameter) {
3076                 const scope_t *scope = &current_function->scope;
3077
3078                 const declaration_t *parameter = scope->declarations;
3079                 for (; parameter != NULL; parameter = parameter->next) {
3080                         if (! parameter->used) {
3081                                 print_in_function();
3082                                 warningf(parameter->source_position,
3083                                         "unused parameter '%Y'", parameter->symbol);
3084                         }
3085                 }
3086         }
3087         if (warning.unused_variable) {
3088         }
3089 }
3090
3091 static void parse_external_declaration(void)
3092 {
3093         /* function-definitions and declarations both start with declaration
3094          * specifiers */
3095         declaration_specifiers_t specifiers;
3096         memset(&specifiers, 0, sizeof(specifiers));
3097         parse_declaration_specifiers(&specifiers);
3098
3099         /* must be a declaration */
3100         if(token.type == ';') {
3101                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3102                 return;
3103         }
3104
3105         /* declarator is common to both function-definitions and declarations */
3106         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3107
3108         /* must be a declaration */
3109         if(token.type == ',' || token.type == '=' || token.type == ';') {
3110                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3111                 return;
3112         }
3113
3114         /* must be a function definition */
3115         parse_kr_declaration_list(ndeclaration);
3116
3117         if(token.type != '{') {
3118                 parse_error_expected("while parsing function definition", '{', 0);
3119                 eat_statement();
3120                 return;
3121         }
3122
3123         type_t *type = ndeclaration->type;
3124
3125         /* note that we don't skip typerefs: the standard doesn't allow them here
3126          * (so we can't use is_type_function here) */
3127         if(type->kind != TYPE_FUNCTION) {
3128                 if (is_type_valid(type)) {
3129                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
3130                                type, ndeclaration->symbol);
3131                 }
3132                 eat_block();
3133                 return;
3134         }
3135
3136         /* Â§ 6.7.5.3 (14) a function definition with () means no
3137          * parameters (and not unspecified parameters) */
3138         if(type->function.unspecified_parameters) {
3139                 type_t *duplicate = duplicate_type(type);
3140                 duplicate->function.unspecified_parameters = false;
3141
3142                 type = typehash_insert(duplicate);
3143                 if(type != duplicate) {
3144                         obstack_free(type_obst, duplicate);
3145                 }
3146                 ndeclaration->type = type;
3147         }
3148
3149         declaration_t *const declaration = record_function_definition(ndeclaration);
3150         if(ndeclaration != declaration) {
3151                 declaration->scope = ndeclaration->scope;
3152         }
3153         type = skip_typeref(declaration->type);
3154
3155         /* push function parameters and switch scope */
3156         int       top        = environment_top();
3157         scope_t  *last_scope = scope;
3158         set_scope(&declaration->scope);
3159
3160         declaration_t *parameter = declaration->scope.declarations;
3161         for( ; parameter != NULL; parameter = parameter->next) {
3162                 if(parameter->parent_scope == &ndeclaration->scope) {
3163                         parameter->parent_scope = scope;
3164                 }
3165                 assert(parameter->parent_scope == NULL
3166                                 || parameter->parent_scope == scope);
3167                 parameter->parent_scope = scope;
3168                 environment_push(parameter);
3169         }
3170
3171         if(declaration->init.statement != NULL) {
3172                 parser_error_multiple_definition(declaration, token.source_position);
3173                 eat_block();
3174                 goto end_of_parse_external_declaration;
3175         } else {
3176                 /* parse function body */
3177                 int            label_stack_top      = label_top();
3178                 declaration_t *old_current_function = current_function;
3179                 current_function                    = declaration;
3180
3181                 declaration->init.statement = parse_compound_statement();
3182                 first_err = true;
3183                 check_labels();
3184                 check_declarations();
3185
3186                 assert(current_function == declaration);
3187                 current_function = old_current_function;
3188                 label_pop_to(label_stack_top);
3189         }
3190
3191 end_of_parse_external_declaration:
3192         assert(scope == &declaration->scope);
3193         set_scope(last_scope);
3194         environment_pop_to(top);
3195 }
3196
3197 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3198                                   source_position_t source_position)
3199 {
3200         type_t *type        = allocate_type_zero(TYPE_BITFIELD, source_position);
3201         type->bitfield.base = base;
3202         type->bitfield.size = size;
3203
3204         return type;
3205 }
3206
3207 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3208                                           symbol_t *symbol)
3209 {
3210         declaration_t *iter = compound_declaration->scope.declarations;
3211         for( ; iter != NULL; iter = iter->next) {
3212                 if(iter->namespc != NAMESPACE_NORMAL)
3213                         continue;
3214
3215                 if(iter->symbol == NULL) {
3216                         type_t *type = skip_typeref(iter->type);
3217                         if(is_type_compound(type)) {
3218                                 declaration_t *result
3219                                         = find_compound_entry(type->compound.declaration, symbol);
3220                                 if(result != NULL)
3221                                         return result;
3222                         }
3223                         continue;
3224                 }
3225
3226                 if(iter->symbol == symbol) {
3227                         return iter;
3228                 }
3229         }
3230
3231         return NULL;
3232 }
3233
3234 static void parse_compound_declarators(declaration_t *struct_declaration,
3235                 const declaration_specifiers_t *specifiers)
3236 {
3237         declaration_t *last_declaration = struct_declaration->scope.declarations;
3238         if(last_declaration != NULL) {
3239                 while(last_declaration->next != NULL) {
3240                         last_declaration = last_declaration->next;
3241                 }
3242         }
3243
3244         while(1) {
3245                 declaration_t *declaration;
3246
3247                 if(token.type == ':') {
3248                         source_position_t source_position = HERE;
3249                         next_token();
3250
3251                         type_t *base_type = specifiers->type;
3252                         expression_t *size = parse_constant_expression();
3253
3254                         if(!is_type_integer(skip_typeref(base_type))) {
3255                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
3256                                        base_type);
3257                         }
3258
3259                         type_t *type = make_bitfield_type(base_type, size, source_position);
3260
3261                         declaration                  = allocate_declaration_zero();
3262                         declaration->namespc         = NAMESPACE_NORMAL;
3263                         declaration->storage_class   = STORAGE_CLASS_NONE;
3264                         declaration->source_position = source_position;
3265                         declaration->modifiers       = specifiers->decl_modifiers;
3266                         declaration->type            = type;
3267                 } else {
3268                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3269
3270                         type_t *orig_type = declaration->type;
3271                         type_t *type      = skip_typeref(orig_type);
3272
3273                         if(token.type == ':') {
3274                                 source_position_t source_position = HERE;
3275                                 next_token();
3276                                 expression_t *size = parse_constant_expression();
3277
3278                                 if(!is_type_integer(type)) {
3279                                         errorf(HERE, "bitfield base type '%T' is not an "
3280                                                "integer type", orig_type);
3281                                 }
3282
3283                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3284                                 declaration->type = bitfield_type;
3285                         } else {
3286                                 /* TODO we ignore arrays for now... what is missing is a check
3287                                  * that they're at the end of the struct */
3288                                 if(is_type_incomplete(type) && !is_type_array(type)) {
3289                                         errorf(HERE,
3290                                                "compound member '%Y' has incomplete type '%T'",
3291                                                declaration->symbol, orig_type);
3292                                 } else if(is_type_function(type)) {
3293                                         errorf(HERE, "compound member '%Y' must not have function "
3294                                                "type '%T'", declaration->symbol, orig_type);
3295                                 }
3296                         }
3297                 }
3298
3299                 /* make sure we don't define a symbol multiple times */
3300                 symbol_t *symbol = declaration->symbol;
3301                 if(symbol != NULL) {
3302                         declaration_t *prev_decl
3303                                 = find_compound_entry(struct_declaration, symbol);
3304
3305                         if(prev_decl != NULL) {
3306                                 assert(prev_decl->symbol == symbol);
3307                                 errorf(declaration->source_position,
3308                                        "multiple declarations of symbol '%Y'", symbol);
3309                                 errorf(prev_decl->source_position,
3310                                        "previous declaration of '%Y' was here", symbol);
3311                         }
3312                 }
3313
3314                 /* append declaration */
3315                 if(last_declaration != NULL) {
3316                         last_declaration->next = declaration;
3317                 } else {
3318                         struct_declaration->scope.declarations = declaration;
3319                 }
3320                 last_declaration = declaration;
3321
3322                 if(token.type != ',')
3323                         break;
3324                 next_token();
3325         }
3326         expect_void(';');
3327 }
3328
3329 static void parse_compound_type_entries(declaration_t *compound_declaration)
3330 {
3331         eat('{');
3332
3333         while(token.type != '}' && token.type != T_EOF) {
3334                 declaration_specifiers_t specifiers;
3335                 memset(&specifiers, 0, sizeof(specifiers));
3336                 parse_declaration_specifiers(&specifiers);
3337
3338                 parse_compound_declarators(compound_declaration, &specifiers);
3339         }
3340         if(token.type == T_EOF) {
3341                 errorf(HERE, "EOF while parsing struct");
3342         }
3343         next_token();
3344 }
3345
3346 static type_t *parse_typename(void)
3347 {
3348         declaration_specifiers_t specifiers;
3349         memset(&specifiers, 0, sizeof(specifiers));
3350         parse_declaration_specifiers(&specifiers);
3351         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
3352                 /* TODO: improve error message, user does probably not know what a
3353                  * storage class is...
3354                  */
3355                 errorf(HERE, "typename may not have a storage class");
3356         }
3357
3358         type_t *result = parse_abstract_declarator(specifiers.type);
3359
3360         return result;
3361 }
3362
3363
3364
3365
3366 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3367 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3368                                                           expression_t *left);
3369
3370 typedef struct expression_parser_function_t expression_parser_function_t;
3371 struct expression_parser_function_t {
3372         unsigned                         precedence;
3373         parse_expression_function        parser;
3374         unsigned                         infix_precedence;
3375         parse_expression_infix_function  infix_parser;
3376 };
3377
3378 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3379
3380 /**
3381  * Creates a new invalid expression.
3382  */
3383 static expression_t *create_invalid_expression(void)
3384 {
3385         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
3386         expression->base.source_position = token.source_position;
3387         return expression;
3388 }
3389
3390 /**
3391  * Prints an error message if an expression was expected but not read
3392  */
3393 static expression_t *expected_expression_error(void)
3394 {
3395         /* skip the error message if the error token was read */
3396         if (token.type != T_ERROR) {
3397                 errorf(HERE, "expected expression, got token '%K'", &token);
3398         }
3399         next_token();
3400
3401         return create_invalid_expression();
3402 }
3403
3404 /**
3405  * Parse a string constant.
3406  */
3407 static expression_t *parse_string_const(void)
3408 {
3409         wide_string_t wres;
3410         if (token.type == T_STRING_LITERAL) {
3411                 string_t res = token.v.string;
3412                 next_token();
3413                 while (token.type == T_STRING_LITERAL) {
3414                         res = concat_strings(&res, &token.v.string);
3415                         next_token();
3416                 }
3417                 if (token.type != T_WIDE_STRING_LITERAL) {
3418                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3419                         cnst->base.type    = type_char_ptr;
3420                         cnst->string.value = res;
3421                         return cnst;
3422                 }
3423
3424                 wres = concat_string_wide_string(&res, &token.v.wide_string);
3425         } else {
3426                 wres = token.v.wide_string;
3427         }
3428         next_token();
3429
3430         for (;;) {
3431                 switch (token.type) {
3432                         case T_WIDE_STRING_LITERAL:
3433                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
3434                                 break;
3435
3436                         case T_STRING_LITERAL:
3437                                 wres = concat_wide_string_string(&wres, &token.v.string);
3438                                 break;
3439
3440                         default: {
3441                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3442                                 cnst->base.type         = type_wchar_t_ptr;
3443                                 cnst->wide_string.value = wres;
3444                                 return cnst;
3445                         }
3446                 }
3447                 next_token();
3448         }
3449 }
3450
3451 /**
3452  * Parse an integer constant.
3453  */
3454 static expression_t *parse_int_const(void)
3455 {
3456         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3457         cnst->base.source_position = HERE;
3458         cnst->base.type            = token.datatype;
3459         cnst->conste.v.int_value   = token.v.intvalue;
3460
3461         next_token();
3462
3463         return cnst;
3464 }
3465
3466 /**
3467  * Parse a character constant.
3468  */
3469 static expression_t *parse_char_const(void)
3470 {
3471         expression_t *cnst         = allocate_expression_zero(EXPR_CHAR_CONST);
3472         cnst->base.source_position = HERE;
3473         cnst->base.type            = token.datatype;
3474         cnst->conste.v.chars.begin = token.v.string.begin;
3475         cnst->conste.v.chars.size  = token.v.string.size;
3476
3477         if (cnst->conste.v.chars.size != 1) {
3478                 if (warning.multichar && (c_mode & _GNUC)) {
3479                         /* TODO */
3480                         warningf(HERE, "multi-character character constant");
3481                 } else {
3482                         errorf(HERE, "more than 1 characters in character constant");
3483                 }
3484         }
3485         next_token();
3486
3487         return cnst;
3488 }
3489
3490 /**
3491  * Parse a float constant.
3492  */
3493 static expression_t *parse_float_const(void)
3494 {
3495         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3496         cnst->base.type            = token.datatype;
3497         cnst->conste.v.float_value = token.v.floatvalue;
3498
3499         next_token();
3500
3501         return cnst;
3502 }
3503
3504 static declaration_t *create_implicit_function(symbol_t *symbol,
3505                 const source_position_t source_position)
3506 {
3507         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
3508         ntype->function.return_type            = type_int;
3509         ntype->function.unspecified_parameters = true;
3510
3511         type_t *type = typehash_insert(ntype);
3512         if(type != ntype) {
3513                 free_type(ntype);
3514         }
3515
3516         declaration_t *const declaration = allocate_declaration_zero();
3517         declaration->storage_class   = STORAGE_CLASS_EXTERN;
3518         declaration->type            = type;
3519         declaration->symbol          = symbol;
3520         declaration->source_position = source_position;
3521         declaration->parent_scope  = global_scope;
3522
3523         scope_t *old_scope = scope;
3524         set_scope(global_scope);
3525
3526         environment_push(declaration);
3527         /* prepends the declaration to the global declarations list */
3528         declaration->next   = scope->declarations;
3529         scope->declarations = declaration;
3530
3531         assert(scope == global_scope);
3532         set_scope(old_scope);
3533
3534         return declaration;
3535 }
3536
3537 /**
3538  * Creates a return_type (func)(argument_type) function type if not
3539  * already exists.
3540  *
3541  * @param return_type    the return type
3542  * @param argument_type  the argument type
3543  */
3544 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3545 {
3546         function_parameter_t *parameter
3547                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3548         memset(parameter, 0, sizeof(parameter[0]));
3549         parameter->type = argument_type;
3550
3551         type_t *type               = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3552         type->function.return_type = return_type;
3553         type->function.parameters  = parameter;
3554
3555         type_t *result = typehash_insert(type);
3556         if(result != type) {
3557                 free_type(type);
3558         }
3559
3560         return result;
3561 }
3562
3563 /**
3564  * Creates a function type for some function like builtins.
3565  *
3566  * @param symbol   the symbol describing the builtin
3567  */
3568 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3569 {
3570         switch(symbol->ID) {
3571         case T___builtin_alloca:
3572                 return make_function_1_type(type_void_ptr, type_size_t);
3573         case T___builtin_nan:
3574                 return make_function_1_type(type_double, type_char_ptr);
3575         case T___builtin_nanf:
3576                 return make_function_1_type(type_float, type_char_ptr);
3577         case T___builtin_nand:
3578                 return make_function_1_type(type_long_double, type_char_ptr);
3579         case T___builtin_va_end:
3580                 return make_function_1_type(type_void, type_valist);
3581         default:
3582                 panic("not implemented builtin symbol found");
3583         }
3584 }
3585
3586 /**
3587  * Performs automatic type cast as described in Â§ 6.3.2.1.
3588  *
3589  * @param orig_type  the original type
3590  */
3591 static type_t *automatic_type_conversion(type_t *orig_type)
3592 {
3593         type_t *type = skip_typeref(orig_type);
3594         if(is_type_array(type)) {
3595                 array_type_t *array_type   = &type->array;
3596                 type_t       *element_type = array_type->element_type;
3597                 unsigned      qualifiers   = array_type->type.qualifiers;
3598
3599                 return make_pointer_type(element_type, qualifiers);
3600         }
3601
3602         if(is_type_function(type)) {
3603                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3604         }
3605
3606         return orig_type;
3607 }
3608
3609 /**
3610  * reverts the automatic casts of array to pointer types and function
3611  * to function-pointer types as defined Â§ 6.3.2.1
3612  */
3613 type_t *revert_automatic_type_conversion(const expression_t *expression)
3614 {
3615         switch (expression->kind) {
3616                 case EXPR_REFERENCE: return expression->reference.declaration->type;
3617                 case EXPR_SELECT:    return expression->select.compound_entry->type;
3618
3619                 case EXPR_UNARY_DEREFERENCE: {
3620                         const expression_t *const value = expression->unary.value;
3621                         type_t             *const type  = skip_typeref(value->base.type);
3622                         assert(is_type_pointer(type));
3623                         return type->pointer.points_to;
3624                 }
3625
3626                 case EXPR_BUILTIN_SYMBOL:
3627                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3628
3629                 case EXPR_ARRAY_ACCESS: {
3630                         const expression_t *array_ref = expression->array_access.array_ref;
3631                         type_t             *type_left = skip_typeref(array_ref->base.type);
3632                         if (!is_type_valid(type_left))
3633                                 return type_left;
3634                         assert(is_type_pointer(type_left));
3635                         return type_left->pointer.points_to;
3636                 }
3637
3638                 default: break;
3639         }
3640
3641         return expression->base.type;
3642 }
3643
3644 static expression_t *parse_reference(void)
3645 {
3646         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3647
3648         reference_expression_t *ref = &expression->reference;
3649         ref->symbol = token.v.symbol;
3650
3651         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3652
3653         source_position_t source_position = token.source_position;
3654         next_token();
3655
3656         if(declaration == NULL) {
3657                 if (! strict_mode && token.type == '(') {
3658                         /* an implicitly defined function */
3659                         if (warning.implicit_function_declaration) {
3660                                 warningf(HERE, "implicit declaration of function '%Y'",
3661                                         ref->symbol);
3662                         }
3663
3664                         declaration = create_implicit_function(ref->symbol,
3665                                                                source_position);
3666                 } else {
3667                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3668                         return create_invalid_expression();
3669                 }
3670         }
3671
3672         type_t *type         = declaration->type;
3673
3674         /* we always do the auto-type conversions; the & and sizeof parser contains
3675          * code to revert this! */
3676         type = automatic_type_conversion(type);
3677
3678         ref->declaration = declaration;
3679         ref->base.type   = type;
3680
3681         /* this declaration is used */
3682         declaration->used = true;
3683
3684         return expression;
3685 }
3686
3687 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3688 {
3689         (void) expression;
3690         (void) dest_type;
3691         /* TODO check if explicit cast is allowed and issue warnings/errors */
3692 }
3693
3694 static expression_t *parse_compound_literal(type_t *type)
3695 {
3696         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
3697
3698         expression->compound_literal.type        = type;
3699         expression->compound_literal.initializer = parse_initializer(type);
3700         expression->base.type                    = automatic_type_conversion(type);
3701
3702         return expression;
3703 }
3704
3705 static expression_t *parse_cast(void)
3706 {
3707         source_position_t source_position = token.source_position;
3708
3709         type_t *type  = parse_typename();
3710
3711         expect(')');
3712
3713         if(token.type == '{') {
3714                 return parse_compound_literal(type);
3715         }
3716
3717         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3718         cast->base.source_position = source_position;
3719
3720         expression_t *value = parse_sub_expression(20);
3721
3722         check_cast_allowed(value, type);
3723
3724         cast->base.type   = type;
3725         cast->unary.value = value;
3726
3727         return cast;
3728 }
3729
3730 static expression_t *parse_statement_expression(void)
3731 {
3732         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3733
3734         statement_t *statement           = parse_compound_statement();
3735         expression->statement.statement  = statement;
3736         expression->base.source_position = statement->base.source_position;
3737
3738         /* find last statement and use its type */
3739         type_t *type = type_void;
3740         const statement_t *stmt = statement->compound.statements;
3741         if (stmt != NULL) {
3742                 while (stmt->base.next != NULL)
3743                         stmt = stmt->base.next;
3744
3745                 if (stmt->kind == STATEMENT_EXPRESSION) {
3746                         type = stmt->expression.expression->base.type;
3747                 }
3748         } else {
3749                 warningf(expression->base.source_position, "empty statement expression ({})");
3750         }
3751         expression->base.type = type;
3752
3753         expect(')');
3754
3755         return expression;
3756 }
3757
3758 static expression_t *parse_brace_expression(void)
3759 {
3760         eat('(');
3761
3762         switch(token.type) {
3763         case '{':
3764                 /* gcc extension: a statement expression */
3765                 return parse_statement_expression();
3766
3767         TYPE_QUALIFIERS
3768         TYPE_SPECIFIERS
3769                 return parse_cast();
3770         case T_IDENTIFIER:
3771                 if(is_typedef_symbol(token.v.symbol)) {
3772                         return parse_cast();
3773                 }
3774         }
3775
3776         expression_t *result = parse_expression();
3777         expect(')');
3778
3779         return result;
3780 }
3781
3782 static expression_t *parse_function_keyword(void)
3783 {
3784         next_token();
3785         /* TODO */
3786
3787         if (current_function == NULL) {
3788                 errorf(HERE, "'__func__' used outside of a function");
3789         }
3790
3791         expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
3792         expression->base.type    = type_char_ptr;
3793
3794         return expression;
3795 }
3796
3797 static expression_t *parse_pretty_function_keyword(void)
3798 {
3799         eat(T___PRETTY_FUNCTION__);
3800         /* TODO */
3801
3802         if (current_function == NULL) {
3803                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3804         }
3805
3806         expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
3807         expression->base.type    = type_char_ptr;
3808
3809         return expression;
3810 }
3811
3812 static designator_t *parse_designator(void)
3813 {
3814         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
3815         result->source_position = HERE;
3816
3817         if(token.type != T_IDENTIFIER) {
3818                 parse_error_expected("while parsing member designator",
3819                                      T_IDENTIFIER, 0);
3820                 eat_paren();
3821                 return NULL;
3822         }
3823         result->symbol = token.v.symbol;
3824         next_token();
3825
3826         designator_t *last_designator = result;
3827         while(true) {
3828                 if(token.type == '.') {
3829                         next_token();
3830                         if(token.type != T_IDENTIFIER) {
3831                                 parse_error_expected("while parsing member designator",
3832                                                      T_IDENTIFIER, 0);
3833                                 eat_paren();
3834                                 return NULL;
3835                         }
3836                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3837                         designator->source_position = HERE;
3838                         designator->symbol          = token.v.symbol;
3839                         next_token();
3840
3841                         last_designator->next = designator;
3842                         last_designator       = designator;
3843                         continue;
3844                 }
3845                 if(token.type == '[') {
3846                         next_token();
3847                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3848                         designator->source_position = HERE;
3849                         designator->array_index     = parse_expression();
3850                         if(designator->array_index == NULL) {
3851                                 eat_paren();
3852                                 return NULL;
3853                         }
3854                         expect(']');
3855
3856                         last_designator->next = designator;
3857                         last_designator       = designator;
3858                         continue;
3859                 }
3860                 break;
3861         }
3862
3863         return result;
3864 }
3865
3866 static expression_t *parse_offsetof(void)
3867 {
3868         eat(T___builtin_offsetof);
3869
3870         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
3871         expression->base.type    = type_size_t;
3872
3873         expect('(');
3874         type_t *type = parse_typename();
3875         expect(',');
3876         designator_t *designator = parse_designator();
3877         expect(')');
3878
3879         expression->offsetofe.type       = type;
3880         expression->offsetofe.designator = designator;
3881
3882         type_path_t path;
3883         memset(&path, 0, sizeof(path));
3884         path.top_type = type;
3885         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3886
3887         descend_into_subtype(&path);
3888
3889         if(!walk_designator(&path, designator, true)) {
3890                 return create_invalid_expression();
3891         }
3892
3893         DEL_ARR_F(path.path);
3894
3895         return expression;
3896 }
3897
3898 static expression_t *parse_va_start(void)
3899 {
3900         eat(T___builtin_va_start);
3901
3902         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3903
3904         expect('(');
3905         expression->va_starte.ap = parse_assignment_expression();
3906         expect(',');
3907         expression_t *const expr = parse_assignment_expression();
3908         if (expr->kind == EXPR_REFERENCE) {
3909                 declaration_t *const decl = expr->reference.declaration;
3910                 if (decl == NULL)
3911                         return create_invalid_expression();
3912                 if (decl->parent_scope == &current_function->scope &&
3913                     decl->next == NULL) {
3914                         expression->va_starte.parameter = decl;
3915                         expect(')');
3916                         return expression;
3917                 }
3918         }
3919         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3920
3921         return create_invalid_expression();
3922 }
3923
3924 static expression_t *parse_va_arg(void)
3925 {
3926         eat(T___builtin_va_arg);
3927
3928         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3929
3930         expect('(');
3931         expression->va_arge.ap = parse_assignment_expression();
3932         expect(',');
3933         expression->base.type = parse_typename();
3934         expect(')');
3935
3936         return expression;
3937 }
3938
3939 static expression_t *parse_builtin_symbol(void)
3940 {
3941         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3942
3943         symbol_t *symbol = token.v.symbol;
3944
3945         expression->builtin_symbol.symbol = symbol;
3946         next_token();
3947
3948         type_t *type = get_builtin_symbol_type(symbol);
3949         type = automatic_type_conversion(type);
3950
3951         expression->base.type = type;
3952         return expression;
3953 }
3954
3955 static expression_t *parse_builtin_constant(void)
3956 {
3957         eat(T___builtin_constant_p);
3958
3959         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3960
3961         expect('(');
3962         expression->builtin_constant.value = parse_assignment_expression();
3963         expect(')');
3964         expression->base.type = type_int;
3965
3966         return expression;
3967 }
3968
3969 static expression_t *parse_builtin_prefetch(void)
3970 {
3971         eat(T___builtin_prefetch);
3972
3973         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3974
3975         expect('(');
3976         expression->builtin_prefetch.adr = parse_assignment_expression();
3977         if (token.type == ',') {
3978                 next_token();
3979                 expression->builtin_prefetch.rw = parse_assignment_expression();
3980         }
3981         if (token.type == ',') {
3982                 next_token();
3983                 expression->builtin_prefetch.locality = parse_assignment_expression();
3984         }
3985         expect(')');
3986         expression->base.type = type_void;
3987
3988         return expression;
3989 }
3990
3991 static expression_t *parse_compare_builtin(void)
3992 {
3993         expression_t *expression;
3994
3995         switch(token.type) {
3996         case T___builtin_isgreater:
3997                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3998                 break;
3999         case T___builtin_isgreaterequal:
4000                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4001                 break;
4002         case T___builtin_isless:
4003                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4004                 break;
4005         case T___builtin_islessequal:
4006                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4007                 break;
4008         case T___builtin_islessgreater:
4009                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4010                 break;
4011         case T___builtin_isunordered:
4012                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4013                 break;
4014         default:
4015                 panic("invalid compare builtin found");
4016                 break;
4017         }
4018         expression->base.source_position = HERE;
4019         next_token();
4020
4021         expect('(');
4022         expression->binary.left = parse_assignment_expression();
4023         expect(',');
4024         expression->binary.right = parse_assignment_expression();
4025         expect(')');
4026
4027         type_t *const orig_type_left  = expression->binary.left->base.type;
4028         type_t *const orig_type_right = expression->binary.right->base.type;
4029
4030         type_t *const type_left  = skip_typeref(orig_type_left);
4031         type_t *const type_right = skip_typeref(orig_type_right);
4032         if(!is_type_float(type_left) && !is_type_float(type_right)) {
4033                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4034                         type_error_incompatible("invalid operands in comparison",
4035                                 expression->base.source_position, orig_type_left, orig_type_right);
4036                 }
4037         } else {
4038                 semantic_comparison(&expression->binary);
4039         }
4040
4041         return expression;
4042 }
4043
4044 static expression_t *parse_builtin_expect(void)
4045 {
4046         eat(T___builtin_expect);
4047
4048         expression_t *expression
4049                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4050
4051         expect('(');
4052         expression->binary.left = parse_assignment_expression();
4053         expect(',');
4054         expression->binary.right = parse_constant_expression();
4055         expect(')');
4056
4057         expression->base.type = expression->binary.left->base.type;
4058
4059         return expression;
4060 }
4061
4062 static expression_t *parse_assume(void) {
4063         eat(T_assume);
4064
4065         expression_t *expression
4066                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4067
4068         expect('(');
4069         expression->unary.value = parse_assignment_expression();
4070         expect(')');
4071
4072         expression->base.type = type_void;
4073         return expression;
4074 }
4075
4076 static expression_t *parse_primary_expression(void)
4077 {
4078         switch (token.type) {
4079                 case T_INTEGER:                  return parse_int_const();
4080                 case T_CHARS:                    return parse_char_const();
4081                 case T_FLOATINGPOINT:            return parse_float_const();
4082                 case T_STRING_LITERAL:
4083                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
4084                 case T_IDENTIFIER:               return parse_reference();
4085                 case T___FUNCTION__:
4086                 case T___func__:                 return parse_function_keyword();
4087                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
4088                 case T___builtin_offsetof:       return parse_offsetof();
4089                 case T___builtin_va_start:       return parse_va_start();
4090                 case T___builtin_va_arg:         return parse_va_arg();
4091                 case T___builtin_expect:         return parse_builtin_expect();
4092                 case T___builtin_alloca:
4093                 case T___builtin_nan:
4094                 case T___builtin_nand:
4095                 case T___builtin_nanf:
4096                 case T___builtin_va_end:         return parse_builtin_symbol();
4097                 case T___builtin_isgreater:
4098                 case T___builtin_isgreaterequal:
4099                 case T___builtin_isless:
4100                 case T___builtin_islessequal:
4101                 case T___builtin_islessgreater:
4102                 case T___builtin_isunordered:    return parse_compare_builtin();
4103                 case T___builtin_constant_p:     return parse_builtin_constant();
4104                 case T___builtin_prefetch:       return parse_builtin_prefetch();
4105                 case T_assume:                   return parse_assume();
4106
4107                 case '(':                        return parse_brace_expression();
4108         }
4109
4110         errorf(HERE, "unexpected token %K, expected an expression", &token);
4111         eat_statement();
4112
4113         return create_invalid_expression();
4114 }
4115
4116 /**
4117  * Check if the expression has the character type and issue a warning then.
4118  */
4119 static void check_for_char_index_type(const expression_t *expression) {
4120         type_t       *const type      = expression->base.type;
4121         const type_t *const base_type = skip_typeref(type);
4122
4123         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4124                         warning.char_subscripts) {
4125                 warningf(expression->base.source_position,
4126                         "array subscript has type '%T'", type);
4127         }
4128 }
4129
4130 static expression_t *parse_array_expression(unsigned precedence,
4131                                             expression_t *left)
4132 {
4133         (void) precedence;
4134
4135         eat('[');
4136
4137         expression_t *inside = parse_expression();
4138
4139         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4140
4141         array_access_expression_t *array_access = &expression->array_access;
4142
4143         type_t *const orig_type_left   = left->base.type;
4144         type_t *const orig_type_inside = inside->base.type;
4145
4146         type_t *const type_left   = skip_typeref(orig_type_left);
4147         type_t *const type_inside = skip_typeref(orig_type_inside);
4148
4149         type_t *return_type;
4150         if (is_type_pointer(type_left)) {
4151                 return_type             = type_left->pointer.points_to;
4152                 array_access->array_ref = left;
4153                 array_access->index     = inside;
4154                 check_for_char_index_type(inside);
4155         } else if (is_type_pointer(type_inside)) {
4156                 return_type             = type_inside->pointer.points_to;
4157                 array_access->array_ref = inside;
4158                 array_access->index     = left;
4159                 array_access->flipped   = true;
4160                 check_for_char_index_type(left);
4161         } else {
4162                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4163                         errorf(HERE,
4164                                 "array access on object with non-pointer types '%T', '%T'",
4165                                 orig_type_left, orig_type_inside);
4166                 }
4167                 return_type             = type_error_type;
4168                 array_access->array_ref = create_invalid_expression();
4169         }
4170
4171         if(token.type != ']') {
4172                 parse_error_expected("Problem while parsing array access", ']', 0);
4173                 return expression;
4174         }
4175         next_token();
4176
4177         return_type           = automatic_type_conversion(return_type);
4178         expression->base.type = return_type;
4179
4180         return expression;
4181 }
4182
4183 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4184 {
4185         expression_t *tp_expression = allocate_expression_zero(kind);
4186         tp_expression->base.type    = type_size_t;
4187
4188         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4189                 next_token();
4190                 tp_expression->typeprop.type = parse_typename();
4191                 expect(')');
4192         } else {
4193                 expression_t *expression = parse_sub_expression(precedence);
4194                 expression->base.type    = revert_automatic_type_conversion(expression);
4195
4196                 tp_expression->typeprop.type          = expression->base.type;
4197                 tp_expression->typeprop.tp_expression = expression;
4198         }
4199
4200         return tp_expression;
4201 }
4202
4203 static expression_t *parse_sizeof(unsigned precedence)
4204 {
4205         eat(T_sizeof);
4206         return parse_typeprop(EXPR_SIZEOF, precedence);
4207 }
4208
4209 static expression_t *parse_alignof(unsigned precedence)
4210 {
4211         eat(T___alignof__);
4212         return parse_typeprop(EXPR_SIZEOF, precedence);
4213 }
4214
4215 static expression_t *parse_select_expression(unsigned precedence,
4216                                              expression_t *compound)
4217 {
4218         (void) precedence;
4219         assert(token.type == '.' || token.type == T_MINUSGREATER);
4220
4221         bool is_pointer = (token.type == T_MINUSGREATER);
4222         next_token();
4223
4224         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
4225         select->select.compound = compound;
4226
4227         if(token.type != T_IDENTIFIER) {
4228                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4229                 return select;
4230         }
4231         symbol_t *symbol      = token.v.symbol;
4232         select->select.symbol = symbol;
4233         next_token();
4234
4235         type_t *const orig_type = compound->base.type;
4236         type_t *const type      = skip_typeref(orig_type);
4237
4238         type_t *type_left = type;
4239         if(is_pointer) {
4240                 if (!is_type_pointer(type)) {
4241                         if (is_type_valid(type)) {
4242                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4243                         }
4244                         return create_invalid_expression();
4245                 }
4246                 type_left = type->pointer.points_to;
4247         }
4248         type_left = skip_typeref(type_left);
4249
4250         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4251             type_left->kind != TYPE_COMPOUND_UNION) {
4252                 if (is_type_valid(type_left)) {
4253                         errorf(HERE, "request for member '%Y' in something not a struct or "
4254                                "union, but '%T'", symbol, type_left);
4255                 }
4256                 return create_invalid_expression();
4257         }
4258
4259         declaration_t *const declaration = type_left->compound.declaration;
4260
4261         if(!declaration->init.is_defined) {
4262                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4263                        symbol, type_left);
4264                 return create_invalid_expression();
4265         }
4266
4267         declaration_t *iter = find_compound_entry(declaration, symbol);
4268         if(iter == NULL) {
4269                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4270                 return create_invalid_expression();
4271         }
4272
4273         /* we always do the auto-type conversions; the & and sizeof parser contains
4274          * code to revert this! */
4275         type_t *expression_type = automatic_type_conversion(iter->type);
4276
4277         select->select.compound_entry = iter;
4278         select->base.type             = expression_type;
4279
4280         if(expression_type->kind == TYPE_BITFIELD) {
4281                 expression_t *extract
4282                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4283                 extract->unary.value = select;
4284                 extract->base.type   = expression_type->bitfield.base;
4285
4286                 return extract;
4287         }
4288
4289         return select;
4290 }
4291
4292 /**
4293  * Parse a call expression, ie. expression '( ... )'.
4294  *
4295  * @param expression  the function address
4296  */
4297 static expression_t *parse_call_expression(unsigned precedence,
4298                                            expression_t *expression)
4299 {
4300         (void) precedence;
4301         expression_t *result = allocate_expression_zero(EXPR_CALL);
4302
4303         call_expression_t *call = &result->call;
4304         call->function          = expression;
4305
4306         type_t *const orig_type = expression->base.type;
4307         type_t *const type      = skip_typeref(orig_type);
4308
4309         function_type_t *function_type = NULL;
4310         if (is_type_pointer(type)) {
4311                 type_t *const to_type = skip_typeref(type->pointer.points_to);
4312
4313                 if (is_type_function(to_type)) {
4314                         function_type   = &to_type->function;
4315                         call->base.type = function_type->return_type;
4316                 }
4317         }
4318
4319         if (function_type == NULL && is_type_valid(type)) {
4320                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4321         }
4322
4323         /* parse arguments */
4324         eat('(');
4325
4326         if(token.type != ')') {
4327                 call_argument_t *last_argument = NULL;
4328
4329                 while(true) {
4330                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4331
4332                         argument->expression = parse_assignment_expression();
4333                         if(last_argument == NULL) {
4334                                 call->arguments = argument;
4335                         } else {
4336                                 last_argument->next = argument;
4337                         }
4338                         last_argument = argument;
4339
4340                         if(token.type != ',')
4341                                 break;
4342                         next_token();
4343                 }
4344         }
4345         expect(')');
4346
4347         if(function_type != NULL) {
4348                 function_parameter_t *parameter = function_type->parameters;
4349                 call_argument_t      *argument  = call->arguments;
4350                 for( ; parameter != NULL && argument != NULL;
4351                                 parameter = parameter->next, argument = argument->next) {
4352                         type_t *expected_type = parameter->type;
4353                         /* TODO report scope in error messages */
4354                         expression_t *const arg_expr = argument->expression;
4355                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4356                         if (res_type == NULL) {
4357                                 /* TODO improve error message */
4358                                 errorf(arg_expr->base.source_position,
4359                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4360                                         arg_expr, arg_expr->base.type, expected_type);
4361                         } else {
4362                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
4363                         }
4364                 }
4365                 /* too few parameters */
4366                 if(parameter != NULL) {
4367                         errorf(HERE, "too few arguments to function '%E'", expression);
4368                 } else if(argument != NULL) {
4369                         /* too many parameters */
4370                         if(!function_type->variadic
4371                                         && !function_type->unspecified_parameters) {
4372                                 errorf(HERE, "too many arguments to function '%E'", expression);
4373                         } else {
4374                                 /* do default promotion */
4375                                 for( ; argument != NULL; argument = argument->next) {
4376                                         type_t *type = argument->expression->base.type;
4377
4378                                         type = skip_typeref(type);
4379                                         if(is_type_integer(type)) {
4380                                                 type = promote_integer(type);
4381                                         } else if(type == type_float) {
4382                                                 type = type_double;
4383                                         }
4384
4385                                         argument->expression
4386                                                 = create_implicit_cast(argument->expression, type);
4387                                 }
4388
4389                                 check_format(&result->call);
4390                         }
4391                 } else {
4392                         check_format(&result->call);
4393                 }
4394         }
4395
4396         return result;
4397 }
4398
4399 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4400
4401 static bool same_compound_type(const type_t *type1, const type_t *type2)
4402 {
4403         return
4404                 is_type_compound(type1) &&
4405                 type1->kind == type2->kind &&
4406                 type1->compound.declaration == type2->compound.declaration;
4407 }
4408
4409 /**
4410  * Parse a conditional expression, ie. 'expression ? ... : ...'.
4411  *
4412  * @param expression  the conditional expression
4413  */
4414 static expression_t *parse_conditional_expression(unsigned precedence,
4415                                                   expression_t *expression)
4416 {
4417         eat('?');
4418
4419         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4420
4421         conditional_expression_t *conditional = &result->conditional;
4422         conditional->condition = expression;
4423
4424         /* 6.5.15.2 */
4425         type_t *const condition_type_orig = expression->base.type;
4426         type_t *const condition_type      = skip_typeref(condition_type_orig);
4427         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4428                 type_error("expected a scalar type in conditional condition",
4429                            expression->base.source_position, condition_type_orig);
4430         }
4431
4432         expression_t *true_expression = parse_expression();
4433         expect(':');
4434         expression_t *false_expression = parse_sub_expression(precedence);
4435
4436         type_t *const orig_true_type  = true_expression->base.type;
4437         type_t *const orig_false_type = false_expression->base.type;
4438         type_t *const true_type       = skip_typeref(orig_true_type);
4439         type_t *const false_type      = skip_typeref(orig_false_type);
4440
4441         /* 6.5.15.3 */
4442         type_t *result_type;
4443         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4444                 result_type = semantic_arithmetic(true_type, false_type);
4445
4446                 true_expression  = create_implicit_cast(true_expression, result_type);
4447                 false_expression = create_implicit_cast(false_expression, result_type);
4448
4449                 conditional->true_expression  = true_expression;
4450                 conditional->false_expression = false_expression;
4451                 conditional->base.type        = result_type;
4452         } else if (same_compound_type(true_type, false_type) || (
4453             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4454             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4455                 )) {
4456                 /* just take 1 of the 2 types */
4457                 result_type = true_type;
4458         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4459                         && pointers_compatible(true_type, false_type)) {
4460                 /* ok */
4461                 result_type = true_type;
4462         } else if (is_type_pointer(true_type)
4463                         && is_null_pointer_constant(false_expression)) {
4464                 result_type = true_type;
4465         } else if (is_type_pointer(false_type)
4466                         && is_null_pointer_constant(true_expression)) {
4467                 result_type = false_type;
4468         } else {
4469                 /* TODO: one pointer to void*, other some pointer */
4470
4471                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4472                         type_error_incompatible("while parsing conditional",
4473                                                 expression->base.source_position, true_type,
4474                                                 false_type);
4475                 }
4476                 result_type = type_error_type;
4477         }
4478
4479         conditional->true_expression
4480                 = create_implicit_cast(true_expression, result_type);
4481         conditional->false_expression
4482                 = create_implicit_cast(false_expression, result_type);
4483         conditional->base.type = result_type;
4484         return result;
4485 }
4486
4487 /**
4488  * Parse an extension expression.
4489  */
4490 static expression_t *parse_extension(unsigned precedence)
4491 {
4492         eat(T___extension__);
4493
4494         /* TODO enable extensions */
4495         expression_t *expression = parse_sub_expression(precedence);
4496         /* TODO disable extensions */
4497         return expression;
4498 }
4499
4500 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4501 {
4502         eat(T___builtin_classify_type);
4503
4504         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4505         result->base.type    = type_int;
4506
4507         expect('(');
4508         expression_t *expression = parse_sub_expression(precedence);
4509         expect(')');
4510         result->classify_type.type_expression = expression;
4511
4512         return result;
4513 }
4514
4515 static void semantic_incdec(unary_expression_t *expression)
4516 {
4517         type_t *const orig_type = expression->value->base.type;
4518         type_t *const type      = skip_typeref(orig_type);
4519         /* TODO !is_type_real && !is_type_pointer */
4520         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4521                 if (is_type_valid(type)) {
4522                         /* TODO: improve error message */
4523                         errorf(HERE, "operation needs an arithmetic or pointer type");
4524                 }
4525                 return;
4526         }
4527
4528         expression->base.type = orig_type;
4529 }
4530
4531 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4532 {
4533         type_t *const orig_type = expression->value->base.type;
4534         type_t *const type      = skip_typeref(orig_type);
4535         if(!is_type_arithmetic(type)) {
4536                 if (is_type_valid(type)) {
4537                         /* TODO: improve error message */
4538                         errorf(HERE, "operation needs an arithmetic type");
4539                 }
4540                 return;
4541         }
4542
4543         expression->base.type = orig_type;
4544 }
4545
4546 static void semantic_unexpr_scalar(unary_expression_t *expression)
4547 {
4548         type_t *const orig_type = expression->value->base.type;
4549         type_t *const type      = skip_typeref(orig_type);
4550         if (!is_type_scalar(type)) {
4551                 if (is_type_valid(type)) {
4552                         errorf(HERE, "operand of ! must be of scalar type");
4553                 }
4554                 return;
4555         }
4556
4557         expression->base.type = orig_type;
4558 }
4559
4560 static void semantic_unexpr_integer(unary_expression_t *expression)
4561 {
4562         type_t *const orig_type = expression->value->base.type;
4563         type_t *const type      = skip_typeref(orig_type);
4564         if (!is_type_integer(type)) {
4565                 if (is_type_valid(type)) {
4566                         errorf(HERE, "operand of ~ must be of integer type");
4567                 }
4568                 return;
4569         }
4570
4571         expression->base.type = orig_type;
4572 }
4573
4574 static void semantic_dereference(unary_expression_t *expression)
4575 {
4576         type_t *const orig_type = expression->value->base.type;
4577         type_t *const type      = skip_typeref(orig_type);
4578         if(!is_type_pointer(type)) {
4579                 if (is_type_valid(type)) {
4580                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4581                 }
4582                 return;
4583         }
4584
4585         type_t *result_type   = type->pointer.points_to;
4586         result_type           = automatic_type_conversion(result_type);
4587         expression->base.type = result_type;
4588 }
4589
4590 /**
4591  * Check the semantic of the address taken expression.
4592  */
4593 static void semantic_take_addr(unary_expression_t *expression)
4594 {
4595         expression_t *value = expression->value;
4596         value->base.type    = revert_automatic_type_conversion(value);
4597
4598         type_t *orig_type = value->base.type;
4599         if(!is_type_valid(orig_type))
4600                 return;
4601
4602         if(value->kind == EXPR_REFERENCE) {
4603                 declaration_t *const declaration = value->reference.declaration;
4604                 if(declaration != NULL) {
4605                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4606                                 errorf(expression->base.source_position,
4607                                         "address of register variable '%Y' requested",
4608                                         declaration->symbol);
4609                         }
4610                         declaration->address_taken = 1;
4611                 }
4612         }
4613
4614         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4615 }
4616
4617 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4618 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4619 {                                                                              \
4620         eat(token_type);                                                           \
4621                                                                                    \
4622         expression_t *unary_expression                                             \
4623                 = allocate_expression_zero(unexpression_type);                         \
4624         unary_expression->base.source_position = HERE;                             \
4625         unary_expression->unary.value = parse_sub_expression(precedence);          \
4626                                                                                    \
4627         sfunc(&unary_expression->unary);                                           \
4628                                                                                    \
4629         return unary_expression;                                                   \
4630 }
4631
4632 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4633                                semantic_unexpr_arithmetic)
4634 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4635                                semantic_unexpr_arithmetic)
4636 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4637                                semantic_unexpr_scalar)
4638 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4639                                semantic_dereference)
4640 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4641                                semantic_take_addr)
4642 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4643                                semantic_unexpr_integer)
4644 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4645                                semantic_incdec)
4646 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4647                                semantic_incdec)
4648
4649 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4650                                                sfunc)                         \
4651 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4652                                                expression_t *left)            \
4653 {                                                                             \
4654         (void) precedence;                                                        \
4655         eat(token_type);                                                          \
4656                                                                               \
4657         expression_t *unary_expression                                            \
4658                 = allocate_expression_zero(unexpression_type);                        \
4659         unary_expression->unary.value = left;                                     \
4660                                                                                   \
4661         sfunc(&unary_expression->unary);                                          \
4662                                                                               \
4663         return unary_expression;                                                  \
4664 }
4665
4666 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4667                                        EXPR_UNARY_POSTFIX_INCREMENT,
4668                                        semantic_incdec)
4669 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4670                                        EXPR_UNARY_POSTFIX_DECREMENT,
4671                                        semantic_incdec)
4672
4673 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4674 {
4675         /* TODO: handle complex + imaginary types */
4676
4677         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4678         if(type_left == type_long_double || type_right == type_long_double) {
4679                 return type_long_double;
4680         } else if(type_left == type_double || type_right == type_double) {
4681                 return type_double;
4682         } else if(type_left == type_float || type_right == type_float) {
4683                 return type_float;
4684         }
4685
4686         type_right = promote_integer(type_right);
4687         type_left  = promote_integer(type_left);
4688
4689         if(type_left == type_right)
4690                 return type_left;
4691
4692         bool signed_left  = is_type_signed(type_left);
4693         bool signed_right = is_type_signed(type_right);
4694         int  rank_left    = get_rank(type_left);
4695         int  rank_right   = get_rank(type_right);
4696         if(rank_left < rank_right) {
4697                 if(signed_left == signed_right || !signed_right) {
4698                         return type_right;
4699                 } else {
4700                         return type_left;
4701                 }
4702         } else {
4703                 if(signed_left == signed_right || !signed_left) {
4704                         return type_left;
4705                 } else {
4706                         return type_right;
4707                 }
4708         }
4709 }
4710
4711 /**
4712  * Check the semantic restrictions for a binary expression.
4713  */
4714 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4715 {
4716         expression_t *const left            = expression->left;
4717         expression_t *const right           = expression->right;
4718         type_t       *const orig_type_left  = left->base.type;
4719         type_t       *const orig_type_right = right->base.type;
4720         type_t       *const type_left       = skip_typeref(orig_type_left);
4721         type_t       *const type_right      = skip_typeref(orig_type_right);
4722
4723         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4724                 /* TODO: improve error message */
4725                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4726                         errorf(HERE, "operation needs arithmetic types");
4727                 }
4728                 return;
4729         }
4730
4731         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4732         expression->left      = create_implicit_cast(left, arithmetic_type);
4733         expression->right     = create_implicit_cast(right, arithmetic_type);
4734         expression->base.type = arithmetic_type;
4735 }
4736
4737 static void semantic_shift_op(binary_expression_t *expression)
4738 {
4739         expression_t *const left            = expression->left;
4740         expression_t *const right           = expression->right;
4741         type_t       *const orig_type_left  = left->base.type;
4742         type_t       *const orig_type_right = right->base.type;
4743         type_t       *      type_left       = skip_typeref(orig_type_left);
4744         type_t       *      type_right      = skip_typeref(orig_type_right);
4745
4746         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4747                 /* TODO: improve error message */
4748                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4749                         errorf(HERE, "operation needs integer types");
4750                 }
4751                 return;
4752         }
4753
4754         type_left  = promote_integer(type_left);
4755         type_right = promote_integer(type_right);
4756
4757         expression->left      = create_implicit_cast(left, type_left);
4758         expression->right     = create_implicit_cast(right, type_right);
4759         expression->base.type = type_left;
4760 }
4761
4762 static void semantic_add(binary_expression_t *expression)
4763 {
4764         expression_t *const left            = expression->left;
4765         expression_t *const right           = expression->right;
4766         type_t       *const orig_type_left  = left->base.type;
4767         type_t       *const orig_type_right = right->base.type;
4768         type_t       *const type_left       = skip_typeref(orig_type_left);
4769         type_t       *const type_right      = skip_typeref(orig_type_right);
4770
4771         /* Â§ 5.6.5 */
4772         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4773                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4774                 expression->left  = create_implicit_cast(left, arithmetic_type);
4775                 expression->right = create_implicit_cast(right, arithmetic_type);
4776                 expression->base.type = arithmetic_type;
4777                 return;
4778         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4779                 expression->base.type = type_left;
4780         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4781                 expression->base.type = type_right;
4782         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4783                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4784         }
4785 }
4786
4787 static void semantic_sub(binary_expression_t *expression)
4788 {
4789         expression_t *const left            = expression->left;
4790         expression_t *const right           = expression->right;
4791         type_t       *const orig_type_left  = left->base.type;
4792         type_t       *const orig_type_right = right->base.type;
4793         type_t       *const type_left       = skip_typeref(orig_type_left);
4794         type_t       *const type_right      = skip_typeref(orig_type_right);
4795
4796         /* Â§ 5.6.5 */
4797         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4798                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4799                 expression->left        = create_implicit_cast(left, arithmetic_type);
4800                 expression->right       = create_implicit_cast(right, arithmetic_type);
4801                 expression->base.type =  arithmetic_type;
4802                 return;
4803         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4804                 expression->base.type = type_left;
4805         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4806                 if(!pointers_compatible(type_left, type_right)) {
4807                         errorf(HERE,
4808                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
4809                                orig_type_left, orig_type_right);
4810                 } else {
4811                         expression->base.type = type_ptrdiff_t;
4812                 }
4813         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4814                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
4815                        orig_type_left, orig_type_right);
4816         }
4817 }
4818
4819 /**
4820  * Check the semantics of comparison expressions.
4821  *
4822  * @param expression   The expression to check.
4823  */
4824 static void semantic_comparison(binary_expression_t *expression)
4825 {
4826         expression_t *left            = expression->left;
4827         expression_t *right           = expression->right;
4828         type_t       *orig_type_left  = left->base.type;
4829         type_t       *orig_type_right = right->base.type;
4830
4831         type_t *type_left  = skip_typeref(orig_type_left);
4832         type_t *type_right = skip_typeref(orig_type_right);
4833
4834         /* TODO non-arithmetic types */
4835         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4836                 if (warning.sign_compare &&
4837                     (expression->base.kind != EXPR_BINARY_EQUAL &&
4838                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
4839                     (is_type_signed(type_left) != is_type_signed(type_right))) {
4840                         warningf(expression->base.source_position,
4841                                  "comparison between signed and unsigned");
4842                 }
4843                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4844                 expression->left        = create_implicit_cast(left, arithmetic_type);
4845                 expression->right       = create_implicit_cast(right, arithmetic_type);
4846                 expression->base.type   = arithmetic_type;
4847                 if (warning.float_equal &&
4848                     (expression->base.kind == EXPR_BINARY_EQUAL ||
4849                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
4850                     is_type_float(arithmetic_type)) {
4851                         warningf(expression->base.source_position,
4852                                  "comparing floating point with == or != is unsafe");
4853                 }
4854         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4855                 /* TODO check compatibility */
4856         } else if (is_type_pointer(type_left)) {
4857                 expression->right = create_implicit_cast(right, type_left);
4858         } else if (is_type_pointer(type_right)) {
4859                 expression->left = create_implicit_cast(left, type_right);
4860         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4861                 type_error_incompatible("invalid operands in comparison",
4862                                         expression->base.source_position,
4863                                         type_left, type_right);
4864         }
4865         expression->base.type = type_int;
4866 }
4867
4868 static void semantic_arithmetic_assign(binary_expression_t *expression)
4869 {
4870         expression_t *left            = expression->left;
4871         expression_t *right           = expression->right;
4872         type_t       *orig_type_left  = left->base.type;
4873         type_t       *orig_type_right = right->base.type;
4874
4875         type_t *type_left  = skip_typeref(orig_type_left);
4876         type_t *type_right = skip_typeref(orig_type_right);
4877
4878         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4879                 /* TODO: improve error message */
4880                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4881                         errorf(HERE, "operation needs arithmetic types");
4882                 }
4883                 return;
4884         }
4885
4886         /* combined instructions are tricky. We can't create an implicit cast on
4887          * the left side, because we need the uncasted form for the store.
4888          * The ast2firm pass has to know that left_type must be right_type
4889          * for the arithmetic operation and create a cast by itself */
4890         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4891         expression->right       = create_implicit_cast(right, arithmetic_type);
4892         expression->base.type   = type_left;
4893 }
4894
4895 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4896 {
4897         expression_t *const left            = expression->left;
4898         expression_t *const right           = expression->right;
4899         type_t       *const orig_type_left  = left->base.type;
4900         type_t       *const orig_type_right = right->base.type;
4901         type_t       *const type_left       = skip_typeref(orig_type_left);
4902         type_t       *const type_right      = skip_typeref(orig_type_right);
4903
4904         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4905                 /* combined instructions are tricky. We can't create an implicit cast on
4906                  * the left side, because we need the uncasted form for the store.
4907                  * The ast2firm pass has to know that left_type must be right_type
4908                  * for the arithmetic operation and create a cast by itself */
4909                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4910                 expression->right     = create_implicit_cast(right, arithmetic_type);
4911                 expression->base.type = type_left;
4912         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4913                 expression->base.type = type_left;
4914         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4915                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4916         }
4917 }
4918
4919 /**
4920  * Check the semantic restrictions of a logical expression.
4921  */
4922 static void semantic_logical_op(binary_expression_t *expression)
4923 {
4924         expression_t *const left            = expression->left;
4925         expression_t *const right           = expression->right;
4926         type_t       *const orig_type_left  = left->base.type;
4927         type_t       *const orig_type_right = right->base.type;
4928         type_t       *const type_left       = skip_typeref(orig_type_left);
4929         type_t       *const type_right      = skip_typeref(orig_type_right);
4930
4931         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4932                 /* TODO: improve error message */
4933                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4934                         errorf(HERE, "operation needs scalar types");
4935                 }
4936                 return;
4937         }
4938
4939         expression->base.type = type_int;
4940 }
4941
4942 /**
4943  * Checks if a compound type has constant fields.
4944  */
4945 static bool has_const_fields(const compound_type_t *type)
4946 {
4947         const scope_t       *scope       = &type->declaration->scope;
4948         const declaration_t *declaration = scope->declarations;
4949
4950         for (; declaration != NULL; declaration = declaration->next) {
4951                 if (declaration->namespc != NAMESPACE_NORMAL)
4952                         continue;
4953
4954                 const type_t *decl_type = skip_typeref(declaration->type);
4955                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4956                         return true;
4957         }
4958         /* TODO */
4959         return false;
4960 }
4961
4962 /**
4963  * Check the semantic restrictions of a binary assign expression.
4964  */
4965 static void semantic_binexpr_assign(binary_expression_t *expression)
4966 {
4967         expression_t *left           = expression->left;
4968         type_t       *orig_type_left = left->base.type;
4969
4970         type_t *type_left = revert_automatic_type_conversion(left);
4971         type_left         = skip_typeref(orig_type_left);
4972
4973         /* must be a modifiable lvalue */
4974         if (is_type_array(type_left)) {
4975                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4976                 return;
4977         }
4978         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4979                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4980                        orig_type_left);
4981                 return;
4982         }
4983         if(is_type_incomplete(type_left)) {
4984                 errorf(HERE,
4985                        "left-hand side of assignment '%E' has incomplete type '%T'",
4986                        left, orig_type_left);
4987                 return;
4988         }
4989         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4990                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4991                        left, orig_type_left);
4992                 return;
4993         }
4994
4995         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
4996                                                  "assignment");
4997         if (res_type == NULL) {
4998                 errorf(expression->base.source_position,
4999                         "cannot assign to '%T' from '%T'",
5000                         orig_type_left, expression->right->base.type);
5001         } else {
5002                 expression->right = create_implicit_cast(expression->right, res_type);
5003         }
5004
5005         expression->base.type = orig_type_left;
5006 }
5007
5008 static bool expression_has_effect(const expression_t *const expr)
5009 {
5010         switch (expr->kind) {
5011                 case EXPR_UNKNOWN:                   break;
5012                 case EXPR_INVALID:                   break;
5013                 case EXPR_REFERENCE:                 return false;
5014                 case EXPR_CONST:                     return false;
5015                 case EXPR_CHAR_CONST:                return false;
5016                 case EXPR_STRING_LITERAL:            return false;
5017                 case EXPR_WIDE_STRING_LITERAL:       return false;
5018                 case EXPR_CALL: {
5019                         const call_expression_t *const call = &expr->call;
5020                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5021                                 return true;
5022
5023                         switch (call->function->builtin_symbol.symbol->ID) {
5024                                 case T___builtin_va_end: return true;
5025                                 default:                 return false;
5026                         }
5027                 }
5028                 case EXPR_CONDITIONAL: {
5029                         const conditional_expression_t *const cond = &expr->conditional;
5030                         return
5031                                 expression_has_effect(cond->true_expression) &&
5032                                 expression_has_effect(cond->false_expression);
5033                 }
5034                 case EXPR_SELECT:                    return false;
5035                 case EXPR_ARRAY_ACCESS:              return false;
5036                 case EXPR_SIZEOF:                    return false;
5037                 case EXPR_CLASSIFY_TYPE:             return false;
5038                 case EXPR_ALIGNOF:                   return false;
5039
5040                 case EXPR_FUNCTION:                  return false;
5041                 case EXPR_PRETTY_FUNCTION:           return false;
5042                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
5043                 case EXPR_BUILTIN_CONSTANT_P:        return false;
5044                 case EXPR_BUILTIN_PREFETCH:          return true;
5045                 case EXPR_OFFSETOF:                  return false;
5046                 case EXPR_VA_START:                  return true;
5047                 case EXPR_VA_ARG:                    return true;
5048                 case EXPR_STATEMENT:                 return true; // TODO
5049                 case EXPR_COMPOUND_LITERAL:          return false;
5050
5051                 case EXPR_UNARY_NEGATE:              return false;
5052                 case EXPR_UNARY_PLUS:                return false;
5053                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
5054                 case EXPR_UNARY_NOT:                 return false;
5055                 case EXPR_UNARY_DEREFERENCE:         return false;
5056                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
5057                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
5058                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
5059                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
5060                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
5061                 case EXPR_UNARY_CAST: {
5062                         type_t *type = skip_typeref(expr->base.type);
5063                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
5064                 }
5065                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
5066                 case EXPR_UNARY_ASSUME:              return true;
5067                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
5068
5069                 case EXPR_BINARY_ADD:                return false;
5070                 case EXPR_BINARY_SUB:                return false;
5071                 case EXPR_BINARY_MUL:                return false;
5072                 case EXPR_BINARY_DIV:                return false;
5073                 case EXPR_BINARY_MOD:                return false;
5074                 case EXPR_BINARY_EQUAL:              return false;
5075                 case EXPR_BINARY_NOTEQUAL:           return false;
5076                 case EXPR_BINARY_LESS:               return false;
5077                 case EXPR_BINARY_LESSEQUAL:          return false;
5078                 case EXPR_BINARY_GREATER:            return false;
5079                 case EXPR_BINARY_GREATEREQUAL:       return false;
5080                 case EXPR_BINARY_BITWISE_AND:        return false;
5081                 case EXPR_BINARY_BITWISE_OR:         return false;
5082                 case EXPR_BINARY_BITWISE_XOR:        return false;
5083                 case EXPR_BINARY_SHIFTLEFT:          return false;
5084                 case EXPR_BINARY_SHIFTRIGHT:         return false;
5085                 case EXPR_BINARY_ASSIGN:             return true;
5086                 case EXPR_BINARY_MUL_ASSIGN:         return true;
5087                 case EXPR_BINARY_DIV_ASSIGN:         return true;
5088                 case EXPR_BINARY_MOD_ASSIGN:         return true;
5089                 case EXPR_BINARY_ADD_ASSIGN:         return true;
5090                 case EXPR_BINARY_SUB_ASSIGN:         return true;
5091                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
5092                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
5093                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5094                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5095                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
5096                 case EXPR_BINARY_LOGICAL_AND:
5097                 case EXPR_BINARY_LOGICAL_OR:
5098                 case EXPR_BINARY_COMMA:
5099                         return expression_has_effect(expr->binary.right);
5100
5101                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
5102                 case EXPR_BINARY_ISGREATER:          return false;
5103                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
5104                 case EXPR_BINARY_ISLESS:             return false;
5105                 case EXPR_BINARY_ISLESSEQUAL:        return false;
5106                 case EXPR_BINARY_ISLESSGREATER:      return false;
5107                 case EXPR_BINARY_ISUNORDERED:        return false;
5108         }
5109
5110         panic("unexpected statement");
5111 }
5112
5113 static void semantic_comma(binary_expression_t *expression)
5114 {
5115         if (warning.unused_value) {
5116                 const expression_t *const left = expression->left;
5117                 if (!expression_has_effect(left)) {
5118                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5119                 }
5120         }
5121         expression->base.type = expression->right->base.type;
5122 }
5123
5124 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
5125 static expression_t *parse_##binexpression_type(unsigned precedence,      \
5126                                                 expression_t *left)       \
5127 {                                                                         \
5128         eat(token_type);                                                      \
5129         source_position_t pos = HERE;                                         \
5130                                                                           \
5131         expression_t *right = parse_sub_expression(precedence + lr);          \
5132                                                                           \
5133         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5134         binexpr->base.source_position = pos;                                  \
5135         binexpr->binary.left  = left;                                         \
5136         binexpr->binary.right = right;                                        \
5137         sfunc(&binexpr->binary);                                              \
5138                                                                           \
5139         return binexpr;                                                       \
5140 }
5141
5142 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
5143 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
5144 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
5145 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
5146 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
5147 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
5148 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
5149 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
5150 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
5151
5152 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
5153                       semantic_comparison, 1)
5154 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5155                       semantic_comparison, 1)
5156 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
5157                       semantic_comparison, 1)
5158 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
5159                       semantic_comparison, 1)
5160
5161 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5162                       semantic_binexpr_arithmetic, 1)
5163 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5164                       semantic_binexpr_arithmetic, 1)
5165 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5166                       semantic_binexpr_arithmetic, 1)
5167 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5168                       semantic_logical_op, 1)
5169 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5170                       semantic_logical_op, 1)
5171 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5172                       semantic_shift_op, 1)
5173 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5174                       semantic_shift_op, 1)
5175 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5176                       semantic_arithmetic_addsubb_assign, 0)
5177 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5178                       semantic_arithmetic_addsubb_assign, 0)
5179 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5180                       semantic_arithmetic_assign, 0)
5181 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5182                       semantic_arithmetic_assign, 0)
5183 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5184                       semantic_arithmetic_assign, 0)
5185 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5186                       semantic_arithmetic_assign, 0)
5187 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5188                       semantic_arithmetic_assign, 0)
5189 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5190                       semantic_arithmetic_assign, 0)
5191 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5192                       semantic_arithmetic_assign, 0)
5193 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5194                       semantic_arithmetic_assign, 0)
5195
5196 static expression_t *parse_sub_expression(unsigned precedence)
5197 {
5198         if(token.type < 0) {
5199                 return expected_expression_error();
5200         }
5201
5202         expression_parser_function_t *parser
5203                 = &expression_parsers[token.type];
5204         source_position_t             source_position = token.source_position;
5205         expression_t                 *left;
5206
5207         if(parser->parser != NULL) {
5208                 left = parser->parser(parser->precedence);
5209         } else {
5210                 left = parse_primary_expression();
5211         }
5212         assert(left != NULL);
5213         left->base.source_position = source_position;
5214
5215         while(true) {
5216                 if(token.type < 0) {
5217                         return expected_expression_error();
5218                 }
5219
5220                 parser = &expression_parsers[token.type];
5221                 if(parser->infix_parser == NULL)
5222                         break;
5223                 if(parser->infix_precedence < precedence)
5224                         break;
5225
5226                 left = parser->infix_parser(parser->infix_precedence, left);
5227
5228                 assert(left != NULL);
5229                 assert(left->kind != EXPR_UNKNOWN);
5230                 left->base.source_position = source_position;
5231         }
5232
5233         return left;
5234 }
5235
5236 /**
5237  * Parse an expression.
5238  */
5239 static expression_t *parse_expression(void)
5240 {
5241         return parse_sub_expression(1);
5242 }
5243
5244 /**
5245  * Register a parser for a prefix-like operator with given precedence.
5246  *
5247  * @param parser      the parser function
5248  * @param token_type  the token type of the prefix token
5249  * @param precedence  the precedence of the operator
5250  */
5251 static void register_expression_parser(parse_expression_function parser,
5252                                        int token_type, unsigned precedence)
5253 {
5254         expression_parser_function_t *entry = &expression_parsers[token_type];
5255
5256         if(entry->parser != NULL) {
5257                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5258                 panic("trying to register multiple expression parsers for a token");
5259         }
5260         entry->parser     = parser;
5261         entry->precedence = precedence;
5262 }
5263
5264 /**
5265  * Register a parser for an infix operator with given precedence.
5266  *
5267  * @param parser      the parser function
5268  * @param token_type  the token type of the infix operator
5269  * @param precedence  the precedence of the operator
5270  */
5271 static void register_infix_parser(parse_expression_infix_function parser,
5272                 int token_type, unsigned precedence)
5273 {
5274         expression_parser_function_t *entry = &expression_parsers[token_type];
5275
5276         if(entry->infix_parser != NULL) {
5277                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5278                 panic("trying to register multiple infix expression parsers for a "
5279                       "token");
5280         }
5281         entry->infix_parser     = parser;
5282         entry->infix_precedence = precedence;
5283 }
5284
5285 /**
5286  * Initialize the expression parsers.
5287  */
5288 static void init_expression_parsers(void)
5289 {
5290         memset(&expression_parsers, 0, sizeof(expression_parsers));
5291
5292         register_infix_parser(parse_array_expression,         '[',              30);
5293         register_infix_parser(parse_call_expression,          '(',              30);
5294         register_infix_parser(parse_select_expression,        '.',              30);
5295         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
5296         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5297                                                               T_PLUSPLUS,       30);
5298         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5299                                                               T_MINUSMINUS,     30);
5300
5301         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
5302         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
5303         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
5304         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
5305         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
5306         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
5307         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
5308         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
5309         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
5310         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
5311         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
5312         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
5313         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5314                                                     T_EXCLAMATIONMARKEQUAL, 13);
5315         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
5316         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
5317         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
5318         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
5319         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
5320         register_infix_parser(parse_conditional_expression,   '?',               7);
5321         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
5322         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
5323         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
5324         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
5325         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
5326         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
5327         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5328                                                                 T_LESSLESSEQUAL, 2);
5329         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5330                                                           T_GREATERGREATEREQUAL, 2);
5331         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5332                                                                      T_ANDEQUAL, 2);
5333         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5334                                                                     T_PIPEEQUAL, 2);
5335         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5336                                                                    T_CARETEQUAL, 2);
5337
5338         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
5339
5340         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
5341         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
5342         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
5343         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
5344         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
5345         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
5346         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5347                                                                   T_PLUSPLUS,   25);
5348         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5349                                                                   T_MINUSMINUS, 25);
5350         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
5351         register_expression_parser(parse_alignof,                T___alignof__, 25);
5352         register_expression_parser(parse_extension,            T___extension__, 25);
5353         register_expression_parser(parse_builtin_classify_type,
5354                                                      T___builtin_classify_type, 25);
5355 }
5356
5357 /**
5358  * Parse a asm statement constraints specification.
5359  */
5360 static asm_constraint_t *parse_asm_constraints(void)
5361 {
5362         asm_constraint_t *result = NULL;
5363         asm_constraint_t *last   = NULL;
5364
5365         while(token.type == T_STRING_LITERAL || token.type == '[') {
5366                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5367                 memset(constraint, 0, sizeof(constraint[0]));
5368
5369                 if(token.type == '[') {
5370                         eat('[');
5371                         if(token.type != T_IDENTIFIER) {
5372                                 parse_error_expected("while parsing asm constraint",
5373                                                      T_IDENTIFIER, 0);
5374                                 return NULL;
5375                         }
5376                         constraint->symbol = token.v.symbol;
5377
5378                         expect(']');
5379                 }
5380
5381                 constraint->constraints = parse_string_literals();
5382                 expect('(');
5383                 constraint->expression = parse_expression();
5384                 expect(')');
5385
5386                 if(last != NULL) {
5387                         last->next = constraint;
5388                 } else {
5389                         result = constraint;
5390                 }
5391                 last = constraint;
5392
5393                 if(token.type != ',')
5394                         break;
5395                 eat(',');
5396         }
5397
5398         return result;
5399 }
5400
5401 /**
5402  * Parse a asm statement clobber specification.
5403  */
5404 static asm_clobber_t *parse_asm_clobbers(void)
5405 {
5406         asm_clobber_t *result = NULL;
5407         asm_clobber_t *last   = NULL;
5408
5409         while(token.type == T_STRING_LITERAL) {
5410                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5411                 clobber->clobber       = parse_string_literals();
5412
5413                 if(last != NULL) {
5414                         last->next = clobber;
5415                 } else {
5416                         result = clobber;
5417                 }
5418                 last = clobber;
5419
5420                 if(token.type != ',')
5421                         break;
5422                 eat(',');
5423         }
5424
5425         return result;
5426 }
5427
5428 /**
5429  * Parse an asm statement.
5430  */
5431 static statement_t *parse_asm_statement(void)
5432 {
5433         eat(T_asm);
5434
5435         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
5436         statement->base.source_position = token.source_position;
5437
5438         asm_statement_t *asm_statement = &statement->asms;
5439
5440         if(token.type == T_volatile) {
5441                 next_token();
5442                 asm_statement->is_volatile = true;
5443         }
5444
5445         expect('(');
5446         asm_statement->asm_text = parse_string_literals();
5447
5448         if(token.type != ':')
5449                 goto end_of_asm;
5450         eat(':');
5451
5452         asm_statement->inputs = parse_asm_constraints();
5453         if(token.type != ':')
5454                 goto end_of_asm;
5455         eat(':');
5456
5457         asm_statement->outputs = parse_asm_constraints();
5458         if(token.type != ':')
5459                 goto end_of_asm;
5460         eat(':');
5461
5462         asm_statement->clobbers = parse_asm_clobbers();
5463
5464 end_of_asm:
5465         expect(')');
5466         expect(';');
5467         return statement;
5468 }
5469
5470 /**
5471  * Parse a case statement.
5472  */
5473 static statement_t *parse_case_statement(void)
5474 {
5475         eat(T_case);
5476
5477         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5478
5479         statement->base.source_position  = token.source_position;
5480         statement->case_label.expression = parse_expression();
5481
5482         if (c_mode & _GNUC) {
5483                 if (token.type == T_DOTDOTDOT) {
5484                         next_token();
5485                         statement->case_label.end_range = parse_expression();
5486                 }
5487         }
5488
5489         expect(':');
5490
5491         if (! is_constant_expression(statement->case_label.expression)) {
5492                 errorf(statement->base.source_position,
5493                         "case label does not reduce to an integer constant");
5494         } else {
5495                 /* TODO: check if the case label is already known */
5496                 if (current_switch != NULL) {
5497                         /* link all cases into the switch statement */
5498                         if (current_switch->last_case == NULL) {
5499                                 current_switch->first_case =
5500                                 current_switch->last_case  = &statement->case_label;
5501                         } else {
5502                                 current_switch->last_case->next = &statement->case_label;
5503                         }
5504                 } else {
5505                         errorf(statement->base.source_position,
5506                                 "case label not within a switch statement");
5507                 }
5508         }
5509         statement->case_label.statement = parse_statement();
5510
5511         return statement;
5512 }
5513
5514 /**
5515  * Finds an existing default label of a switch statement.
5516  */
5517 static case_label_statement_t *
5518 find_default_label(const switch_statement_t *statement)
5519 {
5520         case_label_statement_t *label = statement->first_case;
5521         for ( ; label != NULL; label = label->next) {
5522                 if (label->expression == NULL)
5523                         return label;
5524         }
5525         return NULL;
5526 }
5527
5528 /**
5529  * Parse a default statement.
5530  */
5531 static statement_t *parse_default_statement(void)
5532 {
5533         eat(T_default);
5534
5535         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5536
5537         statement->base.source_position = token.source_position;
5538
5539         expect(':');
5540         if (current_switch != NULL) {
5541                 const case_label_statement_t *def_label = find_default_label(current_switch);
5542                 if (def_label != NULL) {
5543                         errorf(HERE, "multiple default labels in one switch");
5544                         errorf(def_label->base.source_position,
5545                                 "this is the first default label");
5546                 } else {
5547                         /* link all cases into the switch statement */
5548                         if (current_switch->last_case == NULL) {
5549                                 current_switch->first_case =
5550                                         current_switch->last_case  = &statement->case_label;
5551                         } else {
5552                                 current_switch->last_case->next = &statement->case_label;
5553                         }
5554                 }
5555         } else {
5556                 errorf(statement->base.source_position,
5557                         "'default' label not within a switch statement");
5558         }
5559         statement->case_label.statement = parse_statement();
5560
5561         return statement;
5562 }
5563
5564 /**
5565  * Return the declaration for a given label symbol or create a new one.
5566  */
5567 static declaration_t *get_label(symbol_t *symbol)
5568 {
5569         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
5570         assert(current_function != NULL);
5571         /* if we found a label in the same function, then we already created the
5572          * declaration */
5573         if(candidate != NULL
5574                         && candidate->parent_scope == &current_function->scope) {
5575                 return candidate;
5576         }
5577
5578         /* otherwise we need to create a new one */
5579         declaration_t *const declaration = allocate_declaration_zero();
5580         declaration->namespc       = NAMESPACE_LABEL;
5581         declaration->symbol        = symbol;
5582
5583         label_push(declaration);
5584
5585         return declaration;
5586 }
5587
5588 /**
5589  * Parse a label statement.
5590  */
5591 static statement_t *parse_label_statement(void)
5592 {
5593         assert(token.type == T_IDENTIFIER);
5594         symbol_t *symbol = token.v.symbol;
5595         next_token();
5596
5597         declaration_t *label = get_label(symbol);
5598
5599         /* if source position is already set then the label is defined twice,
5600          * otherwise it was just mentioned in a goto so far */
5601         if(label->source_position.input_name != NULL) {
5602                 errorf(HERE, "duplicate label '%Y'", symbol);
5603                 errorf(label->source_position, "previous definition of '%Y' was here",
5604                        symbol);
5605         } else {
5606                 label->source_position = token.source_position;
5607         }
5608
5609         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
5610
5611         statement->base.source_position = token.source_position;
5612         statement->label.label          = label;
5613
5614         eat(':');
5615
5616         if(token.type == '}') {
5617                 /* TODO only warn? */
5618                 errorf(HERE, "label at end of compound statement");
5619                 return statement;
5620         } else {
5621                 if (token.type == ';') {
5622                         /* eat an empty statement here, to avoid the warning about an empty
5623                          * after a label.  label:; is commonly used to have a label before
5624                          * a }. */
5625                         next_token();
5626                 } else {
5627                         statement->label.statement = parse_statement();
5628                 }
5629         }
5630
5631         /* remember the labels's in a list for later checking */
5632         if (label_last == NULL) {
5633                 label_first = &statement->label;
5634         } else {
5635                 label_last->next = &statement->label;
5636         }
5637         label_last = &statement->label;
5638
5639         return statement;
5640 }
5641
5642 /**
5643  * Parse an if statement.
5644  */
5645 static statement_t *parse_if(void)
5646 {
5647         eat(T_if);
5648
5649         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
5650         statement->base.source_position = token.source_position;
5651
5652         expect('(');
5653         statement->ifs.condition = parse_expression();
5654         expect(')');
5655
5656         statement->ifs.true_statement = parse_statement();
5657         if(token.type == T_else) {
5658                 next_token();
5659                 statement->ifs.false_statement = parse_statement();
5660         }
5661
5662         return statement;
5663 }
5664
5665 /**
5666  * Parse a switch statement.
5667  */
5668 static statement_t *parse_switch(void)
5669 {
5670         eat(T_switch);
5671
5672         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
5673         statement->base.source_position = token.source_position;
5674
5675         expect('(');
5676         expression_t *const expr = parse_expression();
5677         type_t       *      type = skip_typeref(expr->base.type);
5678         if (is_type_integer(type)) {
5679                 type = promote_integer(type);
5680         } else if (is_type_valid(type)) {
5681                 errorf(expr->base.source_position,
5682                        "switch quantity is not an integer, but '%T'", type);
5683                 type = type_error_type;
5684         }
5685         statement->switchs.expression = create_implicit_cast(expr, type);
5686         expect(')');
5687
5688         switch_statement_t *rem = current_switch;
5689         current_switch          = &statement->switchs;
5690         statement->switchs.body = parse_statement();
5691         current_switch          = rem;
5692
5693         if (warning.switch_default
5694                         && find_default_label(&statement->switchs) == NULL) {
5695                 warningf(statement->base.source_position, "switch has no default case");
5696         }
5697
5698         return statement;
5699 }
5700
5701 static statement_t *parse_loop_body(statement_t *const loop)
5702 {
5703         statement_t *const rem = current_loop;
5704         current_loop = loop;
5705
5706         statement_t *const body = parse_statement();
5707
5708         current_loop = rem;
5709         return body;
5710 }
5711
5712 /**
5713  * Parse a while statement.
5714  */
5715 static statement_t *parse_while(void)
5716 {
5717         eat(T_while);
5718
5719         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
5720         statement->base.source_position = token.source_position;
5721
5722         expect('(');
5723         statement->whiles.condition = parse_expression();
5724         expect(')');
5725
5726         statement->whiles.body = parse_loop_body(statement);
5727
5728         return statement;
5729 }
5730
5731 /**
5732  * Parse a do statement.
5733  */
5734 static statement_t *parse_do(void)
5735 {
5736         eat(T_do);
5737
5738         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
5739
5740         statement->base.source_position = token.source_position;
5741
5742         statement->do_while.body = parse_loop_body(statement);
5743
5744         expect(T_while);
5745         expect('(');
5746         statement->do_while.condition = parse_expression();
5747         expect(')');
5748         expect(';');
5749
5750         return statement;
5751 }
5752
5753 /**
5754  * Parse a for statement.
5755  */
5756 static statement_t *parse_for(void)
5757 {
5758         eat(T_for);
5759
5760         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
5761         statement->base.source_position = token.source_position;
5762
5763         expect('(');
5764
5765         int      top        = environment_top();
5766         scope_t *last_scope = scope;
5767         set_scope(&statement->fors.scope);
5768
5769         if(token.type != ';') {
5770                 if(is_declaration_specifier(&token, false)) {
5771                         parse_declaration(record_declaration);
5772                 } else {
5773                         expression_t *const init = parse_expression();
5774                         statement->fors.initialisation = init;
5775                         if (warning.unused_value  && !expression_has_effect(init)) {
5776                                 warningf(init->base.source_position, "initialisation of 'for'-statement has no effect");
5777                         }
5778                         expect(';');
5779                 }
5780         } else {
5781                 expect(';');
5782         }
5783
5784         if(token.type != ';') {
5785                 statement->fors.condition = parse_expression();
5786         }
5787         expect(';');
5788         if(token.type != ')') {
5789                 expression_t *const step = parse_expression();
5790                 statement->fors.step = step;
5791                 if (warning.unused_value  && !expression_has_effect(step)) {
5792                         warningf(step->base.source_position, "step of 'for'-statement has no effect");
5793                 }
5794         }
5795         expect(')');
5796         statement->fors.body = parse_loop_body(statement);
5797
5798         assert(scope == &statement->fors.scope);
5799         set_scope(last_scope);
5800         environment_pop_to(top);
5801
5802         return statement;
5803 }
5804
5805 /**
5806  * Parse a goto statement.
5807  */
5808 static statement_t *parse_goto(void)
5809 {
5810         eat(T_goto);
5811
5812         if(token.type != T_IDENTIFIER) {
5813                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5814                 eat_statement();
5815                 return NULL;
5816         }
5817         symbol_t *symbol = token.v.symbol;
5818         next_token();
5819
5820         declaration_t *label = get_label(symbol);
5821
5822         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
5823         statement->base.source_position = token.source_position;
5824
5825         statement->gotos.label = label;
5826
5827         /* remember the goto's in a list for later checking */
5828         if (goto_last == NULL) {
5829                 goto_first = &statement->gotos;
5830         } else {
5831                 goto_last->next = &statement->gotos;
5832         }
5833         goto_last = &statement->gotos;
5834
5835         expect(';');
5836
5837         return statement;
5838 }
5839
5840 /**
5841  * Parse a continue statement.
5842  */
5843 static statement_t *parse_continue(void)
5844 {
5845         statement_t *statement;
5846         if (current_loop == NULL) {
5847                 errorf(HERE, "continue statement not within loop");
5848                 statement = NULL;
5849         } else {
5850                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5851
5852                 statement->base.source_position = token.source_position;
5853         }
5854
5855         eat(T_continue);
5856         expect(';');
5857
5858         return statement;
5859 }
5860
5861 /**
5862  * Parse a break statement.
5863  */
5864 static statement_t *parse_break(void)
5865 {
5866         statement_t *statement;
5867         if (current_switch == NULL && current_loop == NULL) {
5868                 errorf(HERE, "break statement not within loop or switch");
5869                 statement = NULL;
5870         } else {
5871                 statement = allocate_statement_zero(STATEMENT_BREAK);
5872
5873                 statement->base.source_position = token.source_position;
5874         }
5875
5876         eat(T_break);
5877         expect(';');
5878
5879         return statement;
5880 }
5881
5882 /**
5883  * Check if a given declaration represents a local variable.
5884  */
5885 static bool is_local_var_declaration(const declaration_t *declaration) {
5886         switch ((storage_class_tag_t) declaration->storage_class) {
5887         case STORAGE_CLASS_NONE:
5888         case STORAGE_CLASS_AUTO:
5889         case STORAGE_CLASS_REGISTER: {
5890                 const type_t *type = skip_typeref(declaration->type);
5891                 if(is_type_function(type)) {
5892                         return false;
5893                 } else {
5894                         return true;
5895                 }
5896         }
5897         default:
5898                 return false;
5899         }
5900 }
5901
5902 /**
5903  * Check if a given declaration represents a variable.
5904  */
5905 static bool is_var_declaration(const declaration_t *declaration) {
5906         switch ((storage_class_tag_t) declaration->storage_class) {
5907         case STORAGE_CLASS_NONE:
5908         case STORAGE_CLASS_EXTERN:
5909         case STORAGE_CLASS_STATIC:
5910         case STORAGE_CLASS_AUTO:
5911         case STORAGE_CLASS_REGISTER:
5912         case STORAGE_CLASS_THREAD:
5913         case STORAGE_CLASS_THREAD_EXTERN:
5914         case STORAGE_CLASS_THREAD_STATIC: {
5915                 const type_t *type = skip_typeref(declaration->type);
5916                 if(is_type_function(type)) {
5917                         return false;
5918                 } else {
5919                         return true;
5920                 }
5921         }
5922         default:
5923                 return false;
5924         }
5925 }
5926
5927 /**
5928  * Check if a given expression represents a local variable.
5929  */
5930 static bool is_local_variable(const expression_t *expression)
5931 {
5932         if (expression->base.kind != EXPR_REFERENCE) {
5933                 return false;
5934         }
5935         const declaration_t *declaration = expression->reference.declaration;
5936         return is_local_var_declaration(declaration);
5937 }
5938
5939 /**
5940  * Check if a given expression represents a local variable and
5941  * return its declaration then, else return NULL.
5942  */
5943 declaration_t *expr_is_variable(const expression_t *expression)
5944 {
5945         if (expression->base.kind != EXPR_REFERENCE) {
5946                 return NULL;
5947         }
5948         declaration_t *declaration = expression->reference.declaration;
5949         if (is_var_declaration(declaration))
5950                 return declaration;
5951         return NULL;
5952 }
5953
5954 /**
5955  * Parse a return statement.
5956  */
5957 static statement_t *parse_return(void)
5958 {
5959         eat(T_return);
5960
5961         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
5962         statement->base.source_position = token.source_position;
5963
5964         expression_t *return_value = NULL;
5965         if(token.type != ';') {
5966                 return_value = parse_expression();
5967         }
5968         expect(';');
5969
5970         const type_t *const func_type = current_function->type;
5971         assert(is_type_function(func_type));
5972         type_t *const return_type = skip_typeref(func_type->function.return_type);
5973
5974         if(return_value != NULL) {
5975                 type_t *return_value_type = skip_typeref(return_value->base.type);
5976
5977                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5978                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5979                         warningf(statement->base.source_position,
5980                                  "'return' with a value, in function returning void");
5981                         return_value = NULL;
5982                 } else {
5983                         type_t *const res_type = semantic_assign(return_type,
5984                                 return_value, "'return'");
5985                         if (res_type == NULL) {
5986                                 errorf(statement->base.source_position,
5987                                        "cannot return something of type '%T' in function returning '%T'",
5988                                        return_value->base.type, return_type);
5989                         } else {
5990                                 return_value = create_implicit_cast(return_value, res_type);
5991                         }
5992                 }
5993                 /* check for returning address of a local var */
5994                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5995                         const expression_t *expression = return_value->unary.value;
5996                         if (is_local_variable(expression)) {
5997                                 warningf(statement->base.source_position,
5998                                          "function returns address of local variable");
5999                         }
6000                 }
6001         } else {
6002                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6003                         warningf(statement->base.source_position,
6004                                  "'return' without value, in function returning non-void");
6005                 }
6006         }
6007         statement->returns.value = return_value;
6008
6009         return statement;
6010 }
6011
6012 /**
6013  * Parse a declaration statement.
6014  */
6015 static statement_t *parse_declaration_statement(void)
6016 {
6017         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6018
6019         statement->base.source_position = token.source_position;
6020
6021         declaration_t *before = last_declaration;
6022         parse_declaration(record_declaration);
6023
6024         if(before == NULL) {
6025                 statement->declaration.declarations_begin = scope->declarations;
6026         } else {
6027                 statement->declaration.declarations_begin = before->next;
6028         }
6029         statement->declaration.declarations_end = last_declaration;
6030
6031         return statement;
6032 }
6033
6034 /**
6035  * Parse an expression statement, ie. expr ';'.
6036  */
6037 static statement_t *parse_expression_statement(void)
6038 {
6039         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6040
6041         statement->base.source_position  = token.source_position;
6042         expression_t *const expr         = parse_expression();
6043         statement->expression.expression = expr;
6044
6045         if (warning.unused_value  && !expression_has_effect(expr)) {
6046                 warningf(expr->base.source_position, "statement has no effect");
6047         }
6048
6049         expect(';');
6050
6051         return statement;
6052 }
6053
6054 /**
6055  * Parse a statement.
6056  */
6057 static statement_t *parse_statement(void)
6058 {
6059         statement_t   *statement = NULL;
6060
6061         /* declaration or statement */
6062         switch(token.type) {
6063         case T_asm:
6064                 statement = parse_asm_statement();
6065                 break;
6066
6067         case T_case:
6068                 statement = parse_case_statement();
6069                 break;
6070
6071         case T_default:
6072                 statement = parse_default_statement();
6073                 break;
6074
6075         case '{':
6076                 statement = parse_compound_statement();
6077                 break;
6078
6079         case T_if:
6080                 statement = parse_if();
6081                 break;
6082
6083         case T_switch:
6084                 statement = parse_switch();
6085                 break;
6086
6087         case T_while:
6088                 statement = parse_while();
6089                 break;
6090
6091         case T_do:
6092                 statement = parse_do();
6093                 break;
6094
6095         case T_for:
6096                 statement = parse_for();
6097                 break;
6098
6099         case T_goto:
6100                 statement = parse_goto();
6101                 break;
6102
6103         case T_continue:
6104                 statement = parse_continue();
6105                 break;
6106
6107         case T_break:
6108                 statement = parse_break();
6109                 break;
6110
6111         case T_return:
6112                 statement = parse_return();
6113                 break;
6114
6115         case ';':
6116                 if (warning.empty_statement) {
6117                         warningf(HERE, "statement is empty");
6118                 }
6119                 next_token();
6120                 statement = NULL;
6121                 break;
6122
6123         case T_IDENTIFIER:
6124                 if(look_ahead(1)->type == ':') {
6125                         statement = parse_label_statement();
6126                         break;
6127                 }
6128
6129                 if(is_typedef_symbol(token.v.symbol)) {
6130                         statement = parse_declaration_statement();
6131                         break;
6132                 }
6133
6134                 statement = parse_expression_statement();
6135                 break;
6136
6137         case T___extension__:
6138                 /* this can be a prefix to a declaration or an expression statement */
6139                 /* we simply eat it now and parse the rest with tail recursion */
6140                 do {
6141                         next_token();
6142                 } while(token.type == T___extension__);
6143                 statement = parse_statement();
6144                 break;
6145
6146         DECLARATION_START
6147                 statement = parse_declaration_statement();
6148                 break;
6149
6150         default:
6151                 statement = parse_expression_statement();
6152                 break;
6153         }
6154
6155         assert(statement == NULL
6156                         || statement->base.source_position.input_name != NULL);
6157
6158         return statement;
6159 }
6160
6161 /**
6162  * Parse a compound statement.
6163  */
6164 static statement_t *parse_compound_statement(void)
6165 {
6166         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6167
6168         statement->base.source_position = token.source_position;
6169
6170         eat('{');
6171
6172         int      top        = environment_top();
6173         scope_t *last_scope = scope;
6174         set_scope(&statement->compound.scope);
6175
6176         statement_t *last_statement = NULL;
6177
6178         while(token.type != '}' && token.type != T_EOF) {
6179                 statement_t *sub_statement = parse_statement();
6180                 if(sub_statement == NULL)
6181                         continue;
6182
6183                 if(last_statement != NULL) {
6184                         last_statement->base.next = sub_statement;
6185                 } else {
6186                         statement->compound.statements = sub_statement;
6187                 }
6188
6189                 while(sub_statement->base.next != NULL)
6190                         sub_statement = sub_statement->base.next;
6191
6192                 last_statement = sub_statement;
6193         }
6194
6195         if(token.type == '}') {
6196                 next_token();
6197         } else {
6198                 errorf(statement->base.source_position,
6199                        "end of file while looking for closing '}'");
6200         }
6201
6202         assert(scope == &statement->compound.scope);
6203         set_scope(last_scope);
6204         environment_pop_to(top);
6205
6206         return statement;
6207 }
6208
6209 /**
6210  * Initialize builtin types.
6211  */
6212 static void initialize_builtin_types(void)
6213 {
6214         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
6215         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
6216         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
6217         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
6218         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
6219         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6220         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
6221         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
6222
6223         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
6224         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6225         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
6226         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
6227 }
6228
6229 /**
6230  * Check for unused global static functions and variables
6231  */
6232 static void check_unused_globals(void)
6233 {
6234         if (!warning.unused_function && !warning.unused_variable)
6235                 return;
6236
6237         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6238                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6239                         continue;
6240
6241                 type_t *const type = decl->type;
6242                 const char *s;
6243                 if (is_type_function(skip_typeref(type))) {
6244                         if (!warning.unused_function || decl->is_inline)
6245                                 continue;
6246
6247                         s = (decl->init.statement != NULL ? "defined" : "declared");
6248                 } else {
6249                         if (!warning.unused_variable)
6250                                 continue;
6251
6252                         s = "defined";
6253                 }
6254
6255                 warningf(decl->source_position, "'%#T' %s but not used",
6256                         type, decl->symbol, s);
6257         }
6258 }
6259
6260 /**
6261  * Parse a translation unit.
6262  */
6263 static translation_unit_t *parse_translation_unit(void)
6264 {
6265         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6266
6267         assert(global_scope == NULL);
6268         global_scope = &unit->scope;
6269
6270         assert(scope == NULL);
6271         set_scope(&unit->scope);
6272
6273         initialize_builtin_types();
6274
6275         while(token.type != T_EOF) {
6276                 if (token.type == ';') {
6277                         /* TODO error in strict mode */
6278                         warningf(HERE, "stray ';' outside of function");
6279                         next_token();
6280                 } else {
6281                         parse_external_declaration();
6282                 }
6283         }
6284
6285         assert(scope == &unit->scope);
6286         scope          = NULL;
6287         last_declaration = NULL;
6288
6289         assert(global_scope == &unit->scope);
6290         check_unused_globals();
6291         global_scope = NULL;
6292
6293         return unit;
6294 }
6295
6296 /**
6297  * Parse the input.
6298  *
6299  * @return  the translation unit or NULL if errors occurred.
6300  */
6301 translation_unit_t *parse(void)
6302 {
6303         environment_stack = NEW_ARR_F(stack_entry_t, 0);
6304         label_stack       = NEW_ARR_F(stack_entry_t, 0);
6305         diagnostic_count  = 0;
6306         error_count       = 0;
6307         warning_count     = 0;
6308
6309         type_set_output(stderr);
6310         ast_set_output(stderr);
6311
6312         lookahead_bufpos = 0;
6313         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6314                 next_token();
6315         }
6316         translation_unit_t *unit = parse_translation_unit();
6317
6318         DEL_ARR_F(environment_stack);
6319         DEL_ARR_F(label_stack);
6320
6321         if(error_count > 0)
6322                 return NULL;
6323
6324         return unit;
6325 }
6326
6327 /**
6328  * Initialize the parser.
6329  */
6330 void init_parser(void)
6331 {
6332         init_expression_parsers();
6333         obstack_init(&temp_obst);
6334
6335         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6336         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6337 }
6338
6339 /**
6340  * Terminate the parser.
6341  */
6342 void exit_parser(void)
6343 {
6344         obstack_free(&temp_obst, NULL);
6345 }