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