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