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