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