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