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