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