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