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