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