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