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