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