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