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