Generate an error, if argument and parameter type are incompatible.
[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 (type->kind != TYPE_FUNCTION &&
2502                     declaration->is_inline &&
2503                     is_type_valid(type)) {
2504                         warningf(declaration->source_position,
2505                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2506                 }
2507
2508                 if(token.type == '=') {
2509                         parse_init_declarator_rest(declaration);
2510                 }
2511
2512                 if(token.type != ',')
2513                         break;
2514                 eat(',');
2515
2516                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2517         }
2518         expect_void(';');
2519 }
2520
2521 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2522 {
2523         symbol_t *symbol  = declaration->symbol;
2524         if(symbol == NULL) {
2525                 errorf(HERE, "anonymous declaration not valid as function parameter");
2526                 return declaration;
2527         }
2528         namespace_t namespc = (namespace_t) declaration->namespc;
2529         if(namespc != NAMESPACE_NORMAL) {
2530                 return record_declaration(declaration);
2531         }
2532
2533         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2534         if(previous_declaration == NULL ||
2535                         previous_declaration->parent_context != context) {
2536                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2537                        symbol);
2538                 return declaration;
2539         }
2540
2541         if(previous_declaration->type == NULL) {
2542                 previous_declaration->type           = declaration->type;
2543                 previous_declaration->storage_class  = declaration->storage_class;
2544                 previous_declaration->parent_context = context;
2545                 return previous_declaration;
2546         } else {
2547                 return record_declaration(declaration);
2548         }
2549 }
2550
2551 static void parse_declaration(parsed_declaration_func finished_declaration)
2552 {
2553         declaration_specifiers_t specifiers;
2554         memset(&specifiers, 0, sizeof(specifiers));
2555         parse_declaration_specifiers(&specifiers);
2556
2557         if(token.type == ';') {
2558                 parse_anonymous_declaration_rest(&specifiers, finished_declaration);
2559         } else {
2560                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2561                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2562         }
2563 }
2564
2565 static void parse_kr_declaration_list(declaration_t *declaration)
2566 {
2567         type_t *type = skip_typeref(declaration->type);
2568         if(!is_type_function(type))
2569                 return;
2570
2571         if(!type->function.kr_style_parameters)
2572                 return;
2573
2574         /* push function parameters */
2575         int         top          = environment_top();
2576         context_t  *last_context = context;
2577         set_context(&declaration->context);
2578
2579         declaration_t *parameter = declaration->context.declarations;
2580         for( ; parameter != NULL; parameter = parameter->next) {
2581                 assert(parameter->parent_context == NULL);
2582                 parameter->parent_context = context;
2583                 environment_push(parameter);
2584         }
2585
2586         /* parse declaration list */
2587         while(is_declaration_specifier(&token, false)) {
2588                 parse_declaration(finished_kr_declaration);
2589         }
2590
2591         /* pop function parameters */
2592         assert(context == &declaration->context);
2593         set_context(last_context);
2594         environment_pop_to(top);
2595
2596         /* update function type */
2597         type_t *new_type = duplicate_type(type);
2598         new_type->function.kr_style_parameters = false;
2599
2600         function_parameter_t *parameters     = NULL;
2601         function_parameter_t *last_parameter = NULL;
2602
2603         declaration_t *parameter_declaration = declaration->context.declarations;
2604         for( ; parameter_declaration != NULL;
2605                         parameter_declaration = parameter_declaration->next) {
2606                 type_t *parameter_type = parameter_declaration->type;
2607                 if(parameter_type == NULL) {
2608                         if (strict_mode) {
2609                                 errorf(HERE, "no type specified for function parameter '%Y'",
2610                                        parameter_declaration->symbol);
2611                         } else {
2612                                 warningf(HERE, "no type specified for function parameter '%Y', using int",
2613                                          parameter_declaration->symbol);
2614                                 parameter_type              = type_int;
2615                                 parameter_declaration->type = parameter_type;
2616                         }
2617                 }
2618
2619                 semantic_parameter(parameter_declaration);
2620                 parameter_type = parameter_declaration->type;
2621
2622                 function_parameter_t *function_parameter
2623                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2624                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2625
2626                 function_parameter->type = parameter_type;
2627                 if(last_parameter != NULL) {
2628                         last_parameter->next = function_parameter;
2629                 } else {
2630                         parameters = function_parameter;
2631                 }
2632                 last_parameter = function_parameter;
2633         }
2634         new_type->function.parameters = parameters;
2635
2636         type = typehash_insert(new_type);
2637         if(type != new_type) {
2638                 obstack_free(type_obst, new_type);
2639         }
2640
2641         declaration->type = type;
2642 }
2643
2644 /**
2645  * Check if all labels are defined in the current function.
2646  */
2647 static void check_for_missing_labels(void)
2648 {
2649         bool first_err = true;
2650         for (const goto_statement_t *goto_statement = goto_first;
2651              goto_statement != NULL;
2652              goto_statement = goto_statement->next) {
2653                  const declaration_t *label = goto_statement->label;
2654
2655                  if (label->source_position.input_name == NULL) {
2656                          if (first_err) {
2657                                  first_err = false;
2658                                  diagnosticf("%s: In function '%Y':\n",
2659                                          current_function->source_position.input_name,
2660                                          current_function->symbol);
2661                          }
2662                          errorf(goto_statement->statement.source_position,
2663                                  "label '%Y' used but not defined", label->symbol);
2664                  }
2665         }
2666         goto_first = goto_last = NULL;
2667 }
2668
2669 static void parse_external_declaration(void)
2670 {
2671         /* function-definitions and declarations both start with declaration
2672          * specifiers */
2673         declaration_specifiers_t specifiers;
2674         memset(&specifiers, 0, sizeof(specifiers));
2675         parse_declaration_specifiers(&specifiers);
2676
2677         /* must be a declaration */
2678         if(token.type == ';') {
2679                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2680                 return;
2681         }
2682
2683         /* declarator is common to both function-definitions and declarations */
2684         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2685
2686         /* must be a declaration */
2687         if(token.type == ',' || token.type == '=' || token.type == ';') {
2688                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
2689                 return;
2690         }
2691
2692         /* must be a function definition */
2693         parse_kr_declaration_list(ndeclaration);
2694
2695         if(token.type != '{') {
2696                 parse_error_expected("while parsing function definition", '{', 0);
2697                 eat_statement();
2698                 return;
2699         }
2700
2701         type_t *type = ndeclaration->type;
2702
2703         /* note that we don't skip typerefs: the standard doesn't allow them here
2704          * (so we can't use is_type_function here) */
2705         if(type->kind != TYPE_FUNCTION) {
2706                 if (is_type_valid(type)) {
2707                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
2708                                type, ndeclaration->symbol);
2709                 }
2710                 eat_block();
2711                 return;
2712         }
2713
2714         /* Â§ 6.7.5.3 (14) a function definition with () means no
2715          * parameters (and not unspecified parameters) */
2716         if(type->function.unspecified_parameters) {
2717                 type_t *duplicate = duplicate_type(type);
2718                 duplicate->function.unspecified_parameters = false;
2719
2720                 type = typehash_insert(duplicate);
2721                 if(type != duplicate) {
2722                         obstack_free(type_obst, duplicate);
2723                 }
2724                 ndeclaration->type = type;
2725         }
2726
2727         declaration_t *const declaration = record_function_definition(ndeclaration);
2728         if(ndeclaration != declaration) {
2729                 declaration->context = ndeclaration->context;
2730         }
2731         type = skip_typeref(declaration->type);
2732
2733         /* push function parameters and switch context */
2734         int         top          = environment_top();
2735         context_t  *last_context = context;
2736         set_context(&declaration->context);
2737
2738         declaration_t *parameter = declaration->context.declarations;
2739         for( ; parameter != NULL; parameter = parameter->next) {
2740                 if(parameter->parent_context == &ndeclaration->context) {
2741                         parameter->parent_context = context;
2742                 }
2743                 assert(parameter->parent_context == NULL
2744                                 || parameter->parent_context == context);
2745                 parameter->parent_context = context;
2746                 environment_push(parameter);
2747         }
2748
2749         if(declaration->init.statement != NULL) {
2750                 parser_error_multiple_definition(declaration, token.source_position);
2751                 eat_block();
2752                 goto end_of_parse_external_declaration;
2753         } else {
2754                 /* parse function body */
2755                 int            label_stack_top      = label_top();
2756                 declaration_t *old_current_function = current_function;
2757                 current_function                    = declaration;
2758
2759                 declaration->init.statement = parse_compound_statement();
2760                 check_for_missing_labels();
2761
2762                 assert(current_function == declaration);
2763                 current_function = old_current_function;
2764                 label_pop_to(label_stack_top);
2765         }
2766
2767 end_of_parse_external_declaration:
2768         assert(context == &declaration->context);
2769         set_context(last_context);
2770         environment_pop_to(top);
2771 }
2772
2773 static type_t *make_bitfield_type(type_t *base, expression_t *size)
2774 {
2775         type_t *type        = allocate_type_zero(TYPE_BITFIELD);
2776         type->bitfield.base = base;
2777         type->bitfield.size = size;
2778
2779         return type;
2780 }
2781
2782 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2783 {
2784         /* TODO: check constraints for struct declarations (in specifiers) */
2785         while(1) {
2786                 declaration_t *declaration;
2787
2788                 if(token.type == ':') {
2789                         next_token();
2790
2791                         type_t *base_type = specifiers->type;
2792                         expression_t *size = parse_constant_expression();
2793
2794                         type_t *type = make_bitfield_type(base_type, size);
2795
2796                         declaration = allocate_declaration_zero();
2797                         declaration->namespc         = NAMESPACE_NORMAL;
2798                         declaration->storage_class   = STORAGE_CLASS_NONE;
2799                         declaration->source_position = token.source_position;
2800                         declaration->modifiers       = specifiers->decl_modifiers;
2801                         declaration->type            = type;
2802                 } else {
2803                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
2804
2805                         if(token.type == ':') {
2806                                 next_token();
2807                                 expression_t *size = parse_constant_expression();
2808
2809                                 type_t *type = make_bitfield_type(declaration->type, size);
2810                                 declaration->type = type;
2811                         }
2812                 }
2813                 record_declaration(declaration);
2814
2815                 if(token.type != ',')
2816                         break;
2817                 next_token();
2818         }
2819         expect_void(';');
2820 }
2821
2822 static void parse_compound_type_entries(void)
2823 {
2824         eat('{');
2825
2826         while(token.type != '}' && token.type != T_EOF) {
2827                 declaration_specifiers_t specifiers;
2828                 memset(&specifiers, 0, sizeof(specifiers));
2829                 parse_declaration_specifiers(&specifiers);
2830
2831                 parse_struct_declarators(&specifiers);
2832         }
2833         if(token.type == T_EOF) {
2834                 errorf(HERE, "EOF while parsing struct");
2835         }
2836         next_token();
2837 }
2838
2839 static type_t *parse_typename(void)
2840 {
2841         declaration_specifiers_t specifiers;
2842         memset(&specifiers, 0, sizeof(specifiers));
2843         parse_declaration_specifiers(&specifiers);
2844         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2845                 /* TODO: improve error message, user does probably not know what a
2846                  * storage class is...
2847                  */
2848                 errorf(HERE, "typename may not have a storage class");
2849         }
2850
2851         type_t *result = parse_abstract_declarator(specifiers.type);
2852
2853         return result;
2854 }
2855
2856
2857
2858
2859 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2860 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2861                                                           expression_t *left);
2862
2863 typedef struct expression_parser_function_t expression_parser_function_t;
2864 struct expression_parser_function_t {
2865         unsigned                         precedence;
2866         parse_expression_function        parser;
2867         unsigned                         infix_precedence;
2868         parse_expression_infix_function  infix_parser;
2869 };
2870
2871 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2872
2873 /**
2874  * Creates a new invalid expression.
2875  */
2876 static expression_t *create_invalid_expression(void)
2877 {
2878         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2879         expression->base.source_position = token.source_position;
2880         return expression;
2881 }
2882
2883 /**
2884  * Prints an error message if an expression was expected but not read
2885  */
2886 static expression_t *expected_expression_error(void)
2887 {
2888         /* skip the error message if the error token was read */
2889         if (token.type != T_ERROR) {
2890                 errorf(HERE, "expected expression, got token '%K'", &token);
2891         }
2892         next_token();
2893
2894         return create_invalid_expression();
2895 }
2896
2897 /**
2898  * Parse a string constant.
2899  */
2900 static expression_t *parse_string_const(void)
2901 {
2902         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2903         cnst->base.datatype = type_string;
2904         cnst->string.value  = parse_string_literals();
2905
2906         return cnst;
2907 }
2908
2909 /**
2910  * Parse a wide string constant.
2911  */
2912 static expression_t *parse_wide_string_const(void)
2913 {
2914         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2915         cnst->base.datatype      = type_wchar_t_ptr;
2916         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2917         next_token();
2918         return cnst;
2919 }
2920
2921 /**
2922  * Parse an integer constant.
2923  */
2924 static expression_t *parse_int_const(void)
2925 {
2926         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2927         cnst->base.datatype      = token.datatype;
2928         cnst->conste.v.int_value = token.v.intvalue;
2929
2930         next_token();
2931
2932         return cnst;
2933 }
2934
2935 /**
2936  * Parse a float constant.
2937  */
2938 static expression_t *parse_float_const(void)
2939 {
2940         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2941         cnst->base.datatype        = token.datatype;
2942         cnst->conste.v.float_value = token.v.floatvalue;
2943
2944         next_token();
2945
2946         return cnst;
2947 }
2948
2949 static declaration_t *create_implicit_function(symbol_t *symbol,
2950                 const source_position_t source_position)
2951 {
2952         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2953         ntype->function.return_type            = type_int;
2954         ntype->function.unspecified_parameters = true;
2955
2956         type_t *type = typehash_insert(ntype);
2957         if(type != ntype) {
2958                 free_type(ntype);
2959         }
2960
2961         declaration_t *const declaration = allocate_declaration_zero();
2962         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2963         declaration->type            = type;
2964         declaration->symbol          = symbol;
2965         declaration->source_position = source_position;
2966         declaration->parent_context  = global_context;
2967
2968         context_t *old_context = context;
2969         set_context(global_context);
2970
2971         environment_push(declaration);
2972         /* prepend the declaration to the global declarations list */
2973         declaration->next     = context->declarations;
2974         context->declarations = declaration;
2975
2976         assert(context == global_context);
2977         set_context(old_context);
2978
2979         return declaration;
2980 }
2981
2982 /**
2983  * Creates a return_type (func)(argument_type) function type if not
2984  * already exists.
2985  *
2986  * @param return_type    the return type
2987  * @param argument_type  the argument type
2988  */
2989 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
2990 {
2991         function_parameter_t *parameter
2992                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2993         memset(parameter, 0, sizeof(parameter[0]));
2994         parameter->type = argument_type;
2995
2996         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
2997         type->function.return_type = return_type;
2998         type->function.parameters  = parameter;
2999
3000         type_t *result = typehash_insert(type);
3001         if(result != type) {
3002                 free_type(type);
3003         }
3004
3005         return result;
3006 }
3007
3008 /**
3009  * Creates a function type for some function like builtins.
3010  *
3011  * @param symbol   the symbol describing the builtin
3012  */
3013 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3014 {
3015         switch(symbol->ID) {
3016         case T___builtin_alloca:
3017                 return make_function_1_type(type_void_ptr, type_size_t);
3018         case T___builtin_nan:
3019                 return make_function_1_type(type_double, type_string);
3020         case T___builtin_nanf:
3021                 return make_function_1_type(type_float, type_string);
3022         case T___builtin_nand:
3023                 return make_function_1_type(type_long_double, type_string);
3024         case T___builtin_va_end:
3025                 return make_function_1_type(type_void, type_valist);
3026         default:
3027                 panic("not implemented builtin symbol found");
3028         }
3029 }
3030
3031 /**
3032  * Performs automatic type cast as described in Â§ 6.3.2.1.
3033  *
3034  * @param orig_type  the original type
3035  */
3036 static type_t *automatic_type_conversion(type_t *orig_type)
3037 {
3038         type_t *type = skip_typeref(orig_type);
3039         if(is_type_array(type)) {
3040                 array_type_t *array_type   = &type->array;
3041                 type_t       *element_type = array_type->element_type;
3042                 unsigned      qualifiers   = array_type->type.qualifiers;
3043
3044                 return make_pointer_type(element_type, qualifiers);
3045         }
3046
3047         if(is_type_function(type)) {
3048                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3049         }
3050
3051         return orig_type;
3052 }
3053
3054 /**
3055  * reverts the automatic casts of array to pointer types and function
3056  * to function-pointer types as defined Â§ 6.3.2.1
3057  */
3058 type_t *revert_automatic_type_conversion(const expression_t *expression)
3059 {
3060         switch(expression->kind) {
3061         case EXPR_REFERENCE: {
3062                 const reference_expression_t *ref = &expression->reference;
3063                 return ref->declaration->type;
3064         }
3065         case EXPR_SELECT: {
3066                 const select_expression_t *select = &expression->select;
3067                 return select->compound_entry->type;
3068         }
3069         case EXPR_UNARY_DEREFERENCE: {
3070                 expression_t   *value        = expression->unary.value;
3071                 type_t         *type         = skip_typeref(value->base.datatype);
3072                 pointer_type_t *pointer_type = &type->pointer;
3073
3074                 return pointer_type->points_to;
3075         }
3076         case EXPR_BUILTIN_SYMBOL: {
3077                 const builtin_symbol_expression_t *builtin
3078                         = &expression->builtin_symbol;
3079                 return get_builtin_symbol_type(builtin->symbol);
3080         }
3081         case EXPR_ARRAY_ACCESS: {
3082                 const expression_t *const array_ref = expression->array_access.array_ref;
3083                 type_t             *const type_left = skip_typeref(array_ref->base.datatype);
3084                 if (!is_type_valid(type_left))
3085                         return type_left;
3086                 assert(is_type_pointer(type_left));
3087                 return type_left->pointer.points_to;
3088         }
3089
3090         default:
3091                 break;
3092         }
3093
3094         return expression->base.datatype;
3095 }
3096
3097 static expression_t *parse_reference(void)
3098 {
3099         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3100
3101         reference_expression_t *ref = &expression->reference;
3102         ref->symbol = token.v.symbol;
3103
3104         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3105
3106         source_position_t source_position = token.source_position;
3107         next_token();
3108
3109         if(declaration == NULL) {
3110                 if (! strict_mode && token.type == '(') {
3111                         /* an implicitly defined function */
3112                         warningf(HERE, "implicit declaration of function '%Y'",
3113                                  ref->symbol);
3114
3115                         declaration = create_implicit_function(ref->symbol,
3116                                                                source_position);
3117                 } else {
3118                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3119                         return expression;
3120                 }
3121         }
3122
3123         type_t *type         = declaration->type;
3124
3125         /* we always do the auto-type conversions; the & and sizeof parser contains
3126          * code to revert this! */
3127         type = automatic_type_conversion(type);
3128
3129         ref->declaration         = declaration;
3130         ref->expression.datatype = type;
3131
3132         return expression;
3133 }
3134
3135 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3136 {
3137         (void) expression;
3138         (void) dest_type;
3139         /* TODO check if explicit cast is allowed and issue warnings/errors */
3140 }
3141
3142 static expression_t *parse_cast(void)
3143 {
3144         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3145
3146         cast->base.source_position = token.source_position;
3147
3148         type_t *type  = parse_typename();
3149
3150         expect(')');
3151         expression_t *value = parse_sub_expression(20);
3152
3153         check_cast_allowed(value, type);
3154
3155         cast->base.datatype = type;
3156         cast->unary.value   = value;
3157
3158         return cast;
3159 }
3160
3161 static expression_t *parse_statement_expression(void)
3162 {
3163         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3164
3165         statement_t *statement          = parse_compound_statement();
3166         expression->statement.statement = statement;
3167         if(statement == NULL) {
3168                 expect(')');
3169                 return NULL;
3170         }
3171
3172         assert(statement->kind == STATEMENT_COMPOUND);
3173         compound_statement_t *compound_statement = &statement->compound;
3174
3175         /* find last statement and use it's type */
3176         const statement_t *last_statement = NULL;
3177         const statement_t *iter           = compound_statement->statements;
3178         for( ; iter != NULL; iter = iter->base.next) {
3179                 last_statement = iter;
3180         }
3181
3182         if(last_statement->kind == STATEMENT_EXPRESSION) {
3183                 const expression_statement_t *expression_statement
3184                         = &last_statement->expression;
3185                 expression->base.datatype
3186                         = expression_statement->expression->base.datatype;
3187         } else {
3188                 expression->base.datatype = type_void;
3189         }
3190
3191         expect(')');
3192
3193         return expression;
3194 }
3195
3196 static expression_t *parse_brace_expression(void)
3197 {
3198         eat('(');
3199
3200         switch(token.type) {
3201         case '{':
3202                 /* gcc extension: a statement expression */
3203                 return parse_statement_expression();
3204
3205         TYPE_QUALIFIERS
3206         TYPE_SPECIFIERS
3207                 return parse_cast();
3208         case T_IDENTIFIER:
3209                 if(is_typedef_symbol(token.v.symbol)) {
3210                         return parse_cast();
3211                 }
3212         }
3213
3214         expression_t *result = parse_expression();
3215         expect(')');
3216
3217         return result;
3218 }
3219
3220 static expression_t *parse_function_keyword(void)
3221 {
3222         next_token();
3223         /* TODO */
3224
3225         if (current_function == NULL) {
3226                 errorf(HERE, "'__func__' used outside of a function");
3227         }
3228
3229         string_literal_expression_t *expression
3230                 = allocate_ast_zero(sizeof(expression[0]));
3231
3232         expression->expression.kind     = EXPR_FUNCTION;
3233         expression->expression.datatype = type_string;
3234
3235         return (expression_t*) expression;
3236 }
3237
3238 static expression_t *parse_pretty_function_keyword(void)
3239 {
3240         eat(T___PRETTY_FUNCTION__);
3241         /* TODO */
3242
3243         if (current_function == NULL) {
3244                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3245         }
3246
3247         string_literal_expression_t *expression
3248                 = allocate_ast_zero(sizeof(expression[0]));
3249
3250         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3251         expression->expression.datatype = type_string;
3252
3253         return (expression_t*) expression;
3254 }
3255
3256 static designator_t *parse_designator(void)
3257 {
3258         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3259
3260         if(token.type != T_IDENTIFIER) {
3261                 parse_error_expected("while parsing member designator",
3262                                      T_IDENTIFIER, 0);
3263                 eat_paren();
3264                 return NULL;
3265         }
3266         result->symbol = token.v.symbol;
3267         next_token();
3268
3269         designator_t *last_designator = result;
3270         while(true) {
3271                 if(token.type == '.') {
3272                         next_token();
3273                         if(token.type != T_IDENTIFIER) {
3274                                 parse_error_expected("while parsing member designator",
3275                                                      T_IDENTIFIER, 0);
3276                                 eat_paren();
3277                                 return NULL;
3278                         }
3279                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3280                         designator->symbol       = token.v.symbol;
3281                         next_token();
3282
3283                         last_designator->next = designator;
3284                         last_designator       = designator;
3285                         continue;
3286                 }
3287                 if(token.type == '[') {
3288                         next_token();
3289                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3290                         designator->array_access = parse_expression();
3291                         if(designator->array_access == NULL) {
3292                                 eat_paren();
3293                                 return NULL;
3294                         }
3295                         expect(']');
3296
3297                         last_designator->next = designator;
3298                         last_designator       = designator;
3299                         continue;
3300                 }
3301                 break;
3302         }
3303
3304         return result;
3305 }
3306
3307 static expression_t *parse_offsetof(void)
3308 {
3309         eat(T___builtin_offsetof);
3310
3311         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3312         expression->base.datatype = type_size_t;
3313
3314         expect('(');
3315         expression->offsetofe.type = parse_typename();
3316         expect(',');
3317         expression->offsetofe.designator = parse_designator();
3318         expect(')');
3319
3320         return expression;
3321 }
3322
3323 static expression_t *parse_va_start(void)
3324 {
3325         eat(T___builtin_va_start);
3326
3327         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3328
3329         expect('(');
3330         expression->va_starte.ap = parse_assignment_expression();
3331         expect(',');
3332         expression_t *const expr = parse_assignment_expression();
3333         if (expr->kind == EXPR_REFERENCE) {
3334                 declaration_t *const decl = expr->reference.declaration;
3335                 if (decl->parent_context == &current_function->context &&
3336                     decl->next == NULL) {
3337                         expression->va_starte.parameter = decl;
3338                         expect(')');
3339                         return expression;
3340                 }
3341         }
3342         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3343
3344         return create_invalid_expression();
3345 }
3346
3347 static expression_t *parse_va_arg(void)
3348 {
3349         eat(T___builtin_va_arg);
3350
3351         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3352
3353         expect('(');
3354         expression->va_arge.ap = parse_assignment_expression();
3355         expect(',');
3356         expression->base.datatype = parse_typename();
3357         expect(')');
3358
3359         return expression;
3360 }
3361
3362 static expression_t *parse_builtin_symbol(void)
3363 {
3364         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3365
3366         symbol_t *symbol = token.v.symbol;
3367
3368         expression->builtin_symbol.symbol = symbol;
3369         next_token();
3370
3371         type_t *type = get_builtin_symbol_type(symbol);
3372         type = automatic_type_conversion(type);
3373
3374         expression->base.datatype = type;
3375         return expression;
3376 }
3377
3378 static expression_t *parse_builtin_constant(void)
3379 {
3380         eat(T___builtin_constant_p);
3381
3382         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3383
3384         expect('(');
3385         expression->builtin_constant.value = parse_assignment_expression();
3386         expect(')');
3387         expression->base.datatype = type_int;
3388
3389         return expression;
3390 }
3391
3392 static expression_t *parse_builtin_prefetch(void)
3393 {
3394         eat(T___builtin_prefetch);
3395
3396         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3397
3398         expect('(');
3399         expression->builtin_prefetch.adr = parse_assignment_expression();
3400         if (token.type == ',') {
3401                 next_token();
3402                 expression->builtin_prefetch.rw = parse_assignment_expression();
3403         }
3404         if (token.type == ',') {
3405                 next_token();
3406                 expression->builtin_prefetch.locality = parse_assignment_expression();
3407         }
3408         expect(')');
3409         expression->base.datatype = type_void;
3410
3411         return expression;
3412 }
3413
3414 static expression_t *parse_compare_builtin(void)
3415 {
3416         expression_t *expression;
3417
3418         switch(token.type) {
3419         case T___builtin_isgreater:
3420                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3421                 break;
3422         case T___builtin_isgreaterequal:
3423                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3424                 break;
3425         case T___builtin_isless:
3426                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3427                 break;
3428         case T___builtin_islessequal:
3429                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3430                 break;
3431         case T___builtin_islessgreater:
3432                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3433                 break;
3434         case T___builtin_isunordered:
3435                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3436                 break;
3437         default:
3438                 panic("invalid compare builtin found");
3439                 break;
3440         }
3441         next_token();
3442
3443         expect('(');
3444         expression->binary.left = parse_assignment_expression();
3445         expect(',');
3446         expression->binary.right = parse_assignment_expression();
3447         expect(')');
3448
3449         type_t *const orig_type_left  = expression->binary.left->base.datatype;
3450         type_t *const orig_type_right = expression->binary.right->base.datatype;
3451
3452         type_t *const type_left  = skip_typeref(orig_type_left);
3453         type_t *const type_right = skip_typeref(orig_type_right);
3454         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3455                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
3456                         type_error_incompatible("invalid operands in comparison",
3457                                 token.source_position, orig_type_left, orig_type_right);
3458                 }
3459         } else {
3460                 semantic_comparison(&expression->binary);
3461         }
3462
3463         return expression;
3464 }
3465
3466 static expression_t *parse_builtin_expect(void)
3467 {
3468         eat(T___builtin_expect);
3469
3470         expression_t *expression
3471                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3472
3473         expect('(');
3474         expression->binary.left = parse_assignment_expression();
3475         expect(',');
3476         expression->binary.right = parse_constant_expression();
3477         expect(')');
3478
3479         expression->base.datatype = expression->binary.left->base.datatype;
3480
3481         return expression;
3482 }
3483
3484 static expression_t *parse_assume(void) {
3485         eat(T_assume);
3486
3487         expression_t *expression
3488                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3489
3490         expect('(');
3491         expression->unary.value = parse_assignment_expression();
3492         expect(')');
3493
3494         expression->base.datatype = type_void;
3495         return expression;
3496 }
3497
3498 static expression_t *parse_alignof(void) {
3499         eat(T___alignof__);
3500
3501         expression_t *expression
3502                 = allocate_expression_zero(EXPR_ALIGNOF);
3503
3504         expect('(');
3505         expression->alignofe.type = parse_typename();
3506         expect(')');
3507
3508         expression->base.datatype = type_size_t;
3509         return expression;
3510 }
3511
3512 static expression_t *parse_primary_expression(void)
3513 {
3514         switch(token.type) {
3515         case T_INTEGER:
3516                 return parse_int_const();
3517         case T_FLOATINGPOINT:
3518                 return parse_float_const();
3519         case T_STRING_LITERAL:
3520                 return parse_string_const();
3521         case T_WIDE_STRING_LITERAL:
3522                 return parse_wide_string_const();
3523         case T_IDENTIFIER:
3524                 return parse_reference();
3525         case T___FUNCTION__:
3526         case T___func__:
3527                 return parse_function_keyword();
3528         case T___PRETTY_FUNCTION__:
3529                 return parse_pretty_function_keyword();
3530         case T___builtin_offsetof:
3531                 return parse_offsetof();
3532         case T___builtin_va_start:
3533                 return parse_va_start();
3534         case T___builtin_va_arg:
3535                 return parse_va_arg();
3536         case T___builtin_expect:
3537                 return parse_builtin_expect();
3538         case T___builtin_nanf:
3539         case T___builtin_alloca:
3540         case T___builtin_va_end:
3541                 return parse_builtin_symbol();
3542         case T___builtin_isgreater:
3543         case T___builtin_isgreaterequal:
3544         case T___builtin_isless:
3545         case T___builtin_islessequal:
3546         case T___builtin_islessgreater:
3547         case T___builtin_isunordered:
3548                 return parse_compare_builtin();
3549         case T___builtin_constant_p:
3550                 return parse_builtin_constant();
3551         case T___builtin_prefetch:
3552                 return parse_builtin_prefetch();
3553         case T___alignof__:
3554                 return parse_alignof();
3555         case T_assume:
3556                 return parse_assume();
3557
3558         case '(':
3559                 return parse_brace_expression();
3560         }
3561
3562         errorf(HERE, "unexpected token '%K'", &token);
3563         eat_statement();
3564
3565         return create_invalid_expression();
3566 }
3567
3568 /**
3569  * Check if the expression has the character type and issue a warning then.
3570  */
3571 static void check_for_char_index_type(const expression_t *expression) {
3572         type_t *type      = expression->base.datatype;
3573         type_t *base_type = skip_typeref(type);
3574
3575         if (base_type->base.kind == TYPE_ATOMIC) {
3576                 switch (base_type->atomic.akind == ATOMIC_TYPE_CHAR) {
3577                         warningf(expression->base.source_position,
3578                                 "array subscript has type '%T'", type);
3579                 }
3580         }
3581 }
3582
3583 static expression_t *parse_array_expression(unsigned precedence,
3584                                             expression_t *left)
3585 {
3586         (void) precedence;
3587
3588         eat('[');
3589
3590         expression_t *inside = parse_expression();
3591
3592         array_access_expression_t *array_access
3593                 = allocate_ast_zero(sizeof(array_access[0]));
3594
3595         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3596
3597         type_t *const orig_type_left   = left->base.datatype;
3598         type_t *const orig_type_inside = inside->base.datatype;
3599
3600         type_t *const type_left   = skip_typeref(orig_type_left);
3601         type_t *const type_inside = skip_typeref(orig_type_inside);
3602
3603         type_t *return_type;
3604         if (is_type_pointer(type_left)) {
3605                 pointer_type_t *const pointer = &type_left->pointer;
3606                 return_type             = pointer->points_to;
3607                 array_access->array_ref = left;
3608                 array_access->index     = inside;
3609                 check_for_char_index_type(inside);
3610         } else if (is_type_pointer(type_inside)) {
3611                 pointer_type_t *const pointer = &type_inside->pointer;
3612                 return_type             = pointer->points_to;
3613                 array_access->array_ref = inside;
3614                 array_access->index     = left;
3615                 array_access->flipped   = true;
3616                 check_for_char_index_type(left);
3617         } else {
3618                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
3619                         errorf(HERE,
3620                                 "array access on object with non-pointer types '%T', '%T'",
3621                                 orig_type_left, orig_type_inside);
3622                 }
3623                 return_type             = type_error_type;
3624                 array_access->array_ref = create_invalid_expression();
3625         }
3626
3627         if(token.type != ']') {
3628                 parse_error_expected("Problem while parsing array access", ']', 0);
3629                 return (expression_t*) array_access;
3630         }
3631         next_token();
3632
3633         return_type = automatic_type_conversion(return_type);
3634         array_access->expression.datatype = return_type;
3635
3636         return (expression_t*) array_access;
3637 }
3638
3639 static expression_t *parse_sizeof(unsigned precedence)
3640 {
3641         eat(T_sizeof);
3642
3643         sizeof_expression_t *sizeof_expression
3644                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3645         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3646         sizeof_expression->expression.datatype = type_size_t;
3647
3648         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3649                 next_token();
3650                 sizeof_expression->type = parse_typename();
3651                 expect(')');
3652         } else {
3653                 expression_t *expression  = parse_sub_expression(precedence);
3654                 expression->base.datatype = revert_automatic_type_conversion(expression);
3655
3656                 sizeof_expression->type            = expression->base.datatype;
3657                 sizeof_expression->size_expression = expression;
3658         }
3659
3660         return (expression_t*) sizeof_expression;
3661 }
3662
3663 static expression_t *parse_select_expression(unsigned precedence,
3664                                              expression_t *compound)
3665 {
3666         (void) precedence;
3667         assert(token.type == '.' || token.type == T_MINUSGREATER);
3668
3669         bool is_pointer = (token.type == T_MINUSGREATER);
3670         next_token();
3671
3672         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3673         select->select.compound = compound;
3674
3675         if(token.type != T_IDENTIFIER) {
3676                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3677                 return select;
3678         }
3679         symbol_t *symbol      = token.v.symbol;
3680         select->select.symbol = symbol;
3681         next_token();
3682
3683         type_t *const orig_type = compound->base.datatype;
3684         type_t *const type      = skip_typeref(orig_type);
3685
3686         type_t *type_left = type;
3687         if(is_pointer) {
3688                 if (!is_type_pointer(type)) {
3689                         if (is_type_valid(type)) {
3690                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
3691                         }
3692                         return create_invalid_expression();
3693                 }
3694                 pointer_type_t *pointer_type = &type->pointer;
3695                 type_left                    = pointer_type->points_to;
3696         }
3697         type_left = skip_typeref(type_left);
3698
3699         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
3700             type_left->kind != TYPE_COMPOUND_UNION) {
3701                 if (is_type_valid(type_left)) {
3702                         errorf(HERE, "request for member '%Y' in something not a struct or "
3703                                "union, but '%T'", symbol, type_left);
3704                 }
3705                 return create_invalid_expression();
3706         }
3707
3708         compound_type_t *compound_type = &type_left->compound;
3709         declaration_t   *declaration   = compound_type->declaration;
3710
3711         if(!declaration->init.is_defined) {
3712                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
3713                        symbol, type_left);
3714                 return create_invalid_expression();
3715         }
3716
3717         declaration_t *iter = declaration->context.declarations;
3718         for( ; iter != NULL; iter = iter->next) {
3719                 if(iter->symbol == symbol) {
3720                         break;
3721                 }
3722         }
3723         if(iter == NULL) {
3724                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
3725                 return create_invalid_expression();
3726         }
3727
3728         /* we always do the auto-type conversions; the & and sizeof parser contains
3729          * code to revert this! */
3730         type_t *expression_type = automatic_type_conversion(iter->type);
3731
3732         select->select.compound_entry = iter;
3733         select->base.datatype         = expression_type;
3734
3735         if(expression_type->kind == TYPE_BITFIELD) {
3736                 expression_t *extract
3737                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
3738                 extract->unary.value   = select;
3739                 extract->base.datatype = expression_type->bitfield.base;
3740
3741                 return extract;
3742         }
3743
3744         return select;
3745 }
3746
3747 /**
3748  * Parse a call expression, ie. expression '( ... )'.
3749  *
3750  * @param expression  the function address
3751  */
3752 static expression_t *parse_call_expression(unsigned precedence,
3753                                            expression_t *expression)
3754 {
3755         (void) precedence;
3756         expression_t *result = allocate_expression_zero(EXPR_CALL);
3757
3758         call_expression_t *call = &result->call;
3759         call->function          = expression;
3760
3761         type_t *const orig_type = expression->base.datatype;
3762         type_t *const type      = skip_typeref(orig_type);
3763
3764         function_type_t *function_type = NULL;
3765         if (is_type_pointer(type)) {
3766                 type_t *const to_type = skip_typeref(type->pointer.points_to);
3767
3768                 if (is_type_function(to_type)) {
3769                         function_type             = &to_type->function;
3770                         call->expression.datatype = function_type->return_type;
3771                 }
3772         }
3773
3774         if (function_type == NULL && is_type_valid(type)) {
3775                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
3776         }
3777
3778         /* parse arguments */
3779         eat('(');
3780
3781         if(token.type != ')') {
3782                 call_argument_t *last_argument = NULL;
3783
3784                 while(true) {
3785                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3786
3787                         argument->expression = parse_assignment_expression();
3788                         if(last_argument == NULL) {
3789                                 call->arguments = argument;
3790                         } else {
3791                                 last_argument->next = argument;
3792                         }
3793                         last_argument = argument;
3794
3795                         if(token.type != ',')
3796                                 break;
3797                         next_token();
3798                 }
3799         }
3800         expect(')');
3801
3802         if(function_type != NULL) {
3803                 function_parameter_t *parameter = function_type->parameters;
3804                 call_argument_t      *argument  = call->arguments;
3805                 for( ; parameter != NULL && argument != NULL;
3806                                 parameter = parameter->next, argument = argument->next) {
3807                         type_t *expected_type = parameter->type;
3808                         /* TODO report context in error messages */
3809                         expression_t *const arg_expr = argument->expression;
3810                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
3811                         if (res_type == NULL) {
3812                                 /* TODO improve error message */
3813                                 errorf(arg_expr->base.source_position,
3814                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
3815                                         arg_expr, arg_expr->base.datatype, expected_type);
3816                         } else {
3817                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
3818                         }
3819                 }
3820                 /* too few parameters */
3821                 if(parameter != NULL) {
3822                         errorf(HERE, "too few arguments to function '%E'", expression);
3823                 } else if(argument != NULL) {
3824                         /* too many parameters */
3825                         if(!function_type->variadic
3826                                         && !function_type->unspecified_parameters) {
3827                                 errorf(HERE, "too many arguments to function '%E'", expression);
3828                         } else {
3829                                 /* do default promotion */
3830                                 for( ; argument != NULL; argument = argument->next) {
3831                                         type_t *type = argument->expression->base.datatype;
3832
3833                                         type = skip_typeref(type);
3834                                         if(is_type_integer(type)) {
3835                                                 type = promote_integer(type);
3836                                         } else if(type == type_float) {
3837                                                 type = type_double;
3838                                         }
3839
3840                                         argument->expression
3841                                                 = create_implicit_cast(argument->expression, type);
3842                                 }
3843
3844                                 check_format(&result->call);
3845                         }
3846                 } else {
3847                         check_format(&result->call);
3848                 }
3849         }
3850
3851         return result;
3852 }
3853
3854 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3855
3856 static bool same_compound_type(const type_t *type1, const type_t *type2)
3857 {
3858         if(!is_type_compound(type1))
3859                 return false;
3860         if(type1->kind != type2->kind)
3861                 return false;
3862
3863         const compound_type_t *compound1 = &type1->compound;
3864         const compound_type_t *compound2 = &type2->compound;
3865
3866         return compound1->declaration == compound2->declaration;
3867 }
3868
3869 /**
3870  * Parse a conditional expression, ie. 'expression ? ... : ...'.
3871  *
3872  * @param expression  the conditional expression
3873  */
3874 static expression_t *parse_conditional_expression(unsigned precedence,
3875                                                   expression_t *expression)
3876 {
3877         eat('?');
3878
3879         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3880
3881         conditional_expression_t *conditional = &result->conditional;
3882         conditional->condition = expression;
3883
3884         /* 6.5.15.2 */
3885         type_t *const condition_type_orig = expression->base.datatype;
3886         type_t *const condition_type      = skip_typeref(condition_type_orig);
3887         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
3888                 type_error("expected a scalar type in conditional condition",
3889                            expression->base.source_position, condition_type_orig);
3890         }
3891
3892         expression_t *true_expression = parse_expression();
3893         expect(':');
3894         expression_t *false_expression = parse_sub_expression(precedence);
3895
3896         conditional->true_expression  = true_expression;
3897         conditional->false_expression = false_expression;
3898
3899         type_t *const orig_true_type  = true_expression->base.datatype;
3900         type_t *const orig_false_type = false_expression->base.datatype;
3901         type_t *const true_type       = skip_typeref(orig_true_type);
3902         type_t *const false_type      = skip_typeref(orig_false_type);
3903
3904         /* 6.5.15.3 */
3905         type_t *result_type;
3906         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3907                 result_type = semantic_arithmetic(true_type, false_type);
3908
3909                 true_expression  = create_implicit_cast(true_expression, result_type);
3910                 false_expression = create_implicit_cast(false_expression, result_type);
3911
3912                 conditional->true_expression     = true_expression;
3913                 conditional->false_expression    = false_expression;
3914                 conditional->expression.datatype = result_type;
3915         } else if (same_compound_type(true_type, false_type) || (
3916             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3917             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
3918                 )) {
3919                 /* just take 1 of the 2 types */
3920                 result_type = true_type;
3921         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3922                         && pointers_compatible(true_type, false_type)) {
3923                 /* ok */
3924                 result_type = true_type;
3925         } else {
3926                 /* TODO */
3927                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
3928                         type_error_incompatible("while parsing conditional",
3929                                                 expression->base.source_position, true_type,
3930                                                 false_type);
3931                 }
3932                 result_type = type_error_type;
3933         }
3934
3935         conditional->expression.datatype = result_type;
3936         return result;
3937 }
3938
3939 /**
3940  * Parse an extension expression.
3941  */
3942 static expression_t *parse_extension(unsigned precedence)
3943 {
3944         eat(T___extension__);
3945
3946         /* TODO enable extensions */
3947         expression_t *expression = parse_sub_expression(precedence);
3948         /* TODO disable extensions */
3949         return expression;
3950 }
3951
3952 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3953 {
3954         eat(T___builtin_classify_type);
3955
3956         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
3957         result->base.datatype = type_int;
3958
3959         expect('(');
3960         expression_t *expression = parse_sub_expression(precedence);
3961         expect(')');
3962         result->classify_type.type_expression = expression;
3963
3964         return result;
3965 }
3966
3967 static void semantic_incdec(unary_expression_t *expression)
3968 {
3969         type_t *const orig_type = expression->value->base.datatype;
3970         type_t *const type      = skip_typeref(orig_type);
3971         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
3972                 if (is_type_valid(type)) {
3973                         /* TODO: improve error message */
3974                         errorf(HERE, "operation needs an arithmetic or pointer type");
3975                 }
3976                 return;
3977         }
3978
3979         expression->expression.datatype = orig_type;
3980 }
3981
3982 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3983 {
3984         type_t *const orig_type = expression->value->base.datatype;
3985         type_t *const type      = skip_typeref(orig_type);
3986         if(!is_type_arithmetic(type)) {
3987                 if (is_type_valid(type)) {
3988                         /* TODO: improve error message */
3989                         errorf(HERE, "operation needs an arithmetic type");
3990                 }
3991                 return;
3992         }
3993
3994         expression->expression.datatype = orig_type;
3995 }
3996
3997 static void semantic_unexpr_scalar(unary_expression_t *expression)
3998 {
3999         type_t *const orig_type = expression->value->base.datatype;
4000         type_t *const type      = skip_typeref(orig_type);
4001         if (!is_type_scalar(type)) {
4002                 if (is_type_valid(type)) {
4003                         errorf(HERE, "operand of ! must be of scalar type");
4004                 }
4005                 return;
4006         }
4007
4008         expression->expression.datatype = orig_type;
4009 }
4010
4011 static void semantic_unexpr_integer(unary_expression_t *expression)
4012 {
4013         type_t *const orig_type = expression->value->base.datatype;
4014         type_t *const type      = skip_typeref(orig_type);
4015         if (!is_type_integer(type)) {
4016                 if (is_type_valid(type)) {
4017                         errorf(HERE, "operand of ~ must be of integer type");
4018                 }
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 *const orig_type = expression->value->base.datatype;
4028         type_t *const type      = skip_typeref(orig_type);
4029         if(!is_type_pointer(type)) {
4030                 if (is_type_valid(type)) {
4031                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4032                 }
4033                 return;
4034         }
4035
4036         pointer_type_t *pointer_type = &type->pointer;
4037         type_t         *result_type  = pointer_type->points_to;
4038
4039         result_type = automatic_type_conversion(result_type);
4040         expression->expression.datatype = result_type;
4041 }
4042
4043 /**
4044  * Check the semantic of the address taken expression.
4045  */
4046 static void semantic_take_addr(unary_expression_t *expression)
4047 {
4048         expression_t *value  = expression->value;
4049         value->base.datatype = revert_automatic_type_conversion(value);
4050
4051         type_t *orig_type = value->base.datatype;
4052         if(!is_type_valid(orig_type))
4053                 return;
4054
4055         if(value->kind == EXPR_REFERENCE) {
4056                 reference_expression_t *reference   = (reference_expression_t*) value;
4057                 declaration_t          *declaration = reference->declaration;
4058                 if(declaration != NULL) {
4059                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4060                                 errorf(expression->expression.source_position,
4061                                         "address of register variable '%Y' requested",
4062                                         declaration->symbol);
4063                         }
4064                         declaration->address_taken = 1;
4065                 }
4066         }
4067
4068         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4069 }
4070
4071 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4072 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4073 {                                                                              \
4074         eat(token_type);                                                           \
4075                                                                                    \
4076         expression_t *unary_expression                                             \
4077                 = allocate_expression_zero(unexpression_type);                         \
4078         unary_expression->base.source_position = HERE;                             \
4079         unary_expression->unary.value = parse_sub_expression(precedence);          \
4080                                                                                    \
4081         sfunc(&unary_expression->unary);                                           \
4082                                                                                    \
4083         return unary_expression;                                                   \
4084 }
4085
4086 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4087                                semantic_unexpr_arithmetic)
4088 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4089                                semantic_unexpr_arithmetic)
4090 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4091                                semantic_unexpr_scalar)
4092 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4093                                semantic_dereference)
4094 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4095                                semantic_take_addr)
4096 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4097                                semantic_unexpr_integer)
4098 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4099                                semantic_incdec)
4100 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4101                                semantic_incdec)
4102
4103 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4104                                                sfunc)                         \
4105 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4106                                                expression_t *left)            \
4107 {                                                                             \
4108         (void) precedence;                                                        \
4109         eat(token_type);                                                          \
4110                                                                               \
4111         expression_t *unary_expression                                            \
4112                 = allocate_expression_zero(unexpression_type);                        \
4113         unary_expression->unary.value = left;                                     \
4114                                                                                   \
4115         sfunc(&unary_expression->unary);                                          \
4116                                                                               \
4117         return unary_expression;                                                  \
4118 }
4119
4120 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4121                                        EXPR_UNARY_POSTFIX_INCREMENT,
4122                                        semantic_incdec)
4123 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4124                                        EXPR_UNARY_POSTFIX_DECREMENT,
4125                                        semantic_incdec)
4126
4127 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4128 {
4129         /* TODO: handle complex + imaginary types */
4130
4131         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4132         if(type_left == type_long_double || type_right == type_long_double) {
4133                 return type_long_double;
4134         } else if(type_left == type_double || type_right == type_double) {
4135                 return type_double;
4136         } else if(type_left == type_float || type_right == type_float) {
4137                 return type_float;
4138         }
4139
4140         type_right = promote_integer(type_right);
4141         type_left  = promote_integer(type_left);
4142
4143         if(type_left == type_right)
4144                 return type_left;
4145
4146         bool signed_left  = is_type_signed(type_left);
4147         bool signed_right = is_type_signed(type_right);
4148         int  rank_left    = get_rank(type_left);
4149         int  rank_right   = get_rank(type_right);
4150         if(rank_left < rank_right) {
4151                 if(signed_left == signed_right || !signed_right) {
4152                         return type_right;
4153                 } else {
4154                         return type_left;
4155                 }
4156         } else {
4157                 if(signed_left == signed_right || !signed_left) {
4158                         return type_left;
4159                 } else {
4160                         return type_right;
4161                 }
4162         }
4163 }
4164
4165 /**
4166  * Check the semantic restrictions for a binary expression.
4167  */
4168 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4169 {
4170         expression_t *const left            = expression->left;
4171         expression_t *const right           = expression->right;
4172         type_t       *const orig_type_left  = left->base.datatype;
4173         type_t       *const orig_type_right = right->base.datatype;
4174         type_t       *const type_left       = skip_typeref(orig_type_left);
4175         type_t       *const type_right      = skip_typeref(orig_type_right);
4176
4177         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4178                 /* TODO: improve error message */
4179                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4180                         errorf(HERE, "operation needs arithmetic types");
4181                 }
4182                 return;
4183         }
4184
4185         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4186         expression->left  = create_implicit_cast(left, arithmetic_type);
4187         expression->right = create_implicit_cast(right, arithmetic_type);
4188         expression->expression.datatype = arithmetic_type;
4189 }
4190
4191 static void semantic_shift_op(binary_expression_t *expression)
4192 {
4193         expression_t *const left            = expression->left;
4194         expression_t *const right           = expression->right;
4195         type_t       *const orig_type_left  = left->base.datatype;
4196         type_t       *const orig_type_right = right->base.datatype;
4197         type_t       *      type_left       = skip_typeref(orig_type_left);
4198         type_t       *      type_right      = skip_typeref(orig_type_right);
4199
4200         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4201                 /* TODO: improve error message */
4202                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4203                         errorf(HERE, "operation needs integer types");
4204                 }
4205                 return;
4206         }
4207
4208         type_left  = promote_integer(type_left);
4209         type_right = promote_integer(type_right);
4210
4211         expression->left  = create_implicit_cast(left, type_left);
4212         expression->right = create_implicit_cast(right, type_right);
4213         expression->expression.datatype = type_left;
4214 }
4215
4216 static void semantic_add(binary_expression_t *expression)
4217 {
4218         expression_t *const left            = expression->left;
4219         expression_t *const right           = expression->right;
4220         type_t       *const orig_type_left  = left->base.datatype;
4221         type_t       *const orig_type_right = right->base.datatype;
4222         type_t       *const type_left       = skip_typeref(orig_type_left);
4223         type_t       *const type_right      = skip_typeref(orig_type_right);
4224
4225         /* Â§ 5.6.5 */
4226         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4227                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4228                 expression->left  = create_implicit_cast(left, arithmetic_type);
4229                 expression->right = create_implicit_cast(right, arithmetic_type);
4230                 expression->expression.datatype = arithmetic_type;
4231                 return;
4232         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4233                 expression->expression.datatype = type_left;
4234         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4235                 expression->expression.datatype = type_right;
4236         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4237                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4238         }
4239 }
4240
4241 static void semantic_sub(binary_expression_t *expression)
4242 {
4243         expression_t *const left            = expression->left;
4244         expression_t *const right           = expression->right;
4245         type_t       *const orig_type_left  = left->base.datatype;
4246         type_t       *const orig_type_right = right->base.datatype;
4247         type_t       *const type_left       = skip_typeref(orig_type_left);
4248         type_t       *const type_right      = skip_typeref(orig_type_right);
4249
4250         /* Â§ 5.6.5 */
4251         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4252                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4253                 expression->left  = create_implicit_cast(left, arithmetic_type);
4254                 expression->right = create_implicit_cast(right, arithmetic_type);
4255                 expression->expression.datatype = arithmetic_type;
4256                 return;
4257         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4258                 expression->expression.datatype = type_left;
4259         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4260                 if(!pointers_compatible(type_left, type_right)) {
4261                         errorf(HERE, "pointers to incompatible objects to binary '-' ('%T', '%T')", orig_type_left, orig_type_right);
4262                 } else {
4263                         expression->expression.datatype = type_ptrdiff_t;
4264                 }
4265         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4266                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')", orig_type_left, orig_type_right);
4267         }
4268 }
4269
4270 static void semantic_comparison(binary_expression_t *expression)
4271 {
4272         expression_t *left            = expression->left;
4273         expression_t *right           = expression->right;
4274         type_t       *orig_type_left  = left->base.datatype;
4275         type_t       *orig_type_right = right->base.datatype;
4276
4277         type_t *type_left  = skip_typeref(orig_type_left);
4278         type_t *type_right = skip_typeref(orig_type_right);
4279
4280         /* TODO non-arithmetic types */
4281         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4282                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4283                 expression->left  = create_implicit_cast(left, arithmetic_type);
4284                 expression->right = create_implicit_cast(right, arithmetic_type);
4285                 expression->expression.datatype = arithmetic_type;
4286         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4287                 /* TODO check compatibility */
4288         } else if (is_type_pointer(type_left)) {
4289                 expression->right = create_implicit_cast(right, type_left);
4290         } else if (is_type_pointer(type_right)) {
4291                 expression->left = create_implicit_cast(left, type_right);
4292         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4293                 type_error_incompatible("invalid operands in comparison",
4294                                         token.source_position, type_left, type_right);
4295         }
4296         expression->expression.datatype = type_int;
4297 }
4298
4299 static void semantic_arithmetic_assign(binary_expression_t *expression)
4300 {
4301         expression_t *left            = expression->left;
4302         expression_t *right           = expression->right;
4303         type_t       *orig_type_left  = left->base.datatype;
4304         type_t       *orig_type_right = right->base.datatype;
4305
4306         type_t *type_left  = skip_typeref(orig_type_left);
4307         type_t *type_right = skip_typeref(orig_type_right);
4308
4309         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4310                 /* TODO: improve error message */
4311                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4312                         errorf(HERE, "operation needs arithmetic types");
4313                 }
4314                 return;
4315         }
4316
4317         /* combined instructions are tricky. We can't create an implicit cast on
4318          * the left side, because we need the uncasted form for the store.
4319          * The ast2firm pass has to know that left_type must be right_type
4320          * for the arithmetic operation and create a cast by itself */
4321         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4322         expression->right       = create_implicit_cast(right, arithmetic_type);
4323         expression->expression.datatype = type_left;
4324 }
4325
4326 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4327 {
4328         expression_t *const left            = expression->left;
4329         expression_t *const right           = expression->right;
4330         type_t       *const orig_type_left  = left->base.datatype;
4331         type_t       *const orig_type_right = right->base.datatype;
4332         type_t       *const type_left       = skip_typeref(orig_type_left);
4333         type_t       *const type_right      = skip_typeref(orig_type_right);
4334
4335         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4336                 /* combined instructions are tricky. We can't create an implicit cast on
4337                  * the left side, because we need the uncasted form for the store.
4338                  * The ast2firm pass has to know that left_type must be right_type
4339                  * for the arithmetic operation and create a cast by itself */
4340                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4341                 expression->right = create_implicit_cast(right, arithmetic_type);
4342                 expression->expression.datatype = type_left;
4343         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4344                 expression->expression.datatype = type_left;
4345         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4346                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4347         }
4348 }
4349
4350 /**
4351  * Check the semantic restrictions of a logical expression.
4352  */
4353 static void semantic_logical_op(binary_expression_t *expression)
4354 {
4355         expression_t *const left            = expression->left;
4356         expression_t *const right           = expression->right;
4357         type_t       *const orig_type_left  = left->base.datatype;
4358         type_t       *const orig_type_right = right->base.datatype;
4359         type_t       *const type_left       = skip_typeref(orig_type_left);
4360         type_t       *const type_right      = skip_typeref(orig_type_right);
4361
4362         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4363                 /* TODO: improve error message */
4364                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4365                         errorf(HERE, "operation needs scalar types");
4366                 }
4367                 return;
4368         }
4369
4370         expression->expression.datatype = type_int;
4371 }
4372
4373 /**
4374  * Checks if a compound type has constant fields.
4375  */
4376 static bool has_const_fields(const compound_type_t *type)
4377 {
4378         const context_t     *context = &type->declaration->context;
4379         const declaration_t *declaration = context->declarations;
4380
4381         for (; declaration != NULL; declaration = declaration->next) {
4382                 if (declaration->namespc != NAMESPACE_NORMAL)
4383                         continue;
4384
4385                 const type_t *decl_type = skip_typeref(declaration->type);
4386                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4387                         return true;
4388         }
4389         /* TODO */
4390         return false;
4391 }
4392
4393 /**
4394  * Check the semantic restrictions of a binary assign expression.
4395  */
4396 static void semantic_binexpr_assign(binary_expression_t *expression)
4397 {
4398         expression_t *left           = expression->left;
4399         type_t       *orig_type_left = left->base.datatype;
4400
4401         type_t *type_left = revert_automatic_type_conversion(left);
4402         type_left         = skip_typeref(orig_type_left);
4403
4404         /* must be a modifiable lvalue */
4405         if (is_type_array(type_left)) {
4406                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4407                 return;
4408         }
4409         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4410                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4411                        orig_type_left);
4412                 return;
4413         }
4414         if(is_type_incomplete(type_left)) {
4415                 errorf(HERE,
4416                        "left-hand side of assignment '%E' has incomplete type '%T'",
4417                        left, orig_type_left);
4418                 return;
4419         }
4420         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4421                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4422                        left, orig_type_left);
4423                 return;
4424         }
4425
4426         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
4427                                                  "assignment");
4428         if (res_type == NULL) {
4429                 errorf(expression->expression.source_position,
4430                         "cannot assign to '%T' from '%T'",
4431                         orig_type_left, expression->right->base.datatype);
4432         } else {
4433                 expression->right = create_implicit_cast(expression->right, res_type);
4434         }
4435
4436         expression->expression.datatype = orig_type_left;
4437 }
4438
4439 static void semantic_comma(binary_expression_t *expression)
4440 {
4441         expression->expression.datatype = expression->right->base.datatype;
4442 }
4443
4444 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4445 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4446                                                 expression_t *left)       \
4447 {                                                                         \
4448         eat(token_type);                                                      \
4449                                                                           \
4450         expression_t *right = parse_sub_expression(precedence + lr);          \
4451                                                                           \
4452         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4453         binexpr->binary.left  = left;                                         \
4454         binexpr->binary.right = right;                                        \
4455         sfunc(&binexpr->binary);                                              \
4456                                                                           \
4457         return binexpr;                                                       \
4458 }
4459
4460 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4461 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4462 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4463 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4464 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4465 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4466 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4467 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4468 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4469
4470 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4471                       semantic_comparison, 1)
4472 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4473                       semantic_comparison, 1)
4474 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4475                       semantic_comparison, 1)
4476 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4477                       semantic_comparison, 1)
4478
4479 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4480                       semantic_binexpr_arithmetic, 1)
4481 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4482                       semantic_binexpr_arithmetic, 1)
4483 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4484                       semantic_binexpr_arithmetic, 1)
4485 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4486                       semantic_logical_op, 1)
4487 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4488                       semantic_logical_op, 1)
4489 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4490                       semantic_shift_op, 1)
4491 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4492                       semantic_shift_op, 1)
4493 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4494                       semantic_arithmetic_addsubb_assign, 0)
4495 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4496                       semantic_arithmetic_addsubb_assign, 0)
4497 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4498                       semantic_arithmetic_assign, 0)
4499 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4500                       semantic_arithmetic_assign, 0)
4501 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4502                       semantic_arithmetic_assign, 0)
4503 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4504                       semantic_arithmetic_assign, 0)
4505 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4506                       semantic_arithmetic_assign, 0)
4507 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4508                       semantic_arithmetic_assign, 0)
4509 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4510                       semantic_arithmetic_assign, 0)
4511 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4512                       semantic_arithmetic_assign, 0)
4513
4514 static expression_t *parse_sub_expression(unsigned precedence)
4515 {
4516         if(token.type < 0) {
4517                 return expected_expression_error();
4518         }
4519
4520         expression_parser_function_t *parser
4521                 = &expression_parsers[token.type];
4522         source_position_t             source_position = token.source_position;
4523         expression_t                 *left;
4524
4525         if(parser->parser != NULL) {
4526                 left = parser->parser(parser->precedence);
4527         } else {
4528                 left = parse_primary_expression();
4529         }
4530         assert(left != NULL);
4531         left->base.source_position = source_position;
4532
4533         while(true) {
4534                 if(token.type < 0) {
4535                         return expected_expression_error();
4536                 }
4537
4538                 parser = &expression_parsers[token.type];
4539                 if(parser->infix_parser == NULL)
4540                         break;
4541                 if(parser->infix_precedence < precedence)
4542                         break;
4543
4544                 left = parser->infix_parser(parser->infix_precedence, left);
4545
4546                 assert(left != NULL);
4547                 assert(left->kind != EXPR_UNKNOWN);
4548                 left->base.source_position = source_position;
4549         }
4550
4551         return left;
4552 }
4553
4554 /**
4555  * Parse an expression.
4556  */
4557 static expression_t *parse_expression(void)
4558 {
4559         return parse_sub_expression(1);
4560 }
4561
4562 /**
4563  * Register a parser for a prefix-like operator with given precedence.
4564  *
4565  * @param parser      the parser function
4566  * @param token_type  the token type of the prefix token
4567  * @param precedence  the precedence of the operator
4568  */
4569 static void register_expression_parser(parse_expression_function parser,
4570                                        int token_type, unsigned precedence)
4571 {
4572         expression_parser_function_t *entry = &expression_parsers[token_type];
4573
4574         if(entry->parser != NULL) {
4575                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4576                 panic("trying to register multiple expression parsers for a token");
4577         }
4578         entry->parser     = parser;
4579         entry->precedence = precedence;
4580 }
4581
4582 /**
4583  * Register a parser for an infix operator with given precedence.
4584  *
4585  * @param parser      the parser function
4586  * @param token_type  the token type of the infix operator
4587  * @param precedence  the precedence of the operator
4588  */
4589 static void register_infix_parser(parse_expression_infix_function parser,
4590                 int token_type, unsigned precedence)
4591 {
4592         expression_parser_function_t *entry = &expression_parsers[token_type];
4593
4594         if(entry->infix_parser != NULL) {
4595                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4596                 panic("trying to register multiple infix expression parsers for a "
4597                       "token");
4598         }
4599         entry->infix_parser     = parser;
4600         entry->infix_precedence = precedence;
4601 }
4602
4603 /**
4604  * Initialize the expression parsers.
4605  */
4606 static void init_expression_parsers(void)
4607 {
4608         memset(&expression_parsers, 0, sizeof(expression_parsers));
4609
4610         register_infix_parser(parse_array_expression,         '[',              30);
4611         register_infix_parser(parse_call_expression,          '(',              30);
4612         register_infix_parser(parse_select_expression,        '.',              30);
4613         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4614         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4615                                                               T_PLUSPLUS,       30);
4616         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4617                                                               T_MINUSMINUS,     30);
4618
4619         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4620         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4621         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4622         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4623         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4624         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4625         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4626         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4627         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4628         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4629         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4630         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4631         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4632                                                     T_EXCLAMATIONMARKEQUAL, 13);
4633         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4634         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4635         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4636         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4637         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4638         register_infix_parser(parse_conditional_expression,   '?',               7);
4639         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4640         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4641         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4642         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4643         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4644         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4645         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4646                                                                 T_LESSLESSEQUAL, 2);
4647         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4648                                                           T_GREATERGREATEREQUAL, 2);
4649         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4650                                                                      T_ANDEQUAL, 2);
4651         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4652                                                                     T_PIPEEQUAL, 2);
4653         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4654                                                                    T_CARETEQUAL, 2);
4655
4656         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4657
4658         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4659         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4660         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4661         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4662         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4663         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4664         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4665                                                                   T_PLUSPLUS,   25);
4666         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4667                                                                   T_MINUSMINUS, 25);
4668         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4669         register_expression_parser(parse_extension,            T___extension__, 25);
4670         register_expression_parser(parse_builtin_classify_type,
4671                                                      T___builtin_classify_type, 25);
4672 }
4673
4674 /**
4675  * Parse a asm statement constraints specification.
4676  */
4677 static asm_constraint_t *parse_asm_constraints(void)
4678 {
4679         asm_constraint_t *result = NULL;
4680         asm_constraint_t *last   = NULL;
4681
4682         while(token.type == T_STRING_LITERAL || token.type == '[') {
4683                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4684                 memset(constraint, 0, sizeof(constraint[0]));
4685
4686                 if(token.type == '[') {
4687                         eat('[');
4688                         if(token.type != T_IDENTIFIER) {
4689                                 parse_error_expected("while parsing asm constraint",
4690                                                      T_IDENTIFIER, 0);
4691                                 return NULL;
4692                         }
4693                         constraint->symbol = token.v.symbol;
4694
4695                         expect(']');
4696                 }
4697
4698                 constraint->constraints = parse_string_literals();
4699                 expect('(');
4700                 constraint->expression = parse_expression();
4701                 expect(')');
4702
4703                 if(last != NULL) {
4704                         last->next = constraint;
4705                 } else {
4706                         result = constraint;
4707                 }
4708                 last = constraint;
4709
4710                 if(token.type != ',')
4711                         break;
4712                 eat(',');
4713         }
4714
4715         return result;
4716 }
4717
4718 /**
4719  * Parse a asm statement clobber specification.
4720  */
4721 static asm_clobber_t *parse_asm_clobbers(void)
4722 {
4723         asm_clobber_t *result = NULL;
4724         asm_clobber_t *last   = NULL;
4725
4726         while(token.type == T_STRING_LITERAL) {
4727                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4728                 clobber->clobber       = parse_string_literals();
4729
4730                 if(last != NULL) {
4731                         last->next = clobber;
4732                 } else {
4733                         result = clobber;
4734                 }
4735                 last = clobber;
4736
4737                 if(token.type != ',')
4738                         break;
4739                 eat(',');
4740         }
4741
4742         return result;
4743 }
4744
4745 /**
4746  * Parse an asm statement.
4747  */
4748 static statement_t *parse_asm_statement(void)
4749 {
4750         eat(T_asm);
4751
4752         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4753         statement->base.source_position = token.source_position;
4754
4755         asm_statement_t *asm_statement = &statement->asms;
4756
4757         if(token.type == T_volatile) {
4758                 next_token();
4759                 asm_statement->is_volatile = true;
4760         }
4761
4762         expect('(');
4763         asm_statement->asm_text = parse_string_literals();
4764
4765         if(token.type != ':')
4766                 goto end_of_asm;
4767         eat(':');
4768
4769         asm_statement->inputs = parse_asm_constraints();
4770         if(token.type != ':')
4771                 goto end_of_asm;
4772         eat(':');
4773
4774         asm_statement->outputs = parse_asm_constraints();
4775         if(token.type != ':')
4776                 goto end_of_asm;
4777         eat(':');
4778
4779         asm_statement->clobbers = parse_asm_clobbers();
4780
4781 end_of_asm:
4782         expect(')');
4783         expect(';');
4784         return statement;
4785 }
4786
4787 /**
4788  * Parse a case statement.
4789  */
4790 static statement_t *parse_case_statement(void)
4791 {
4792         eat(T_case);
4793
4794         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4795
4796         statement->base.source_position  = token.source_position;
4797         statement->case_label.expression = parse_expression();
4798
4799         expect(':');
4800
4801         if (! is_constant_expression(statement->case_label.expression)) {
4802                 errorf(statement->base.source_position,
4803                         "case label does not reduce to an integer constant");
4804         } else {
4805                 /* TODO: check if the case label is already known */
4806                 if (current_switch != NULL) {
4807                         /* link all cases into the switch statement */
4808                         if (current_switch->last_case == NULL) {
4809                                 current_switch->first_case =
4810                                 current_switch->last_case  = &statement->case_label;
4811                         } else {
4812                                 current_switch->last_case->next = &statement->case_label;
4813                         }
4814                 } else {
4815                         errorf(statement->base.source_position,
4816                                 "case label not within a switch statement");
4817                 }
4818         }
4819         statement->case_label.label_statement = parse_statement();
4820
4821         return statement;
4822 }
4823
4824 /**
4825  * Finds an existing default label of a switch statement.
4826  */
4827 static case_label_statement_t *
4828 find_default_label(const switch_statement_t *statement)
4829 {
4830         for (case_label_statement_t *label = statement->first_case;
4831              label != NULL;
4832                  label = label->next) {
4833                 if (label->expression == NULL)
4834                         return label;
4835         }
4836         return NULL;
4837 }
4838
4839 /**
4840  * Parse a default statement.
4841  */
4842 static statement_t *parse_default_statement(void)
4843 {
4844         eat(T_default);
4845
4846         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4847
4848         statement->base.source_position = token.source_position;
4849
4850         expect(':');
4851         if (current_switch != NULL) {
4852                 const case_label_statement_t *def_label = find_default_label(current_switch);
4853                 if (def_label != NULL) {
4854                         errorf(HERE, "multiple default labels in one switch");
4855                         errorf(def_label->statement.source_position,
4856                                 "this is the first default label");
4857                 } else {
4858                         /* link all cases into the switch statement */
4859                         if (current_switch->last_case == NULL) {
4860                                 current_switch->first_case =
4861                                         current_switch->last_case  = &statement->case_label;
4862                         } else {
4863                                 current_switch->last_case->next = &statement->case_label;
4864                         }
4865                 }
4866         } else {
4867                 errorf(statement->base.source_position,
4868                         "'default' label not within a switch statement");
4869         }
4870         statement->label.label_statement = parse_statement();
4871
4872         return statement;
4873 }
4874
4875 /**
4876  * Return the declaration for a given label symbol or create a new one.
4877  */
4878 static declaration_t *get_label(symbol_t *symbol)
4879 {
4880         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4881         assert(current_function != NULL);
4882         /* if we found a label in the same function, then we already created the
4883          * declaration */
4884         if(candidate != NULL
4885                         && candidate->parent_context == &current_function->context) {
4886                 return candidate;
4887         }
4888
4889         /* otherwise we need to create a new one */
4890         declaration_t *const declaration = allocate_declaration_zero();
4891         declaration->namespc       = NAMESPACE_LABEL;
4892         declaration->symbol        = symbol;
4893
4894         label_push(declaration);
4895
4896         return declaration;
4897 }
4898
4899 /**
4900  * Parse a label statement.
4901  */
4902 static statement_t *parse_label_statement(void)
4903 {
4904         assert(token.type == T_IDENTIFIER);
4905         symbol_t *symbol = token.v.symbol;
4906         next_token();
4907
4908         declaration_t *label = get_label(symbol);
4909
4910         /* if source position is already set then the label is defined twice,
4911          * otherwise it was just mentioned in a goto so far */
4912         if(label->source_position.input_name != NULL) {
4913                 errorf(HERE, "duplicate label '%Y'", symbol);
4914                 errorf(label->source_position, "previous definition of '%Y' was here",
4915                        symbol);
4916         } else {
4917                 label->source_position = token.source_position;
4918         }
4919
4920         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4921
4922         label_statement->statement.kind            = STATEMENT_LABEL;
4923         label_statement->statement.source_position = token.source_position;
4924         label_statement->label                     = label;
4925
4926         eat(':');
4927
4928         if(token.type == '}') {
4929                 /* TODO only warn? */
4930                 errorf(HERE, "label at end of compound statement");
4931                 return (statement_t*) label_statement;
4932         } else {
4933                 label_statement->label_statement = parse_statement();
4934         }
4935
4936         return (statement_t*) label_statement;
4937 }
4938
4939 /**
4940  * Parse an if statement.
4941  */
4942 static statement_t *parse_if(void)
4943 {
4944         eat(T_if);
4945
4946         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4947         statement->statement.kind            = STATEMENT_IF;
4948         statement->statement.source_position = token.source_position;
4949
4950         expect('(');
4951         statement->condition = parse_expression();
4952         expect(')');
4953
4954         statement->true_statement = parse_statement();
4955         if(token.type == T_else) {
4956                 next_token();
4957                 statement->false_statement = parse_statement();
4958         }
4959
4960         return (statement_t*) statement;
4961 }
4962
4963 /**
4964  * Parse a switch statement.
4965  */
4966 static statement_t *parse_switch(void)
4967 {
4968         eat(T_switch);
4969
4970         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4971         statement->statement.kind            = STATEMENT_SWITCH;
4972         statement->statement.source_position = token.source_position;
4973
4974         expect('(');
4975         expression_t *const expr = parse_expression();
4976         type_t       *      type = skip_typeref(expr->base.datatype);
4977         if (is_type_integer(type)) {
4978                 type = promote_integer(type);
4979         } else if (is_type_valid(type)) {
4980                 errorf(expr->base.source_position, "switch quantity is not an integer, but '%T'", type);
4981                 type = type_error_type;
4982         }
4983         statement->expression = create_implicit_cast(expr, type);
4984         expect(')');
4985
4986         switch_statement_t *rem = current_switch;
4987         current_switch  = statement;
4988         statement->body = parse_statement();
4989         current_switch  = rem;
4990
4991         return (statement_t*) statement;
4992 }
4993
4994 static statement_t *parse_loop_body(statement_t *const loop)
4995 {
4996         statement_t *const rem = current_loop;
4997         current_loop = loop;
4998         statement_t *const body = parse_statement();
4999         current_loop = rem;
5000         return body;
5001 }
5002
5003 /**
5004  * Parse a while statement.
5005  */
5006 static statement_t *parse_while(void)
5007 {
5008         eat(T_while);
5009
5010         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5011         statement->statement.kind            = STATEMENT_WHILE;
5012         statement->statement.source_position = token.source_position;
5013
5014         expect('(');
5015         statement->condition = parse_expression();
5016         expect(')');
5017
5018         statement->body = parse_loop_body((statement_t*)statement);
5019
5020         return (statement_t*) statement;
5021 }
5022
5023 /**
5024  * Parse a do statement.
5025  */
5026 static statement_t *parse_do(void)
5027 {
5028         eat(T_do);
5029
5030         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5031         statement->statement.kind            = STATEMENT_DO_WHILE;
5032         statement->statement.source_position = token.source_position;
5033
5034         statement->body = parse_loop_body((statement_t*)statement);
5035         expect(T_while);
5036         expect('(');
5037         statement->condition = parse_expression();
5038         expect(')');
5039         expect(';');
5040
5041         return (statement_t*) statement;
5042 }
5043
5044 /**
5045  * Parse a for statement.
5046  */
5047 static statement_t *parse_for(void)
5048 {
5049         eat(T_for);
5050
5051         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5052         statement->statement.kind            = STATEMENT_FOR;
5053         statement->statement.source_position = token.source_position;
5054
5055         expect('(');
5056
5057         int         top          = environment_top();
5058         context_t  *last_context = context;
5059         set_context(&statement->context);
5060
5061         if(token.type != ';') {
5062                 if(is_declaration_specifier(&token, false)) {
5063                         parse_declaration(record_declaration);
5064                 } else {
5065                         statement->initialisation = parse_expression();
5066                         expect(';');
5067                 }
5068         } else {
5069                 expect(';');
5070         }
5071
5072         if(token.type != ';') {
5073                 statement->condition = parse_expression();
5074         }
5075         expect(';');
5076         if(token.type != ')') {
5077                 statement->step = parse_expression();
5078         }
5079         expect(')');
5080         statement->body = parse_loop_body((statement_t*)statement);
5081
5082         assert(context == &statement->context);
5083         set_context(last_context);
5084         environment_pop_to(top);
5085
5086         return (statement_t*) statement;
5087 }
5088
5089 /**
5090  * Parse a goto statement.
5091  */
5092 static statement_t *parse_goto(void)
5093 {
5094         eat(T_goto);
5095
5096         if(token.type != T_IDENTIFIER) {
5097                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5098                 eat_statement();
5099                 return NULL;
5100         }
5101         symbol_t *symbol = token.v.symbol;
5102         next_token();
5103
5104         declaration_t *label = get_label(symbol);
5105
5106         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5107
5108         statement->statement.kind            = STATEMENT_GOTO;
5109         statement->statement.source_position = token.source_position;
5110
5111         statement->label = label;
5112
5113         /* remember the goto's in a list for later checking */
5114         if (goto_last == NULL) {
5115                 goto_first = goto_last = statement;
5116         } else {
5117                 goto_last->next = statement;
5118         }
5119
5120         expect(';');
5121
5122         return (statement_t*) statement;
5123 }
5124
5125 /**
5126  * Parse a continue statement.
5127  */
5128 static statement_t *parse_continue(void)
5129 {
5130         statement_t *statement;
5131         if (current_loop == NULL) {
5132                 errorf(HERE, "continue statement not within loop");
5133                 statement = NULL;
5134         } else {
5135                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5136
5137                 statement->base.source_position = token.source_position;
5138         }
5139
5140         eat(T_continue);
5141         expect(';');
5142
5143         return statement;
5144 }
5145
5146 /**
5147  * Parse a break statement.
5148  */
5149 static statement_t *parse_break(void)
5150 {
5151         statement_t *statement;
5152         if (current_switch == NULL && current_loop == NULL) {
5153                 errorf(HERE, "break statement not within loop or switch");
5154                 statement = NULL;
5155         } else {
5156                 statement = allocate_statement_zero(STATEMENT_BREAK);
5157
5158                 statement->base.source_position = token.source_position;
5159         }
5160
5161         eat(T_break);
5162         expect(';');
5163
5164         return statement;
5165 }
5166
5167 /**
5168  * Check if a given declaration represents a local variable.
5169  */
5170 static bool is_local_var_declaration(const declaration_t *declaration) {
5171         switch ((storage_class_tag_t) declaration->storage_class) {
5172         case STORAGE_CLASS_NONE:
5173         case STORAGE_CLASS_AUTO:
5174         case STORAGE_CLASS_REGISTER: {
5175                 const type_t *type = skip_typeref(declaration->type);
5176                 if(is_type_function(type)) {
5177                         return false;
5178                 } else {
5179                         return true;
5180                 }
5181         }
5182         default:
5183                 return false;
5184         }
5185 }
5186
5187 /**
5188  * Check if a given expression represents a local variable.
5189  */
5190 static bool is_local_variable(const expression_t *expression)
5191 {
5192         if (expression->base.kind != EXPR_REFERENCE) {
5193                 return false;
5194         }
5195         const declaration_t *declaration = expression->reference.declaration;
5196         return is_local_var_declaration(declaration);
5197 }
5198
5199 /**
5200  * Parse a return statement.
5201  */
5202 static statement_t *parse_return(void)
5203 {
5204         eat(T_return);
5205
5206         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5207
5208         statement->statement.kind            = STATEMENT_RETURN;
5209         statement->statement.source_position = token.source_position;
5210
5211         assert(is_type_function(current_function->type));
5212         function_type_t *function_type = &current_function->type->function;
5213         type_t          *return_type   = function_type->return_type;
5214
5215         expression_t *return_value = NULL;
5216         if(token.type != ';') {
5217                 return_value = parse_expression();
5218         }
5219         expect(';');
5220
5221         return_type = skip_typeref(return_type);
5222
5223         if(return_value != NULL) {
5224                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
5225
5226                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5227                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5228                         warningf(statement->statement.source_position,
5229                                 "'return' with a value, in function returning void");
5230                         return_value = NULL;
5231                 } else {
5232                         type_t *const res_type = semantic_assign(return_type,
5233                                 return_value, "'return'");
5234                         if (res_type == NULL) {
5235                                 errorf(statement->statement.source_position,
5236                                         "cannot return something of type '%T' in function returning '%T'",
5237                                         return_value->base.datatype, return_type);
5238                         } else {
5239                                 return_value = create_implicit_cast(return_value, res_type);
5240                         }
5241                 }
5242                 /* check for returning address of a local var */
5243                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5244                         const expression_t *expression = return_value->unary.value;
5245                         if (is_local_variable(expression)) {
5246                                 warningf(statement->statement.source_position,
5247                                         "function returns address of local variable");
5248                         }
5249                 }
5250         } else {
5251                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5252                         warningf(statement->statement.source_position,
5253                                 "'return' without value, in function returning non-void");
5254                 }
5255         }
5256         statement->return_value = return_value;
5257
5258         return (statement_t*) statement;
5259 }
5260
5261 /**
5262  * Parse a declaration statement.
5263  */
5264 static statement_t *parse_declaration_statement(void)
5265 {
5266         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5267
5268         statement->base.source_position = token.source_position;
5269
5270         declaration_t *before = last_declaration;
5271         parse_declaration(record_declaration);
5272
5273         if(before == NULL) {
5274                 statement->declaration.declarations_begin = context->declarations;
5275         } else {
5276                 statement->declaration.declarations_begin = before->next;
5277         }
5278         statement->declaration.declarations_end = last_declaration;
5279
5280         return statement;
5281 }
5282
5283 /**
5284  * Parse an expression statement, ie. expr ';'.
5285  */
5286 static statement_t *parse_expression_statement(void)
5287 {
5288         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5289
5290         statement->base.source_position  = token.source_position;
5291         statement->expression.expression = parse_expression();
5292
5293         expect(';');
5294
5295         return statement;
5296 }
5297
5298 /**
5299  * Parse a statement.
5300  */
5301 static statement_t *parse_statement(void)
5302 {
5303         statement_t   *statement = NULL;
5304
5305         /* declaration or statement */
5306         switch(token.type) {
5307         case T_asm:
5308                 statement = parse_asm_statement();
5309                 break;
5310
5311         case T_case:
5312                 statement = parse_case_statement();
5313                 break;
5314
5315         case T_default:
5316                 statement = parse_default_statement();
5317                 break;
5318
5319         case '{':
5320                 statement = parse_compound_statement();
5321                 break;
5322
5323         case T_if:
5324                 statement = parse_if();
5325                 break;
5326
5327         case T_switch:
5328                 statement = parse_switch();
5329                 break;
5330
5331         case T_while:
5332                 statement = parse_while();
5333                 break;
5334
5335         case T_do:
5336                 statement = parse_do();
5337                 break;
5338
5339         case T_for:
5340                 statement = parse_for();
5341                 break;
5342
5343         case T_goto:
5344                 statement = parse_goto();
5345                 break;
5346
5347         case T_continue:
5348                 statement = parse_continue();
5349                 break;
5350
5351         case T_break:
5352                 statement = parse_break();
5353                 break;
5354
5355         case T_return:
5356                 statement = parse_return();
5357                 break;
5358
5359         case ';':
5360                 next_token();
5361                 statement = NULL;
5362                 break;
5363
5364         case T_IDENTIFIER:
5365                 if(look_ahead(1)->type == ':') {
5366                         statement = parse_label_statement();
5367                         break;
5368                 }
5369
5370                 if(is_typedef_symbol(token.v.symbol)) {
5371                         statement = parse_declaration_statement();
5372                         break;
5373                 }
5374
5375                 statement = parse_expression_statement();
5376                 break;
5377
5378         case T___extension__:
5379                 /* this can be a prefix to a declaration or an expression statement */
5380                 /* we simply eat it now and parse the rest with tail recursion */
5381                 do {
5382                         next_token();
5383                 } while(token.type == T___extension__);
5384                 statement = parse_statement();
5385                 break;
5386
5387         DECLARATION_START
5388                 statement = parse_declaration_statement();
5389                 break;
5390
5391         default:
5392                 statement = parse_expression_statement();
5393                 break;
5394         }
5395
5396         assert(statement == NULL
5397                         || statement->base.source_position.input_name != NULL);
5398
5399         return statement;
5400 }
5401
5402 /**
5403  * Parse a compound statement.
5404  */
5405 static statement_t *parse_compound_statement(void)
5406 {
5407         compound_statement_t *compound_statement
5408                 = allocate_ast_zero(sizeof(compound_statement[0]));
5409         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5410         compound_statement->statement.source_position = token.source_position;
5411
5412         eat('{');
5413
5414         int        top          = environment_top();
5415         context_t *last_context = context;
5416         set_context(&compound_statement->context);
5417
5418         statement_t *last_statement = NULL;
5419
5420         while(token.type != '}' && token.type != T_EOF) {
5421                 statement_t *statement = parse_statement();
5422                 if(statement == NULL)
5423                         continue;
5424
5425                 if(last_statement != NULL) {
5426                         last_statement->base.next = statement;
5427                 } else {
5428                         compound_statement->statements = statement;
5429                 }
5430
5431                 while(statement->base.next != NULL)
5432                         statement = statement->base.next;
5433
5434                 last_statement = statement;
5435         }
5436
5437         if(token.type == '}') {
5438                 next_token();
5439         } else {
5440                 errorf(compound_statement->statement.source_position, "end of file while looking for closing '}'");
5441         }
5442
5443         assert(context == &compound_statement->context);
5444         set_context(last_context);
5445         environment_pop_to(top);
5446
5447         return (statement_t*) compound_statement;
5448 }
5449
5450 /**
5451  * Initialize builtin types.
5452  */
5453 static void initialize_builtin_types(void)
5454 {
5455         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5456         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5457         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5458         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5459         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5460         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5461         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5462         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5463
5464         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5465         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5466         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5467         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5468 }
5469
5470 /**
5471  * Parse a translation unit.
5472  */
5473 static translation_unit_t *parse_translation_unit(void)
5474 {
5475         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5476
5477         assert(global_context == NULL);
5478         global_context = &unit->context;
5479
5480         assert(context == NULL);
5481         set_context(&unit->context);
5482
5483         initialize_builtin_types();
5484
5485         while(token.type != T_EOF) {
5486                 if (token.type == ';') {
5487                         /* TODO error in strict mode */
5488                         warningf(HERE, "stray ';' outside of function");
5489                         next_token();
5490                 } else {
5491                         parse_external_declaration();
5492                 }
5493         }
5494
5495         assert(context == &unit->context);
5496         context          = NULL;
5497         last_declaration = NULL;
5498
5499         assert(global_context == &unit->context);
5500         global_context = NULL;
5501
5502         return unit;
5503 }
5504
5505 /**
5506  * Parse the input.
5507  *
5508  * @return  the translation unit or NULL if errors occurred.
5509  */
5510 translation_unit_t *parse(void)
5511 {
5512         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5513         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5514         diagnostic_count  = 0;
5515         error_count       = 0;
5516         warning_count     = 0;
5517
5518         type_set_output(stderr);
5519         ast_set_output(stderr);
5520
5521         lookahead_bufpos = 0;
5522         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5523                 next_token();
5524         }
5525         translation_unit_t *unit = parse_translation_unit();
5526
5527         DEL_ARR_F(environment_stack);
5528         DEL_ARR_F(label_stack);
5529
5530         if(error_count > 0)
5531                 return NULL;
5532
5533         return unit;
5534 }
5535
5536 /**
5537  * Initialize the parser.
5538  */
5539 void init_parser(void)
5540 {
5541         init_expression_parsers();
5542         obstack_init(&temp_obst);
5543
5544         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5545         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5546 }
5547
5548 /**
5549  * Terminate the parser.
5550  */
5551 void exit_parser(void)
5552 {
5553         obstack_free(&temp_obst, NULL);
5554 }