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