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